Interface NaruTask
- All Superinterfaces:
NToElement
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intExit code reported when a task failed without publishing one of its own.static final intExit code reported when a task was killed rather than allowed to finish. -
Method Summary
Modifier and TypeMethodDescriptionaddAwaitReceived(NaruEvent event) booleanaddHistory(String m) voidaddHistory(NaruMessage assistantMsg) voidaddResultMessage(NMsg msg) addStatements(NaruStatement... any) voidaddSystemHistory(Function<NaruTask, NaruMessage> sysHistory) addToolExclusion(String toolName) addToolTag(String toolTag) voidappendRoutineLine(int increment, String name) voidawait()Block until this task is finished.booleanBlock until this task is finished, or untiltimeoutelapses.bg()voiddefault NaruTaskcancel()Stop this task, and report it asNaruTaskStatus.KILLEDwith exit codeEXIT_INTERRUPTED.chat(NaruModelConfig modelKey, NaruModelRequest request) intcontext(NaruSource... sources) defaultAdvance(NaruStatement stmt) duration()How long this task ran, or empty until it has ended.endTime()When this task reached a terminal state, or empty while it is still live.error()Why this task failed, or empty if it did not fail.evalExpression(String condition) intexitCode()The task's own verdict, from the exit code its last statement published.expandString(String condition) fg()fireEvent(String eventType, Map<String, Object> args, NaruEventTarget target, NaruRetentionPolicy retention) frame()getTaskEnv(String key, boolean inherited) booleanhold()longid()inbox()inputBuffer(String buffer) inputMode(NaruInputMode inputMode) voidinvokeDirective(String line) invokeDirective(NaruDirective dir, NaruDirectiveCallContext context) voidinvokeRoutine(String routineName) booleanWhether this task has finished, which is final: a completed task never runs again.booleanisFg()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".booleanisHeld()booleanWhetherkill()has been requested and not yet cleared byreset().default booleanWhether the answer from the lastchat(net.thevpc.naru.api.model.NaruModelConfig, net.thevpc.naru.api.model.NaruModelRequest)was already shown to the user as it arrived.booleanWhether the task finished without complaint: completed, with no error and a zero exit code.kill()voidlog(NaruLogMode mode, NMsg s) model()name()voidonComplete(Consumer<NaruTask> callback) Runcallbackwhen 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.parent()longparentId()parseStatement(String line) intpc()pc(int nextPc) int[]pctrace()popFrame()prependStatements(NaruStatement... any) promptMode(NaruPromptMode newMode) pushStatementModelCall(String prompt) booleanremoveHistoryAt(int index) removeToolExclusion(String toolName) removeToolTag(String toolTag) voidrequestInput(NMsg prompt) voidreset()resolveVariable(String key) session()setExtraContext(String extraContext) voidsetLastResult(NaruMessage lastResult) setModel(NaruModelConfig model) setProjectDir(NPath projectDir) voidsetReturnResult(Object returnResult) voidsetRoutineLine(int index, String name) setTaskEnv(String key, Object value) setWorkingDir(NPath workingDir) status()subscribe(String eventType, NaruEventSubscription subscription) taskMode()taskMode(NaruTaskMode newMode) voidthrowError(NMsg nMsg) Throw if this task did not succeed, otherwise return this task for chaining.voidtick()toFuture()This task's completion, for a caller that would rather compose than block.inttrimHistory(int count) unhold()unsetTaskEnv(String key) useRoutine(String name) value()What the task produced, empty if it produced nothing.One of this task's variables.default ObjectvarOrDefault(String key, Object fallback) One of this task's variables, orfallbackif it has no such variable.vars()The task's own variables, as they stood when it ended.Methods inherited from interface net.thevpc.nuts.elem.NToElement
toElement
-
Field Details
-
EXIT_INTERRUPTED
static final int EXIT_INTERRUPTEDExit 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_FAILUREExit 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 andendTime(),error()andduration()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()andvars(). 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
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
How long this task ran, or empty until it has ended. -
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_INPUTandNaruTaskStatus.BLOCKED_ON_EVENT, and true only forNaruTaskStatus.DONE,NaruTaskStatus.FAILEDandNaruTaskStatus.KILLED. -
isSuccess
boolean isSuccess()Whether the task finished without complaint: completed, with no error and a zero exit code. A task can bedoneand still not successful -- it produced an answer and an objection, and those are reported independently. -
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 reportsEXIT_INTERRUPTED, and a failure that published nothing reportsEXIT_FAILURE, so a non-success never quietly looks like a success. Frozen at termination. -
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
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
emptyoptional, 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
One of this task's variables, orfallbackif 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.INTERACTIVEtask, 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. Useawait(Duration)for those, or drive an interactive task by answering it. -
await
Block until this task is finished, or untiltimeoutelapses.- Returns:
- whether the task finished, so a timeout is not confused with a task that produced nothing
-
onComplete
Runcallbackwhen 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
CompletableFuture<NaruTask> 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. UsethrowIfFailed()to treat a failure as exceptional. -
cancel
Stop this task, and report it asNaruTaskStatus.KILLEDwith exit codeEXIT_INTERRUPTED. Cooperative: a task that does not yield is not forced.Idempotent, and harmless on a task that has already finished.
-
cancel
-
stackFrames
List<NaruTaskStackFrame> stackFrames() -
stacktrace
List<NaruTaskStackItem> stacktrace() -
creationTime
Instant creationTime() -
fg
NaruTask fg() -
bg
NaruTask bg() -
status
NaruTaskStatus status() -
load
-
workingDir
NPath workingDir() -
setProjectDir
-
inputMode
NaruInputMode inputMode() -
inputMode
-
promptMode
NaruPromptMode promptMode() -
promptMode
-
taskMode
NaruTaskMode taskMode() -
taskMode
-
projectDir
NPath projectDir() -
getExtraContext
String getExtraContext() -
setExtraContext
-
log
-
addToolExclusion
-
removeToolExclusion
-
findToolExclusions
-
removeToolTag
-
addToolTag
-
findToolTags
List<NaruToolTag> findToolTags() -
findTools
List<NaruToolDefinition> findTools() -
context
-
removeHistoryAt
boolean removeHistoryAt(int index) -
pc
int pc() -
pc
-
clearHistory
int clearHistory() -
model
NaruModelConfig model() -
setModel
-
trimHistory
int trimHistory(int count) -
kill
NaruTask kill() -
isKillRequested
boolean isKillRequested()Whetherkill()has been requested and not yet cleared byreset().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 toRUNNINGaround every tick. -
hasMoreStatements
boolean hasMoreStatements() -
addStatement
-
prependStatement
-
prependStatements
-
loadLines
-
loadFiles
-
addStatements
-
throwError
-
inputBuffer
String inputBuffer() -
inputBuffer
-
addHistory
-
addSystemHistory
-
addHistory
-
setLastResult
-
setReturnResult
-
getReturnResult
Object getReturnResult() -
getLastResult
NaruMessage getLastResult() -
tick
void tick() -
invokeDirective
-
invokeDirective
-
invokeRoutine
-
nextStatement
NOptional<NaruStatement> nextStatement() -
peekStatement
NOptional<NaruStatement> peekStatement() -
peekFrame
NaruTaskFrame peekFrame() -
popFrame
NaruTask popFrame() -
pushFrame
-
frame
NaruTaskFrame frame() -
pctrace
int[] pctrace() -
schedulerMode
NaruSchedulerMode schedulerMode() -
schedulerMode
-
unsetTaskEnv
-
setTaskEnv
-
getTaskEnv
-
resolveVariable
-
pushStatementModelCall
-
varResolver
NExprVarResolver varResolver() -
expressionBuilder
NExprContextBuilder expressionBuilder() -
evalExpression
-
expandString
-
parseFile
-
parseStatement
-
resolve
-
chat
-
isResponseStreamed
default boolean isResponseStreamed()Whether the answer from the lastchat(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
-
reset
void reset() -
hold
NaruTask hold() -
unhold
NaruTask unhold() -
isHeld
boolean isHeld() -
awaitFilter
-
awaitFilter
NaruEventFilter awaitFilter() -
awaitReceived
-
releaseStepPermit
NaruTask releaseStepPermit() -
inbox
NaruTaskInbox inbox() -
eventSubscriptions
Map<String,NaruEventSubscription> eventSubscriptions() -
subscribe
-
acquireStepPermit
NaruTask acquireStepPermit() -
parentId
long parentId() -
name
String name() -
name
-
parent
-
defaultAdvance
-
requestInput
-
consumeInput
String consumeInput() -
fireEvent
NaruTask fireEvent(String eventType, Map<String, Object> args, NaruEventTarget target, NaruRetentionPolicy retention) -
sleep
-
addAwaitReceived
-
editRoutine
NOptional<NaruRoutine> editRoutine() -
editRoutineName
String editRoutineName() -
useRoutine
-
setRoutineLine
-
appendRoutineLine
-
getTaskEnv
-
call
-
addResultMessage
-