@astralyn/pi 1.4.5 → 1.4.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +20 -0
- package/dist/bundle/chunks/{chunk-I5S7H7GA.js → chunk-EYKC6ESU.js} +1 -1
- package/dist/bundle/chunks/chunk-KDO6L76C.js +230 -0
- package/dist/bundle/chunks/chunk-RBTJBQWX.js +1500 -0
- package/dist/bundle/chunks/{execute-GMFGC27P.js → execute-5ZQUS52M.js} +1 -1
- package/dist/bundle/chunks/{virtual-modules-6FUV7ZDV.js → virtual-modules-KCQU7LOC.js} +1 -1
- package/dist/bundle/cli.js +1 -1
- package/dist/bundle/index.js +1 -1
- package/dist/bundle/rpc-entry.js +1 -1
- package/dist/core/extensions/index.d.ts +1 -1
- package/dist/core/extensions/index.d.ts.map +1 -1
- package/dist/core/extensions/index.js.map +1 -1
- package/dist/core/isolated-session.d.ts +23 -0
- package/dist/core/isolated-session.d.ts.map +1 -0
- package/dist/core/isolated-session.js +55 -0
- package/dist/core/isolated-session.js.map +1 -0
- package/dist/core/tasks/codec.d.ts +12 -0
- package/dist/core/tasks/codec.d.ts.map +1 -0
- package/dist/core/tasks/codec.js +139 -0
- package/dist/core/tasks/codec.js.map +1 -0
- package/dist/core/tasks/execution.d.ts +64 -0
- package/dist/core/tasks/execution.d.ts.map +1 -0
- package/dist/core/tasks/execution.js +272 -0
- package/dist/core/tasks/execution.js.map +1 -0
- package/dist/core/tasks/output.d.ts +12 -6
- package/dist/core/tasks/output.d.ts.map +1 -1
- package/dist/core/tasks/output.js +38 -38
- package/dist/core/tasks/output.js.map +1 -1
- package/dist/core/tasks/presentation.d.ts +14 -5
- package/dist/core/tasks/presentation.d.ts.map +1 -1
- package/dist/core/tasks/presentation.js +56 -185
- package/dist/core/tasks/presentation.js.map +1 -1
- package/dist/core/tasks/runtime.d.ts +9 -9
- package/dist/core/tasks/runtime.d.ts.map +1 -1
- package/dist/core/tasks/runtime.js +63 -254
- package/dist/core/tasks/runtime.js.map +1 -1
- package/dist/core/tasks/scheduler.d.ts +16 -0
- package/dist/core/tasks/scheduler.d.ts.map +1 -0
- package/dist/core/tasks/scheduler.js +42 -0
- package/dist/core/tasks/scheduler.js.map +1 -0
- package/dist/core/tasks/session.d.ts +1 -0
- package/dist/core/tasks/session.d.ts.map +1 -1
- package/dist/core/tasks/session.js +15 -27
- package/dist/core/tasks/session.js.map +1 -1
- package/dist/core/tasks/store.js +4 -4
- package/dist/core/tasks/store.js.map +1 -1
- package/dist/core/tasks/types.d.ts +63 -53
- package/dist/core/tasks/types.d.ts.map +1 -1
- package/dist/core/tasks/types.js +3 -9
- package/dist/core/tasks/types.js.map +1 -1
- package/dist/core/tools/shell-execution.js +4 -4
- package/dist/core/tools/shell-execution.js.map +1 -1
- package/dist/core/tools/shell-tool.d.ts.map +1 -1
- package/dist/core/tools/shell-tool.js +23 -30
- package/dist/core/tools/shell-tool.js.map +1 -1
- package/dist/core/usage-totals.d.ts +1 -3
- package/dist/core/usage-totals.d.ts.map +1 -1
- package/dist/core/usage-totals.js +17 -8
- package/dist/core/usage-totals.js.map +1 -1
- package/dist/extensions/agent/activity.d.ts +4 -4
- package/dist/extensions/agent/activity.d.ts.map +1 -1
- package/dist/extensions/agent/activity.js +15 -24
- package/dist/extensions/agent/activity.js.map +1 -1
- package/dist/extensions/agent/index.d.ts +2 -11
- package/dist/extensions/agent/index.d.ts.map +1 -1
- package/dist/extensions/agent/index.js +3 -88
- package/dist/extensions/agent/index.js.map +1 -1
- package/dist/extensions/agent/progress.d.ts +31 -0
- package/dist/extensions/agent/progress.d.ts.map +1 -0
- package/dist/extensions/agent/progress.js +145 -0
- package/dist/extensions/agent/progress.js.map +1 -0
- package/dist/extensions/agent/render.d.ts.map +1 -1
- package/dist/extensions/agent/render.js +8 -17
- package/dist/extensions/agent/render.js.map +1 -1
- package/dist/extensions/agent/report.d.ts +9 -0
- package/dist/extensions/agent/report.d.ts.map +1 -0
- package/dist/extensions/agent/report.js +40 -0
- package/dist/extensions/agent/report.js.map +1 -0
- package/dist/extensions/agent/settings-panel.d.ts +43 -0
- package/dist/extensions/agent/settings-panel.d.ts.map +1 -0
- package/dist/extensions/agent/settings-panel.js +125 -0
- package/dist/extensions/agent/settings-panel.js.map +1 -0
- package/dist/extensions/agent/settings.d.ts +1 -1
- package/dist/extensions/agent/settings.d.ts.map +1 -1
- package/dist/extensions/agent/settings.js +101 -83
- package/dist/extensions/agent/settings.js.map +1 -1
- package/dist/extensions/agent/tool.d.ts +13 -0
- package/dist/extensions/agent/tool.d.ts.map +1 -0
- package/dist/extensions/agent/tool.js +84 -0
- package/dist/extensions/agent/tool.js.map +1 -0
- package/dist/extensions/agent/types.d.ts +19 -21
- package/dist/extensions/agent/types.d.ts.map +1 -1
- package/dist/extensions/agent/types.js +2 -10
- package/dist/extensions/agent/types.js.map +1 -1
- package/dist/extensions/agent/worker.d.ts +16 -0
- package/dist/extensions/agent/worker.d.ts.map +1 -0
- package/dist/extensions/agent/worker.js +68 -0
- package/dist/extensions/agent/worker.js.map +1 -0
- package/dist/extensions/tasks/tool/actions.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/actions.js +1 -9
- package/dist/extensions/tasks/tool/actions.js.map +1 -1
- package/dist/extensions/tasks/tool/schema.js +1 -1
- package/dist/extensions/tasks/tool/schema.js.map +1 -1
- package/dist/extensions/tasks/tool/types.d.ts +2 -8
- package/dist/extensions/tasks/tool/types.d.ts.map +1 -1
- package/dist/extensions/tasks/tool/types.js +0 -2
- package/dist/extensions/tasks/tool/types.js.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/completion-render.js +27 -26
- package/dist/extensions/tasks/ui/completion-render.js.map +1 -1
- package/dist/extensions/tasks/ui/inspector.d.ts +5 -3
- package/dist/extensions/tasks/ui/inspector.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/inspector.js +18 -6
- package/dist/extensions/tasks/ui/inspector.js.map +1 -1
- package/dist/extensions/tasks/ui/layout.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/layout.js +111 -75
- package/dist/extensions/tasks/ui/layout.js.map +1 -1
- package/dist/extensions/tasks/ui/list.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/list.js +43 -28
- package/dist/extensions/tasks/ui/list.js.map +1 -1
- package/dist/extensions/tasks/ui/manager.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/manager.js +8 -2
- package/dist/extensions/tasks/ui/manager.js.map +1 -1
- package/dist/extensions/tasks/ui/model.d.ts +4 -0
- package/dist/extensions/tasks/ui/model.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/model.js +12 -1
- package/dist/extensions/tasks/ui/model.js.map +1 -1
- package/dist/extensions/tasks/ui/render.js +3 -4
- package/dist/extensions/tasks/ui/render.js.map +1 -1
- package/dist/extensions/tasks/ui/task-view.d.ts +0 -5
- package/dist/extensions/tasks/ui/task-view.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/task-view.js +0 -7
- package/dist/extensions/tasks/ui/task-view.js.map +1 -1
- package/dist/extensions/tasks/ui/tree.js +1 -1
- package/dist/extensions/tasks/ui/tree.js.map +1 -1
- package/dist/extensions/tasks/ui/views.d.ts +10 -5
- package/dist/extensions/tasks/ui/views.d.ts.map +1 -1
- package/dist/extensions/tasks/ui/views.js +61 -36
- package/dist/extensions/tasks/ui/views.js.map +1 -1
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
- package/dist/modes/interactive/components/keybinding-hints.js +2 -1
- package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
- package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/model-selector.js +7 -4
- package/dist/modes/interactive/components/model-selector.js.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
- package/dist/modes/interactive/components/thinking-selector.js +10 -3
- package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
- package/docs/bundled/extensions/agent.md +12 -10
- package/docs/bundled/extensions/statusline.md +1 -1
- package/docs/bundled/tasks.md +15 -14
- package/docs/extensions.md +22 -6
- package/docs/sdk.md +2 -2
- package/docs/session-format.md +27 -23
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/bundle/chunks/chunk-FSJ45CRP.js +0 -229
- package/dist/bundle/chunks/chunk-W3FIUMGM.js +0 -1501
- package/dist/core/tasks/history.d.ts +0 -4
- package/dist/core/tasks/history.d.ts.map +0 -1
- package/dist/core/tasks/history.js +0 -131
- package/dist/core/tasks/history.js.map +0 -1
- package/dist/extensions/agent/runner.d.ts +0 -24
- package/dist/extensions/agent/runner.d.ts.map +0 -1
- package/dist/extensions/agent/runner.js +0 -274
- package/dist/extensions/agent/runner.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/tasks/types.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/tasks/types.ts"],"names":[],"mappings":"AAMA,MAAM,CAAC,MAAM,sBAAsB,GAAG,CAAC,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,CAAU,CAAC;AAG1G,MAAM,CAAC,MAAM,iBAAiB,GAAG,wBAAwB,CAAC;AAqL1D,MAAM,CAAC,MAAM,yBAAyB,GACrC,yHAAyH,CAAC;AAE3H,MAAM,UAAU,cAAc,CAAC,MAAkB;IAChD,OAAQ,sBAA4C,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AACvE,CAAC;AAED;;;;;GAKG;AACH,MAAM,OAAO,eAAgB,SAAQ,KAAK;IAGzC,YAAY,IAA6B,EAAE,OAAuB;QACjE,KAAK,CAAC,IAAI,KAAK,WAAW,CAAC,CAAC,CAAC,mBAAmB,CAAC,CAAC,CAAC,iBAAiB,CAAC,CAAC;QACtE,IAAI,CAAC,IAAI,GAAG,iBAAiB,CAAC;QAC9B,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;IACxB,CAAC;CACD","sourcesContent":["import type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport type { Usage } from \"@earendil-works/pi-ai/compat\";\n\n/** An executor-owned machine source: the task ID prefix, never a dispatch key for the runtime. */\nexport type TaskKind = string;\nexport type TaskMode = \"foreground\" | \"background\";\nexport const TASK_TERMINAL_STATUSES = [\"completed\", \"partial\", \"failed\", \"cancelled\", \"timeout\"] as const;\nexport type TaskTerminalStatus = (typeof TASK_TERMINAL_STATUSES)[number];\nexport type TaskStatus = \"queued\" | \"running\" | \"stopping\" | TaskTerminalStatus;\nexport const TASK_KIND_PATTERN = /^[a-z][a-z0-9-]{0,63}$/;\n\n/**\n * How a task's output is shaped, declared by its executor:\n * a `log` streams and carries its outcome at the end; a `report` is one finished document.\n */\nexport type TaskOutputKind = \"log\" | \"report\";\n\n/** A bounded snapshot; truncation is recorded at the source, never inferred from text. */\nexport interface TaskText {\n\ttext: string;\n\ttruncated: boolean;\n}\n\n/** What the task was asked to do, such as a shell command or a delegated briefing. */\nexport interface TaskInput extends TaskText {\n\t/** Human label for the input, such as \"Command\" or \"Prompt\". */\n\tlabel: string;\n\t/** Optional syntax-highlighting language. */\n\tlanguage?: string;\n}\n\n/** One labelled Details row, such as [\"Directory\", \"/repo\"] or [\"Exit\", \"1\"]. */\nexport type TaskFact = readonly [label: string, value: string];\n\n/** A read-only view of one task; the runtime returns frozen snapshots. */\nexport interface TaskSnapshot {\n\tid: string;\n\tkind: TaskKind;\n\t/** Human source name, such as \"Bash\" or \"Agent\". */\n\tlabel: string;\n\ttitle: string;\n\toutput: TaskOutputKind;\n\tinput?: TaskInput;\n\tfacts?: TaskFact[];\n\ttoolCallId: string;\n\tanchorId: string | null;\n\tmode: TaskMode;\n\tstatus: TaskStatus;\n\tstartedAt: number;\n\tendedAt?: number;\n\toutputPath?: string;\n\t/** Bounded model-readable result text. */\n\tresult?: TaskText;\n\t/** Additional human-only Output text; model-facing reads use the result instead. */\n\tdisplay?: TaskText;\n\terror?: string;\n}\n\nexport interface TaskUpdate<T> {\n\t/** Model-readable progress; also forwarded to a foreground caller's onUpdate. */\n\tresult: AgentToolResult<T>;\n\t/** Additional human-only Output text. */\n\tdisplay?: string;\n\t/** Cumulative usage so far, settled once if the execution ends without a final usage. */\n\tusage?: Usage;\n}\n\nexport interface TaskCompletion<T> {\n\tresult: AgentToolResult<T>;\n\t/** Defaults to completed, or cancelled when the task was already cancelled. */\n\tstatus?: TaskTerminalStatus;\n\t/** Additional human-only Output text, excluded from tasks read and completion context. */\n\tdisplay?: string;\n\t/** Terminal diagnostic, stored independently of log slices and bounded to 4096 bytes. */\n\terror?: string;\n\t/** Terminal Details rows; a label replaces the same label given at launch. */\n\tfacts?: TaskFact[];\n\t/** Authoritative cumulative usage; overrides the result's usage and the latest published usage. */\n\tusage?: Usage;\n}\n\nexport interface TaskControl<T> {\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\treadonly mode: TaskMode;\n\tonModeChange(listener: (mode: TaskMode) => void): () => void;\n\t/** The executor's own preflight passed; from now on the caller may be handed off to the background. */\n\taccept(): void;\n\tpublish(update: TaskUpdate<T>): void;\n\t/** Register once; cleanup must own only this exclusively-created file and close its writer first. */\n\tattachOutput(path: string, cleanup?: () => void | Promise<void>): void;\n\t/** Cancel this execution, for example when an executor policy limit is exceeded. */\n\tcancel(): void;\n}\n\nexport interface TaskExecution<T> {\n\tkind: TaskKind;\n\t/** Human source name; defaults to `kind`. */\n\tlabel?: string;\n\ttitle: string;\n\t/** Defaults to `log`. */\n\toutput?: TaskOutputKind;\n\tinput?: TaskInput;\n\tfacts?: TaskFact[];\n\ttoolCallId: string;\n\tbackground?: boolean;\n\t/**\n\t * At most `limit` executions sharing `key` run at once. Later ones wait as queued tasks\n\t * whose `run` starts when a slot frees; a queued task can be handed off or cancelled.\n\t */\n\tconcurrency?: { key: string; limit: number };\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<T>) => void;\n\trun(control: TaskControl<T>): Promise<TaskCompletion<T>>;\n}\n\nexport type TaskToolOutcome<T> =\n\t| { kind: \"result\"; result: AgentToolResult<T>; status: TaskTerminalStatus; error?: string }\n\t| { kind: \"background\"; task: TaskSnapshot };\n\nexport interface TaskRead {\n\ttask: TaskSnapshot;\n\ttext: string;\n\t/** Bounded log-read/expiry diagnostic, independent of text slicing and byte offsets. */\n\treadError?: string;\n\ttotalBytes: number;\n\ttruncated: boolean;\n\tfromByte?: number;\n}\n\n/** Optional host integration for products built on the execution runtime. */\nexport interface TasksSessionContext {\n\t/** Ends only management-tool waits when new steering arrives. */\n\treadonly waitInterruptSignal?: AbortSignal;\n\t/** Hold a settled result until the wait's tool result has been persisted. */\n\tprepareWait(toolCallId: string, taskId: string): void;\n\t/** Running tasks that navigating to `targetId` would cancel on this session branch. */\n\tstoppedByTreeNavigation(targetId: string): TaskSnapshot[];\n}\n\n/** Session-bound public capability. Captured instances close on runtime replacement. */\nexport interface TasksContext {\n\treadonly enabled: boolean;\n\treadonly closed?: boolean;\n\t/** Present when the runtime is attached to Pi's durable session lifecycle. */\n\treadonly session?: TasksSessionContext;\n\texecute<T>(execution: TaskExecution<T>): Promise<TaskToolOutcome<T>>;\n\tlist(): TaskSnapshot[];\n\tget(id: string): TaskSnapshot;\n\tread(id: string, options?: { mode?: \"head\" | \"tail\"; bytes?: number; sinceBytes?: number }): Promise<TaskRead>;\n\t/** Observation only: terminal delivery is acknowledged by the host via markDelivered after result persistence. */\n\twait(id: string, timeoutMs?: number, signal?: AbortSignal, interruptSignal?: AbortSignal): Promise<TaskSnapshot>;\n\t/**\n\t * Observe the first task running at call time to settle. Returns undefined when there is\n\t * no such task, the window ends, or interruptSignal fires. Tasks started later are excluded.\n\t */\n\twaitAny(timeoutMs?: number, signal?: AbortSignal, interruptSignal?: AbortSignal): Promise<TaskSnapshot | undefined>;\n\tkill(id: string): boolean;\n\t/**\n\t * Move running foreground executions to the background while background slots remain;\n\t * returns how many moved. Throws when eligible work exists but every slot is taken.\n\t */\n\tdetachForeground(): number;\n\t/** Whether this execution can move now, including host policy and available background slots. */\n\tcanDetach(id: string): boolean;\n\t/** Returns false when the task cannot move; throws when every background slot is taken. */\n\tdetach(id: string): boolean;\n\tsubscribe(listener: () => void): () => void;\n\t/** Keep retained output available without delaying completion delivery. */\n\tretain(id: string): () => void;\n\t/** Hold automatic delivery while preparing a result for the host to persist. */\n\tholdDelivery(id: string): () => void;\n}\n\nexport interface TaskRuntimeOptions {\n\tenabled?: boolean;\n\tbackgroundAllowed?: boolean;\n\t/** Durable host integration; standalone runtimes leave waits observational. */\n\tsession?: TasksSessionContext;\n\tanchor?: () => string | null;\n\t/** Admission limit for unsettled background tasks; foreground work is bounded by its caller. */\n\tmaxBackground?: number;\n\t/** Per-history limit: foreground and background tasks each get this allowance. */\n\tmaxHistory?: number;\n\t/** Best-effort cleanup errors, bounded to 4096 bytes; no retries or execution failure. */\n\tonCleanupError?: (message: string) => void;\n\t/** Synchronous persistence before terminal observers or notifications. */\n\tonSettled?: (task: TaskSnapshot, usage: Usage | undefined) => void;\n}\n\nexport const TASK_BACKGROUND_REJECTION =\n\t\"Background execution is not permitted in this host. Run with background: false or omit background. No work was started.\";\n\nexport function isTaskTerminal(status: TaskStatus): status is TaskTerminalStatus {\n\treturn (TASK_TERMINAL_STATUSES as readonly string[]).includes(status);\n}\n\n/**\n * A failed id lookup, typed so hosts can enrich the message without matching\n * on message text. `matches` snapshots exactly the records the id or prefix\n * resolved against — including records outside the current branch, which\n * list() hides but prefix matching still collides with.\n */\nexport class TaskLookupError extends Error {\n\treadonly kind: \"unknown\" | \"ambiguous\";\n\treadonly matches: TaskSnapshot[];\n\tconstructor(kind: \"unknown\" | \"ambiguous\", matches: TaskSnapshot[]) {\n\t\tsuper(kind === \"ambiguous\" ? \"Ambiguous task ID\" : \"Unknown task ID\");\n\t\tthis.name = \"TaskLookupError\";\n\t\tthis.kind = kind;\n\t\tthis.matches = matches;\n\t}\n}\n"]}
|
|
@@ -50,7 +50,7 @@ export async function runShellCommand(options) {
|
|
|
50
50
|
outputError = error instanceof Error ? error : new Error(String(error));
|
|
51
51
|
try {
|
|
52
52
|
if (managed)
|
|
53
|
-
managed.control.
|
|
53
|
+
managed.control.cancel();
|
|
54
54
|
}
|
|
55
55
|
catch {
|
|
56
56
|
// Late data must not throw through a process observer.
|
|
@@ -76,7 +76,7 @@ export async function runShellCommand(options) {
|
|
|
76
76
|
: undefined,
|
|
77
77
|
};
|
|
78
78
|
if (managed)
|
|
79
|
-
managed.control.publish(result);
|
|
79
|
+
managed.control.publish({ result });
|
|
80
80
|
else
|
|
81
81
|
options.onUpdate?.(result);
|
|
82
82
|
};
|
|
@@ -139,7 +139,7 @@ export async function runShellCommand(options) {
|
|
|
139
139
|
});
|
|
140
140
|
};
|
|
141
141
|
try {
|
|
142
|
-
managed.control.
|
|
142
|
+
managed.control.attachOutput(path, cleanup);
|
|
143
143
|
}
|
|
144
144
|
catch (error) {
|
|
145
145
|
await cleanup();
|
|
@@ -190,7 +190,7 @@ export async function runShellCommand(options) {
|
|
|
190
190
|
return {
|
|
191
191
|
status: failure?.status,
|
|
192
192
|
error: failure?.error,
|
|
193
|
-
...(exitCode !== undefined ? { exitCode } : {}),
|
|
193
|
+
...(exitCode !== undefined ? { facts: [["Exit", exitCode === null ? "signal" : String(exitCode)]] } : {}),
|
|
194
194
|
result: {
|
|
195
195
|
...(fullOutput && typeof exitCode === "number"
|
|
196
196
|
? {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell-execution.js","sourceRoot":"","sources":["../../../src/core/tools/shell-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,SAAS,EAAE,MAAM,oB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AAC,CAAC,EAAE,gBAAgB,EAAE,KAAK,CAAC,cAAc,EAAE;gCAC5C,CAAC,CAAC,EAAE,CAAC;4BACN,SAAS,EAAE,QAAQ;4BACnB,iBAAiB,EAAE,IAAI,CAAC,KAAK,CAAC,CAAC,WAAW,CAAC,GAAG,EAAE,GAAG,SAAS,CAAC,GAAG,GAAG,CAAC,GAAG,EAAE;yBACzE;wBACD,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,OAAO,EAAE,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;qBACrC;oBACF,CAAC,CAAC,EAAE,CAAC;gBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;gBAClG,OAAO;aACP;SACD,CAAC;IACH,CAAC;YAAS,CAAC;QACV,eAAe,GAAG,KAAK,CAAC;QACxB,WAAW,EAAE,EAAE,CAAC;QAChB,gBAAgB,EAAE,CAAC;QACnB,MAAM,MAAM,CAAC,aAAa,EAAE,CAAC;IAC9B,CAAC;AACF,CAAC","sourcesContent":["import { unlink } from \"node:fs/promises\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport { boundText } from \"../tasks/output.ts\";\nimport type { TaskCompletion, TaskControl } from \"../tasks/types.ts\";\nimport type { BashOperations, BashSpawnContext } from \"./bash.ts\";\nimport { OutputAccumulator, type OutputSnapshot } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS } from \"./renderers/bash.ts\";\nimport type { BashToolDetails } from \"./shell-tool.ts\";\nimport { formatSize } from \"./truncate.ts\";\n\nexport const MAX_BACKGROUND_OUTPUT_BYTES = 20 * 1024 * 1024;\n\nexport interface ManagedShellExecution {\n\tcontrol: TaskControl<BashToolDetails | undefined>;\n}\n\ninterface ShellExecutionOptions {\n\toperations: BashOperations;\n\tcontext: BashSpawnContext;\n\ttempFilePrefix: string;\n\ttimeout?: number;\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<BashToolDetails | undefined>) => void;\n\tmanaged?: ManagedShellExecution;\n}\n\ninterface ShellFailure {\n\tstatus: \"failed\" | \"cancelled\" | \"timeout\";\n\terror: string;\n}\n\n/** Interpret the documented BashOperations error markers once, before formatting output. */\nfunction shellFailure(error: unknown): ShellFailure {\n\tif (error instanceof Error && error.message === \"aborted\") return { status: \"cancelled\", error: \"Command aborted\" };\n\tif (error instanceof Error && error.message.startsWith(\"timeout:\"))\n\t\treturn { status: \"timeout\", error: `Command timed out after ${error.message.split(\":\")[1]} seconds` };\n\treturn { status: \"failed\", error: boundText(error instanceof Error ? error.message : String(error), 4096) };\n}\n\nfunction formatOutput(\n\toutput: OutputAccumulator,\n\tsnapshot: OutputSnapshot,\n\tmanaged: boolean,\n\temptyText: string,\n): { text: string; details: BashToolDetails | undefined } {\n\tconst truncation = snapshot.truncation;\n\tlet text = snapshot.content || emptyText;\n\tlet details: BashToolDetails | undefined = managed ? { fullOutputPath: snapshot.fullOutputPath } : undefined;\n\tif (truncation.truncated) {\n\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\tconst endLine = truncation.totalLines;\n\t\tif (truncation.lastLinePartial) {\n\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t} else {\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(truncation.maxBytes)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t}\n\t}\n\treturn { text, details };\n}\n\n/** One process and one output owner across foreground/background handoff. */\nexport async function runShellCommand(\n\toptions: ShellExecutionOptions,\n): Promise<TaskCompletion<BashToolDetails | undefined>> {\n\tconst { operations, context, managed, signal, timeout } = options;\n\tconst output = new OutputAccumulator({ tempFilePrefix: options.tempFilePrefix, persistFromStart: !!managed });\n\tconst startedAt = performance.now();\n\tlet outputError: Error | undefined;\n\tlet acceptingOutput = true;\n\tlet unsubscribe: (() => void) | undefined;\n\tlet updateTimer: NodeJS.Timeout | undefined;\n\tlet updateDirty = false;\n\tlet lastUpdateAt = 0;\n\n\tconst failOutput = (error: unknown) => {\n\t\tif (outputError) return;\n\t\toutputError = error instanceof Error ? error : new Error(String(error));\n\t\ttry {\n\t\t\tif (managed) managed.control.requestCancel();\n\t\t} catch {\n\t\t\t// Late data must not throw through a process observer.\n\t\t}\n\t};\n\tconst checkOutputLimit = () => {\n\t\tif (managed?.control.mode === \"background\" && output.getTotalBytes() > MAX_BACKGROUND_OUTPUT_BYTES) {\n\t\t\tfailOutput(new Error(\"Background command exceeded the 20 MiB output limit\"));\n\t\t}\n\t};\n\tconst snapshot = () =>\n\t\toutput.snapshot({\n\t\t\tpersistIfTruncated: true,\n\t\t\tmaxBytes: managed?.control.mode === \"background\" ? 40 * 1024 : undefined,\n\t\t});\n\tconst publish = (snapshot?: OutputSnapshot) => {\n\t\tconst result: AgentToolResult<BashToolDetails | undefined> = {\n\t\t\tcontent: snapshot ? [{ type: \"text\", text: snapshot.content }] : [],\n\t\t\tdetails: snapshot\n\t\t\t\t? {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t};\n\t\tif (managed) managed.control.publish(result);\n\t\telse options.onUpdate?.(result);\n\t};\n\tconst emitOutputUpdate = () => {\n\t\tif ((!managed && !options.onUpdate) || !updateDirty) return;\n\t\tupdateDirty = false;\n\t\tlastUpdateAt = Date.now();\n\t\tpublish(snapshot());\n\t};\n\tconst clearUpdateTimer = () => {\n\t\tif (updateTimer) clearTimeout(updateTimer);\n\t\tupdateTimer = undefined;\n\t};\n\tconst scheduleOutputUpdate = () => {\n\t\tif (!managed && !options.onUpdate) return;\n\t\tupdateDirty = true;\n\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\tif (delay <= 0) {\n\t\t\tclearUpdateTimer();\n\t\t\temitOutputUpdate();\n\t\t} else {\n\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\tupdateTimer = undefined;\n\t\t\t\temitOutputUpdate();\n\t\t\t}, delay);\n\t\t}\n\t};\n\tconst handleData = (data: Buffer) => {\n\t\tif (!acceptingOutput || outputError) return;\n\t\ttry {\n\t\t\tif (\n\t\t\t\tmanaged?.control.mode === \"background\" &&\n\t\t\t\toutput.getTotalBytes() + data.length > MAX_BACKGROUND_OUTPUT_BYTES\n\t\t\t) {\n\t\t\t\tconst remaining = Math.max(0, MAX_BACKGROUND_OUTPUT_BYTES - output.getTotalBytes());\n\t\t\t\toutput.append(data.subarray(0, remaining));\n\t\t\t\tfailOutput(new Error(\"Background command exceeded the 20 MiB output limit\"));\n\t\t\t} else output.append(data);\n\t\t\tscheduleOutputUpdate();\n\t\t} catch (error) {\n\t\t\tif (!managed) throw error;\n\t\t\tfailOutput(error);\n\t\t}\n\t};\n\n\ttry {\n\t\tif (managed) {\n\t\t\tconst path = output.snapshot().fullOutputPath!;\n\t\t\tconst cleanup = async () => {\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\tawait unlink(path).catch((error: NodeJS.ErrnoException) => {\n\t\t\t\t\tif (error.code !== \"ENOENT\") throw error;\n\t\t\t\t});\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tmanaged.control.setOutputPath(path, cleanup);\n\t\t\t} catch (error) {\n\t\t\t\tawait cleanup();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// Detach must check a silent foreground log too, preserving bytes already written.\n\t\t\tunsubscribe = managed.control.onModeChange(checkOutputLimit);\n\t\t}\n\t\tpublish();\n\t\tlet failure: ShellFailure | undefined;\n\t\tlet exitCode: number | null | undefined;\n\t\ttry {\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\tconst execution = operations.exec(context.command, context.cwd, {\n\t\t\t\tonData: handleData,\n\t\t\t\tsignal,\n\t\t\t\ttimeout,\n\t\t\t\tenv: context.env,\n\t\t\t});\n\t\t\tmanaged?.control.accept();\n\t\t\t({ exitCode } = await execution);\n\t\t\tif (exitCode === null) {\n\t\t\t\tfailure = { status: \"failed\", error: \"Command terminated without an exit code\" };\n\t\t\t} else if (exitCode !== 0) {\n\t\t\t\tfailure = { status: \"failed\", error: `Command exited with code ${exitCode}` };\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = shellFailure(error);\n\t\t}\n\t\tacceptingOutput = false;\n\t\toutput.finish();\n\t\tclearUpdateTimer();\n\t\tif (managed) publish(snapshot());\n\t\telse emitOutputUpdate();\n\t\tconst final = snapshot();\n\t\tawait output.closeTempFile();\n\t\t// Final progress/cleanup can re-enter handoff. Classify policy cancellation\n\t\t// after those callbacks, independently of the process's abort marker.\n\t\tif (outputError) failure = { status: \"failed\", error: boundText(outputError.message, 4096) };\n\t\tconst { text, details } = formatOutput(output, final, !!managed, failure ? \"\" : \"(no output)\");\n\t\tconst fullOutput =\n\t\t\ttypeof exitCode === \"number\" && !outputError ? await output.readFullOutput(1024 * 1024) : undefined;\n\t\treturn {\n\t\t\tstatus: failure?.status,\n\t\t\terror: failure?.error,\n\t\t\t...(exitCode !== undefined ? { exitCode } : {}),\n\t\t\tresult: {\n\t\t\t\t...(fullOutput && typeof exitCode === \"number\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tstructuredContent: {\n\t\t\t\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t\t\t\t...(fullOutput.truncated && final.fullOutputPath\n\t\t\t\t\t\t\t\t\t? { full_output_path: final.fullOutputPath }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\t\t\t\twall_time_seconds: Math.round((performance.now() - startedAt) / 100) / 10,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...(failure ? { isError: true } : {}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tcontent: [{ type: \"text\", text: failure ? `${text ? `${text}\\n\\n` : \"\"}${failure.error}` : text }],\n\t\t\t\tdetails,\n\t\t\t},\n\t\t};\n\t} finally {\n\t\tacceptingOutput = false;\n\t\tunsubscribe?.();\n\t\tclearUpdateTimer();\n\t\tawait output.closeTempFile();\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shell-execution.js","sourceRoot":"","sources":["../../../src/core/tools/shell-execution.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,MAAM,EAAE,MAAM,kBAAkB,CAAC;AAE1C,OAAO,EAAE,SAAS,EAAE,MAAM,oBAAoB,CAAC;AAG/C,OAAO,EAAE,iBAAiB,EAAuB,MAAM,yBAAyB,CAAC;AACjF,OAAO,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAE9D,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;AAE3C,MAAM,CAAC,MAAM,2BAA2B,GAAG,EAAE,GAAG,IAAI,GAAG,IAAI,CAAC;AAqB5D,4FAA4F;AAC5F,SAAS,YAAY,CAAC,KAAc;IACnC,IAAI,KAAK,YAAY,KAAK,IAAI,KAAK,CAAC,OAAO,KAAK,SAAS;QAAE,OAAO,EAAE,MAAM,EAAE,WAAW,EAAE,KAAK,EAAE,iBAAiB,EAAE,CAAC;IACpH,IAAI,KAAK,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AE,CAAC,CAAC,CAAC,EAAE,CAAC;qBACrC;oBACF,CAAC,CAAC,EAAE,CAAC;gBACN,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC,GAAG,IAAI,MAAM,CAAC,CAAC,CAAC,EAAE,GAAG,OAAO,CAAC,KAAK,EAAE,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC;gBAClG,OAAO;aACP;SACD,CAAC;IACH,CAAC;YAAS,CAAC;QACV,eAAe,GAAG,KAAK,CAAC;QACxB,WAAW,EAAE,EAAE,CAAC;QAChB,gBAAgB,EAAE,CAAC;QACnB,MAAM,MAAM,CAAC,aAAa,EAAE,CAAC;IAC9B,CAAC;AACF,CAAC","sourcesContent":["import { unlink } from \"node:fs/promises\";\nimport type { AgentToolResult } from \"@earendil-works/pi-agent-core\";\nimport { boundText } from \"../tasks/output.ts\";\nimport type { TaskCompletion, TaskControl } from \"../tasks/types.ts\";\nimport type { BashOperations, BashSpawnContext } from \"./bash.ts\";\nimport { OutputAccumulator, type OutputSnapshot } from \"./output-accumulator.ts\";\nimport { BASH_UPDATE_THROTTLE_MS } from \"./renderers/bash.ts\";\nimport type { BashToolDetails } from \"./shell-tool.ts\";\nimport { formatSize } from \"./truncate.ts\";\n\nexport const MAX_BACKGROUND_OUTPUT_BYTES = 20 * 1024 * 1024;\n\nexport interface ManagedShellExecution {\n\tcontrol: TaskControl<BashToolDetails | undefined>;\n}\n\ninterface ShellExecutionOptions {\n\toperations: BashOperations;\n\tcontext: BashSpawnContext;\n\ttempFilePrefix: string;\n\ttimeout?: number;\n\tsignal?: AbortSignal;\n\tonUpdate?: (result: AgentToolResult<BashToolDetails | undefined>) => void;\n\tmanaged?: ManagedShellExecution;\n}\n\ninterface ShellFailure {\n\tstatus: \"failed\" | \"cancelled\" | \"timeout\";\n\terror: string;\n}\n\n/** Interpret the documented BashOperations error markers once, before formatting output. */\nfunction shellFailure(error: unknown): ShellFailure {\n\tif (error instanceof Error && error.message === \"aborted\") return { status: \"cancelled\", error: \"Command aborted\" };\n\tif (error instanceof Error && error.message.startsWith(\"timeout:\"))\n\t\treturn { status: \"timeout\", error: `Command timed out after ${error.message.split(\":\")[1]} seconds` };\n\treturn { status: \"failed\", error: boundText(error instanceof Error ? error.message : String(error), 4096) };\n}\n\nfunction formatOutput(\n\toutput: OutputAccumulator,\n\tsnapshot: OutputSnapshot,\n\tmanaged: boolean,\n\temptyText: string,\n): { text: string; details: BashToolDetails | undefined } {\n\tconst truncation = snapshot.truncation;\n\tlet text = snapshot.content || emptyText;\n\tlet details: BashToolDetails | undefined = managed ? { fullOutputPath: snapshot.fullOutputPath } : undefined;\n\tif (truncation.truncated) {\n\t\tdetails = { truncation, fullOutputPath: snapshot.fullOutputPath };\n\t\tconst startLine = truncation.totalLines - truncation.outputLines + 1;\n\t\tconst endLine = truncation.totalLines;\n\t\tif (truncation.lastLinePartial) {\n\t\t\tconst lastLineSize = formatSize(output.getLastLineBytes());\n\t\t\ttext += `\\n\\n[Showing last ${formatSize(truncation.outputBytes)} of line ${endLine} (line is ${lastLineSize}). Full output: ${snapshot.fullOutputPath}]`;\n\t\t} else if (truncation.truncatedBy === \"lines\") {\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines}. Full output: ${snapshot.fullOutputPath}]`;\n\t\t} else {\n\t\t\ttext += `\\n\\n[Showing lines ${startLine}-${endLine} of ${truncation.totalLines} (${formatSize(truncation.maxBytes)} limit). Full output: ${snapshot.fullOutputPath}]`;\n\t\t}\n\t}\n\treturn { text, details };\n}\n\n/** One process and one output owner across foreground/background handoff. */\nexport async function runShellCommand(\n\toptions: ShellExecutionOptions,\n): Promise<TaskCompletion<BashToolDetails | undefined>> {\n\tconst { operations, context, managed, signal, timeout } = options;\n\tconst output = new OutputAccumulator({ tempFilePrefix: options.tempFilePrefix, persistFromStart: !!managed });\n\tconst startedAt = performance.now();\n\tlet outputError: Error | undefined;\n\tlet acceptingOutput = true;\n\tlet unsubscribe: (() => void) | undefined;\n\tlet updateTimer: NodeJS.Timeout | undefined;\n\tlet updateDirty = false;\n\tlet lastUpdateAt = 0;\n\n\tconst failOutput = (error: unknown) => {\n\t\tif (outputError) return;\n\t\toutputError = error instanceof Error ? error : new Error(String(error));\n\t\ttry {\n\t\t\tif (managed) managed.control.cancel();\n\t\t} catch {\n\t\t\t// Late data must not throw through a process observer.\n\t\t}\n\t};\n\tconst checkOutputLimit = () => {\n\t\tif (managed?.control.mode === \"background\" && output.getTotalBytes() > MAX_BACKGROUND_OUTPUT_BYTES) {\n\t\t\tfailOutput(new Error(\"Background command exceeded the 20 MiB output limit\"));\n\t\t}\n\t};\n\tconst snapshot = () =>\n\t\toutput.snapshot({\n\t\t\tpersistIfTruncated: true,\n\t\t\tmaxBytes: managed?.control.mode === \"background\" ? 40 * 1024 : undefined,\n\t\t});\n\tconst publish = (snapshot?: OutputSnapshot) => {\n\t\tconst result: AgentToolResult<BashToolDetails | undefined> = {\n\t\t\tcontent: snapshot ? [{ type: \"text\", text: snapshot.content }] : [],\n\t\t\tdetails: snapshot\n\t\t\t\t? {\n\t\t\t\t\t\ttruncation: snapshot.truncation.truncated ? snapshot.truncation : undefined,\n\t\t\t\t\t\tfullOutputPath: snapshot.fullOutputPath,\n\t\t\t\t\t}\n\t\t\t\t: undefined,\n\t\t};\n\t\tif (managed) managed.control.publish({ result });\n\t\telse options.onUpdate?.(result);\n\t};\n\tconst emitOutputUpdate = () => {\n\t\tif ((!managed && !options.onUpdate) || !updateDirty) return;\n\t\tupdateDirty = false;\n\t\tlastUpdateAt = Date.now();\n\t\tpublish(snapshot());\n\t};\n\tconst clearUpdateTimer = () => {\n\t\tif (updateTimer) clearTimeout(updateTimer);\n\t\tupdateTimer = undefined;\n\t};\n\tconst scheduleOutputUpdate = () => {\n\t\tif (!managed && !options.onUpdate) return;\n\t\tupdateDirty = true;\n\t\tconst delay = BASH_UPDATE_THROTTLE_MS - (Date.now() - lastUpdateAt);\n\t\tif (delay <= 0) {\n\t\t\tclearUpdateTimer();\n\t\t\temitOutputUpdate();\n\t\t} else {\n\t\t\tupdateTimer ??= setTimeout(() => {\n\t\t\t\tupdateTimer = undefined;\n\t\t\t\temitOutputUpdate();\n\t\t\t}, delay);\n\t\t}\n\t};\n\tconst handleData = (data: Buffer) => {\n\t\tif (!acceptingOutput || outputError) return;\n\t\ttry {\n\t\t\tif (\n\t\t\t\tmanaged?.control.mode === \"background\" &&\n\t\t\t\toutput.getTotalBytes() + data.length > MAX_BACKGROUND_OUTPUT_BYTES\n\t\t\t) {\n\t\t\t\tconst remaining = Math.max(0, MAX_BACKGROUND_OUTPUT_BYTES - output.getTotalBytes());\n\t\t\t\toutput.append(data.subarray(0, remaining));\n\t\t\t\tfailOutput(new Error(\"Background command exceeded the 20 MiB output limit\"));\n\t\t\t} else output.append(data);\n\t\t\tscheduleOutputUpdate();\n\t\t} catch (error) {\n\t\t\tif (!managed) throw error;\n\t\t\tfailOutput(error);\n\t\t}\n\t};\n\n\ttry {\n\t\tif (managed) {\n\t\t\tconst path = output.snapshot().fullOutputPath!;\n\t\t\tconst cleanup = async () => {\n\t\t\t\tawait output.closeTempFile();\n\t\t\t\tawait unlink(path).catch((error: NodeJS.ErrnoException) => {\n\t\t\t\t\tif (error.code !== \"ENOENT\") throw error;\n\t\t\t\t});\n\t\t\t};\n\t\t\ttry {\n\t\t\t\tmanaged.control.attachOutput(path, cleanup);\n\t\t\t} catch (error) {\n\t\t\t\tawait cleanup();\n\t\t\t\tthrow error;\n\t\t\t}\n\t\t\t// Detach must check a silent foreground log too, preserving bytes already written.\n\t\t\tunsubscribe = managed.control.onModeChange(checkOutputLimit);\n\t\t}\n\t\tpublish();\n\t\tlet failure: ShellFailure | undefined;\n\t\tlet exitCode: number | null | undefined;\n\t\ttry {\n\t\t\tif (signal?.aborted) throw new Error(\"aborted\");\n\t\t\tconst execution = operations.exec(context.command, context.cwd, {\n\t\t\t\tonData: handleData,\n\t\t\t\tsignal,\n\t\t\t\ttimeout,\n\t\t\t\tenv: context.env,\n\t\t\t});\n\t\t\tmanaged?.control.accept();\n\t\t\t({ exitCode } = await execution);\n\t\t\tif (exitCode === null) {\n\t\t\t\tfailure = { status: \"failed\", error: \"Command terminated without an exit code\" };\n\t\t\t} else if (exitCode !== 0) {\n\t\t\t\tfailure = { status: \"failed\", error: `Command exited with code ${exitCode}` };\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tfailure = shellFailure(error);\n\t\t}\n\t\tacceptingOutput = false;\n\t\toutput.finish();\n\t\tclearUpdateTimer();\n\t\tif (managed) publish(snapshot());\n\t\telse emitOutputUpdate();\n\t\tconst final = snapshot();\n\t\tawait output.closeTempFile();\n\t\t// Final progress/cleanup can re-enter handoff. Classify policy cancellation\n\t\t// after those callbacks, independently of the process's abort marker.\n\t\tif (outputError) failure = { status: \"failed\", error: boundText(outputError.message, 4096) };\n\t\tconst { text, details } = formatOutput(output, final, !!managed, failure ? \"\" : \"(no output)\");\n\t\tconst fullOutput =\n\t\t\ttypeof exitCode === \"number\" && !outputError ? await output.readFullOutput(1024 * 1024) : undefined;\n\t\treturn {\n\t\t\tstatus: failure?.status,\n\t\t\terror: failure?.error,\n\t\t\t...(exitCode !== undefined ? { facts: [[\"Exit\", exitCode === null ? \"signal\" : String(exitCode)]] } : {}),\n\t\t\tresult: {\n\t\t\t\t...(fullOutput && typeof exitCode === \"number\"\n\t\t\t\t\t? {\n\t\t\t\t\t\t\tstructuredContent: {\n\t\t\t\t\t\t\t\toutput: fullOutput.content,\n\t\t\t\t\t\t\t\ttruncated: fullOutput.truncated,\n\t\t\t\t\t\t\t\t...(fullOutput.truncated && final.fullOutputPath\n\t\t\t\t\t\t\t\t\t? { full_output_path: final.fullOutputPath }\n\t\t\t\t\t\t\t\t\t: {}),\n\t\t\t\t\t\t\t\texit_code: exitCode,\n\t\t\t\t\t\t\t\twall_time_seconds: Math.round((performance.now() - startedAt) / 100) / 10,\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t...(failure ? { isError: true } : {}),\n\t\t\t\t\t\t}\n\t\t\t\t\t: {}),\n\t\t\t\tcontent: [{ type: \"text\", text: failure ? `${text ? `${text}\\n\\n` : \"\"}${failure.error}` : text }],\n\t\t\t\tdetails,\n\t\t\t},\n\t\t};\n\t} finally {\n\t\tacceptingOutput = false;\n\t\tunsubscribe?.();\n\t\tclearUpdateTimer();\n\t\tawait output.closeTempFile();\n\t}\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell-tool.d.ts","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,MAAM,EAAE,IAAI,EAAE,MAAM,SAAS,CAAC;AAC5C,OAAO,KAAK,EAAoB,cAAc,EAAE,MAAM,wBAAwB,CAAC;AAE/E,OAAO,EACN,KAAK,cAAc,EACnB,KAAK,eAAe,EAGpB,KAAK,eAAe,EACpB,MAAM,WAAW,CAAC;AAKnB,OAAO,EAAwC,KAAK,gBAAgB,EAAE,MAAM,eAAe,CAAC;AAE5F,QAAA,MAAM,UAAU;;;;EASd,CAAC;AAEH,eAAO,MAAM,gCAAgC;;;CAGnC,CAAC;AAEX,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,OAAO,UAAU,CAAC,CAAC;AAetD,MAAM,WAAW,eAAe;IAC/B,UAAU,CAAC,EAAE,gBAAgB,CAAC;IAC9B,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,uEAAuE;IACvE,UAAU,CAAC,EAAE;QAAE,IAAI,EAAE,YAAY,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;CACpD;AAED,MAAM,MAAM,eAAe,GAAG;IAC7B,OAAO,CAAC,EAAE,MAAM,IAAI,CAAC;CACrB,CAAC;AAiBF,wBAAgB,yBAAyB,CACxC,GAAG,EAAE,MAAM,EACX,MAAM,EAAE,eAA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,CAAC,EAAE,eAAe,GACvB,UAAU,CAAC,OAAO,yBAAyB,CAAC,CAK9C;AAED,wBAAgB,cAAc,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,eAAe;;;;iCAQpE"}
|
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { Type } from "typebox";
|
|
2
|
-
import { TaskExecutionError } from "../tasks/types.js";
|
|
3
2
|
import { resolveSpawnContext, resolveTimeoutMs, } from "./bash.js";
|
|
4
3
|
import { createShellRenderers } from "./renderers/bash.js";
|
|
5
4
|
import { runShellCommand } from "./shell-execution.js";
|
|
@@ -30,7 +29,7 @@ const bashOutputSchema = Type.Union([
|
|
|
30
29
|
Type.Object({ task_id: Type.String(), status: Type.String() }),
|
|
31
30
|
]);
|
|
32
31
|
/** Translate terminal shell failures to the native foreground tool contract once. */
|
|
33
|
-
function shellToolResult(completion
|
|
32
|
+
function shellToolResult(completion) {
|
|
34
33
|
const status = completion.status;
|
|
35
34
|
if (completion.result.structuredContent)
|
|
36
35
|
return completion.result;
|
|
@@ -40,7 +39,7 @@ function shellToolResult(completion, managed) {
|
|
|
40
39
|
.map((part) => part.text)
|
|
41
40
|
.join("\n");
|
|
42
41
|
const message = completion.error ? text || completion.error : `${text ? `${text}\n\n` : ""}Command ${status}`;
|
|
43
|
-
throw
|
|
42
|
+
throw new Error(message);
|
|
44
43
|
}
|
|
45
44
|
return completion.result;
|
|
46
45
|
}
|
|
@@ -64,49 +63,43 @@ export function createShellToolDefinition(cwd, config, options) {
|
|
|
64
63
|
throw new Error("Task service is closed");
|
|
65
64
|
const run = async (managed) => {
|
|
66
65
|
const signal = managed?.control.signal ?? parentSignal;
|
|
67
|
-
|
|
68
|
-
if (
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
resolveTimeoutMs(timeout);
|
|
72
|
-
}
|
|
73
|
-
const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command;
|
|
74
|
-
const spawnContext = resolveSpawnContext(resolvedCommand, ctx?.cwd || cwd, spawnHook, exposeSessionEnvironment, ctx);
|
|
75
|
-
return await runShellCommand({
|
|
76
|
-
operations: ops,
|
|
77
|
-
context: spawnContext,
|
|
78
|
-
tempFilePrefix: config.tempFilePrefix,
|
|
79
|
-
timeout,
|
|
80
|
-
signal,
|
|
81
|
-
onUpdate: originalUpdate,
|
|
82
|
-
managed,
|
|
83
|
-
});
|
|
84
|
-
}
|
|
85
|
-
catch (error) {
|
|
86
|
-
// Setup and cleanup exceptions carry an explicit terminal status.
|
|
87
|
-
if (!managed)
|
|
88
|
-
throw error;
|
|
89
|
-
throw new TaskExecutionError(error instanceof Error ? error.message : String(error), managed.control.signal.aborted ? "cancelled" : "failed");
|
|
66
|
+
if (managed) {
|
|
67
|
+
if (signal?.aborted)
|
|
68
|
+
throw new Error("Command aborted");
|
|
69
|
+
resolveTimeoutMs(timeout);
|
|
90
70
|
}
|
|
71
|
+
const resolvedCommand = commandPrefix ? `${commandPrefix}\n${command}` : command;
|
|
72
|
+
const spawnContext = resolveSpawnContext(resolvedCommand, ctx?.cwd || cwd, spawnHook, exposeSessionEnvironment, ctx);
|
|
73
|
+
// A setup throw settles a managed task as failed, or cancelled once its signal fired.
|
|
74
|
+
return await runShellCommand({
|
|
75
|
+
operations: ops,
|
|
76
|
+
context: spawnContext,
|
|
77
|
+
tempFilePrefix: config.tempFilePrefix,
|
|
78
|
+
timeout,
|
|
79
|
+
signal,
|
|
80
|
+
onUpdate: originalUpdate,
|
|
81
|
+
managed,
|
|
82
|
+
});
|
|
91
83
|
};
|
|
92
84
|
if (!host) {
|
|
93
85
|
if (background)
|
|
94
86
|
throw new Error("Background execution is not available in this host. No command was started.");
|
|
95
|
-
return shellToolResult(await run()
|
|
87
|
+
return shellToolResult(await run());
|
|
96
88
|
}
|
|
97
89
|
const outcome = await host.execute({
|
|
98
90
|
kind: config.name,
|
|
91
|
+
label: config.shellName[0].toUpperCase() + config.shellName.slice(1),
|
|
99
92
|
title: command,
|
|
93
|
+
input: { label: "Command", text: command, truncated: false, language: config.name },
|
|
94
|
+
facts: [["Directory", ctx?.cwd || cwd]],
|
|
100
95
|
toolCallId,
|
|
101
|
-
command,
|
|
102
|
-
cwd: ctx?.cwd || cwd,
|
|
103
96
|
background,
|
|
104
97
|
signal: parentSignal,
|
|
105
98
|
onUpdate: originalUpdate,
|
|
106
99
|
run: (control) => run({ control }),
|
|
107
100
|
});
|
|
108
101
|
if (outcome.kind === "result")
|
|
109
|
-
return shellToolResult(outcome
|
|
102
|
+
return shellToolResult(outcome);
|
|
110
103
|
const tail = `Task ID: ${outcome.task.id}. Status: ${outcome.task.status}. Completion arrives automatically as a notification — do not poll or immediately wait on it; continue with other work or hand back to the user. Use tasks read to inspect output, tasks wait only when your next step is blocked on a result (one ID or any running task; prefer foreground next time in that case), or tasks kill to stop it.`;
|
|
111
104
|
// Shell execution can become background work in two ways, and the model has to know which
|
|
112
105
|
// one it got: a submitted background command starts from an empty log, while a detached
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"shell-tool.js","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAE5C,OAAO,EAAuB,kBAAkB,EAAE,MAAM,mBAAmB,CAAC;AAC5E,OAAO,EAGN,mBAAmB,EACnB,gBAAgB,GAEhB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAA8B,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE,OAAO,EAAE,kBAAkB,EAAE,MAAM,8BAA8B,CAAC;AAClE,OAAO,EAAE,iBAAiB,EAAE,iBAAiB,EAAyB,MAAM,eAAe,CAAC;AAE5F,MAAM,UAAU,GAAG,IAAI,CAAC,MAAM,CAAC;IAC9B,OAAO,EAAE,IAAI,CAAC,M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MAAM,IAAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport { type TaskCompletion, TaskExecutionError } from \"../tasks/types.ts\";\nimport {\n\ttype BashOperations,\n\ttype BashToolOptions,\n\tresolveSpawnContext,\n\tresolveTimeoutMs,\n\ttype ShellToolConfig,\n} from \"./bash.ts\";\nimport { createShellRenderers } from \"./renderers/bash.ts\";\nimport { type ManagedShellExecution, runShellCommand } from \"./shell-execution.ts\";\nimport { createLocalBashOperations } from \"./shell-operations.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult } from \"./truncate.ts\";\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"true returns a managed task ID immediately and runs the command in the background, and you are notified when it completes — do not poll for its result; omit or false to block until exit\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands, foreground or background\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nconst bashOutputSchema = Type.Union([\n\tType.Object({\n\t\toutput: Type.String({\n\t\t\tdescription: \"Combined stdout and stderr, up to 1 MiB, keeping head and tail when truncated.\",\n\t\t}),\n\t\ttruncated: Type.Boolean(),\n\t\tfull_output_path: Type.Optional(Type.String()),\n\t\texit_code: Type.Number(),\n\t\twall_time_seconds: Type.Number(),\n\t}),\n\tType.Object({ task_id: Type.String(), status: Type.String() }),\n]);\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Settled handoff snapshot, not a command completion or exit code. */\n\tbackground?: { kind: \"background\"; taskId: string };\n}\n\nexport type BashRenderState = {\n\tdispose?: () => void;\n};\n\n/** Translate terminal shell failures to the native foreground tool contract once. */\nfunction shellToolResult(completion: TaskCompletion<BashToolDetails | undefined>, managed: boolean) {\n\tconst status = completion.status;\n\tif (completion.result.structuredContent) return completion.result;\n\tif (status === \"failed\" || status === \"timeout\" || status === \"cancelled\") {\n\t\tconst text = completion.result.content\n\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t.map((part) => part.text)\n\t\t\t.join(\"\\n\");\n\t\tconst message = completion.error ? text || completion.error : `${text ? `${text}\\n\\n` : \"\"}Command ${status}`;\n\t\tthrow managed ? new TaskExecutionError(message, status) : new Error(message);\n\t}\n\treturn completion.result;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions: BashToolOptions & { operations: BashOperations },\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options.operations;\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr, truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); the full output is saved to a temp file. Optionally provide a timeout in seconds (no default). Choose the mode per call: foreground (default) blocks until the command exits — use it when your next step needs the output; background: true returns immediately with a task ID — use it for long-running work (builds, servers, watchers, big test suites) or when you have independent work to continue. A handoff is not completion: the result arrives later as an automatic completion notification; meanwhile use tasks read to inspect output, tasks wait with an ID for one task or without one for any running task, and tasks kill to stop it. Steering interrupts only a wait, never execution. Background output is limited to 20 MiB; an expired tasks wait window never stops the command.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\ttoolCallId,\n\t\t\t{ command, timeout, background }: BashToolInput,\n\t\t\tparentSignal?: AbortSignal,\n\t\t\toriginalUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst host = ctx?.tasks;\n\t\t\tif (host?.closed) throw new Error(\"Task service is closed\");\n\t\t\tconst run = async (managed?: ManagedShellExecution): Promise<TaskCompletion<BashToolDetails | undefined>> => {\n\t\t\t\tconst signal = managed?.control.signal ?? parentSignal;\n\t\t\t\ttry {\n\t\t\t\t\tif (managed) {\n\t\t\t\t\t\tif (signal?.aborted) throw new Error(\"Command aborted\");\n\t\t\t\t\t\tresolveTimeoutMs(timeout);\n\t\t\t\t\t}\n\t\t\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\t\t\tresolvedCommand,\n\t\t\t\t\t\tctx?.cwd || cwd,\n\t\t\t\t\t\tspawnHook,\n\t\t\t\t\t\texposeSessionEnvironment,\n\t\t\t\t\t\tctx,\n\t\t\t\t\t);\n\t\t\t\t\treturn await runShellCommand({\n\t\t\t\t\t\toperations: ops,\n\t\t\t\t\t\tcontext: spawnContext,\n\t\t\t\t\t\ttempFilePrefix: config.tempFilePrefix,\n\t\t\t\t\t\ttimeout,\n\t\t\t\t\t\tsignal,\n\t\t\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\t\t\tmanaged,\n\t\t\t\t\t});\n\t\t\t\t} catch (error) {\n\t\t\t\t\t// Setup and cleanup exceptions carry an explicit terminal status.\n\t\t\t\t\tif (!managed) throw error;\n\t\t\t\t\tthrow new TaskExecutionError(\n\t\t\t\t\t\terror instanceof Error ? error.message : String(error),\n\t\t\t\t\t\tmanaged.control.signal.aborted ? \"cancelled\" : \"failed\",\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t};\n\t\t\tif (!host) {\n\t\t\t\tif (background)\n\t\t\t\t\tthrow new Error(\"Background execution is not available in this host. No command was started.\");\n\t\t\t\treturn shellToolResult(await run(), false);\n\t\t\t}\n\t\t\tconst outcome = await host.execute<BashToolDetails | undefined>({\n\t\t\t\tkind: config.name,\n\t\t\t\ttitle: command,\n\t\t\t\ttoolCallId,\n\t\t\t\tcommand,\n\t\t\t\tcwd: ctx?.cwd || cwd,\n\t\t\t\tbackground,\n\t\t\t\tsignal: parentSignal,\n\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\trun: (control) => run({ control }),\n\t\t\t});\n\t\t\tif (outcome.kind === \"result\") return shellToolResult(outcome, true);\n\t\t\tconst tail = `Task ID: ${outcome.task.id}. Status: ${outcome.task.status}. Completion arrives automatically as a notification — do not poll or immediately wait on it; continue with other work or hand back to the user. Use tasks read to inspect output, tasks wait only when your next step is blocked on a result (one ID or any running task; prefer foreground next time in that case), or tasks kill to stop it.`;\n\t\t\t// Shell execution can become background work in two ways, and the model has to know which\n\t\t\t// one it got: a submitted background command starts from an empty log, while a detached\n\t\t\t// one already holds output and keeps its original timeout.\n\t\t\tconst handoff =\n\t\t\t\tbackground === true\n\t\t\t\t\t? `Command handed to background. ${tail}`\n\t\t\t\t\t: `Command moved to the background while it was running, by the user. The execution continues unchanged — no restart, and a supplied timeout is still measured from command startup. Output produced so far is already in the log, so tasks read now returns partial output, not a fresh start. ${tail}`;\n\t\t\treturn {\n\t\t\t\tstructuredContent: { task_id: outcome.task.id, status: outcome.task.status },\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `${handoff}${outcome.task.outputPath ? `\\nFull output: ${outcome.task.outputPath}` : \"\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: {\n\t\t\t\t\tbackground: { kind: \"background\", taskId: outcome.task.id },\n\t\t\t\t\tfullOutputPath: outcome.task.outputPath,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\t...createShellRenderers(config),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ReturnType<typeof createShellToolDefinition> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, {\n\t\t...options,\n\t\toperations: options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath }),\n\t});\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions) {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"shell-tool.js","sourceRoot":"","sources":["../../../src/core/tools/shell-tool.ts"],"names":[],"mappings":"AAAA,OAAO,EAAe,IAAI,EAAE,MAAM,SAAS,CAAC;AAG5C,OAAO,EAGN,mBAAmB,EACnB,gBAAgB,GAEhB,MAAM,WAAW,CAAC;AACnB,OAAO,EAAE,oBAAoB,EAAE,MAAM,qBAAqB,CAAC;AAC3D,OAAO,EAA8B,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACnF,OAAO,EAAE,yBAAyB,EAAE,MAAM,uBAAuB,CAAC;AAClE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AAI,GAAG,kBAAkB,CAAC,UAAU,CAAC,CAAC;IAC5C,MAAM,CAAC,MAAM,CAAC,IAAI,EAAE;QACnB,aAAa,EAAE,UAAU,CAAC,aAAa;QACvC,gBAAgB,EAAE,UAAU,CAAC,gBAAgB;KAC7C,CAAC,CAAC;IACH,OAAO,IAAI,CAAC;AACb,CAAC","sourcesContent":["import { type Static, Type } from \"typebox\";\nimport type { ExtensionContext, ToolDefinition } from \"../extensions/types.ts\";\nimport type { TaskCompletion } from \"../tasks/types.ts\";\nimport {\n\ttype BashOperations,\n\ttype BashToolOptions,\n\tresolveSpawnContext,\n\tresolveTimeoutMs,\n\ttype ShellToolConfig,\n} from \"./bash.ts\";\nimport { createShellRenderers } from \"./renderers/bash.ts\";\nimport { type ManagedShellExecution, runShellCommand } from \"./shell-execution.ts\";\nimport { createLocalBashOperations } from \"./shell-operations.ts\";\nimport { wrapToolDefinition } from \"./tool-definition-wrapper.ts\";\nimport { DEFAULT_MAX_BYTES, DEFAULT_MAX_LINES, type TruncationResult } from \"./truncate.ts\";\n\nconst bashSchema = Type.Object({\n\tcommand: Type.String({ description: \"Shell command to execute\" }),\n\ttimeout: Type.Optional(Type.Number({ description: \"Timeout in seconds (optional, no default timeout)\" })),\n\tbackground: Type.Optional(\n\t\tType.Boolean({\n\t\t\tdescription:\n\t\t\t\t\"true returns a managed task ID immediately and runs the command in the background, and you are notified when it completes — do not poll for its result; omit or false to block until exit\",\n\t\t}),\n\t),\n});\n\nexport const bashToolSystemPromptContribution = {\n\tsnippet: \"Execute bash commands, foreground or background\",\n\tguidelines: [\"You can inspect PI_* environment variables for current model and session details.\"],\n} as const;\n\nexport type BashToolInput = Static<typeof bashSchema>;\n\nconst bashOutputSchema = Type.Union([\n\tType.Object({\n\t\toutput: Type.String({\n\t\t\tdescription: \"Combined stdout and stderr, up to 1 MiB, keeping head and tail when truncated.\",\n\t\t}),\n\t\ttruncated: Type.Boolean(),\n\t\tfull_output_path: Type.Optional(Type.String()),\n\t\texit_code: Type.Number(),\n\t\twall_time_seconds: Type.Number(),\n\t}),\n\tType.Object({ task_id: Type.String(), status: Type.String() }),\n]);\n\nexport interface BashToolDetails {\n\ttruncation?: TruncationResult;\n\tfullOutputPath?: string;\n\t/** Settled handoff snapshot, not a command completion or exit code. */\n\tbackground?: { kind: \"background\"; taskId: string };\n}\n\nexport type BashRenderState = {\n\tdispose?: () => void;\n};\n\n/** Translate terminal shell failures to the native foreground tool contract once. */\nfunction shellToolResult(completion: TaskCompletion<BashToolDetails | undefined>) {\n\tconst status = completion.status;\n\tif (completion.result.structuredContent) return completion.result;\n\tif (status === \"failed\" || status === \"timeout\" || status === \"cancelled\") {\n\t\tconst text = completion.result.content\n\t\t\t.filter((part) => part.type === \"text\")\n\t\t\t.map((part) => part.text)\n\t\t\t.join(\"\\n\");\n\t\tconst message = completion.error ? text || completion.error : `${text ? `${text}\\n\\n` : \"\"}Command ${status}`;\n\t\tthrow new Error(message);\n\t}\n\treturn completion.result;\n}\n\nexport function createShellToolDefinition(\n\tcwd: string,\n\tconfig: ShellToolConfig,\n\toptions: BashToolOptions & { operations: BashOperations },\n): ToolDefinition<typeof bashSchema, BashToolDetails | undefined, BashRenderState> {\n\tconst ops = options.operations;\n\tconst commandPrefix = options?.commandPrefix;\n\tconst exposeSessionEnvironment = options?.exposeSessionEnvironment ?? true;\n\tconst spawnHook = options?.spawnHook;\n\treturn {\n\t\tname: config.name,\n\t\tlabel: config.label,\n\t\tdescription: `Execute a ${config.shellName} command in the current working directory. Returns stdout and stderr, truncated to the last ${DEFAULT_MAX_LINES} lines or ${DEFAULT_MAX_BYTES / 1024}KB (whichever is hit first); the full output is saved to a temp file. Optionally provide a timeout in seconds (no default). Choose the mode per call: foreground (default) blocks until the command exits — use it when your next step needs the output; background: true returns immediately with a task ID — use it for long-running work (builds, servers, watchers, big test suites) or when you have independent work to continue. A handoff is not completion: the result arrives later as an automatic completion notification; meanwhile use tasks read to inspect output, tasks wait with an ID for one task or without one for any running task, and tasks kill to stop it. Steering interrupts only a wait, never execution. Background output is limited to 20 MiB; an expired tasks wait window never stops the command.`,\n\t\tpromptSnippet: config.promptSnippet,\n\t\tpromptGuidelines: exposeSessionEnvironment && config.promptGuidelines ? [...config.promptGuidelines] : undefined,\n\t\tparameters: bashSchema,\n\t\toutputSchema: bashOutputSchema,\n\t\tconstrainedSampling: { type: \"json_schema\", strict: \"prefer\" },\n\t\tasync execute(\n\t\t\ttoolCallId,\n\t\t\t{ command, timeout, background }: BashToolInput,\n\t\t\tparentSignal?: AbortSignal,\n\t\t\toriginalUpdate?,\n\t\t\tctx?: ExtensionContext,\n\t\t) {\n\t\t\tconst host = ctx?.tasks;\n\t\t\tif (host?.closed) throw new Error(\"Task service is closed\");\n\t\t\tconst run = async (managed?: ManagedShellExecution): Promise<TaskCompletion<BashToolDetails | undefined>> => {\n\t\t\t\tconst signal = managed?.control.signal ?? parentSignal;\n\t\t\t\tif (managed) {\n\t\t\t\t\tif (signal?.aborted) throw new Error(\"Command aborted\");\n\t\t\t\t\tresolveTimeoutMs(timeout);\n\t\t\t\t}\n\t\t\t\tconst resolvedCommand = commandPrefix ? `${commandPrefix}\\n${command}` : command;\n\t\t\t\tconst spawnContext = resolveSpawnContext(\n\t\t\t\t\tresolvedCommand,\n\t\t\t\t\tctx?.cwd || cwd,\n\t\t\t\t\tspawnHook,\n\t\t\t\t\texposeSessionEnvironment,\n\t\t\t\t\tctx,\n\t\t\t\t);\n\t\t\t\t// A setup throw settles a managed task as failed, or cancelled once its signal fired.\n\t\t\t\treturn await runShellCommand({\n\t\t\t\t\toperations: ops,\n\t\t\t\t\tcontext: spawnContext,\n\t\t\t\t\ttempFilePrefix: config.tempFilePrefix,\n\t\t\t\t\ttimeout,\n\t\t\t\t\tsignal,\n\t\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\t\tmanaged,\n\t\t\t\t});\n\t\t\t};\n\t\t\tif (!host) {\n\t\t\t\tif (background)\n\t\t\t\t\tthrow new Error(\"Background execution is not available in this host. No command was started.\");\n\t\t\t\treturn shellToolResult(await run());\n\t\t\t}\n\t\t\tconst outcome = await host.execute<BashToolDetails | undefined>({\n\t\t\t\tkind: config.name,\n\t\t\t\tlabel: config.shellName[0]!.toUpperCase() + config.shellName.slice(1),\n\t\t\t\ttitle: command,\n\t\t\t\tinput: { label: \"Command\", text: command, truncated: false, language: config.name },\n\t\t\t\tfacts: [[\"Directory\", ctx?.cwd || cwd]],\n\t\t\t\ttoolCallId,\n\t\t\t\tbackground,\n\t\t\t\tsignal: parentSignal,\n\t\t\t\tonUpdate: originalUpdate,\n\t\t\t\trun: (control) => run({ control }),\n\t\t\t});\n\t\t\tif (outcome.kind === \"result\") return shellToolResult(outcome);\n\t\t\tconst tail = `Task ID: ${outcome.task.id}. Status: ${outcome.task.status}. Completion arrives automatically as a notification — do not poll or immediately wait on it; continue with other work or hand back to the user. Use tasks read to inspect output, tasks wait only when your next step is blocked on a result (one ID or any running task; prefer foreground next time in that case), or tasks kill to stop it.`;\n\t\t\t// Shell execution can become background work in two ways, and the model has to know which\n\t\t\t// one it got: a submitted background command starts from an empty log, while a detached\n\t\t\t// one already holds output and keeps its original timeout.\n\t\t\tconst handoff =\n\t\t\t\tbackground === true\n\t\t\t\t\t? `Command handed to background. ${tail}`\n\t\t\t\t\t: `Command moved to the background while it was running, by the user. The execution continues unchanged — no restart, and a supplied timeout is still measured from command startup. Output produced so far is already in the log, so tasks read now returns partial output, not a fresh start. ${tail}`;\n\t\t\treturn {\n\t\t\t\tstructuredContent: { task_id: outcome.task.id, status: outcome.task.status },\n\t\t\t\tcontent: [\n\t\t\t\t\t{\n\t\t\t\t\t\ttype: \"text\",\n\t\t\t\t\t\ttext: `${handoff}${outcome.task.outputPath ? `\\nFull output: ${outcome.task.outputPath}` : \"\"}`,\n\t\t\t\t\t},\n\t\t\t\t],\n\t\t\t\tdetails: {\n\t\t\t\t\tbackground: { kind: \"background\", taskId: outcome.task.id },\n\t\t\t\t\tfullOutputPath: outcome.task.outputPath,\n\t\t\t\t},\n\t\t\t};\n\t\t},\n\t\t...createShellRenderers(config),\n\t};\n}\n\nconst bashToolConfig: ShellToolConfig = {\n\tname: \"bash\",\n\tlabel: \"bash\",\n\tshellName: \"bash\",\n\tprompt: \"$\",\n\tpromptSnippet: bashToolSystemPromptContribution.snippet,\n\tpromptGuidelines: bashToolSystemPromptContribution.guidelines,\n\ttempFilePrefix: \"pi-bash\",\n};\n\nexport function createBashToolDefinition(\n\tcwd: string,\n\toptions?: BashToolOptions,\n): ReturnType<typeof createShellToolDefinition> {\n\treturn createShellToolDefinition(cwd, bashToolConfig, {\n\t\t...options,\n\t\toperations: options?.operations ?? createLocalBashOperations({ shellPath: options?.shellPath }),\n\t});\n}\n\nexport function createBashTool(cwd: string, options?: BashToolOptions) {\n\tconst definition = createBashToolDefinition(cwd, options);\n\tconst tool = wrapToolDefinition(definition);\n\tObject.assign(tool, {\n\t\tpromptSnippet: definition.promptSnippet,\n\t\tpromptGuidelines: definition.promptGuidelines,\n\t});\n\treturn tool;\n}\n"]}
|
|
@@ -16,13 +16,11 @@ export interface UsageCostBreakdownEntry {
|
|
|
16
16
|
cost: number;
|
|
17
17
|
tokens: number;
|
|
18
18
|
}
|
|
19
|
-
export declare const TASK_USAGE_TYPE = "task-usage";
|
|
20
19
|
export interface TaskUsageRecord {
|
|
21
|
-
version: 1;
|
|
22
20
|
taskId: string;
|
|
23
21
|
usage: Usage;
|
|
24
22
|
}
|
|
25
|
-
/** Validate
|
|
23
|
+
/** Validate a task record's usage settlement and return only its serializable accounting fields. */
|
|
26
24
|
export declare function getTaskUsageRecord(entry: SessionEntry): TaskUsageRecord | undefined;
|
|
27
25
|
/** Legacy usage plus the first valid ledger record per task. Managed results omit usage. */
|
|
28
26
|
export declare function getAccountedUsages(entries: readonly SessionEntry[]): Usage[];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-totals.d.ts","sourceRoot":"","sources":["../../src/core/usage-totals.ts"],"names":[],"mappings":"AA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
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { TASK_RECORD_TYPE, TASK_SNAPSHOT_VERSION } from "./tasks/codec.js";
|
|
1
2
|
export function createUsageTotals() {
|
|
2
3
|
return {
|
|
3
4
|
input: 0,
|
|
@@ -37,21 +38,30 @@ export function combineUsage(first, second) {
|
|
|
37
38
|
},
|
|
38
39
|
};
|
|
39
40
|
}
|
|
40
|
-
export const TASK_USAGE_TYPE = "task-usage";
|
|
41
41
|
function isRecord(value) {
|
|
42
42
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
43
43
|
}
|
|
44
44
|
function isUsageValue(value) {
|
|
45
45
|
return typeof value === "number" && Number.isFinite(value) && value >= 0;
|
|
46
46
|
}
|
|
47
|
-
/**
|
|
48
|
-
|
|
49
|
-
|
|
47
|
+
/** Released sessions settled usage in separate entries; their billing still counts. */
|
|
48
|
+
const LEGACY_TASK_USAGE_TYPE = "task-usage";
|
|
49
|
+
function settledTaskId(entry) {
|
|
50
|
+
if (entry.type !== "custom" || !isRecord(entry.data))
|
|
50
51
|
return undefined;
|
|
51
52
|
const data = entry.data;
|
|
52
|
-
if (
|
|
53
|
+
if (entry.customType === TASK_RECORD_TYPE)
|
|
54
|
+
return data.version === TASK_SNAPSHOT_VERSION && isRecord(data.task) ? data.task.id : undefined;
|
|
55
|
+
if (entry.customType === LEGACY_TASK_USAGE_TYPE)
|
|
56
|
+
return data.version === 1 ? data.taskId : undefined;
|
|
57
|
+
return undefined;
|
|
58
|
+
}
|
|
59
|
+
/** Validate a task record's usage settlement and return only its serializable accounting fields. */
|
|
60
|
+
export function getTaskUsageRecord(entry) {
|
|
61
|
+
const taskId = settledTaskId(entry);
|
|
62
|
+
if (typeof taskId !== "string" || !taskId.trim() || entry.type !== "custom")
|
|
53
63
|
return undefined;
|
|
54
|
-
|
|
64
|
+
const data = entry.data;
|
|
55
65
|
const usage = data.usage;
|
|
56
66
|
if (!isRecord(usage) || !isRecord(usage.cost))
|
|
57
67
|
return undefined;
|
|
@@ -71,8 +81,7 @@ export function getTaskUsageRecord(entry) {
|
|
|
71
81
|
(cacheWrite1h !== undefined && !isUsageValue(cacheWrite1h)))
|
|
72
82
|
return undefined;
|
|
73
83
|
return {
|
|
74
|
-
|
|
75
|
-
taskId: data.taskId,
|
|
84
|
+
taskId,
|
|
76
85
|
usage: {
|
|
77
86
|
input,
|
|
78
87
|
output,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-totals.js","sourceRoot":"","sources":["../../src/core/usage-totals.ts"],"names":[],"mappings":"AAWA,MAAM,UAAU,iBAAiB;IAChC,OAAO;QACN,KAAK,EAAE,CAAC;QACR,MAAM,EAAE,CAAC;QACT,SAAS,EAAE,CAAC;QACZ,UAAU,EAAE,CAAC;QACb,IAAI,EAAE,CAAC;KACP,CAAC;AACH,CAAC;AAED,MAAM,UAAU,gBAAgB,CAAC,MAAmB,EAAE,KAAY;IACjE,MAAM,CAAC,KAAK,IAAI,KAAK,CAAC,KAAK,CAAC;IAC5B,MAAM,CAAC,MAAM,IAAI,KAAK,CAAC,MAAM,CAAC;IAC9B,MAAM,CAAC,SAAS,IAAI,KAAK,CAAC,SAAS,CAAC;IACpC,MAAM,CAAC,UAAU,IAAI,KAAK,CAAC,UAAU,CAAC;IACtC,MAAM,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC;AACjC,CAAC;AAED,0FAA0F;AAC1F,MAAM,UAAU,YAAY,CAAC,KAAY,EAAE,MAAa;IACvD,OAAO;QACN,KAAK,EAAE,KAAK,CAAC,KAAK,GAAG,MAAM,CAAC,KAAK;QACjC,MAAM,EAAE,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,MAAM;QACpC,SAAS,EAAE,KAAK,CAAC,SAAS,GAAG,MAAM,CAAC,SAAS;QAC7C,UAAU,EAAE,KAAK,CAAC,UAAU,GAAG,MAAM,CAAC,UAAU;QAChD,GAAG,CAAC,KAAK,CAAC,YAAY,KAAK,SA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AAC,KAAK,CAAC,CAAC;AACzE,CAAC;AAED,wFAAwF;AACxF,MAAM,UAAU,qBAAqB,CAAC,OAAgC;IACrE,MAAM,WAAW,GAAG,IAAI,GAAG,EAAuB,CAAC;IAEnD,KAAK,MAAM,EAAE,GAAG,EAAE,KAAK,EAAE,IAAI,qBAAqB,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7D,IAAI,MAAM,GAAG,WAAW,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAClC,IAAI,CAAC,MAAM,EAAE,CAAC;YACb,MAAM,GAAG,iBAAiB,EAAE,CAAC;YAC7B,WAAW,CAAC,GAAG,CAAC,GAAG,EAAE,MAAM,CAAC,CAAC;QAC9B,CAAC;QACD,gBAAgB,CAAC,MAAM,EAAE,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,OAAO,KAAK,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,GAAG,EAAE,MAAM,CAAC,EAAE,EAAE,CAAC,CAAC;QAClD,GAAG;QACH,IAAI,EAAE,MAAM,CAAC,IAAI;QACjB,MAAM,EAAE,MAAM,CAAC,KAAK,GAAG,MAAM,CAAC,MAAM,GAAG,MAAM,CAAC,SAAS,GAAG,MAAM,CAAC,UAAU;KAC3E,CAAC,CAAC;SACD,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,KAAK,CAAC,IAAI,GAAG,CAAC,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC,CAAC;SACrD,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,IAAI,CAAC,CAAC;AACnC,CAAC","sourcesContent":["import type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport type { SessionEntry } from \"./session-manager.ts\";\n\nexport interface UsageTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\nexport function createUsageTotals(): UsageTotals {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\tcost: 0,\n\t};\n}\n\nexport function addUsageToTotals(totals: UsageTotals, usage: Usage): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.cost += usage.cost.total;\n}\n\n/** Sum of two usages, keeping the optional token splits when either side reports them. */\nexport function combineUsage(first: Usage, second: Usage): Usage {\n\treturn {\n\t\tinput: first.input + second.input,\n\t\toutput: first.output + second.output,\n\t\tcacheRead: first.cacheRead + second.cacheRead,\n\t\tcacheWrite: first.cacheWrite + second.cacheWrite,\n\t\t...(first.cacheWrite1h !== undefined || second.cacheWrite1h !== undefined\n\t\t\t? { cacheWrite1h: (first.cacheWrite1h ?? 0) + (second.cacheWrite1h ?? 0) }\n\t\t\t: {}),\n\t\t...(first.reasoning !== undefined || second.reasoning !== undefined\n\t\t\t? { reasoning: (first.reasoning ?? 0) + (second.reasoning ?? 0) }\n\t\t\t: {}),\n\t\ttotalTokens: first.totalTokens + second.totalTokens,\n\t\tcost: {\n\t\t\tinput: first.cost.input + second.cost.input,\n\t\t\toutput: first.cost.output + second.cost.output,\n\t\t\tcacheRead: first.cost.cacheRead + second.cost.cacheRead,\n\t\t\tcacheWrite: first.cost.cacheWrite + second.cost.cacheWrite,\n\t\t\ttotal: first.cost.total + second.cost.total,\n\t\t},\n\t};\n}\n\nexport interface UsageCostBreakdownEntry {\n\tkey: string;\n\tcost: number;\n\ttokens: number;\n}\n\nexport const TASK_USAGE_TYPE = \"task-usage\";\n\nexport interface TaskUsageRecord {\n\tversion: 1;\n\ttaskId: string;\n\tusage: Usage;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isUsageValue(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\n/** Validate persisted ledger data and return only its serializable accounting fields. */\nexport function getTaskUsageRecord(entry: SessionEntry): TaskUsageRecord | undefined {\n\tif (entry.type !== \"custom\" || entry.customType !== TASK_USAGE_TYPE) return undefined;\n\tconst data = entry.data;\n\tif (!isRecord(data) || data.version !== 1 || typeof data.taskId !== \"string\" || !data.taskId.trim()) {\n\t\treturn undefined;\n\t}\n\tconst usage = data.usage;\n\tif (!isRecord(usage) || !isRecord(usage.cost)) return undefined;\n\tconst { input, output, cacheRead, cacheWrite, totalTokens, reasoning, cacheWrite1h } = usage;\n\tconst cost = usage.cost;\n\tif (\n\t\t!isUsageValue(input) ||\n\t\t!isUsageValue(output) ||\n\t\t!isUsageValue(cacheRead) ||\n\t\t!isUsageValue(cacheWrite) ||\n\t\t!isUsageValue(totalTokens) ||\n\t\t!isUsageValue(cost.input) ||\n\t\t!isUsageValue(cost.output) ||\n\t\t!isUsageValue(cost.cacheRead) ||\n\t\t!isUsageValue(cost.cacheWrite) ||\n\t\t!isUsageValue(cost.total) ||\n\t\t(reasoning !== undefined && !isUsageValue(reasoning)) ||\n\t\t(cacheWrite1h !== undefined && !isUsageValue(cacheWrite1h))\n\t)\n\t\treturn undefined;\n\treturn {\n\t\tversion: 1,\n\t\ttaskId: data.taskId,\n\t\tusage: {\n\t\t\tinput,\n\t\t\toutput,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens,\n\t\t\t...(reasoning === undefined ? {} : { reasoning }),\n\t\t\t...(cacheWrite1h === undefined ? {} : { cacheWrite1h }),\n\t\t\tcost: {\n\t\t\t\tinput: cost.input,\n\t\t\t\toutput: cost.output,\n\t\t\t\tcacheRead: cost.cacheRead,\n\t\t\t\tcacheWrite: cost.cacheWrite,\n\t\t\t\ttotal: cost.total,\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction* accountedUsageEntries(entries: readonly SessionEntry[]): Generator<{ key: string; usage: Usage }> {\n\tconst backgroundTasks = new Set<string>();\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tyield {\n\t\t\t\tkey: `${entry.message.provider}/${entry.message.responseModel ?? entry.message.model}`,\n\t\t\t\tusage: entry.message.usage,\n\t\t\t};\n\t\t} else if (entry.type === \"usage\") {\n\t\t\tyield { key: `${entry.provider}/${entry.model}`, usage: entry.usage };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\" && entry.message.usage) {\n\t\t\tyield { key: \"Tools/summaries\", usage: entry.message.usage };\n\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\tyield { key: \"Tools/summaries\", usage: entry.usage };\n\t\t} else {\n\t\t\tconst record = getTaskUsageRecord(entry);\n\t\t\tif (!record || backgroundTasks.has(record.taskId)) continue;\n\t\t\tbackgroundTasks.add(record.taskId);\n\t\t\tyield { key: \"Tools/summaries\", usage: record.usage };\n\t\t}\n\t}\n}\n\n/** Legacy usage plus the first valid ledger record per task. Managed results omit usage. */\nexport function getAccountedUsages(entries: readonly SessionEntry[]): Usage[] {\n\treturn Array.from(accountedUsageEntries(entries), ({ usage }) => usage);\n}\n\n/** Group model-attributed usage by model and all other usage into a separate bucket. */\nexport function getUsageCostBreakdown(entries: readonly SessionEntry[]): UsageCostBreakdownEntry[] {\n\tconst totalsByKey = new Map<string, UsageTotals>();\n\n\tfor (const { key, usage } of accountedUsageEntries(entries)) {\n\t\tlet totals = totalsByKey.get(key);\n\t\tif (!totals) {\n\t\t\ttotals = createUsageTotals();\n\t\t\ttotalsByKey.set(key, totals);\n\t\t}\n\t\taddUsageToTotals(totals, usage);\n\t}\n\n\treturn Array.from(totalsByKey, ([key, totals]) => ({\n\t\tkey,\n\t\tcost: totals.cost,\n\t\ttokens: totals.input + totals.output + totals.cacheRead + totals.cacheWrite,\n\t}))\n\t\t.filter((entry) => entry.cost > 0 || entry.tokens > 0)\n\t\t.sort((a, b) => b.cost - a.cost);\n}\n"]}
|
|
1
|
+
{"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nC,CAAC","sourcesContent":["import type { Usage } from \"@earendil-works/pi-ai/compat\";\nimport type { SessionEntry } from \"./session-manager.ts\";\nimport { TASK_RECORD_TYPE, TASK_SNAPSHOT_VERSION } from \"./tasks/codec.ts\";\n\nexport interface UsageTotals {\n\tinput: number;\n\toutput: number;\n\tcacheRead: number;\n\tcacheWrite: number;\n\tcost: number;\n}\n\nexport function createUsageTotals(): UsageTotals {\n\treturn {\n\t\tinput: 0,\n\t\toutput: 0,\n\t\tcacheRead: 0,\n\t\tcacheWrite: 0,\n\t\tcost: 0,\n\t};\n}\n\nexport function addUsageToTotals(totals: UsageTotals, usage: Usage): void {\n\ttotals.input += usage.input;\n\ttotals.output += usage.output;\n\ttotals.cacheRead += usage.cacheRead;\n\ttotals.cacheWrite += usage.cacheWrite;\n\ttotals.cost += usage.cost.total;\n}\n\n/** Sum of two usages, keeping the optional token splits when either side reports them. */\nexport function combineUsage(first: Usage, second: Usage): Usage {\n\treturn {\n\t\tinput: first.input + second.input,\n\t\toutput: first.output + second.output,\n\t\tcacheRead: first.cacheRead + second.cacheRead,\n\t\tcacheWrite: first.cacheWrite + second.cacheWrite,\n\t\t...(first.cacheWrite1h !== undefined || second.cacheWrite1h !== undefined\n\t\t\t? { cacheWrite1h: (first.cacheWrite1h ?? 0) + (second.cacheWrite1h ?? 0) }\n\t\t\t: {}),\n\t\t...(first.reasoning !== undefined || second.reasoning !== undefined\n\t\t\t? { reasoning: (first.reasoning ?? 0) + (second.reasoning ?? 0) }\n\t\t\t: {}),\n\t\ttotalTokens: first.totalTokens + second.totalTokens,\n\t\tcost: {\n\t\t\tinput: first.cost.input + second.cost.input,\n\t\t\toutput: first.cost.output + second.cost.output,\n\t\t\tcacheRead: first.cost.cacheRead + second.cost.cacheRead,\n\t\t\tcacheWrite: first.cost.cacheWrite + second.cost.cacheWrite,\n\t\t\ttotal: first.cost.total + second.cost.total,\n\t\t},\n\t};\n}\n\nexport interface UsageCostBreakdownEntry {\n\tkey: string;\n\tcost: number;\n\ttokens: number;\n}\n\nexport interface TaskUsageRecord {\n\ttaskId: string;\n\tusage: Usage;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n\treturn typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction isUsageValue(value: unknown): value is number {\n\treturn typeof value === \"number\" && Number.isFinite(value) && value >= 0;\n}\n\n/** Released sessions settled usage in separate entries; their billing still counts. */\nconst LEGACY_TASK_USAGE_TYPE = \"task-usage\";\n\nfunction settledTaskId(entry: SessionEntry): unknown {\n\tif (entry.type !== \"custom\" || !isRecord(entry.data)) return undefined;\n\tconst data = entry.data;\n\tif (entry.customType === TASK_RECORD_TYPE)\n\t\treturn data.version === TASK_SNAPSHOT_VERSION && isRecord(data.task) ? data.task.id : undefined;\n\tif (entry.customType === LEGACY_TASK_USAGE_TYPE) return data.version === 1 ? data.taskId : undefined;\n\treturn undefined;\n}\n\n/** Validate a task record's usage settlement and return only its serializable accounting fields. */\nexport function getTaskUsageRecord(entry: SessionEntry): TaskUsageRecord | undefined {\n\tconst taskId = settledTaskId(entry);\n\tif (typeof taskId !== \"string\" || !taskId.trim() || entry.type !== \"custom\") return undefined;\n\tconst data = entry.data as Record<string, unknown>;\n\tconst usage = data.usage;\n\tif (!isRecord(usage) || !isRecord(usage.cost)) return undefined;\n\tconst { input, output, cacheRead, cacheWrite, totalTokens, reasoning, cacheWrite1h } = usage;\n\tconst cost = usage.cost;\n\tif (\n\t\t!isUsageValue(input) ||\n\t\t!isUsageValue(output) ||\n\t\t!isUsageValue(cacheRead) ||\n\t\t!isUsageValue(cacheWrite) ||\n\t\t!isUsageValue(totalTokens) ||\n\t\t!isUsageValue(cost.input) ||\n\t\t!isUsageValue(cost.output) ||\n\t\t!isUsageValue(cost.cacheRead) ||\n\t\t!isUsageValue(cost.cacheWrite) ||\n\t\t!isUsageValue(cost.total) ||\n\t\t(reasoning !== undefined && !isUsageValue(reasoning)) ||\n\t\t(cacheWrite1h !== undefined && !isUsageValue(cacheWrite1h))\n\t)\n\t\treturn undefined;\n\treturn {\n\t\ttaskId,\n\t\tusage: {\n\t\t\tinput,\n\t\t\toutput,\n\t\t\tcacheRead,\n\t\t\tcacheWrite,\n\t\t\ttotalTokens,\n\t\t\t...(reasoning === undefined ? {} : { reasoning }),\n\t\t\t...(cacheWrite1h === undefined ? {} : { cacheWrite1h }),\n\t\t\tcost: {\n\t\t\t\tinput: cost.input,\n\t\t\t\toutput: cost.output,\n\t\t\t\tcacheRead: cost.cacheRead,\n\t\t\t\tcacheWrite: cost.cacheWrite,\n\t\t\t\ttotal: cost.total,\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction* accountedUsageEntries(entries: readonly SessionEntry[]): Generator<{ key: string; usage: Usage }> {\n\tconst backgroundTasks = new Set<string>();\n\tfor (const entry of entries) {\n\t\tif (entry.type === \"message\" && entry.message.role === \"assistant\") {\n\t\t\tyield {\n\t\t\t\tkey: `${entry.message.provider}/${entry.message.responseModel ?? entry.message.model}`,\n\t\t\t\tusage: entry.message.usage,\n\t\t\t};\n\t\t} else if (entry.type === \"usage\") {\n\t\t\tyield { key: `${entry.provider}/${entry.model}`, usage: entry.usage };\n\t\t} else if (entry.type === \"message\" && entry.message.role === \"toolResult\" && entry.message.usage) {\n\t\t\tyield { key: \"Tools/summaries\", usage: entry.message.usage };\n\t\t} else if ((entry.type === \"branch_summary\" || entry.type === \"compaction\") && entry.usage) {\n\t\t\tyield { key: \"Tools/summaries\", usage: entry.usage };\n\t\t} else {\n\t\t\tconst record = getTaskUsageRecord(entry);\n\t\t\tif (!record || backgroundTasks.has(record.taskId)) continue;\n\t\t\tbackgroundTasks.add(record.taskId);\n\t\t\tyield { key: \"Tools/summaries\", usage: record.usage };\n\t\t}\n\t}\n}\n\n/** Legacy usage plus the first valid ledger record per task. Managed results omit usage. */\nexport function getAccountedUsages(entries: readonly SessionEntry[]): Usage[] {\n\treturn Array.from(accountedUsageEntries(entries), ({ usage }) => usage);\n}\n\n/** Group model-attributed usage by model and all other usage into a separate bucket. */\nexport function getUsageCostBreakdown(entries: readonly SessionEntry[]): UsageCostBreakdownEntry[] {\n\tconst totalsByKey = new Map<string, UsageTotals>();\n\n\tfor (const { key, usage } of accountedUsageEntries(entries)) {\n\t\tlet totals = totalsByKey.get(key);\n\t\tif (!totals) {\n\t\t\ttotals = createUsageTotals();\n\t\t\ttotalsByKey.set(key, totals);\n\t\t}\n\t\taddUsageToTotals(totals, usage);\n\t}\n\n\treturn Array.from(totalsByKey, ([key, totals]) => ({\n\t\tkey,\n\t\tcost: totals.cost,\n\t\ttokens: totals.input + totals.output + totals.cacheRead + totals.cacheWrite,\n\t}))\n\t\t.filter((entry) => entry.cost > 0 || entry.tokens > 0)\n\t\t.sort((a, b) => b.cost - a.cost);\n}\n"]}
|
|
@@ -1,13 +1,13 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
import { type AgentActivity } from "./types.ts";
|
|
1
|
+
import type { AgentActivity } from "./types.ts";
|
|
3
2
|
export declare function clipText(text: string, bytes: number): string;
|
|
4
3
|
export declare function compactArguments(args: unknown): string;
|
|
5
4
|
/** A short display target; full arguments remain available in Tasks Output. */
|
|
6
5
|
export declare function activityTarget(name: string, args: unknown): string;
|
|
6
|
+
/** The stored display target, or one derived from the bounded arguments. */
|
|
7
|
+
export declare function targetOf(activity: AgentActivity): string;
|
|
7
8
|
export declare function formatActivityDuration(ms: number | undefined): string;
|
|
8
9
|
export declare function activityGlyph(status: AgentActivity["status"]): string;
|
|
10
|
+
/** The Transcript's `glyph tool target · duration` form, plus an indented failure excerpt. */
|
|
9
11
|
export declare function activityText(activity: AgentActivity, includeError?: boolean): string;
|
|
10
12
|
export declare function activitiesText(activities: readonly AgentActivity[]): string;
|
|
11
|
-
export declare function boundedAgentText(text: string, maxBytes?: number, fullOutputPath?: string): string;
|
|
12
|
-
export declare function finalAssistantText(messages: readonly AgentMessage[]): string;
|
|
13
13
|
//# sourceMappingURL=activity.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"activity.d.ts","sourceRoot":"","sources":["../../../src/extensions/agent/activity.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"activity.d.ts","sourceRoot":"","sources":["../../../src/extensions/agent/activity.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,YAAY,CAAC;AAEhD,wBAAgB,QAAQ,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,GAAG,MAAM,CAG5D;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,OAAO,GAAG,MAAM,CAMtD;AAED,+EAA+E;AAC/E,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,MAAM,CAgBlE;AAED,4EAA4E;AAC5E,wBAAgB,QAAQ,CAAC,QAAQ,EAAE,aAAa,GAAG,MAAM,CAOxD;AAED,wBAAgB,sBAAsB,CAAC,EAAE,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAGrE;AAED,wBAAgB,aAAa,CAAC,MAAM,EAAE,aAAa,CAAC,QAAQ,CAAC,GAAG,MAAM,CAWrE;AAED,8FAA8F;AAC9F,wBAAgB,YAAY,CAAC,QAAQ,EAAE,aAAa,EAAE,YAAY,UAAO,GAAG,MAAM,CAOjF;AAED,wBAAgB,cAAc,CAAC,UAAU,EAAE,SAAS,aAAa,EAAE,GAAG,MAAM,CAE3E"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
/** Compact, bounded formatting of an Agent's tool-call activity, shared by the Transcript and /tasks. */
|
|
1
2
|
import { boundText } from "../../core/tasks/output.js";
|
|
2
|
-
import { AGENT_REPORT_BYTES } from "./types.js";
|
|
3
3
|
export function clipText(text, bytes) {
|
|
4
4
|
if (Buffer.byteLength(text) <= bytes)
|
|
5
5
|
return text;
|
|
@@ -32,6 +32,17 @@ export function activityTarget(name, args) {
|
|
|
32
32
|
}
|
|
33
33
|
return compactArguments(args);
|
|
34
34
|
}
|
|
35
|
+
/** The stored display target, or one derived from the bounded arguments. */
|
|
36
|
+
export function targetOf(activity) {
|
|
37
|
+
if (activity.target)
|
|
38
|
+
return activity.target;
|
|
39
|
+
try {
|
|
40
|
+
return activityTarget(activity.name, JSON.parse(activity.args));
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
return activity.args;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
35
46
|
export function formatActivityDuration(ms) {
|
|
36
47
|
if (ms === undefined)
|
|
37
48
|
return "";
|
|
@@ -49,9 +60,11 @@ export function activityGlyph(status) {
|
|
|
49
60
|
return "⊘";
|
|
50
61
|
}
|
|
51
62
|
}
|
|
63
|
+
/** The Transcript's `glyph tool target · duration` form, plus an indented failure excerpt. */
|
|
52
64
|
export function activityText(activity, includeError = true) {
|
|
65
|
+
const target = targetOf(activity);
|
|
53
66
|
const duration = formatActivityDuration(activity.durationMs);
|
|
54
|
-
const line = `${activityGlyph(activity.status)} ${activity.name}${
|
|
67
|
+
const line = `${activityGlyph(activity.status)} ${activity.name}${target ? ` ${target}` : ""}${duration ? ` · ${duration}` : ""}`;
|
|
55
68
|
return includeError && activity.error
|
|
56
69
|
? `${line}\n ${clipText(activity.error, 1000).replaceAll("\n", "\n ")}`
|
|
57
70
|
: line;
|
|
@@ -59,26 +72,4 @@ export function activityText(activity, includeError = true) {
|
|
|
59
72
|
export function activitiesText(activities) {
|
|
60
73
|
return activities.map((activity) => activityText(activity)).join("\n");
|
|
61
74
|
}
|
|
62
|
-
export function boundedAgentText(text, maxBytes = AGENT_REPORT_BYTES, fullOutputPath) {
|
|
63
|
-
const notice = fullOutputPath
|
|
64
|
-
? `\n\n[Agent output truncated. Full output: ${fullOutputPath}]`
|
|
65
|
-
: "\n\n[Agent output truncated. Full output unavailable.]";
|
|
66
|
-
if (Buffer.byteLength(text) <= maxBytes)
|
|
67
|
-
return text;
|
|
68
|
-
return boundText(text, maxBytes - Buffer.byteLength(notice)) + notice;
|
|
69
|
-
}
|
|
70
|
-
export function finalAssistantText(messages) {
|
|
71
|
-
for (let index = messages.length - 1; index >= 0; index--) {
|
|
72
|
-
const message = messages[index];
|
|
73
|
-
if (message?.role !== "assistant")
|
|
74
|
-
continue;
|
|
75
|
-
const text = message.content
|
|
76
|
-
.filter((block) => block.type === "text")
|
|
77
|
-
.map((block) => block.text)
|
|
78
|
-
.join("\n");
|
|
79
|
-
if (text.trim())
|
|
80
|
-
return text;
|
|
81
|
-
}
|
|
82
|
-
return "";
|
|
83
|
-
}
|
|
84
75
|
//# sourceMappingURL=activity.js.map
|