Interface NaruTask

All Superinterfaces:
NToElement

public interface NaruTask extends NToElement
  • Field Details

    • EXIT_INTERRUPTED

      static final int EXIT_INTERRUPTED
      Exit code reported when a task was killed rather than allowed to finish. Deliberately the conventional 130: a host reading exit codes should not have to know this enum.
      See Also:
    • EXIT_FAILURE

      static final int EXIT_FAILURE
      Exit code reported when a task failed without publishing one of its own.
      See Also:
  • Method Details

    • isFg

      boolean isFg()
      A task is its own handle on its own result, so this one type answers both "what is this task" and "what did it produce".

      The contract changes shape at termination, and it is worth being explicit about it. While a task is live, status() moves and endTime(), error() and duration() are empty. Once it reaches a terminal state it stops changing forever, and those describe the finished run. In other words: a task is live until it ends, and a record of itself afterwards.

      What freezes is the outcome: endTime(), error(), duration(), value(), exitCode() and vars(). It is frozen because a task outlives its own registration, so it may be the only remaining record of what happened, and a record that a later write can edit is not a record. The descriptive setters (setProjectDir(net.thevpc.nuts.io.NPath), taskMode() and the rest) stay live, because those describe the task rather than its run -- this type is not a value type, so do not cache one expecting immutability. Ask it again when you need to know.

      Nothing here is a snapshot of the session: once a task has been deregistered, this object remains the only way to reach what happened, which is why the answer has to live here rather than in a registry that forgets.

    • id

      long id()
    • endTime

      NOptional<Instant> endTime()
      When this task reached a terminal state, or empty while it is still live. Frozen at that moment, and the marker that says the rest of the outcome is settled too.
    • duration

      NOptional<NDuration> duration()
      How long this task ran, or empty until it has ended.
    • error

      NOptional<String> error()
      Why this task failed, or empty if it did not fail. Frozen at termination.
    • isCompleted

      boolean isCompleted()
      Whether this task has finished, which is final: a completed task never runs again.

      A task waiting on input or on an event is not completed. It is still going to be given another chance, and a host awaiting it is waiting for real work rather than for a verdict -- so this reads false for NaruTaskStatus.BLOCKED_ON_INPUT and NaruTaskStatus.BLOCKED_ON_EVENT, and true only for NaruTaskStatus.DONE, NaruTaskStatus.FAILED and NaruTaskStatus.KILLED.

    • isSuccess

      boolean isSuccess()
      Whether the task finished without complaint: completed, with no error and a zero exit code. A task can be done and still not successful -- it produced an answer and an objection, and those are reported independently.
    • value

      NOptional<Object> value()
      What the task produced, empty if it produced nothing. Frozen at termination.

      Prefers an explicit /return, and falls back to the task's last result so that a script which simply ends still reports what it last computed.

    • exitCode

      int exitCode()
      The task's own verdict, from the exit code its last statement published. A killed task reports EXIT_INTERRUPTED, and a failure that published nothing reports EXIT_FAILURE, so a non-success never quietly looks like a success. Frozen at termination.
    • vars

      Map<String,Object> vars()
      The task's own variables, as they stood when it ended. Task-local only: values a task inherited from its session are not part of what it produced, and reporting them would make every task's output a dump of the session it happened to run in. Frozen at termination, and unmodifiable.
    • var

      default NOptional<Object> var(String key)
      One of this task's variables.

      Distinguishes absent from present and set to nothing, which a task can do deliberately: an empty result is an empty optional, whereas a variable that exists and holds nothing is present with a null value. Collapsing the two would make a script's explicit emptiness indistinguishable from never having set it.

    • varOrDefault

      default Object varOrDefault(String key, Object fallback)
      One of this task's variables, or fallback if it has no such variable.
    • throwIfFailed

      NaruTask throwIfFailed()
      Throw if this task did not succeed, otherwise return this task for chaining.
    • await

      void await()
      Block until this task is finished.

      Rejected for an NaruTaskMode.INTERACTIVE task, which finishes only when a host answers it -- so this would block for as long as the host keeps it alive, which is almost never what the caller meant. Use await(Duration) for those, or drive an interactive task by answering it.

    • await

      boolean await(Duration timeout)
      Block until this task is finished, or until timeout elapses.
      Returns:
      whether the task finished, so a timeout is not confused with a task that produced nothing
    • onComplete

      void onComplete(Consumer<NaruTask> callback)
      Run callback when this task finishes, on a shared background executor rather than the scheduler thread that ran the task -- a callback that blocks must not stall every other task in the session.

      Registered after the task already finished, it runs immediately. A callback that throws is contained: it cannot prevent the task from reporting completion to anyone else.

    • toFuture

      This task's completion, for a caller that would rather compose than block. Completes normally even when the task failed: a failure is a result, not an exceptional condition, and reporting it that way would force every caller to unwrap. Use throwIfFailed() to treat a failure as exceptional.
    • cancel

      default NaruTask cancel()
      Stop this task, and report it as NaruTaskStatus.KILLED with exit code EXIT_INTERRUPTED. Cooperative: a task that does not yield is not forced.

      Idempotent, and harmless on a task that has already finished.

    • cancel

      NaruTask cancel(String reason)
      cancel() with a reason to record against the task, which is then reported by error().
    • stackFrames

      List<NaruTaskStackFrame> stackFrames()
    • stacktrace

      List<NaruTaskStackItem> stacktrace()
    • creationTime

      Instant creationTime()
    • fg

      NaruTask fg()
    • bg

      NaruTask bg()
    • status

      NaruTaskStatus status()
    • load

      NaruTask load(NElement element)
    • workingDir

      NPath workingDir()
    • setProjectDir

      NaruTask setProjectDir(NPath projectDir)
    • inputMode

      NaruInputMode inputMode()
    • inputMode

      NaruTask inputMode(NaruInputMode inputMode)
    • promptMode

      NaruPromptMode promptMode()
    • promptMode

      NaruTask promptMode(NaruPromptMode newMode)
    • taskMode

      NaruTaskMode taskMode()
    • taskMode

      NaruTask taskMode(NaruTaskMode newMode)
    • projectDir

      NPath projectDir()
    • getExtraContext

      String getExtraContext()
    • setExtraContext

      NaruTask setExtraContext(String extraContext)
    • log

      void log(NaruLogMode mode, NMsg s)
    • addToolExclusion

      NaruTask addToolExclusion(String toolName)
    • removeToolExclusion

      NaruTask removeToolExclusion(String toolName)
    • findToolExclusions

      Set<String> findToolExclusions()
    • removeToolTag

      NaruTask removeToolTag(String toolTag)
    • addToolTag

      NaruTask addToolTag(String toolTag)
    • findToolTags

      List<NaruToolTag> findToolTags()
    • findTools

      List<NaruToolDefinition> findTools()
    • context

      NaruModelRequest context(NaruSource... sources)
    • removeHistoryAt

      boolean removeHistoryAt(int index)
    • pc

      int pc()
    • pc

      NaruTask pc(int nextPc)
    • clearHistory

      int clearHistory()
    • model

    • setModel

      NaruTask setModel(NaruModelConfig model)
    • trimHistory

      int trimHistory(int count)
    • kill

      NaruTask kill()
    • isKillRequested

      boolean isKillRequested()
      Whether kill() has been requested and not yet cleared by reset().

      Cancellation is cooperative: kill() marks the task so that the scheduler stops re-queueing it at the next statement boundary, but a statement already executing is not interrupted. Long running tools and model calls should poll this and bail out early rather than run to completion. status() alone is not sufficient for polling, since the scheduler transiently flips it to RUNNING around every tick.

    • hasMoreStatements

      boolean hasMoreStatements()
    • addStatement

      NaruTask addStatement(NaruStatement any)
    • prependStatement

      NaruTask prependStatement(NaruStatement any)
    • prependStatements

      NaruTask prependStatements(NaruStatement... any)
    • loadLines

      NaruTask loadLines(String... any)
    • loadFiles

      NaruTask loadFiles(NPath... any)
    • addStatements

      NaruTask addStatements(NaruStatement... any)
    • throwError

      void throwError(NMsg nMsg)
    • inputBuffer

      String inputBuffer()
    • inputBuffer

      NaruTask inputBuffer(String buffer)
    • addHistory

      boolean addHistory(String m)
    • addSystemHistory

      void addSystemHistory(Function<NaruTask,NaruMessage> sysHistory)
    • addHistory

      void addHistory(NaruMessage assistantMsg)
    • setLastResult

      void setLastResult(NaruMessage lastResult)
    • setReturnResult

      void setReturnResult(Object returnResult)
    • getReturnResult

      Object getReturnResult()
    • getLastResult

      NaruMessage getLastResult()
    • tick

      void tick()
    • invokeDirective

      NaruStmtResult invokeDirective(NaruDirective dir, NaruDirectiveCallContext context)
    • invokeDirective

      void invokeDirective(String line)
    • invokeRoutine

      void invokeRoutine(String routineName)
    • nextStatement

      NOptional<NaruStatement> nextStatement()
    • peekStatement

      NOptional<NaruStatement> peekStatement()
    • peekFrame

      NaruTaskFrame peekFrame()
    • popFrame

      NaruTask popFrame()
    • pushFrame

      NaruTaskFrame pushFrame(String routine, boolean inheritVars)
    • frame

      NaruTaskFrame frame()
    • pctrace

      int[] pctrace()
    • schedulerMode

      NaruSchedulerMode schedulerMode()
    • schedulerMode

      NaruTask schedulerMode(NaruSchedulerMode mode)
    • unsetTaskEnv

      NaruTask unsetTaskEnv(String key)
    • setTaskEnv

      NaruTask setTaskEnv(String key, Object value)
    • getTaskEnv

      NOptional<Object> getTaskEnv(String key, boolean inherited)
    • resolveVariable

      Object resolveVariable(String key)
    • pushStatementModelCall

      NaruTask pushStatementModelCall(String prompt)
    • varResolver

      NExprVarResolver varResolver()
    • expressionBuilder

      NExprContextBuilder expressionBuilder()
    • evalExpression

      Object evalExpression(String condition)
    • expandString

      String expandString(String condition)
    • parseFile

      NOptional<List<NaruStatement>> parseFile(NPath path)
    • parseStatement

      NOptional<NaruStatement> parseStatement(String line)
    • resolve

      NPath resolve(String path)
    • chat

      NaruResponse chat(NaruModelConfig modelKey, NaruModelRequest request)
    • isResponseStreamed

      default boolean isResponseStreamed()
      Whether the answer from the last chat(net.thevpc.naru.api.model.NaruModelConfig, net.thevpc.naru.api.model.NaruModelRequest) was already shown to the user as it arrived.

      The statement that made the call still owns the response, and logging it again would print the same words twice: once token by token, then once whole. A caller that reports the answer should ask this first. False for a batched call, so the normal path is unchanged.

    • session

      NaruSession session()
    • setWorkingDir

      NaruTask setWorkingDir(NPath workingDir)
    • reset

      void reset()
    • hold

      NaruTask hold()
    • unhold

      NaruTask unhold()
    • isHeld

      boolean isHeld()
    • awaitFilter

      NaruTask awaitFilter(NaruEventFilter nv)
    • awaitFilter

      NaruEventFilter awaitFilter()
    • awaitReceived

      List<NaruEvent> awaitReceived()
    • releaseStepPermit

      NaruTask releaseStepPermit()
    • inbox

      NaruTaskInbox inbox()
    • eventSubscriptions

      Map<String,NaruEventSubscription> eventSubscriptions()
    • subscribe

      NaruTask subscribe(String eventType, NaruEventSubscription subscription)
    • acquireStepPermit

      NaruTask acquireStepPermit()
    • parentId

      long parentId()
    • name

      String name()
    • name

      NaruTask name(String newName)
    • parent

      NOptional<NaruTask> parent()
    • defaultAdvance

      NaruTask defaultAdvance(NaruStatement stmt)
    • requestInput

      void requestInput(NMsg prompt)
    • consumeInput

      String consumeInput()
    • fireEvent

      NaruTask fireEvent(String eventType, Map<String,Object> args, NaruEventTarget target, NaruRetentionPolicy retention)
    • sleep

      NaruTask sleep(NDuration duration)
    • addAwaitReceived

      NaruTask addAwaitReceived(NaruEvent event)
    • editRoutine

      NOptional<NaruRoutine> editRoutine()
    • editRoutineName

      String editRoutineName()
    • useRoutine

      NOptional<NaruRoutine> useRoutine(String name)
    • setRoutineLine

      void setRoutineLine(int index, String name)
    • appendRoutineLine

      void appendRoutineLine(int increment, String name)
    • getTaskEnv

      Map<String,Object> getTaskEnv()
    • call

      void call(String cmdline)
    • addResultMessage

      void addResultMessage(NMsg msg)