@zaly/agent 0.1.1 → 0.3.0
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/dist/{agent-BRENvuvx.mjs → agent-GXRF7DUP.mjs} +102 -33
- package/dist/agent-GXRF7DUP.mjs.map +1 -0
- package/dist/{bash-DSy03sAj.mjs → bash-CB_VXpyd.mjs} +2 -2
- package/dist/{bash-DSy03sAj.mjs.map → bash-CB_VXpyd.mjs.map} +1 -1
- package/dist/{compactions-HFjEgrv3.mjs → compactions-92bMlcxJ.mjs} +25 -15
- package/dist/compactions-92bMlcxJ.mjs.map +1 -0
- package/dist/{edit-DT672zIy.mjs → edit-gkb6MCW-.mjs} +2 -2
- package/dist/{edit-DT672zIy.mjs.map → edit-gkb6MCW-.mjs.map} +1 -1
- package/dist/{fetch-BrtIqrid.mjs → fetch-D_GzL2yy.mjs} +4 -4
- package/dist/{fetch-BrtIqrid.mjs.map → fetch-D_GzL2yy.mjs.map} +1 -1
- package/dist/{find-B-vvdlHu.mjs → find-DlrYUTXT.mjs} +2 -2
- package/dist/{find-B-vvdlHu.mjs.map → find-DlrYUTXT.mjs.map} +1 -1
- package/dist/{grep-rvZ5S319.mjs → grep-BI8Rou2q.mjs} +2 -2
- package/dist/{grep-rvZ5S319.mjs.map → grep-BI8Rou2q.mjs.map} +1 -1
- package/dist/{html-VrAsoGBK.mjs → html-B-Lr-9W6.mjs} +9457 -4826
- package/dist/html-B-Lr-9W6.mjs.map +1 -0
- package/dist/{index-node-esm-BwaOzhXB.mjs → index-node-esm-75XSYyIw.mjs} +16 -13
- package/dist/index-node-esm-75XSYyIw.mjs.map +1 -0
- package/dist/index.d.mts +21 -6
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/{manager-1zEE5WiA.mjs → manager-CEociHy_.mjs} +2 -2
- package/dist/{manager-1zEE5WiA.mjs.map → manager-CEociHy_.mjs.map} +1 -1
- package/dist/{masker-DEgR_ntk.mjs → masker-DWuL2Fjs.mjs} +16 -5
- package/dist/{masker-DEgR_ntk.mjs.map → masker-DWuL2Fjs.mjs.map} +1 -1
- package/dist/{read-C5keKntU.mjs → read-DLtNq4XJ.mjs} +2 -2
- package/dist/{read-C5keKntU.mjs.map → read-DLtNq4XJ.mjs.map} +1 -1
- package/dist/{registry-CntkeXlo.mjs → registry-7mJQhyBA.mjs} +3 -3
- package/dist/{registry-CntkeXlo.mjs.map → registry-7mJQhyBA.mjs.map} +1 -1
- package/dist/{rolldown-runtime-DYf_mQCB.mjs → rolldown-runtime-BVN1G_yT.mjs} +4 -4
- package/dist/{session-C8zqqbPE.mjs → session-C5ra-Hi1.mjs} +80 -45
- package/dist/session-C5ra-Hi1.mjs.map +1 -0
- package/dist/{session-Cq52cam5.d.mts → session-WtXqtAaq.d.mts} +19 -10
- package/dist/session-WtXqtAaq.d.mts.map +1 -0
- package/dist/session.d.mts +1 -1
- package/dist/session.mjs +1 -1
- package/dist/{src-C04Qk9KE.mjs → src-Di-H3Oya.mjs} +71 -41
- package/dist/src-Di-H3Oya.mjs.map +1 -0
- package/dist/{subagent-BbcxLzgC.mjs → subagent-BOK4GFd4.mjs} +3 -3
- package/dist/{subagent-BbcxLzgC.mjs.map → subagent-BOK4GFd4.mjs.map} +1 -1
- package/dist/{tasks-Dgsiuh0Q.mjs → tasks-BUFqFoh6.mjs} +2 -2
- package/dist/{tasks-Dgsiuh0Q.mjs.map → tasks-BUFqFoh6.mjs.map} +1 -1
- package/dist/{tasks-D76WXWr2.mjs → tasks-CkDWJk_3.mjs} +4 -4
- package/dist/tasks-CkDWJk_3.mjs.map +1 -0
- package/dist/{tools-DmoUYORG.mjs → tools-Ca7VsMg3.mjs} +2 -2
- package/dist/{tools-DmoUYORG.mjs.map → tools-Ca7VsMg3.mjs.map} +1 -1
- package/dist/{write-BRQFfWAn.mjs → write-y93TC5ng.mjs} +2 -2
- package/dist/{write-BRQFfWAn.mjs.map → write-y93TC5ng.mjs.map} +1 -1
- package/package.json +11 -11
- package/dist/agent-BRENvuvx.mjs.map +0 -1
- package/dist/compactions-HFjEgrv3.mjs.map +0 -1
- package/dist/html-VrAsoGBK.mjs.map +0 -1
- package/dist/index-node-esm-BwaOzhXB.mjs.map +0 -1
- package/dist/session-C8zqqbPE.mjs.map +0 -1
- package/dist/session-Cq52cam5.d.mts.map +0 -1
- package/dist/src-C04Qk9KE.mjs.map +0 -1
- package/dist/tasks-D76WXWr2.mjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"src-Di-H3Oya.mjs","names":["builtin"],"sources":["../src/ctx.ts","../src/prompt/registry.ts","../src/tools/registry.ts","../src/commands.ts","../src/skills.ts","../src/compaction/utils.ts","../src/context/tokens.ts"],"sourcesContent":["import type { Model, ReasoningEffort, Tool } from \"@zaly/ai\"\nimport type { Agent } from \"./agent.ts\"\nimport type { AgentStatus } from \"./events.ts\"\nimport type { Masker } from \"./masker.ts\"\nimport type { Notifier, NotifyOptions } from \"./notify.ts\"\nimport type { PermissionManager, PermissionOptions } from \"./permissions/manager.ts\"\nimport type { Session } from \"./session/session.ts\"\nimport type { Skills } from \"./skills.ts\"\nimport type { Swarm } from \"./swarm.ts\"\nimport type { AgentOptions } from \"./types.ts\"\n\nimport { resolveReasoning } from \"@zaly/ai\"\nimport { Emitter, isInstance, normPath } from \"@zaly/shared\"\nimport { LazyCache } from \"@zaly/shared/cache\"\n\ntype AgentContextOptions = Omit<AgentOptions, \"session\"> & { session: Session }\n\ntype Slots = {\n notifier: Notifier\n masker: Masker\n permissions: PermissionManager\n swarm: Swarm\n}\n\nexport type AgentContextEvents = {\n model: { model?: Model; prev?: Model }\n reasoning: { effort: ReasoningEffort; prev?: ReasoningEffort }\n session: { session: Session; prev?: Session }\n cwd: { cwd: string; prev?: string }\n skills: { skills?: Skills }\n}\n\nexport class AgentContext extends Emitter<AgentContextEvents> {\n #agent?: Agent\n #opts: AgentOptions\n #model?: Model\n #session: Session\n #reasoning: ReasoningEffort\n #cwd: string\n #cache = new LazyCache<Slots>()\n #tools: Tool[]\n #skills?: Skills\n #prompt: string[]\n\n constructor(opts: AgentContextOptions) {\n super()\n this.#opts = opts\n this.#cwd = normPath(opts.cwd)\n this.#reasoning = opts.request?.reasoning ?? \"medium\"\n this.#session = opts.session\n this.#model = opts.model\n this.#skills = opts.skills\n this.#prompt = opts.prompt ?? []\n\n this.#tools = opts.tools ?? []\n this.onEmitError = (error) => this.#opts.logger?.child(\"context\").error(error)\n\n this.on(\"model\", async ({ model }) => {\n if (!this.#session.started) return\n if (model) await this.session.update({ modelId: model.id })\n })\n .on(\"reasoning\", async ({ effort }) => {\n if (!this.#session.started) return\n await this.session.update({ reasoning: effort })\n })\n .on(\"cwd\", ({ cwd }) => {\n if (!this.#session.started) return\n this.#cache.forget(\"permissions\") // reset permissions to force reload with new cwd\n void this.session.update({ cwd })\n })\n }\n\n private async start() {\n const [_masker, notifier] = await Promise.all([this.masker(), this.notifier()])\n\n if (!this.model) throw new Error(\"model is required to start agent session\")\n\n if (notifier) notifier.attach(this.agent)\n\n await this.session.start({\n cwd: this.cwd,\n modelId: this.model.id,\n reasoning: this.reasoning,\n })\n // oxlint-disable-next-line no-await-in-loop\n for (const m of this.#opts.messages ?? []) await this.session.add(m)\n }\n\n attach(agent: Agent) {\n if (this.#agent === agent) return\n if (this.#agent) throw new Error(\"agent already attached to context\")\n if (agent.started) throw new Error(\"cannot attach agent that has already started\")\n this.#agent = agent\n agent.once(\"start\", () => this.start())\n }\n\n get messages() {\n return this.session.messages\n }\n\n get status(): AgentStatus | undefined {\n return this.#agent?.status\n }\n\n get opts() {\n return this.#opts\n }\n\n get cwd() {\n return this.#cwd\n }\n\n set cwd(c: string) {\n if (c === this.#cwd) return\n const prev = this.#cwd\n this.#cwd = normPath(c)\n void this.emit(\"cwd\", { cwd: this.#cwd, prev })\n }\n\n get signal() {\n return this.#agent?.signal\n }\n\n get agent() {\n if (!this.#agent) throw new Error(\"agent not attached to context\")\n return this.#agent\n }\n\n get reasoning(): ReasoningEffort {\n return this.#model\n ? (resolveReasoning(this.#model.spec, this.#reasoning) ?? \"off\")\n : this.#reasoning\n }\n\n set reasoning(r: ReasoningEffort) {\n if (r === this.#reasoning) return\n const prev = this.reasoning\n this.#reasoning = r\n const effort = this.reasoning\n if (effort !== prev) void this.emit(\"reasoning\", { effort, prev })\n }\n\n get session(): Session {\n return this.#session\n }\n\n async useSession(s: Session): Promise<void> {\n const prev = this.#session\n this.#session = s\n const modelId = s.settings.modelId\n if (modelId && modelId !== this.model?.id) {\n if (this.#opts.loadModel) {\n this.model = await this.#opts.loadModel(modelId)\n } else {\n const { loadModel } = await import(\"@zaly/ai\")\n this.model = await loadModel(modelId)\n }\n }\n this.cwd = s.settings.cwd ?? this.cwd\n this.reasoning = s.settings.reasoning ?? this.reasoning\n await this.emit(\"session\", { prev, session: s })\n if (this.#agent?.started)\n await s.start({\n cwd: this.cwd,\n modelId: this.model?.id,\n reasoning: this.reasoning,\n })\n }\n\n get model() {\n return this.#model\n }\n\n set model(m: Model | undefined) {\n if (m === this.#model) return\n const prev = this.#model\n const reasoning = this.reasoning\n this.#model = m\n void this.emit(\"model\", { model: m, prev })\n if (this.reasoning !== reasoning)\n void this.emit(\"reasoning\", { effort: this.reasoning, prev: reasoning })\n }\n\n set tools(tools: Tool[]) {\n this.#tools = tools\n }\n\n get tools(): Tool[] {\n return [...this.#tools, ...(this.skills?.tool ? [this.skills.tool] : [])]\n }\n\n get prompt(): string[] {\n return this.#prompt\n }\n\n set prompt(p: string[]) {\n this.#prompt = p\n }\n\n async swarm() {\n return this.#cache.need(\n \"swarm\",\n async () => {\n const { Swarm } = await import(\"./swarm.ts\")\n return new Swarm()\n },\n this.#opts.swarm\n )\n }\n\n set skills(s: Skills | undefined) {\n if (s === this.#skills) return\n this.#skills = s\n void this.emit(\"skills\", { skills: s })\n }\n\n get skills(): Skills | undefined {\n return this.#skills\n }\n\n private async notifier(): Promise<Notifier | undefined> {\n return this.#cache.want(\n \"notifier\",\n async (opts?: NotifyOptions) => {\n const { Notifier } = await import(\"./notify.ts\")\n return new Notifier(opts)\n },\n this.#opts.notify\n )\n }\n\n async masker(): Promise<Masker | undefined> {\n return this.#cache.want(\n \"masker\",\n async (opts?: AgentOptions[\"mask\"]) => {\n const { Masker } = await import(\"./masker.ts\")\n return new Masker(this.agent, opts)\n },\n this.#opts.mask\n )\n }\n\n async permissions(): Promise<PermissionManager> {\n return this.#cache.need(\n \"permissions\",\n async (opts?: PermissionOptions) => {\n const { PermissionManager } = await import(\"./permissions/manager.ts\")\n return new PermissionManager({ ...opts, cwd: this.cwd })\n },\n this.#opts.permissions\n )\n }\n}\n\nasync function loadSession(spec?: AgentOptions[\"session\"]): Promise<Session> {\n if (isInstance<Session>(spec)) return spec\n else {\n const { Session } = await import(\"./session/session.ts\")\n return await Session.load({ ...spec })\n }\n}\n\nexport async function createAgentContext(opts: AgentOptions): Promise<AgentContext> {\n const session = await loadSession(opts.session)\n return new AgentContext({ ...opts, session })\n}\n\nexport async function createAgent(opts: AgentOptions): Promise<Agent> {\n const [{ Agent }, ctx] = await Promise.all([import(\"./agent.ts\"), createAgentContext(opts)])\n return new Agent(ctx)\n}\n","import type { Model } from \"@zaly/ai\"\n\nimport { BaseCollection } from \"@zaly/shared/collection\"\nimport { createRegistry } from \"@zaly/shared/registry\"\n\nexport interface PromptCtx {\n model: Model\n cwd: string\n}\n\nexport type PromptLoader = (ctx: PromptCtx) => Promise<string>\nexport type Prompt<T extends string | PromptLoader = string | PromptLoader> = {\n name: string\n text: T\n}\nexport type { PromptCollection }\n\nconst builtin = {\n \"AGENTS.md\": (ctx) => import(\"./markdown.ts\").then((m) => m.agentsMdPrompt(ctx)),\n \"MEMORY.md\": (ctx) => import(\"./markdown.ts\").then((m) => m.memoryMdPrompt(ctx)),\n agent: () => import(\"./agent.ts\").then((m) => m.agentPrompt),\n env: (ctx) => import(\"./env.ts\").then((m) => m.prompt(ctx)),\n model: (ctx) => import(\"./model.ts\").then((m) => m.prompt(ctx)),\n} as const satisfies Record<string, PromptLoader>\n\nexport type BuiltinPrompt = keyof typeof builtin\nexport type AnyPrompt = BuiltinPrompt | (string & {})\n\nexport const promptRegistry = createRegistry<PromptLoader>(\"prompt\").from(builtin)\n\nclass PromptCollection extends BaseCollection<AnyPrompt[], Prompt[], Prompt> {\n list(): Prompt[] {\n const ret = new Map<string, Prompt>()\n for (const k of promptRegistry.keys())\n ret.set(k, {\n name: k,\n text: (ctx) => promptRegistry.load(k, ctx),\n })\n for (const r of this.registered) ret.set(r.name, r)\n return [...ret.values()]\n }\n\n async render(ctx: PromptCtx & { prompts?: string[] }): Promise<Prompt<string>[]> {\n const all = new Map(this.list().map((p) => [p.name, p]))\n const ret = await Promise.all(\n (ctx.prompts ?? this.active).map(async (p) => {\n const def = all.get(p)\n if (!def) throw new Error(`Unknown prompt: ${p}`)\n return {\n name: def.name,\n text: typeof def.text === \"string\" ? def.text : await def.text(ctx),\n }\n })\n )\n return ret.map((p) => ({ name: p.name, text: p.text.trim() })).filter((p) => p.text.length > 0)\n }\n}\n\nexport async function promptCollection(): Promise<PromptCollection> {\n return new PromptCollection([\"agent\", \"env\", \"model\", \"AGENTS.md\", \"MEMORY.md\"])\n}\n","import type { Model, Tool } from \"@zaly/ai\"\nimport type { AnyKey } from \"@zaly/shared/registry\"\n\nimport { BaseCollection } from \"@zaly/shared/collection\"\nimport { createRegistry } from \"@zaly/shared/registry\"\n\n/** Per-load context handed to every tool factory. Lets factories\n * customise the tool — typically schema descriptions — based on the\n * agent's model and working directory. Tools that don't care about\n * init just ignore the arg. */\nexport interface ToolInit {\n model: Model\n cwd: string\n}\n\nexport type { ToolCollection }\nexport type ToolLoader = () => Promise<Tool>\nexport type BuiltinTool = keyof typeof builtin\nexport type AnyTool = AnyKey<BuiltinTool>\n\n// PERF: `import(\"./x\")` makes TS load the full module type.\n// The `as string` erases the dynamic import type while emitting the same JS.\nconst builtin = {\n agent_send: () => import(\"./swarm.ts\" as string).then((m) => m.agentSendTool as Tool),\n agent_spawn: () => import(\"./swarm.ts\" as string).then((m) => m.agentSpawnTool as Tool),\n bash: () => import(\"./bash.ts\" as string).then((m) => m.bashTool as Tool),\n edit: () => import(\"./edit.ts\" as string).then((m) => m.editTool as Tool),\n fetch: () => import(\"./fetch.ts\" as string).then((m) => m.fetchTool as Tool),\n find: () => import(\"./find.ts\" as string).then((m) => m.findTool as Tool),\n grep: () => import(\"./grep.ts\" as string).then((m) => m.grepTool as Tool),\n read: () => import(\"./read.ts\" as string).then((m) => m.readTool as Tool),\n search: () => import(\"./search.ts\" as string).then((m) => m.searchTool as Tool),\n subagent: () => import(\"./subagent.ts\" as string).then((m) => m.subagentTool as Tool),\n task_list: () => import(\"./tasks.ts\" as string).then((m) => m.taskListTool as Tool),\n task_poll: () => import(\"./tasks.ts\" as string).then((m) => m.taskPollTool as Tool),\n task_stop: () => import(\"./tasks.ts\" as string).then((m) => m.taskStopTool as Tool),\n wakeup: () => import(\"./wakeup.ts\" as string).then((m) => m.wakeupTool as Tool),\n write: () => import(\"./write.ts\" as string).then((m) => m.writeTool as Tool),\n} as const satisfies Record<string, ToolLoader>\n\nexport const toolRegistry = createRegistry<ToolLoader>(\"tool\").from(builtin)\n\nclass ToolCollection extends BaseCollection<AnyTool[], AnyTool[], Tool> {\n list(): AnyTool[] {\n const ret = new Set(toolRegistry.keys())\n for (const r of this.registered) ret.add(r.name)\n return [...ret]\n }\n\n async load(tools?: AnyTool[]): Promise<Tool[]> {\n const load = async (t: string) =>\n this.registered.findLast((r) => r.name === t) ?? toolRegistry.load(t)\n return await Promise.all((tools ?? this.active).map((t) => load(t)))\n }\n}\n\nexport async function toolCollection(): Promise<ToolCollection> {\n return new ToolCollection([])\n}\n","// oxlint-disable no-await-in-loop\nimport type { ArgsOpts, ArgsResult } from \"@zaly/shared/args\"\nimport type { Logger } from \"@zaly/shared/logger\"\n\nimport { normPath, prettyPath, safeReadFile, toError } from \"@zaly/shared\"\nimport { basename } from \"pathe\"\n\nexport type Command = {\n name: string\n body: string\n path: string\n description?: string\n args: ArgsOpts\n}\n\nexport interface CommandsOptions {\n /** cmd.md paths, sorted from highest to lowest precedence. */\n paths?: string[]\n logger?: Logger\n /** Bash execution of commands:\n * - `true`: Use the system default bash shell.\n * - `false`: Disable bash execution.\n * - `string[]`: Use a custom bash shell with the provided arguments. */\n bash?: boolean | string[]\n /** When `false`, template expressions are disabled and only simple variable interpolation is allowed. */\n expr?: boolean\n}\n\ntype Token =\n | { type: \"text\"; value: string }\n | { type: \"block\"; value: string; lang?: string; body: string }\n | { type: \"script\"; value: string }\n\nconst BASH_RE = /^!`(.*)`$/\n\nexport class Commands {\n #opts: CommandsOptions\n readonly catalog = new Map<string, Command>()\n #logger?: Logger\n\n constructor(opts: CommandsOptions = {}) {\n this.#opts = opts\n this.#logger = opts.logger\n }\n\n async load(): Promise<this> {\n const paths = this.#opts.paths ?? []\n await Promise.all(paths.map(async (path) => await this.add(path)))\n return this\n }\n\n async add(path: string): Promise<void> {\n path = normPath(path)\n const name = basename(path, \".md\")\n const { parseFrontmatter } = await import(\"@zaly/shared/yaml\")\n try {\n const content = await safeReadFile(path)\n if (!content) throw new Error(`Failed to read command file at ${path}`)\n\n const { fm, body } = await parseFrontmatter(content)\n\n const args: ArgsOpts = {}\n const fmArgs = (fm.args ?? {}) as Record<string, Partial<ArgsOpts[string]>>\n\n for (const [o, opt] of Object.entries(fmArgs)) {\n // Set default values for boolean\n if (opt.type === \"boolean\") opt.default ??= false\n // Make string options required if no default is provided\n else if (opt.type === \"string\") opt.required ??= opt.default === undefined\n else {\n this.#logger?.warn(\n `Unsupported argument type for \\`--${o}\\` in command **${name}** at \\`${prettyPath(path)}\\`\\nOnly \\`string\\` and \\`boolean\\` are supported. Skipping this argument.`\n )\n continue\n }\n args[o] = opt as ArgsOpts[string]\n }\n\n const cmd: Command = {\n ...fm,\n args,\n body,\n name,\n path,\n }\n if (this.catalog.has(name)) return\n this.catalog.set(name, cmd)\n } catch (error) {\n this.#logger?.error(`Error loading **command** from ${path}: ${(error as Error).message}`)\n }\n }\n\n get(name: string): Command | undefined {\n return this.catalog.get(name)\n }\n\n async format(input: string | ArgsResult, cmd: Command): Promise<string> {\n let args: ArgsResult\n if (typeof input === \"string\") {\n const { argsParse } = await import(\"@zaly/shared/args\")\n args = await argsParse(input, cmd.args)\n } else args = input\n\n const { createTemplate } = await import(\"@zaly/shared/template\")\n const tpl = createTemplate(cmd.body, {\n expr: this.#opts.expr,\n format: (value) => {\n if (value === args._) return args._.join(\" \")\n },\n name: cmd.name,\n })\n\n const vars = {\n ...args,\n args: args._,\n raw: args.$,\n }\n\n const rendered = tpl(vars)\n if (this.#opts.bash === false) return rendered\n const bash = Array.isArray(this.#opts.bash) ? this.#opts.bash : [\"bash\"]\n\n const lines = rendered.split(\"\\n\")\n\n const ret: string[] = []\n for (const token of this.#tokenize(lines, cmd)) {\n let text: string | undefined\n if (token.type === \"script\") text = await exec(token.value, { bash })\n else if (token.type === \"block\" && /^bash\\s*!$/.test(token.lang ?? \"\"))\n text = await exec(token.body, { bash })\n ret.push(text ?? token.value)\n }\n\n return ret.join(\"\\n\")\n }\n\n *#tokenize(lines: string[], cmd: Command): Generator<Token> {\n let block: string[] = []\n let marker: RegExp | undefined = undefined\n let lang: string | undefined = undefined\n for (const line of lines) {\n const m = line.match(/^\\s*(`{3,}|~{3,})(.*)$/)\n const script = line.match(BASH_RE)\n if (marker && line.match(marker)) {\n block.push(line)\n yield {\n body: block.slice(1, -1).join(\"\\n\"),\n lang,\n type: \"block\",\n value: block.join(\"\\n\"),\n }\n marker = undefined // end of code block\n } else if (!marker && m) {\n marker = new RegExp(`^\\\\s*${m[1]}\\\\s*$`) // start of code block\n lang = m[2].trim() || undefined\n block = [line]\n } else if (marker) block.push(line)\n else if (script) yield { type: \"script\", value: script[1] }\n else yield { type: \"text\", value: line }\n }\n if (marker) throw new Error(`Unclosed code block in command **${cmd.name}**`)\n }\n}\n\nasync function exec(script: string, opts: { bash?: string[] } = {}): Promise<string | undefined> {\n if (!script.trim()) return\n const { spawnCmd } = await import(\"@zaly/shared/process\")\n let result: string\n try {\n const r = await spawnCmd(script, { bash: opts.bash ?? true, throw: true })\n result = r?.trim() ?? \"\"\n } catch (error) {\n result = toError(error).message.trim()\n }\n const md: string[] = []\n if (script.includes(\"\\n\")) {\n md.push(\"```bash\")\n md.push(script)\n md.push(\"```\")\n md.push(\"\")\n md.push(\"```shellsession\")\n md.push(result)\n md.push(\"```\")\n } else {\n md.push(\"```shellsession\")\n md.push(`$ ${script}`)\n md.push(result)\n md.push(\"```\")\n }\n md.push(\"\")\n return md.join(\"\\n\")\n}\n","import type { MetaPart, TextPart, Tool, ToolContext } from \"@zaly/ai\"\nimport type { Agent } from \"./agent.ts\"\n\nimport { AiError, defineTool, extractToolResults } from \"@zaly/ai\"\nimport { safeStatAsync } from \"@zaly/shared\"\nimport { glob } from \"@zaly/shared/glob\"\nimport { readFile } from \"node:fs/promises\"\nimport { isDeepStrictEqual } from \"node:util\"\nimport { dirname } from \"pathe\"\nimport { Type } from \"typebox\"\n\nexport type SkillMeta = {\n name: string\n mtime: number\n desc: string\n path: string\n unchanged?: boolean\n}\n\nexport type SkillTool = Tool<{ name: string }, unknown, SkillMeta>\n\n/**\n * Agent Skills support — discovery, catalog, and the activation tool.\n *\n * Locations scanned (subdirectories containing `SKILL.md`):\n * - `${cwd}/.agent/skills/` — project\n * - `${homedir()}/.agent/skills/` — user (cross-project)\n *\n * Project shadows user on name collision.\n *\n * Progressive disclosure (per the Agent Skills spec):\n * - Catalog (name + description) lives in the tool's schema /\n * description. The model sees this from the start.\n * - Body of the SKILL.md is loaded only when the tool is invoked.\n * - References (files under the skill's directory) are *enumerated*\n * at activation, not read — the model reads them via the `read`\n * tool when its instructions call for it.\n *\n * Lifecycle:\n * - Construct with `new Skills({ cwd })` — no I/O yet.\n * - Call `await skills.load()` to populate the catalog. Idempotent;\n * re-call to pick up newly installed skills (`/reload-plugins`).\n * - `skills.tool` returns the current activation tool, or undefined\n * when the catalog is empty. Lazily built; invalidated on reload.\n */\n\nexport interface SkillEntry {\n name: string\n desc: string\n mtime: number\n body: string\n /** Absolute path to the SKILL.md file. */\n path: string\n /** Absolute path to the skill's base directory (parent of SKILL.md).\n * Used as the workspace anchor for permissions and as the root for\n * resolving references. */\n dir: string\n}\n\nexport interface SkillsOptions {\n /** SKILL.md paths, sorted from highest to lowest precedence. */\n paths?: string[]\n}\n\nexport class Skills {\n readonly catalog = new Map<string, SkillEntry>()\n #tool?: Tool\n #opts: SkillsOptions\n\n protected constructor(opts: SkillsOptions = {}) {\n this.#opts = opts\n }\n\n static async load(opts?: SkillsOptions): Promise<Skills> {\n return new Skills(opts).reload()\n }\n\n /** (Re)scan project + user `.agent/skills/` directories. Wipes the\n * current catalog and the cached tool, then repopulates. Safe to\n * call mid-session — agent uses `this.tool` per-step so the next\n * request after reload picks up the change. */\n async reload(): Promise<this> {\n this.catalog.clear()\n this.#tool = undefined\n const paths = this.#opts.paths ?? []\n // Load all skills in parallel, but add them to the catalog in order so\n // that the first one wins on name collision.\n const skills = await Promise.all(paths.map(async (path) => await this.#load(path)))\n for (const skill of skills)\n if (skill && !this.catalog.has(skill.name)) this.catalog.set(skill.name, skill)\n return this\n }\n\n async #load(path: string): Promise<SkillEntry | undefined> {\n if (!path.endsWith(\"SKILL.md\")) return\n const dir = dirname(path)\n try {\n const { meta, mtime, body } = await readSkill(path)\n if (!meta.name || !meta.description || this.catalog.has(meta.name)) return\n return {\n body,\n desc: meta.description,\n dir,\n mtime,\n name: meta.name,\n path,\n }\n } catch {}\n }\n\n async #update(entry: SkillEntry): Promise<SkillEntry> {\n const updated = (await this.#load(entry.path)) ?? entry\n if (isDeepStrictEqual(updated, entry)) return entry\n this.catalog.set(entry.name, updated)\n this.#tool = undefined\n return updated\n }\n\n /** Skill base directories — pass each to `agent.permissions.addWorkspace`\n * so the model can read bundled `references/` files without tripping\n * permission asks. */\n get dirs(): readonly string[] {\n return [...this.catalog.values()].map((s) => s.dir)\n }\n\n /** The activation tool. Returns `undefined` when the catalog is empty\n * (the agent then omits skills entirely from the model's tool list,\n * per the spec). Lazily built on first access; invalidated by\n * `load()`. */\n get tool(): Tool | undefined {\n if (this.catalog.size === 0) return undefined\n return (this.#tool ??= this.#buildTool())\n }\n\n #buildTool(): SkillTool {\n const names = [...this.catalog.keys()]\n // oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\n return defineTool({\n name: \"skill\",\n desc: this.#buildCatalogDesc(),\n parallel: true,\n params: Type.Object({\n name: Type.Union(\n names.map((n) => Type.Literal(n)),\n {\n description:\n \"Name of the skill to activate. The full SKILL.md \" +\n \"instructions are loaded as the tool result; bundled \" +\n \"files in the skill's directory are listed but not read \" +\n \"— fetch them via the `read` tool when the skill's \" +\n \"instructions require them.\",\n }\n ),\n }),\n call: (args, ctx: ToolContext<SkillMeta>) => this.#call(args.name as string, ctx),\n })\n }\n\n async #call(requested: string, ctx: ToolContext<SkillMeta>): Promise<(MetaPart | TextPart)[]> {\n let skill = this.catalog.get(requested)\n if (!skill) {\n const available = [...this.catalog.keys()]\n throw new AiError({\n code: \"UNKNOWN_SKILL\",\n data: { available, name: requested },\n message: `no skill named \"${requested}\". Available: ${available.join(\", \")}`,\n })\n }\n\n // Refresh the skill entry so we have an up-to-date mtime for staleness checks in `isActivated`.\n skill = await this.#update(skill)\n\n ctx.meta = { desc: skill.desc, mtime: skill.mtime, name: skill.name, path: skill.path }\n const activated = await this.isActivated(skill, ctx)\n if (activated) {\n // Already activated and fresh — no need to reload or update the tool result.\n ctx.meta.unchanged = true\n return [\n {\n content: `skill \"${skill.name}\" unchanged since last read: ${skill.path}`,\n tag: \"unchanged\",\n type: \"meta\",\n },\n ]\n }\n\n const references = await listReferences(skill.dir)\n return [\n {\n data: { dir: skill.dir, name: skill.name, references },\n tag: \"skill\",\n type: \"meta\",\n },\n { text: skill.body, type: \"text\" },\n ]\n }\n\n async isActivated(skill: SkillEntry, ctx: ToolContext<SkillMeta>): Promise<boolean> {\n const messages = ctx.messages ?? []\n for (const { m, $p, p } of extractToolResults<SkillMeta, \"skill\">(messages, [\"skill\"])) {\n const id = m.id\n if (!id || !p.meta || ctx.isMasked?.(id, $p)) continue\n if (p.meta.unchanged) continue\n if (p.meta.name === skill.name) return p.meta.mtime === skill.mtime\n }\n return false\n }\n\n async activate(name: string, agent: Agent) {\n const ret = await agent.useTool<SkillTool>(\n \"skill\",\n { name },\n `Skill \"${name}\" was activated by the user.`\n )\n if (ret.result.meta?.unchanged) return\n return ret\n }\n\n #buildCatalogDesc(): string {\n const header =\n \"Activate one of the available skills below. The skill's full \" +\n \"SKILL.md instructions are loaded as the tool result; the model \" +\n \"should follow them directly. Bundled files are listed in the \" +\n \"result but not eagerly read — fetch the ones the skill's \" +\n \"instructions reference via the `read` tool.\"\n const lines = [...this.catalog.values()].map((s) => `- ${s.name}: ${s.desc}`)\n return `${header}\\n\\nAvailable skills:\\n${lines.join(\"\\n\")}`\n }\n}\n\n// ── Discovery ──────────────────────────────────────────────────────────\n\nasync function readSkill(\n path: string\n): Promise<{ meta: { name?: string; description?: string }; body: string; mtime: number }> {\n const s = await safeStatAsync(path)\n if (!s?.isFile()) throw new Error(`Skill file not found at ${path}`)\n const raw = await readFile(path, \"utf8\")\n const { parseFrontmatter } = await import(\"@zaly/shared/yaml\")\n const { fm, body } = await parseFrontmatter(raw)\n return { body, meta: fm, mtime: s.mtimeMs }\n}\n\nasync function listReferences(dir: string): Promise<string[]> {\n const out: string[] = []\n for await (const rel of glob(\"**\", { cwd: dir, depth: 4, type: \"file\" })) {\n if (rel === \"SKILL.md\" || rel.endsWith(\"/SKILL.md\")) continue\n out.push(rel)\n if (out.length >= 200) break\n }\n return out.toSorted()\n}\n","import type { AnyPart, Message } from \"@zaly/ai\"\nimport type { BashTool } from \"../tools/bash.ts\"\nimport type { EditToolMeta } from \"../tools/edit.ts\"\nimport type { ReadToolMeta } from \"../tools/read.ts\"\nimport type { WriteToolMeta } from \"../tools/write.ts\"\n\nimport {\n attachmentToMeta,\n ContentTransform,\n errorToMeta,\n extractToolCalls,\n extractToolResults,\n metaToText,\n safeParseToolParams,\n sanitizeText,\n stringifyContent,\n toXml,\n} from \"@zaly/ai\"\nimport { safeStringify, formatDuration } from \"@zaly/shared\"\nimport { parseBash } from \"../utils/bash/parser.ts\"\nimport { TOOLS } from \"../utils/bash/tools.ts\"\n\nexport type ToolStat = {\n count: number\n score: number\n /** Turns ago at the most recent occurrence (0 = current/last turn).\n * Use with `lastTs` to give the agent both an \"in-experience\" recency\n * signal and a wall-clock staleness signal. */\n lastTurn: number\n /** Wall-clock ms timestamp of the most recent occurrence. `0` if no\n * occurrence carried a timestamp. */\n lastTs: number\n}\n\n/** Per-file activity tally produced by `extractFiles`. Each entry is a\n * path that the agent touched, with per-kind counts and a frecency\n * `score` that downweights older touches and weights writes/edits\n * more than reads. Sort the top-N by `score` to surface the active\n * working set; `reads` / `writes` / `edits` give the per-kind detail\n * for display. */\nexport type FileUsage = ToolStat & {\n path: string\n reads: number\n writes: number\n edits: number\n}\n\n/** Per-command activity tally produced by `extractBashCommands`. `count`\n * is raw invocations; `score` is the same number but exp-decay-weighted\n * by turn distance from the end of the conversation, so recently-used\n * commands rank above old hot ones. */\nexport type BashUsage = ToolStat & {\n command: string\n}\n\n// ── Frecency tuning ───────────────────────────────────────────────────\n// Half-life measured in user turns, not wall time — what matters for\n// compaction context is what's been hot in the agent's *recent\n// experience*, regardless of how long the user spent between turns.\n// 60 turns is a middle ground: actively-iterated work stays at the top\n// while recurring workflow patterns (git stash, test-runner flags) still\n// clear the minScore filter instead of getting buried under one-shot\n// noise from earlier in the session.\nconst HALF_LIFE_TURN = 60\nconst LAMBDA = Math.LN2 / HALF_LIFE_TURN\n// Per-kind weights — writes are the strongest intent signal (full-file\n// authorship), edits the iteration signal, reads the informational one.\nconst KIND_WEIGHTS = { edit: 2, read: 1, write: 3 } as const\n\nexport type ToolStatOptions = {\n minCount?: number\n minScore?: number\n limit?: number\n sort?: \"score\" | \"count\" | \"key\"\n}\n\nconst sorters = {\n count: (a: [string, ToolStat], b: [string, ToolStat]) => b[1].count - a[1].count,\n key: (a: [string, ToolStat], b: [string, ToolStat]) => a[0].localeCompare(b[0]),\n score: (a: [string, ToolStat], b: [string, ToolStat]) => b[1].score - a[1].score,\n} as const satisfies Record<string, (a: [string, ToolStat], b: [string, ToolStat]) => number>\n\nfunction turnInfo(messages: readonly Message[]) {\n const weights: number[] = []\n const turns: number[] = []\n let turn = 0\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i]\n if (m.role === \"assistant\") turn++\n weights[i] = Math.exp(-LAMBDA * turn)\n turns[i] = turn\n }\n return { turns, weights }\n}\n\nfunction toolStats<T extends ToolStat = ToolStat>(\n map: Map<string, T>,\n opts: ToolStatOptions = {}\n): T[] {\n const limit = opts.limit ?? 50\n const sorter = sorters[opts.sort ?? \"score\"]\n const sorted = [...map.entries()].toSorted(sorter).map(([, stat]) => stat)\n return sorted\n .filter((stat) => stat.count >= (opts.minCount ?? 1))\n .filter((stat) => stat.score >= (opts.minScore ?? 0))\n .slice(0, limit)\n}\n\n/** Walk assistant tool-calls for `read` / `write` / `edit` and tally\n * per-path activity with frecency-weighted scoring. Returns the top-N\n * by score. Each entry carries the per-kind breakdown so the\n * summarizer can describe the *kind* of activity (\"heavily edited\",\n * \"read once, then written\", \"iteratively refined\").\n *\n * Paths are canonicalized via the cwd recorded on each call's session\n * node — relative paths are resolved against the cwd that was active\n * when the call ran, and `~` is expanded. Calls under different cwds\n * that target the same file thus collapse into one bucket. */\nexport function extractFileUsage(\n messages: readonly Message[],\n opts: ToolStatOptions = {}\n): FileUsage[] {\n opts = { minScore: 0.5, ...opts }\n const map = new Map<string, FileUsage>()\n const { turns, weights } = turnInfo(messages)\n\n for (const { m, p, $m: idx } of extractToolResults<EditToolMeta | ReadToolMeta | WriteToolMeta>(\n messages,\n [\"read\", \"write\", \"edit\"]\n )) {\n const path = p.meta?.path\n if (!path) continue\n const entry = map.get(path) ?? {\n count: 0,\n edits: 0,\n lastTs: 0,\n lastTurn: Infinity,\n path,\n reads: 0,\n score: 0,\n writes: 0,\n }\n if (p.name === \"read\") entry.reads++\n else if (p.name === \"write\") entry.writes++\n else entry.edits++\n entry.count++\n entry.score += weights[idx] * KIND_WEIGHTS[p.name as keyof typeof KIND_WEIGHTS]\n if (turns[idx] < entry.lastTurn) entry.lastTurn = turns[idx]\n if (m.ts && m.ts > entry.lastTs) entry.lastTs = m.ts\n map.set(path, entry)\n }\n return toolStats(map, opts)\n}\n\n/** Walk assistant tool-calls for `bash`, parse each command line, and\n * tally per-command frecency. Plumbing commands (cat, head, grep, awk,\n * sed, …) are filtered out — they dominate raw counts but carry no\n * operational signal a summarizer would describe. Returns the top-N\n * by frecency `score`. */\nexport function extractBashUsage(\n messages: readonly Message[],\n opts: ToolStatOptions = {}\n): BashUsage[] {\n opts = { minCount: 2, minScore: 0.5, ...opts } // bash commands are noisier, so default to minCount=2\n const { turns, weights } = turnInfo(messages)\n const map = new Map<string, BashUsage>()\n for (const { m, p, $m: idx } of extractToolCalls(messages, [\"bash\"])) {\n const params = safeParseToolParams<BashTool>(p.params)\n const cmd = params?.command\n if (!cmd) continue\n const result = parseBash(cmd)\n if (!result.ok) continue\n const w = weights[idx] ?? 0\n const t = turns[idx] ?? Infinity\n for (const seg of result.segments) {\n if (TOOLS[seg.cmd]) continue\n const key = `${seg.cmd} ${seg.args.join(\" \")}`\n if (key.includes(\"\\n\")) continue\n const entry = map.get(key) ?? {\n command: key,\n count: 0,\n lastTs: 0,\n lastTurn: Infinity,\n score: 0,\n }\n entry.count++\n entry.score += w\n if (t < entry.lastTurn) entry.lastTurn = t\n if (m.ts && m.ts > entry.lastTs) entry.lastTs = m.ts\n map.set(key, entry)\n }\n }\n return toolStats(map, opts)\n}\n\n// ── Transcript ────────────────────────────────────────────────────────\n\nfunction truncate(text: string, len: number): string {\n return text.length <= len ? text : `${text.slice(0, len)}…`\n}\n\n/** Flatten a list of messages into a single tagged transcript. */\nexport function extractConversation(\n messages: readonly Message[],\n opts: { maxToolResultLen?: number } = {}\n): string {\n const transform = ContentTransform.create<AnyPart>()\n .drop(\"reasoning\")\n .map(\"tool-call\", (part) => ({\n content: [\n {\n text: `${part.name}(${safeStringify(part.params)})`,\n type: \"text\" as const,\n },\n ],\n tag: \"tool-call\",\n type: \"meta\",\n }))\n .map(\"tool-result\", (part) => {\n const text = truncate(stringifyContent(part.content), opts.maxToolResultLen ?? 2000)\n return {\n content: text === \"\" ? undefined : [{ text, type: \"text\" as const }],\n data: { tool: part.name, ...(part.isError ? { error: true } : {}) },\n tag: \"tool-result\",\n type: \"meta\" as const,\n }\n })\n .pipe(attachmentToMeta(\"image\", \"pdf\", \"audio\", \"video\"))\n .pipe(errorToMeta())\n .pipe(metaToText())\n .pipe(sanitizeText())\n\n const blocks: string[] = []\n let role: string | undefined = undefined\n for (const m of messages) {\n const parts =\n typeof m.content === \"string\" ? [{ text: m.content, type: \"text\" as const }] : m.content\n const transformed = transform.runSync(parts)\n const text = stringifyContent(transformed).trim()\n if (!text) continue\n let currentRole = m.role.charAt(0).toUpperCase() + m.role.slice(1) // capitalize\n currentRole = currentRole === \"Tool\" ? \"Assistant\" : currentRole // re-label \"Tool\" as \"Assistant\" for summarization purposes\n blocks.push(role === currentRole ? text : `\\n[${currentRole}]: ${text}`)\n role = currentRole\n }\n const text = blocks.join(\"\\n\").replace(/^\\s+$/gm, \"\").trim()\n return toXml(text, \"conversation\", { indent: false })\n}\n\n// ── Tail selection ────────────────────────────────────────────────────\n\nexport function messageTail(\n messages: readonly Message[],\n opts: { keepTokens?: number }\n): Message[] {\n const maxTokens = opts.keepTokens ?? 20_000\n messages = messages.toReversed()\n const tail: Message[] = []\n const queue: Message[] = []\n\n let used = 0\n let last: number | undefined = undefined\n\n for (const m of messages) {\n queue.unshift(m)\n const usage = m.role === \"assistant\" ? m.meta?.usage : undefined\n if (!usage) continue\n const current = usage.input + usage.output + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0)\n // clamp for masker and similar events that might shrink the context size\n const delta = Math.max(0, (last ?? current) - current)\n if (used + delta > maxTokens) break\n used += delta\n last = current\n tail.unshift(...queue.splice(0))\n }\n return tail\n}\n\n// -- Formatting helpers -────────────────────────────────────────────────────────\n\nconst lastCol = (lastTurn: number, lastTs: number): string => {\n const turn = lastTurn === Infinity ? \"?\" : `${lastTurn}t`\n const wall = lastTs > 0 ? formatDuration(lastTs) : \"?\"\n return `${turn} / ${wall}`\n}\n\nexport function formatBashUsage(commands: BashUsage[]): string {\n if (commands.length === 0) return \"(no bash commands found)\"\n const lines: string[] = []\n lines.push(\"=== Top bash commands (sorted by frecency) ===\")\n lines.push(` ${\"score\".padStart(7)} ${\"count\".padStart(5)} ${\"last\".padEnd(14)} command`)\n for (const c of commands) {\n lines.push(\n ` ${c.score.toFixed(2).padStart(7)} ${String(c.count).padStart(5)} ${lastCol(c.lastTurn, c.lastTs).padEnd(14)} ${c.command}`\n )\n }\n const text = lines.join(\"\\n\")\n return toXml(text, \"bash-commands\", { indent: false })\n}\n\nexport function formatFileUsage(files: FileUsage[]): string {\n if (files.length === 0) return \"(no file ops found)\"\n const lines: string[] = []\n lines.push(\"=== Top files touched (sorted by frecency) ===\")\n lines.push(\n ` ${\"score\".padStart(7)} ${\"total\".padStart(5)} r/w/e ${\"last\".padEnd(14)} path`\n )\n for (const f of files) {\n const rwe = `${f.reads}/${f.writes}/${f.edits}`.padEnd(12)\n lines.push(\n ` ${f.score.toFixed(2).padStart(7)} ${String(f.count).padStart(5)} ${rwe} ${lastCol(f.lastTurn, f.lastTs).padEnd(14)} ${f.path}`\n )\n }\n const text = lines.join(\"\\n\")\n return toXml(text, \"files\", { indent: false })\n}\n","import type {\n AnyPart,\n AnyType,\n Attachment,\n Message,\n ModelSpec,\n ReasoningEffort,\n ReasoningPart,\n Tool,\n} from \"@zaly/ai\"\nimport type { Prompt } from \"../prompt/registry.ts\"\n\nimport { resolveReasoning, stringifyContent } from \"@zaly/ai\"\n\nexport type TokenContext = {\n reasoning?: ReasoningEffort | boolean\n model?: ModelSpec\n}\n\nexport type MessageTokenContext = TokenContext & {\n message?: Message\n}\n\nexport type TokenCount = {\n type: AnyType | Message[\"role\"] | \"prompt\" | \"tool-schema\" | \"system-prompt\"\n kind?: string\n tokens: number\n children?: TokenCount[]\n}\n\nexport type TokenStats = {\n key: string\n tokens: number\n count: number\n children?: Map<string, TokenStats>\n}\n\n// ── token estimation ───────────────────────────────────────────────────\n\nconst CHARS_PER_TOKEN = 4\n\nconst ATTACHMENT_TOKENS: Record<Attachment[\"type\"], number> = {\n audio: 3000,\n image: 1500,\n pdf: 8000,\n video: 5000,\n}\n\nfunction fromText(text: string): number {\n return Math.ceil(text.length / CHARS_PER_TOKEN)\n}\n\nfunction sumTokens(stats: TokenCount[]): number {\n return stats.reduce((sum, s) => sum + s.tokens, 0)\n}\n\nfunction estimateReasoning(part: ReasoningPart, ctx: MessageTokenContext): number {\n let reasoning = ctx.reasoning\n if (ctx.model) {\n let requested: ReasoningEffort = \"medium\"\n if (typeof reasoning === \"string\") requested = reasoning\n else if (reasoning === false) requested = \"off\"\n reasoning = resolveReasoning(ctx.model, requested)\n }\n const enabled =\n reasoning !== \"off\" && reasoning !== false && (!ctx.model || ctx.model.reasoning === true)\n if (!enabled) return 0\n\n if (ctx.message?.role === \"assistant\") {\n // Reasoning parts are for the same model?\n if (ctx.model && ctx.message.meta?.modelId !== ctx.model.id) return 0\n\n const parts = Array.isArray(ctx.message.content)\n ? ctx.message.content.filter((p) => p.type === \"reasoning\")\n : []\n\n // Sanity check\n if (!parts.includes(part)) throw new Error(\"Reasoning part not found in message content\")\n\n const signed = parts.filter((p) => p.signature)\n const reported = ctx.message.meta?.usage?.reasoning\n\n // If the reasoning part is signed, and the message has a reported reasoning token count,\n // attribute the reported reasoning token count to the first signed reasoning part.\n if (signed.length && reported !== undefined && Number.isFinite(reported) && reported >= 0) {\n const first = signed.at(0)\n if (part !== first) return 0\n return reported\n }\n }\n\n // If the reasoning part is not signed, or the message does not have a reported reasoning token count,\n // estimate the token count based on the text length.\n return fromText(part.text)\n}\n\nexport function estimatePart(p: AnyPart, ctx: MessageTokenContext = {}): TokenCount {\n switch (p.type) {\n case \"reasoning\": {\n return { tokens: estimateReasoning(p, ctx), type: p.type }\n }\n case \"text\": {\n return { tokens: fromText(p.text), type: p.type }\n }\n case \"tool-call\": {\n return {\n kind: p.name,\n tokens: fromText(p.name) + fromText(JSON.stringify(p.params ?? {})),\n type: p.type,\n }\n }\n case \"tool-result\": {\n const children = estimateContent(p.content, ctx)\n return {\n children,\n kind: p.name,\n tokens: fromText(p.name) + sumTokens(children),\n type: p.type,\n }\n }\n case \"image\":\n case \"pdf\":\n case \"audio\":\n case \"video\": {\n return { tokens: ATTACHMENT_TOKENS[p.type], type: p.type }\n }\n case \"meta\": {\n const children = p.content ? estimateContent(p.content, ctx) : undefined\n return {\n children,\n kind: p.tag,\n tokens: fromText(stringifyContent(p)),\n type: p.type,\n }\n }\n case \"error\": {\n return { tokens: fromText(stringifyContent(p)), type: p.type }\n }\n default: {\n // @ts-expect-error: exhaustive check\n throw new Error(`Unknown part type: ${p.type}`)\n }\n }\n}\n\nfunction estimateContent(\n content: string | readonly AnyPart[],\n ctx: MessageTokenContext\n): TokenCount[] {\n if (typeof content === \"string\") return [{ tokens: fromText(content), type: \"text\" }]\n let tokens = 0\n const children: TokenCount[] = []\n for (const p of content) {\n const partStats = estimatePart(p, ctx)\n tokens += partStats.tokens\n children.push(partStats)\n }\n return children\n}\n\nfunction estimateMessage(m: Message, ctx: TokenContext): TokenCount {\n const type = m.role\n const children = estimateContent(m.content, { ...ctx, message: m })\n const kind = m.role === \"system\" ? m.meta?.kind : undefined\n return {\n children,\n kind,\n tokens: sumTokens(children),\n type,\n }\n}\n\nfunction estimatePrompt(prompt: (string | Prompt<string>)[], tools?: Tool[]): TokenCount {\n const children: TokenCount[] = prompt.map((p) => ({\n kind: typeof p === \"string\" ? undefined : p.name,\n tokens: fromText(typeof p === \"string\" ? p : p.text),\n type: \"prompt\" as const,\n }))\n children.push(\n ...(tools?.map((t) => ({\n kind: t.name,\n tokens: fromText(t.name) + fromText(t.desc ?? \"\") + fromText(JSON.stringify(t.params ?? {})),\n type: \"tool-schema\" as const,\n })) ?? [])\n )\n return {\n children,\n tokens: sumTokens(children),\n type: \"system-prompt\" as const,\n }\n}\n\nfunction addCount(stat: TokenCount, parent: TokenStats, expand?: (c: TokenCount) => boolean): void {\n const keys = stat.kind ? [stat.type, stat.kind] : [stat.type]\n let child: TokenStats | undefined\n\n for (const key of keys) {\n parent.children ??= new Map()\n child = parent.children.get(key)\n if (!child) {\n child = { children: new Map(), count: 0, key, tokens: 0 }\n parent.children.set(key, child)\n }\n child.tokens += stat.tokens\n child.count++\n parent = child\n }\n\n if (stat.children && child && (!expand || expand(stat))) {\n for (const c of stat.children) addCount(c, child, expand)\n }\n}\n\nexport function tokenStats(\n msgs: readonly Message[],\n opts: {\n prompt?: (string | Prompt<string>)[]\n tools?: Tool[]\n expand?: (c: TokenCount) => boolean\n } & TokenContext = {}\n): TokenStats {\n const root: TokenStats = { children: new Map(), count: 0, key: \"TOTAL\", tokens: 0 }\n const counts: TokenCount[] = []\n if (opts.prompt || opts.tools) counts.push(estimatePrompt(opts.prompt ?? [], opts.tools))\n counts.push(...msgs.map((message) => estimateMessage(message, opts)))\n for (const stats of counts) {\n root.tokens += stats.tokens\n root.count++\n addCount(stats, root, opts.expand)\n }\n return root\n}\n\n// ── stats ──────────────────────────────────────────────────────────────\n\nfunction fmtStats(s: TokenStats, indent = 0): string {\n const header = \" \".repeat(indent) + s.key\n return `${header.padEnd(28)} ${fmt(s.count).padStart(6)}x ${fmt(s.tokens).padStart(14)}`\n}\n\nexport function formatTokenStats(s: TokenStats, indent = 0): string {\n const ret: string[] = []\n const children = s.children\n ? [...s.children.values()].toSorted((a, b) => b.tokens - a.tokens)\n : []\n for (const c of children) {\n ret.push(fmtStats(c, indent))\n if (c.children?.size) ret.push(formatTokenStats(c, indent + 1))\n if (indent === 0) ret.push(\"─\".repeat(51))\n }\n if (indent === 0) {\n ret.unshift(\"─\".repeat(51))\n ret.push(fmtStats(s, indent))\n ret.push(\"─\".repeat(51))\n }\n return ret.join(\"\\n\")\n}\n\nfunction fmt(n: number): string {\n return n.toLocaleString(\"en-US\").replace(/,/g, \"_\")\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgCA,IAAa,eAAb,cAAkC,QAA4B;CAC5D;CACA;CACA;CACA;CACA;CACA;CACA,SAAS,IAAI,UAAiB;CAC9B;CACA;CACA;CAEA,YAAY,MAA2B;EACrC,MAAM;EACN,KAAK,QAAQ;EACb,KAAK,OAAO,SAAS,KAAK,GAAG;EAC7B,KAAK,aAAa,KAAK,SAAS,aAAa;EAC7C,KAAK,WAAW,KAAK;EACrB,KAAK,SAAS,KAAK;EACnB,KAAK,UAAU,KAAK;EACpB,KAAK,UAAU,KAAK,UAAU,CAAC;EAE/B,KAAK,SAAS,KAAK,SAAS,CAAC;EAC7B,KAAK,eAAe,UAAU,KAAK,MAAM,QAAQ,MAAM,SAAS,CAAC,CAAC,MAAM,KAAK;EAE7E,KAAK,GAAG,SAAS,OAAO,EAAE,YAAY;GACpC,IAAI,CAAC,KAAK,SAAS,SAAS;GAC5B,IAAI,OAAO,MAAM,KAAK,QAAQ,OAAO,EAAE,SAAS,MAAM,GAAG,CAAC;EAC5D,CAAC,CAAC,CACC,GAAG,aAAa,OAAO,EAAE,aAAa;GACrC,IAAI,CAAC,KAAK,SAAS,SAAS;GAC5B,MAAM,KAAK,QAAQ,OAAO,EAAE,WAAW,OAAO,CAAC;EACjD,CAAC,CAAC,CACD,GAAG,QAAQ,EAAE,UAAU;GACtB,IAAI,CAAC,KAAK,SAAS,SAAS;GAC5B,KAAK,OAAO,OAAO,aAAa;GAChC,KAAU,QAAQ,OAAO,EAAE,IAAI,CAAC;EAClC,CAAC;CACL;CAEA,MAAc,QAAQ;EACpB,MAAM,CAAC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,SAAS,QAAQ;EAC1B,KAAK,UAAU,MAAM;EACrB,KAAK;EACL,SAAS,OAAO,MAAM,KAAK,MAAM;CACnC;CACA,OAAO;AACT;AAIA,SAAS,SAAS,GAAe,SAAS,GAAW;CAEnD,OAAO,IADQ,KAAK,OAAO,MAAM,IAAI,EAAE,IAAA,CACtB,OAAO,EAAE,EAAE,GAAG,IAAI,EAAE,KAAK,CAAC,CAAC,SAAS,CAAC,EAAE,IAAI,IAAI,EAAE,MAAM,CAAC,CAAC,SAAS,EAAE;AACvF;AAEA,SAAgB,iBAAiB,GAAe,SAAS,GAAW;CAClE,MAAM,MAAgB,CAAC;CACvB,MAAM,WAAW,EAAE,WACf,CAAC,GAAG,EAAE,SAAS,OAAO,CAAC,CAAC,CAAC,UAAU,GAAG,MAAM,EAAE,SAAS,EAAE,MAAM,IAC/D,CAAC;CACL,KAAK,MAAM,KAAK,UAAU;EACxB,IAAI,KAAK,SAAS,GAAG,MAAM,CAAC;EAC5B,IAAI,EAAE,UAAU,MAAM,IAAI,KAAK,iBAAiB,GAAG,SAAS,CAAC,CAAC;EAC9D,IAAI,WAAW,GAAG,IAAI,KAAK,IAAI,OAAO,EAAE,CAAC;CAC3C;CACA,IAAI,WAAW,GAAG;EAChB,IAAI,QAAQ,IAAI,OAAO,EAAE,CAAC;EAC1B,IAAI,KAAK,SAAS,GAAG,MAAM,CAAC;EAC5B,IAAI,KAAK,IAAI,OAAO,EAAE,CAAC;CACzB;CACA,OAAO,IAAI,KAAK,IAAI;AACtB;AAEA,SAAS,IAAI,GAAmB;CAC9B,OAAO,EAAE,eAAe,OAAO,CAAC,CAAC,QAAQ,MAAM,GAAG;AACpD"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { r as uuidv7 } from "./uuid-rfbQ9ad2.mjs";
|
|
2
|
-
import { join } from "pathe";
|
|
3
2
|
import { AiError, defineTool, stringifyContent } from "@zaly/ai";
|
|
3
|
+
import { join } from "pathe";
|
|
4
4
|
import { Type } from "typebox";
|
|
5
5
|
import { tmpdir } from "node:os";
|
|
6
6
|
// src/tools/subagent.ts
|
|
@@ -22,7 +22,7 @@ const subagentTool = defineTool({
|
|
|
22
22
|
const id = uuidv7();
|
|
23
23
|
const sessionPath = join(tmpdir(), `zaly-subagent-${id}.jsonl`);
|
|
24
24
|
const startedAt = Date.now();
|
|
25
|
-
const { Session } = await import("./session-
|
|
25
|
+
const { Session } = await import("./session-C5ra-Hi1.mjs").then((n) => n.n);
|
|
26
26
|
const child = await parent.child({
|
|
27
27
|
prompt: [args.prompt],
|
|
28
28
|
session: await Session.load({ path: sessionPath })
|
|
@@ -132,4 +132,4 @@ const subagentTool = defineTool({
|
|
|
132
132
|
});
|
|
133
133
|
export { subagentTool };
|
|
134
134
|
|
|
135
|
-
//# sourceMappingURL=subagent-
|
|
135
|
+
//# sourceMappingURL=subagent-BOK4GFd4.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"subagent-BbcxLzgC.mjs","names":[],"sources":["../src/tools/subagent.ts"],"sourcesContent":["import type { MetaPart, Streamable, TextPart, ToolContext, ToolResult } from \"@zaly/ai\"\n\nimport { AiError, defineTool, stringifyContent } from \"@zaly/ai\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"pathe\"\nimport { Type } from \"typebox\"\nimport { uuidv7 } from \"../utils/uuid.ts\"\n\n/**\n * Spawn a subagent — a fresh `Agent` instance running on the same model\n * with the same permissions, given a focused task and a curated tool\n * list (the parent's, minus the subagent tool itself when the child\n * would otherwise hit `maxDepth`).\n *\n * Returns a Streamable so the harness's existing grace-window machinery\n * promotes long-running subagents to background tasks: the parent gets a\n * placeholder, the model sees task-list / heartbeat updates, and the\n * final assistant message lands as a `task-done` system inject when the\n * child stops naturally.\n *\n * Persistence: each subagent gets its own JSONL session file under\n * `tmpdir`, keyed by id. The final `<subagent>` MetaPart references the\n * path so the parent can re-load the full conversation if it needs more\n * than the surface answer.\n *\n * Auth: the spawned `Agent` shares the parent's `PermissionManager`\n * instance — same workspaces, same rules. (We don't deep-copy yet; if a\n * subagent legitimately needs a tighter scope, that's a future option.)\n */\n\nexport type SubagentMeta = {\n id: string\n depth: number\n durationMs?: number\n sessionPath: string\n /** Lifecycle state — visible to the model in the `<subagent>` MetaPart\n * so it can tell a partial running snapshot apart from a final\n * answer. `running` snapshots accompany text that's still streaming;\n * `done` snapshots carry the final assistant message. */\n status: \"running\" | \"done\"\n /** Stop reason when the child has finished — `\"natural\"` for a clean\n * finish, anything else surfaces in the parent's `<subagent>` block\n * so the model can see *why* the answer might be incomplete. */\n stop?: string\n /** Aggregate token usage across the child's whole run. */\n usage?: { input: number; output: number }\n}\n\n// oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\nexport const subagentTool = defineTool({\n name: \"subagent\",\n desc:\n \"Spawn a focused subagent with the same model and permissions. Use \" +\n \"for tasks that benefit from a clean context window: deep code \" +\n \"exploration, multi-step research, or anything where dragging the \" +\n \"intermediate steps through your own context would be expensive. The \" +\n \"subagent's final answer comes back as the result; full transcript is \" +\n \"available at the returned `sessionPath` if you need more detail.\",\n parallel: true,\n params: Type.Object({\n description: Type.String({\n description:\n \"Short description of what the subagent should do. Shown to the \" +\n \"user in the TUI. Keep under ~10 words.\",\n }),\n prompt: Type.String({\n description:\n \"System prompt for the subagent — defines its role and constraints. \" +\n \"The subagent does NOT inherit your system prompt; spell out what \" +\n \"it needs to know.\",\n }),\n task: Type.String({\n description:\n \"The actual task the subagent should perform, as if you were sending \" +\n \"it as a user message. Be specific about the deliverable.\",\n }),\n }),\n\n async call(args, ctx: ToolContext<SubagentMeta>): Promise<Streamable> {\n const parent = ctx.agent\n if (!parent) {\n throw new AiError({\n code: \"MISSING_TOOL_CONTEXT\",\n message:\n \"subagent requires an Agent reference on the context (set up by the agent harness).\",\n })\n }\n\n const id = uuidv7()\n const sessionPath = join(tmpdir(), `zaly-subagent-${id}.jsonl`)\n const startedAt = Date.now()\n const { Session } = await import(\"../session/session.ts\")\n\n // `parent.child(...)` handles all the inheritance — cwd, model,\n // permissions, depth + 1, tool list (incl. the loaded skill tool),\n // and the `subagent`-tool filtering at the depth cap.\n const child = await parent.child({\n prompt: [args.prompt],\n session: await Session.load({ path: sessionPath }),\n })\n const depth = child.depth\n\n // Cursor over the child's running text so `poll()` returns only\n // what's new since the last call (mirrors the bash-tool pattern).\n let textBuffer = \"\"\n let cursor = 0\n let finalResult: ToolResult | undefined\n let stopReason: string | undefined\n\n child.on(\"stream-event\", ({ event }) => {\n if (event.type === \"text-delta\" && typeof event.delta === \"string\") {\n textBuffer += event.delta\n }\n })\n child.on(\"stop\", ({ kind }) => {\n stopReason = kind\n })\n\n child.send({ content: args.task, role: \"user\" })\n const runDone = child.run().catch((error: unknown) => {\n stopReason = \"error\"\n throw error\n })\n\n const buildMeta = (running: boolean): SubagentMeta => ({\n depth,\n durationMs: Date.now() - startedAt,\n id,\n sessionPath,\n status: running ? \"running\" : \"done\",\n stop: stopReason,\n usage: { input: child.totalUsage.input, output: child.totalUsage.output },\n })\n\n /** Pull the last assistant text out of the child's session — the\n * user-visible \"answer.\" Falls back to whatever's accumulated in the\n * text buffer if the assistant hasn't committed a message yet. */\n const finalText = (): string => {\n for (let i = child.messages.length - 1; i >= 0; i--) {\n const m = child.messages[i]\n if (m.role !== \"assistant\") continue\n // Assistant content shape excludes Attachment, so it's compatible\n // with `stringifyContent` (which accepts plain Content).\n const text = stringifyContent(m.content as never).trim()\n if (text !== \"\") return text\n }\n return textBuffer.trim()\n }\n\n const buildResult = (running: boolean): ToolResult & { running: boolean } => {\n if (!running && finalResult) return { ...finalResult, running: false }\n\n const meta = buildMeta(running)\n // Live snapshot: emit the meta + only the *new* text since last poll\n // (advancing the cursor), matching the bash tool's increment-poll\n // semantic. The full text is reachable via the session file.\n const slice = textBuffer.slice(cursor)\n cursor = textBuffer.length\n\n // The generic \"still running, more is coming\" notice lives one\n // layer up in `Tasks.#buildPart` (added as a `<task>` MetaPart\n // trailer). Keep this snapshot focused on subagent-specific data\n // — the `<subagent>` envelope + the latest text slice.\n const parts: (MetaPart | TextPart)[] = [{ data: meta, tag: \"subagent\", type: \"meta\" }]\n if (running) {\n if (slice !== \"\") parts.push({ text: slice, type: \"text\" })\n } else {\n const answer = finalText()\n if (answer !== \"\") parts.push({ text: answer, type: \"text\" })\n }\n return { content: parts, isError: false, running }\n }\n\n return {\n abort: () => {\n child.stop()\n },\n done: runDone.then(\n async () => {\n // Flush + close the JSONL writer so the file is fully on disk\n // by the time the parent reads `sessionPath`.\n await child.session.close()\n finalResult = buildResult(false)\n },\n async (error: unknown) => {\n // Surface the error as a subagent result with isError: true.\n // Don't reject the `done` promise — the harness's contract is\n // \"completion is a final snapshot, not a throw.\"\n stopReason ??= \"error\"\n await child.session.close().catch(() => undefined)\n const meta = buildMeta(false)\n const message = error instanceof Error ? error.message : String(error)\n finalResult = {\n content: [\n { data: meta, tag: \"subagent\", type: \"meta\" },\n { text: `subagent failed: ${message}`, type: \"text\" },\n ],\n isError: true,\n }\n }\n ),\n hasNew: () => textBuffer.length > cursor,\n poll: () => buildResult(child.status !== \"idle\" && child.status !== \"paused\"),\n }\n },\n})\n\ndeclare module \"@zaly/ai\" {}\n"],"mappings":";;;;;;AAiDA,MAAa,eAAe,WAAW;CACrC,MAAM;CACN,MACE;CAMF,UAAU;CACV,QAAQ,KAAK,OAAO;EAClB,aAAa,KAAK,OAAO,EACvB,aACE,wGAEJ,CAAC;EACD,QAAQ,KAAK,OAAO,EAClB,aACE,wJAGJ,CAAC;EACD,MAAM,KAAK,OAAO,EAChB,aACE,+HAEJ,CAAC;CACH,CAAC;CAED,MAAM,KAAK,MAAM,KAAqD;EACpE,MAAM,SAAS,IAAI;EACnB,IAAI,CAAC,QACH,MAAM,IAAI,QAAQ;GAChB,MAAM;GACN,SACE;EACJ,CAAC;EAGH,MAAM,KAAK,OAAO;EAClB,MAAM,cAAc,KAAK,OAAO,GAAG,iBAAiB,GAAG,OAAO;EAC9D,MAAM,YAAY,KAAK,IAAI;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,MAAM,MAAM;GACrC,SAAS,WAAW;GAMpB,MAAM,QAAiC,CAAC;IAAE,MAAM;IAAM,KAAK;IAAY,MAAM;GAAO,CAAC;GACrF,IAAI,SACE;QAAA,UAAU,IAAI,MAAM,KAAK;KAAE,MAAM;KAAO,MAAM;IAAO,CAAC;GAAA,OACrD;IACL,MAAM,SAAS,UAAU;IACzB,IAAI,WAAW,IAAI,MAAM,KAAK;KAAE,MAAM;KAAQ,MAAM;IAAO,CAAC;GAC9D;GACA,OAAO;IAAE,SAAS;IAAO,SAAS;IAAO;GAAQ;EACnD;EAEA,OAAO;GACL,aAAa;IACX,MAAM,KAAK;GACb;GACA,MAAM,QAAQ,KACZ,YAAY;IAGV,MAAM,MAAM,QAAQ,MAAM;IAC1B,cAAc,YAAY,KAAK;GACjC,GACA,OAAO,UAAmB;IAIxB,eAAe;IACf,MAAM,MAAM,QAAQ,MAAM,CAAC,CAAC,YAAY,KAAA,CAAS;IACjD,MAAM,OAAO,UAAU,KAAK;IAC5B,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;IACrE,cAAc;KACZ,SAAS,CACP;MAAE,MAAM;MAAM,KAAK;MAAY,MAAM;KAAO,GAC5C;MAAE,MAAM,oBAAoB;MAAW,MAAM;KAAO,CACtD;KACA,SAAS;IACX;GACF,CACF;GACA,cAAc,WAAW,SAAS;GAClC,YAAY,YAAY,MAAM,WAAW,UAAU,MAAM,WAAW,QAAQ;EAC9E;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"subagent-BOK4GFd4.mjs","names":[],"sources":["../src/tools/subagent.ts"],"sourcesContent":["import type { MetaPart, Streamable, TextPart, ToolContext, ToolResult } from \"@zaly/ai\"\n\nimport { AiError, defineTool, stringifyContent } from \"@zaly/ai\"\nimport { tmpdir } from \"node:os\"\nimport { join } from \"pathe\"\nimport { Type } from \"typebox\"\nimport { uuidv7 } from \"../utils/uuid.ts\"\n\n/**\n * Spawn a subagent — a fresh `Agent` instance running on the same model\n * with the same permissions, given a focused task and a curated tool\n * list (the parent's, minus the subagent tool itself when the child\n * would otherwise hit `maxDepth`).\n *\n * Returns a Streamable so the harness's existing grace-window machinery\n * promotes long-running subagents to background tasks: the parent gets a\n * placeholder, the model sees task-list / heartbeat updates, and the\n * final assistant message lands as a `task-done` system inject when the\n * child stops naturally.\n *\n * Persistence: each subagent gets its own JSONL session file under\n * `tmpdir`, keyed by id. The final `<subagent>` MetaPart references the\n * path so the parent can re-load the full conversation if it needs more\n * than the surface answer.\n *\n * Auth: the spawned `Agent` shares the parent's `PermissionManager`\n * instance — same workspaces, same rules. (We don't deep-copy yet; if a\n * subagent legitimately needs a tighter scope, that's a future option.)\n */\n\nexport type SubagentMeta = {\n id: string\n depth: number\n durationMs?: number\n sessionPath: string\n /** Lifecycle state — visible to the model in the `<subagent>` MetaPart\n * so it can tell a partial running snapshot apart from a final\n * answer. `running` snapshots accompany text that's still streaming;\n * `done` snapshots carry the final assistant message. */\n status: \"running\" | \"done\"\n /** Stop reason when the child has finished — `\"natural\"` for a clean\n * finish, anything else surfaces in the parent's `<subagent>` block\n * so the model can see *why* the answer might be incomplete. */\n stop?: string\n /** Aggregate token usage across the child's whole run. */\n usage?: { input: number; output: number }\n}\n\n// oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\nexport const subagentTool = defineTool({\n name: \"subagent\",\n desc:\n \"Spawn a focused subagent with the same model and permissions. Use \" +\n \"for tasks that benefit from a clean context window: deep code \" +\n \"exploration, multi-step research, or anything where dragging the \" +\n \"intermediate steps through your own context would be expensive. The \" +\n \"subagent's final answer comes back as the result; full transcript is \" +\n \"available at the returned `sessionPath` if you need more detail.\",\n parallel: true,\n params: Type.Object({\n description: Type.String({\n description:\n \"Short description of what the subagent should do. Shown to the \" +\n \"user in the TUI. Keep under ~10 words.\",\n }),\n prompt: Type.String({\n description:\n \"System prompt for the subagent — defines its role and constraints. \" +\n \"The subagent does NOT inherit your system prompt; spell out what \" +\n \"it needs to know.\",\n }),\n task: Type.String({\n description:\n \"The actual task the subagent should perform, as if you were sending \" +\n \"it as a user message. Be specific about the deliverable.\",\n }),\n }),\n\n async call(args, ctx: ToolContext<SubagentMeta>): Promise<Streamable> {\n const parent = ctx.agent\n if (!parent) {\n throw new AiError({\n code: \"MISSING_TOOL_CONTEXT\",\n message:\n \"subagent requires an Agent reference on the context (set up by the agent harness).\",\n })\n }\n\n const id = uuidv7()\n const sessionPath = join(tmpdir(), `zaly-subagent-${id}.jsonl`)\n const startedAt = Date.now()\n const { Session } = await import(\"../session/session.ts\")\n\n // `parent.child(...)` handles all the inheritance — cwd, model,\n // permissions, depth + 1, tool list (incl. the loaded skill tool),\n // and the `subagent`-tool filtering at the depth cap.\n const child = await parent.child({\n prompt: [args.prompt],\n session: await Session.load({ path: sessionPath }),\n })\n const depth = child.depth\n\n // Cursor over the child's running text so `poll()` returns only\n // what's new since the last call (mirrors the bash-tool pattern).\n let textBuffer = \"\"\n let cursor = 0\n let finalResult: ToolResult | undefined\n let stopReason: string | undefined\n\n child.on(\"stream-event\", ({ event }) => {\n if (event.type === \"text-delta\" && typeof event.delta === \"string\") {\n textBuffer += event.delta\n }\n })\n child.on(\"stop\", ({ kind }) => {\n stopReason = kind\n })\n\n child.send({ content: args.task, role: \"user\" })\n const runDone = child.run().catch((error: unknown) => {\n stopReason = \"error\"\n throw error\n })\n\n const buildMeta = (running: boolean): SubagentMeta => ({\n depth,\n durationMs: Date.now() - startedAt,\n id,\n sessionPath,\n status: running ? \"running\" : \"done\",\n stop: stopReason,\n usage: { input: child.totalUsage.input, output: child.totalUsage.output },\n })\n\n /** Pull the last assistant text out of the child's session — the\n * user-visible \"answer.\" Falls back to whatever's accumulated in the\n * text buffer if the assistant hasn't committed a message yet. */\n const finalText = (): string => {\n for (let i = child.messages.length - 1; i >= 0; i--) {\n const m = child.messages[i]\n if (m.role !== \"assistant\") continue\n // Assistant content shape excludes Attachment, so it's compatible\n // with `stringifyContent` (which accepts plain Content).\n const text = stringifyContent(m.content as never).trim()\n if (text !== \"\") return text\n }\n return textBuffer.trim()\n }\n\n const buildResult = (running: boolean): ToolResult & { running: boolean } => {\n if (!running && finalResult) return { ...finalResult, running: false }\n\n const meta = buildMeta(running)\n // Live snapshot: emit the meta + only the *new* text since last poll\n // (advancing the cursor), matching the bash tool's increment-poll\n // semantic. The full text is reachable via the session file.\n const slice = textBuffer.slice(cursor)\n cursor = textBuffer.length\n\n // The generic \"still running, more is coming\" notice lives one\n // layer up in `Tasks.#buildPart` (added as a `<task>` MetaPart\n // trailer). Keep this snapshot focused on subagent-specific data\n // — the `<subagent>` envelope + the latest text slice.\n const parts: (MetaPart | TextPart)[] = [{ data: meta, tag: \"subagent\", type: \"meta\" }]\n if (running) {\n if (slice !== \"\") parts.push({ text: slice, type: \"text\" })\n } else {\n const answer = finalText()\n if (answer !== \"\") parts.push({ text: answer, type: \"text\" })\n }\n return { content: parts, isError: false, running }\n }\n\n return {\n abort: () => {\n child.stop()\n },\n done: runDone.then(\n async () => {\n // Flush + close the JSONL writer so the file is fully on disk\n // by the time the parent reads `sessionPath`.\n await child.session.close()\n finalResult = buildResult(false)\n },\n async (error: unknown) => {\n // Surface the error as a subagent result with isError: true.\n // Don't reject the `done` promise — the harness's contract is\n // \"completion is a final snapshot, not a throw.\"\n stopReason ??= \"error\"\n await child.session.close().catch(() => undefined)\n const meta = buildMeta(false)\n const message = error instanceof Error ? error.message : String(error)\n finalResult = {\n content: [\n { data: meta, tag: \"subagent\", type: \"meta\" },\n { text: `subagent failed: ${message}`, type: \"text\" },\n ],\n isError: true,\n }\n }\n ),\n hasNew: () => textBuffer.length > cursor,\n poll: () => buildResult(child.status !== \"idle\" && child.status !== \"paused\"),\n }\n },\n})\n\ndeclare module \"@zaly/ai\" {}\n"],"mappings":";;;;;;AAiDA,MAAa,eAAe,WAAW;CACrC,MAAM;CACN,MACE;CAMF,UAAU;CACV,QAAQ,KAAK,OAAO;EAClB,aAAa,KAAK,OAAO,EACvB,aACE,wGAEJ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W,UAAU,MAAM,WAAW,QAAQ;EAC9E;CACF;AACF,CAAC"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as taskInfoPart } from "./tasks-
|
|
1
|
+
import { r as taskInfoPart } from "./tasks-CkDWJk_3.mjs";
|
|
2
2
|
import { AiError, defineTool } from "@zaly/ai";
|
|
3
3
|
import { Type } from "typebox";
|
|
4
4
|
// src/tools/tasks.ts
|
|
@@ -62,4 +62,4 @@ function requireTasks(ctx) {
|
|
|
62
62
|
}
|
|
63
63
|
export { taskListTool, taskPollTool, taskStopTool };
|
|
64
64
|
|
|
65
|
-
//# sourceMappingURL=tasks-
|
|
65
|
+
//# sourceMappingURL=tasks-BUFqFoh6.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tasks-
|
|
1
|
+
{"version":3,"file":"tasks-BUFqFoh6.mjs","names":[],"sources":["../src/tools/tasks.ts"],"sourcesContent":["import type { ToolContext } from \"@zaly/ai\"\nimport type { Tasks } from \"../tasks.ts\"\n\nimport { defineTool, AiError } from \"@zaly/ai\"\nimport { Type } from \"typebox\"\nimport { taskInfoPart } from \"../tasks.ts\"\n\n/**\n * Generic task management surface for the model.\n *\n * - `task_list`: enumerate running and recently-finished tasks.\n * - `task_stop`: abort a running task. Idempotent.\n *\n * \"Wait for a task\" is intentionally absent — heartbeats keep the loop\n * alive while tasks run, and `task-done` injects the final result as a\n * system message automatically. If the model wants explicit polling\n * cadence on something specific, it schedules a `wakeup` instead.\n *\n * Permission gating, when wired up, is the harness's concern; these\n * tools are intentionally thin so the policy lives one layer up.\n */\n\n// oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\nexport const taskListTool = defineTool({\n name: \"task_list\",\n desc:\n \"List active and recently-finished tasks (running shells, subagents, \" +\n \"any other long-running work the model has kicked off). Use this when \" +\n \"you've lost track of an id, or to check which background work is \" +\n \"still in flight.\",\n parallel: true,\n params: Type.Object({\n includeFinished: Type.Optional(\n Type.Boolean({\n default: false,\n description: \"When true, also include tasks that have already completed in this session.\",\n })\n ),\n }),\n\n call(args, ctx) {\n const tasks = requireTasks(ctx)\n // Routes through `taskInfoPart` so the `result` strip + line-per-task\n // JSON format stays consistent with heartbeat output. Done tasks\n // surface only their identity / timing, not their (potentially huge)\n // captured body.\n const info = tasks\n .info()\n .filter((task) => (args.includeFinished ?? false) || task.status !== \"done\")\n return taskInfoPart(info)\n },\n})\n\n// oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\nexport const taskPollTool = defineTool({\n name: \"task_poll\",\n desc:\n \"Read the latest incremental output from a running task. Returns \" +\n \"only what's arrived since the previous `task_poll` (or since the \" +\n \"task's running placeholder was first surfaced). Use when a heartbeat \" +\n \"flagged a task with `*new*`, or to peek at progress on a long \" +\n \"command (build, test run, tail -f). Errors if the task is already \" +\n \"done (its result was injected as a system message) or has no \" +\n \"streaming output.\",\n parallel: true,\n params: Type.Object({\n id: Type.String({ description: \"Task id to poll.\" }),\n }),\n\n call(args, ctx) {\n const tasks = requireTasks(ctx)\n const snap = tasks.pollOutput(args.id)\n // The snapshot's `content` already carries any streamable-emitted\n // MetaParts (bash's `<shell>`, etc.), so the model sees status +\n // incremental output in one go. Returning content directly avoids\n // the JSON-stringify path normalize would take on a ToolResult shape.\n return snap.content\n },\n})\n\n// oxlint-disable-next-line sort-keys -- semantic field order: name, desc, params, call\nexport const taskStopTool = defineTool({\n name: \"task_stop\",\n desc:\n \"Stop a running task. Aborts the underlying work (e.g. SIGTERM \" +\n \"→ SIGKILL for bash); pending tasks chained behind a stopped task get \" +\n \"auto-cancelled. Idempotent — safe to call on an already-finished task.\",\n params: Type.Object({\n id: Type.String({ description: \"Task id to stop.\" }),\n }),\n\n call(args, ctx) {\n const tasks = requireTasks(ctx)\n const task = tasks.get(args.id)\n if (!task) {\n throw new AiError({\n code: \"NOT_FOUND\",\n data: { id: args.id },\n message: `no task with id \"${args.id}\"`,\n })\n }\n tasks.abort(args.id, \"stopped via task_stop\")\n return `task ${args.id} stopped`\n },\n})\n\n// ── Internals ──────────────────────────────────────────────────────────\n\nfunction requireTasks(ctx: ToolContext): Tasks {\n if (!ctx.tasks) {\n throw new AiError({\n code: \"MISSING_TOOL_CONTEXT\",\n message: \"task tools require a Tasks registry on the context (set up by the agent harness).\",\n })\n }\n return ctx.tasks\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAuBA,MAAa,eAAe,WAAW;CACrC,MAAM;CACN,MACE;CAIF,UAAU;CACV,QAAQ,KAAK,OAAO,EAClB,iBAAiB,KAAK,SACpB,KAAK,QAAQ;EACX,SAAS;EACT,aAAa;CACf,CAAC,CACH,EACF,CAAC;CAED,KAAK,MAAM,KAAK;EAMd,MAAM,OALQ,aAAa,GAKV,CAAC,CACf,KAAK,CAAC,CACN,QAAQ,UAAU,KAAK,mBAAmB,UAAU,KAAK,WAAW,MAAM;EAC7E,OAAO,aAAa,IAAI;CAC1B;AACF,CAAC;AAGD,MAAa,eAAe,WAAW;CACrC,MAAM;CACN,MACE;CAOF,UAAU;CACV,QAAQ,KAAK,OAAO,EAClB,IAAI,KAAK,OAAO,EAAE,aAAa,mBAAmB,CAAC,EACrD,CAAC;CAED,KAAK,MAAM,KAAK;EAOd,OANc,aAAa,GACV,CAAC,CAAC,WAAW,KAAK,EAKzB,CAAC,CAAC;CACd;AACF,CAAC;AAGD,MAAa,eAAe,WAAW;CACrC,MAAM;CACN,MACE;CAGF,QAAQ,KAAK,OAAO,EAClB,IAAI,KAAK,OAAO,EAAE,aAAa,mBAAmB,CAAC,EACrD,CAAC;CAED,KAAK,MAAM,KAAK;EACd,MAAM,QAAQ,aAAa,GAAG;EAE9B,IAAI,CADS,MAAM,IAAI,KAAK,EACpB,GACN,MAAM,IAAI,QAAQ;GAChB,MAAM;GACN,MAAM,EAAE,IAAI,KAAK,GAAG;GACpB,SAAS,oBAAoB,KAAK,GAAG;EACvC,CAAC;EAEH,MAAM,MAAM,KAAK,IAAI,uBAAuB;EAC5C,OAAO,QAAQ,KAAK,GAAG;CACzB;AACF,CAAC;AAID,SAAS,aAAa,KAAyB;CAC7C,IAAI,CAAC,IAAI,OACP,MAAM,IAAI,QAAQ;EAChB,MAAM;EACN,SAAS;CACX,CAAC;CAEH,OAAO,IAAI;AACb"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { r as uuidv7 } from "./uuid-rfbQ9ad2.mjs";
|
|
2
|
-
import { Emitter, safeStringify } from "@zaly/shared";
|
|
3
2
|
import { AiError, isStreamable, runTool, stringifyContent, toErrorResult } from "@zaly/ai";
|
|
3
|
+
import { Emitter, safeStringify } from "@zaly/shared";
|
|
4
4
|
// src/tasks.ts
|
|
5
5
|
const DEFAULT_GRACE_MS = 1e4;
|
|
6
6
|
/**
|
|
@@ -182,14 +182,14 @@ var Tasks = class extends Emitter {
|
|
|
182
182
|
const tasks = [];
|
|
183
183
|
let chainHead;
|
|
184
184
|
const tools = await this.tools();
|
|
185
|
+
const parallel = calls.every((c) => tools.find((t) => t.name === c.name)?.parallel ?? false);
|
|
185
186
|
for (const call of calls) {
|
|
186
187
|
const tool = tools.find((t) => t.name === call.name);
|
|
187
188
|
if (!tool) {
|
|
188
189
|
tasks.push(this.#startSyncResult(call, unknownToolResult(call.name), round));
|
|
189
190
|
continue;
|
|
190
191
|
}
|
|
191
|
-
|
|
192
|
-
if (chainHead && !parallel) {
|
|
192
|
+
if (chainHead) {
|
|
193
193
|
tasks.push(this.#registerPending({
|
|
194
194
|
call,
|
|
195
195
|
ctxBase: ctx,
|
|
@@ -612,4 +612,4 @@ function taskCompletionMessage(task) {
|
|
|
612
612
|
}
|
|
613
613
|
export { taskCompletionMessage as n, taskInfoPart as r, Tasks as t };
|
|
614
614
|
|
|
615
|
-
//# sourceMappingURL=tasks-
|
|
615
|
+
//# sourceMappingURL=tasks-CkDWJk_3.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"tasks-CkDWJk_3.mjs","names":[],"sources":["../src/tasks.ts"],"sourcesContent":["import type {\n ContentPart,\n Message,\n MetaPart,\n TextPart,\n Tool,\n ToolCallPart,\n ToolContext,\n ToolResult,\n ToolResultPart,\n Streamable as TStreamable,\n} from \"@zaly/ai\"\n\nimport { AiError, isStreamable, runTool, stringifyContent, toErrorResult } from \"@zaly/ai\"\nimport { Emitter, safeStringify } from \"@zaly/shared\"\nimport { uuidv7 } from \"./utils/uuid.ts\"\n\nconst DEFAULT_GRACE_MS = 10_000\n\n/** Status of a task. `pending` = queued behind a dependency, not yet\n * started. `running` = work in progress (a Streamable is being polled).\n * `done` = result captured, no longer mutating. */\nexport type TaskStatus = \"pending\" | \"running\" | \"done\"\n\n/** Public projection of a registered task. Status-discriminated so the\n * fields visible at any moment are exactly the ones that make sense\n * for that lifecycle stage:\n *\n * - `running`: `elapsedMs` since start; `hasNewOutput` when the\n * streamable signals that `task_poll` would yield bytes.\n * - `pending`: queued behind another task (`waitingFor`); `elapsedMs`\n * counts time-since-registration.\n * - `done`: settled. Carries `durationMs` and the captured `result`.\n *\n * This is the only public task type — the registry exposes it via\n * `running()` / `finished()` / `get()`, events carry it (`task-done`\n * is narrowed to `status: \"done\"` so listeners get `result` typed\n * without checks), and `task_list` JSON-stringifies it directly. */\nexport type TaskInfo = {\n id: string\n type: string\n desc: string\n} & (\n | { status: \"running\"; elapsedMs: number; hasNewOutput?: boolean }\n | { status: \"pending\"; waitingFor: string; elapsedMs: number }\n | { status: \"done\"; durationMs: number; result: ToolResult }\n)\n\n/** A `TaskInfo` known to be in the `done` state. `task-done` event\n * payloads use this so listeners get `result` and `durationMs` typed\n * without manual narrowing. */\nexport type DoneTaskInfo = Extract<TaskInfo, { status: \"done\" }>\n\n/** Events emitted by a `Tasks` instance. `task-done` only fires for\n * completions that happen *outside* an in-flight `run()` round —\n * round-internal completions are folded into the `run()` return value\n * instead. `heartbeat` fires periodically (when `heartbeatMs` is set\n * and at least one task is active), giving the agent a hook to keep\n * the model engaged on long-running work. */\nexport type TasksEvents = {\n \"task-added\": { task: TaskInfo }\n \"task-removed\": { task: TaskInfo }\n \"task-done\": { task: DoneTaskInfo }\n heartbeat: { running: readonly TaskInfo[] }\n}\n\n/** Augment ToolMeta so tools and consumers can read freshness/state info\n * off `ToolResultPart.meta.task`. The registry stamps this on every\n * result it produces so the model can correlate placeholders to their\n * eventual completion. */\nexport interface TaskMeta {\n task?: {\n id: string\n status: TaskStatus\n type: string\n desc: string\n dependsOn?: string\n durationMs?: number\n }\n}\n\n/** Internal storage record. Not exposed — `toTaskInfo` projects it to\n * `TaskInfo` for any caller that crosses the boundary (events,\n * registry methods, the `task_*` tools). Carries everything the\n * registry needs to drive lifecycle transitions, plus the raw\n * timestamps `TaskInfo` derives elapsed/duration from. */\ninterface InternalTask {\n id: string\n type: string\n desc: string\n status: TaskStatus\n /** Wallclock at registration. */\n startedAt: number\n /** Wallclock at completion; set once status is `done`. */\n finishedAt?: number\n /** Captured result when status is `done`. */\n result?: ToolResult\n /** When set, this task is queued behind another and won't start until\n * the named task transitions to `done`. */\n waitingFor?: string\n /** Streamable returned by the tool, if any — held so we can `abort()`\n * on cancellation and call `poll()` for partial snapshots. */\n streamable?: TStreamable\n /** Resolves when the task transitions to `done`. Used by the round\n * race in `run()`. */\n donePromise: Promise<void>\n resolveDone: () => void\n /** When set, the task belongs to an in-flight `run()` round — its\n * completion does *not* fire `task-done` (the round folds it into the\n * returned parts instead). Cleared once the round ends. */\n ownerRound?: symbol\n /** Stashed call so a pending task can be restarted once its\n * dependency completes. */\n pending?: { tool: Tool; call: ToolCallPart; ctx: ToolContext }\n}\n\n/**\n * Tool registry + execution machinery + long-running task bookkeeping.\n * One Tasks instance per Agent. Owns the tool list (the agent delegates\n * `agent.tools` to it) and runs every assistant tool batch through\n * `run()`, which:\n *\n * - validates each call's params,\n * - dispatches to the named tool (sync results land immediately),\n * - races `Streamable` returns against a grace window,\n * - chains `parallel: false` calls behind their predecessors,\n * - returns `ToolResultPart[]` 1:1 with the assistant's calls,\n * surfacing partial results / placeholders for anything still running\n * when the grace expires.\n *\n * Completions during a round are folded into the returned parts and do\n * NOT fire `task-done`. Completions afterward fire normally — the agent\n * listens and injects a system message into the next step.\n */\nexport class Tasks extends Emitter<TasksEvents> {\n readonly #map = new Map<string, InternalTask>()\n graceMs = DEFAULT_GRACE_MS\n\n #tools: (() => Promise<readonly Tool[]>) | Tool[] = []\n\n /** Heartbeat interval in ms. When set, fires `heartbeat` events while\n * at least one task is pending or running. Self-managing: starts on\n * the first active task, stops when the last one finishes. Set to\n * `undefined` to disable. */\n #heartbeatMs?: number\n #heartbeatTimer?: ReturnType<typeof setInterval>\n\n get heartbeatMs(): number | undefined {\n return this.#heartbeatMs\n }\n set heartbeatMs(value: number | undefined) {\n this.#heartbeatMs = value\n this.#syncHeartbeat()\n }\n\n // ── Public registry surface ─────────────────────────────────────────\n\n /** Snapshot of every active task (pending or running). */\n running(): readonly TaskInfo[] {\n return [...this.#map.values()].filter((t) => t.status !== \"done\").map((t) => toTaskInfo(t))\n }\n\n /** Snapshot of every task that has completed. Drops are by `remove()`\n * or implicit retention; this list grows unless the caller prunes. */\n finished(): readonly DoneTaskInfo[] {\n return [...this.#map.values()]\n .filter((t): t is InternalTask & { status: \"done\" } => t.status === \"done\")\n .map((t) => toTaskInfo(t) as DoneTaskInfo)\n }\n\n /** Look up a task by id. Useful for `task_stop` / `task_poll`. */\n get(id: string): TaskInfo | undefined {\n const t = this.#map.get(id)\n return t ? toTaskInfo(t) : undefined\n }\n\n /** Snapshot of every task in the registry — running, pending, and done. */\n info(): readonly TaskInfo[] {\n return [...this.#map.values()].map(toTaskInfo)\n }\n\n async tools(): Promise<readonly Tool[]> {\n return typeof this.#tools === \"function\" ? this.#tools() : this.#tools\n }\n\n set $tools(tools: (() => Promise<readonly Tool[]>) | Tool[]) {\n this.#tools = tools\n }\n\n /** Non-consuming check: does the underlying streamable have output\n * the model hasn't seen since the last `poll()`? Returns false for\n * tasks without a streamable, completed tasks, or streamables that\n * don't implement the optional `hasNew` hook (no signal to give).\n * Used by heartbeats to flag tasks worth polling. */\n hasNewOutput(id: string): boolean {\n const t = this.#map.get(id)\n if (t?.status !== \"running\" || !t.streamable) return false\n return t.streamable.hasNew?.() ?? false\n }\n\n /** Poll a task's streamable for incremental output without changing\n * its lifecycle state. Advances the streamable's cursor — the next\n * call returns only what arrived since *this* one. Returns the same\n * `ToolResult` shape the original tool produces (parts + meta).\n * Errors when the task is unknown, already done, or has no streamable\n * (the latter is the case for plain-Promise tools — there's no\n * partial state to read). */\n pollOutput(id: string): ToolResult & { running: boolean } {\n const t = this.#map.get(id)\n if (!t) {\n throw new AiError({\n code: \"NOT_FOUND\",\n data: { id },\n message: `no task with id \"${id}\"`,\n })\n }\n if (t.status === \"done\") {\n throw new AiError({\n code: \"TASK_DONE\",\n data: { id },\n message: `task \"${id}\" has already completed; its result was injected as a system message`,\n })\n }\n if (!t.streamable) {\n throw new AiError({\n code: \"NOT_STREAMABLE\",\n data: { id },\n message:\n `task \"${id}\" has no incremental output — it's a plain-Promise tool ` +\n `whose result is delivered all-at-once when complete`,\n })\n }\n return t.streamable.poll()\n }\n\n /** Drop a task from the registry — does not abort. Caller is\n * responsible for `abort()`-ing if the task is still running. */\n remove(id: string): boolean {\n const task = this.#map.get(id)\n if (!task) return false\n this.#map.delete(id)\n void this.emit(\"task-removed\", { task: toTaskInfo(task) })\n return true\n }\n\n /** Mark a task done with a final result. Fires `task-done` UNLESS the\n * task is currently owned by an in-flight `run()` round — in that\n * case the round folds the completion into its returned parts and\n * the event is suppressed. Starts any pending dependents. */\n done(id: string, result: ToolResult): void {\n const task = this.#map.get(id)\n if (!task || task.status === \"done\") return\n task.status = \"done\"\n task.result = result\n task.finishedAt = Date.now()\n task.resolveDone()\n if (!task.ownerRound) {\n void this.emit(\"task-done\", { task: toTaskInfo(task) as DoneTaskInfo })\n }\n this.#startReadyDependents(id, result)\n this.#syncHeartbeat()\n }\n\n /** Abort a running task. Calls the streamable's `abort()` if present;\n * pending tasks transition straight to `done` with a cancelled\n * result. Idempotent. */\n abort(id: string, reason = \"aborted by request\"): void {\n const task = this.#map.get(id)\n if (!task || task.status === \"done\") return\n if (task.streamable) task.streamable.abort()\n if (task.status === \"pending\") {\n this.done(id, toErrorResult(new AiError({ code: \"TASK_ABORTED\", message: reason })))\n }\n // Running tasks: the streamable will eventually settle and call done()\n // via its watcher. We could force a synchronous \"done\" here, but\n // letting the streamable's natural completion path run keeps the\n // final snapshot accurate (output that arrived before abort lands).\n }\n\n /** Abort every active task. Used on agent dispose. Awaits each\n * task's `donePromise` so the registry is fully drained before\n * resolving — so callers can rely on no pending I/O after `dispose`. */\n async killAll(): Promise<void> {\n const active = [...this.#map.values()].filter((t) => t.status !== \"done\")\n for (const t of active) {\n if (t.streamable) t.streamable.abort()\n if (t.status === \"pending\") {\n this.done(\n t.id,\n toErrorResult(new AiError({ code: \"TASK_ABORTED\", message: \"agent disposed\" }))\n )\n }\n }\n await Promise.all(active.map((t) => t.donePromise.catch(() => undefined)))\n this.#syncHeartbeat()\n }\n\n /** Start or stop the heartbeat timer based on whether any task is\n * active and whether `heartbeatMs` is configured. Idempotent — called\n * after every state transition (`add` / `done` / `killAll`). The\n * timer is `unref`'d so it never holds the process open. */\n #syncHeartbeat(): void {\n const hasActive = [...this.#map.values()].some((t) => t.status !== \"done\")\n const want = hasActive && this.#heartbeatMs !== undefined\n if (want && !this.#heartbeatTimer) {\n this.#heartbeatTimer = setInterval(() => {\n void this.emit(\"heartbeat\", { running: this.info().filter((t) => t.status !== \"done\") })\n }, this.#heartbeatMs)\n this.#heartbeatTimer.unref()\n } else if (!want && this.#heartbeatTimer) {\n clearInterval(this.#heartbeatTimer)\n this.#heartbeatTimer = undefined\n }\n }\n\n // ── Batch execution ─────────────────────────────────────────────────\n\n /**\n * Execute a batch of assistant tool calls. Returns ToolResultPart[]\n * mapped 1:1 with `calls`. Sync completions land in the result array\n * immediately; long-running ones return a placeholder and the eventual\n * completion fires `task-done` post-round (the agent injects a system\n * message in response).\n *\n * The `messages` snapshot is what tools see on `ctx.messages` — pass\n * the conversation up to (and including) the assistant message that\n * produced these calls, so freshness checks can scan back through\n * prior tool results.\n */\n async run(\n calls: readonly ToolCallPart[],\n ctx: ToolContext,\n opts: { onResult?: (call: ToolCallPart, result: ToolResultPart, idx: number) => void } = {}\n ): Promise<ToolResultPart[]> {\n const round = Symbol(\"round\")\n const tasks: InternalTask[] = []\n let chainHead: string | undefined\n\n const tools = await this.tools()\n const parallel = calls.every((c) => tools.find((t) => t.name === c.name)?.parallel ?? false)\n\n for (const call of calls) {\n const tool = tools.find((t) => t.name === call.name)\n if (!tool) {\n tasks.push(this.#startSyncResult(call, unknownToolResult(call.name), round))\n continue\n }\n\n if (chainHead) {\n // Queue behind the chain head — won't start until that finishes.\n tasks.push(\n this.#registerPending({ call, ctxBase: ctx, round, tool, waitingFor: chainHead })\n )\n chainHead = tasks[tasks.length - 1].id\n continue\n }\n\n if (this.#needsPreflight(tool, ctx)) {\n // Preflight is intentionally sequential: permission prompts should\n // appear one at a time and should not register/background a task while\n // waiting for the user's answer.\n // oxlint-disable-next-line no-await-in-loop\n const preflight = await this.#preflight(tool, call, ctx)\n if (preflight) {\n tasks.push(this.#startSyncResult(call, preflight, round))\n continue\n }\n }\n\n const task = this.#start({ call, ctxBase: ctx, round, tool })\n tasks.push(task)\n // If this call promoted to a long-running task and `parallel: false`,\n // subsequent serial calls chain behind it.\n if (task.status === \"running\" && !parallel) chainHead = task.id\n }\n\n const parts: ToolResultPart[] = []\n\n const resultPart = (idx: number): ToolResultPart => {\n if (parts[idx]) return parts[idx]\n const task = tasks[idx]\n if (task.status !== \"done\") task.ownerRound = undefined\n const call = calls[idx]\n const part = this.#buildPart(call, task)\n parts[idx] = part\n return part\n }\n\n let onResult = opts.onResult\n\n // Race: every task done, OR grace expires, OR ctx.signal aborts.\n const allDone = Promise.all(\n tasks.map(async (t, ti) => {\n await t.donePromise\n onResult?.(calls[ti], resultPart(ti), ti)\n })\n )\n const grace = sleep(this.graceMs)\n const aborted = ctx.signal\n ? new Promise<void>((resolve) => {\n if (ctx.signal!.aborted) resolve()\n else ctx.signal!.addEventListener(\"abort\", () => resolve(), { once: true })\n })\n : new Promise<void>(() => undefined) // never resolves\n await Promise.race([allDone, grace, aborted])\n onResult = undefined\n\n // Release ownership on still-active tasks BEFORE building the result\n // array, so the post-round listener sees them as free-floating if\n // they happen to settle in the same tick.\n return tasks.map((_, i) => resultPart(i))\n }\n\n // ── Internals ──────────────────────────────────────────────────────\n\n /** Build a \"done\" task synchronously from a precomputed result.\n * Used for unknown-tool errors and validation failures. */\n #startSyncResult(call: ToolCallPart, result: ToolResult, round: symbol): InternalTask {\n // oxlint-disable-next-line sort-keys -- semantic field order\n const task = this.#allocate({ id: uuidv7(), type: call.name, desc: call.name, round })\n task.status = \"done\"\n task.result = result\n task.finishedAt = task.startedAt\n task.resolveDone()\n return task\n }\n\n /** Allocate an internal task record, register it, and emit `task-added`. */\n #allocate(opts: {\n id: string\n type: string\n desc: string\n waitingFor?: string\n round: symbol\n }): InternalTask {\n let resolveDone!: () => void\n const donePromise = new Promise<void>((r) => {\n resolveDone = r\n })\n const task: InternalTask = {\n desc: opts.desc,\n donePromise,\n id: opts.id,\n ownerRound: opts.round,\n resolveDone,\n startedAt: Date.now(),\n status: \"pending\",\n type: opts.type,\n waitingFor: opts.waitingFor,\n }\n this.#map.set(task.id, task)\n void this.emit(\"task-added\", { task: toTaskInfo(task) })\n this.#syncHeartbeat()\n return task\n }\n\n /** Register a pending task (chained behind `dependsOn`). Does not\n * invoke the tool — that happens once the dependency completes. */\n #registerPending(opts: {\n call: ToolCallPart\n tool: Tool\n ctxBase: ToolContext\n waitingFor: string\n round: symbol\n }): InternalTask {\n // oxlint-disable-next-line sort-keys -- semantic field order\n const task = this.#allocate({\n id: uuidv7(),\n type: opts.tool.name,\n desc: descOfCall(opts.call),\n waitingFor: opts.waitingFor,\n round: opts.round,\n })\n task.pending = { call: opts.call, ctx: opts.ctxBase, tool: opts.tool }\n return task\n }\n\n /** Start a tool call. Allocates a task record, validates params,\n * invokes `tool.call`, detects `Streamable`, and wires completion\n * back to `done()`. Returns the task in its post-launch state\n * (`done` for sync failures or already-resolved sync calls,\n * `running` for everything else). */\n #start(opts: {\n call: ToolCallPart\n tool: Tool\n ctxBase: ToolContext\n round: symbol\n }): InternalTask {\n // oxlint-disable-next-line sort-keys -- semantic field order\n const task = this.#allocate({\n id: uuidv7(),\n type: opts.tool.name,\n desc: descOfCall(opts.call),\n round: opts.round,\n })\n this.#dispatch(task, opts.tool, opts.call, opts.ctxBase)\n return task\n }\n\n #needsPreflight(tool: Tool, ctx: ToolContext): boolean {\n return ctx.need !== undefined || tool.preflight !== undefined\n }\n\n /** Run schema validation and semantic/tool permission checks before a\n * public task is allocated. Returns a formatted tool error when the\n * call should short-circuit, otherwise undefined. */\n async #preflight(\n tool: Tool,\n call: ToolCallPart,\n ctxBase: ToolContext\n ): Promise<ToolResult | undefined> {\n const ctx: ToolContext = { ...ctxBase, tasks: this }\n let params: unknown\n try {\n params = await tool.validator.validateParams(call.params)\n await ctx.need?.(\"tool\", tool.name)\n await tool.preflight?.(params, ctx)\n } catch (error) {\n return toErrorResult(error)\n }\n }\n\n /** Validate / call / wire up completion for an existing task record.\n * Used both for fresh tasks (`#start`) and pending-becoming-ready\n * (`#startReadyDependents`). The task's id and registry entry are\n * reused so identifiers stay stable across the pending → running\n * transition.\n *\n * Delegates the validate/call/error machinery to `runTool` (in\n * streaming mode) so there's one source of truth. The task's status\n * is flipped to `running` synchronously — the round loop reads it\n * right after `#start` returns to decide chain heads, and we want\n * that read to see the post-launch state, not the allocation default.\n * Async resolution either keeps it `running` (streamable returned)\n * or transitions to `done` (sync result or error). */\n #dispatch(task: InternalTask, tool: Tool, call: ToolCallPart, ctxBase: ToolContext): void {\n const ctx: ToolContext = { ...ctxBase, tasks: this }\n task.status = \"running\"\n\n const dispatchPromise = runTool(tool, call.params, ctx, { preflight: false, streaming: true })\n\n void dispatchPromise.then(\n (settled) => {\n if (isStreamable(settled)) {\n // Long-running — hold the streamable for partial snapshots /\n // abort, wire its completion back through done().\n task.streamable = settled\n settled.done.then(\n () => {\n const snap = settled.poll()\n this.done(task.id, {\n content: snap.content,\n error: snap.error,\n isError: snap.isError,\n meta: snap.meta,\n })\n },\n // `done` shouldn't reject by contract; treat as internal bug.\n (error: unknown) => this.done(task.id, toErrorResult(error))\n )\n return\n }\n // Sync path: validation error, sync return, or thrown error —\n // runTool has already formatted everything into a ToolResult.\n this.done(task.id, settled)\n },\n // The permission gate threw (or AiError leaked from runTool).\n // Either way, format and settle the task.\n (error: unknown) => this.done(task.id, toErrorResult(error))\n )\n }\n\n /** Walk pending tasks; start any whose `dependsOn` just completed.\n * If the dependency failed, propagate cancellation: dependents land\n * in `done` with an `UPSTREAM_FAILED` result. */\n #startReadyDependents(completedId: string, completedResult: ToolResult): void {\n for (const t of this.#map.values()) {\n if (t.status !== \"pending\" || t.waitingFor !== completedId) continue\n if (completedResult.isError) {\n // Skip dependent — its predecessor failed.\n this.done(\n t.id,\n toErrorResult(\n new AiError({\n code: \"UPSTREAM_FAILED\",\n data: { dependsOn: completedId },\n message: `skipped: upstream task ${completedId} failed`,\n })\n )\n )\n continue\n }\n void this.#startPending(t)\n }\n }\n\n async #startPending(task: InternalTask): Promise<void> {\n const pending = task.pending\n if (!pending) return\n if (!this.#needsPreflight(pending.tool, pending.ctx)) {\n task.pending = undefined\n task.waitingFor = undefined\n task.ownerRound = undefined\n this.#dispatch(task, pending.tool, pending.call, pending.ctx)\n return\n }\n\n const preflight = await this.#preflight(pending.tool, pending.call, pending.ctx)\n if (preflight) {\n this.done(task.id, preflight)\n return\n }\n\n // Restart as a regular task. The round that originally registered\n // this task has already returned its placeholder, so whatever happens\n // now flows through normal `task-done`.\n task.pending = undefined\n task.waitingFor = undefined\n task.ownerRound = undefined\n this.#dispatch(task, pending.tool, pending.call, pending.ctx)\n }\n\n /** Build a `ToolResultPart` for a task at round-end. Done tasks pass\n * through their captured result; still-running tasks get a snapshot\n * from the streamable (if any) plus a placeholder note for the model. */\n #buildPart(call: ToolCallPart, task: InternalTask): ToolResultPart {\n if (task.status === \"done\" && task.result) {\n return {\n content: task.result.content,\n error: task.result.error,\n id: call.id,\n isError: task.result.isError,\n meta: stampTaskMeta(task.result.meta, task),\n name: call.name,\n type: \"tool-result\",\n }\n }\n\n // Pending: never started, will run when its dependency completes.\n // Placeholder uses the standard TaskInfo shape so it's parseable\n // the same way as task_list / heartbeat entries.\n if (task.status === \"pending\") {\n return {\n content: [{ data: toTaskInfo(task), tag: \"task\", type: \"meta\" }],\n id: call.id,\n isError: false,\n meta: stampTaskMeta(undefined, task),\n name: call.name,\n type: \"tool-result\",\n }\n }\n\n // Running: capture whatever the streamable has so far (partial output)\n // and append a `<task>` MetaPart with an explicit \"still running\"\n // hint. Without the hint, models tend to treat partial output as a\n // final answer and respond prematurely; with it they see the state\n // structurally and know the final result will arrive as a later\n // system message. Tagged `<task>` for symmetry with the pending /\n // task_list / heartbeat / task-done entries — same shape everywhere\n // a task surfaces.\n const snap = task.streamable?.poll()\n const baseContent = partialContentFrom(snap)\n const trailer: MetaPart = {\n content:\n \"Task is still running. Partial output above. The final result \" +\n \"will arrive as a system message when the task completes; you \" +\n \"do not need to poll. Continue with other work or wait.\",\n data: {\n ...toTaskInfo(task),\n },\n tag: \"task\",\n type: \"meta\",\n }\n const parts: ContentPart[] = []\n if (typeof baseContent === \"string\") {\n if (baseContent !== \"\") parts.push({ text: baseContent, type: \"text\" })\n } else {\n parts.push(...baseContent)\n }\n parts.push(trailer)\n return {\n content: parts,\n id: call.id,\n isError: false,\n meta: stampTaskMeta(snap?.meta, task),\n name: call.name,\n type: \"tool-result\",\n }\n }\n}\n\n/** Stamp `meta.task` with the current task state. Preserves any\n * tool-attached `meta` fields. Used both on done results (so the\n * model can correlate completion to the original call) and on\n * partial / pending placeholders. */\nfunction stampTaskMeta(\n base: ToolResult[\"meta\"] | undefined,\n task: InternalTask\n): ToolResult[\"meta\"] & TaskMeta {\n return {\n ...base,\n task: {\n dependsOn: task.waitingFor,\n desc: task.desc,\n durationMs: task.finishedAt ? task.finishedAt - task.startedAt : undefined,\n id: task.id,\n status: task.status,\n type: task.type,\n },\n }\n}\n\n/** Build the \"running\" placeholder content from a streamable snapshot.\n * Empty string when there's nothing yet to show; copies the parts\n * array so downstream mutation of the result message can't reach back\n * into the streamable's accumulator. */\nfunction partialContentFrom(\n snap: { content: ToolResult[\"content\"] } | undefined\n): ToolResultPart[\"content\"] {\n if (!snap) return \"\"\n if (typeof snap.content === \"string\") return snap.content\n return [...snap.content]\n}\n\n/** Best-effort human-readable label for a tool call. Reads a\n * `description` field from params if the tool defined one (bash does);\n * otherwise falls back to the tool name. Kept short so log lines stay\n * scannable. */\nfunction descOfCall(call: ToolCallPart): string {\n const params = call.params as { description?: unknown } | null | undefined\n if (params && typeof params === \"object\" && typeof params.description === \"string\") {\n return params.description\n }\n return call.name\n}\n\n/** Synthesize the tool-result payload returned when the model calls a\n * tool that wasn't registered for this turn. Same shape the previous\n * `unknownToolResult` helper produced; inlined here to keep `tasks.ts`\n * self-contained. */\nfunction unknownToolResult(name: string): ToolResult {\n const err = new AiError({\n code: \"UNKNOWN_TOOL\",\n message: `no tool named \"${name}\" is registered for this turn`,\n })\n return toErrorResult(err)\n}\n\nfunction sleep(ms: number): Promise<void> {\n return new Promise((r) => {\n const t = setTimeout(r, ms)\n t.unref()\n })\n}\n\n/** Render an array of `TaskInfo` as a `<tasks>` MetaPart for the model\n * (heartbeat pulses and `task_list`). Each task lands as one line of\n * JSON. The `result` field on done tasks is stripped — listing should\n * give an inventory, not historical output (the result was already\n * injected as a system message at task-done time, and re-shipping it\n * on every heartbeat / list call would be a token bomb). */\nexport function taskInfoPart(info: readonly TaskInfo[]): MetaPart {\n if (info.length === 0) return { data: \"no active tasks\", tag: \"tasks\", type: \"meta\" }\n const data = info.map((t) => safeStringify(t, omitResult)).join(\"\\n\")\n return { data, tag: \"tasks\", type: \"meta\" }\n}\n\n/** JSON.stringify replacer that drops the `result` field. Used by\n * `taskInfoPart` to keep listing payloads bounded. */\nfunction omitResult(key: string, value: unknown): unknown {\n return key === \"result\" ? undefined : value\n}\n\nfunction toTaskInfo(task: InternalTask): TaskInfo {\n const { id, status, type, desc } = task\n const ms = (task.finishedAt ?? Date.now()) - task.startedAt\n if (status === \"running\") {\n return { desc, elapsedMs: ms, hasNewOutput: task.streamable?.hasNew?.(), id, status, type }\n }\n if (status === \"pending\") {\n return { desc, elapsedMs: ms, id, status, type, waitingFor: task.waitingFor ?? \"\" }\n }\n // status === \"done\" — `result` is set by `done()` before status flips,\n // so the `?? toErrorResult(...)` is just a defensive fallback for\n // a malformed record (shouldn't happen in practice).\n return {\n desc,\n durationMs: ms,\n id,\n result:\n task.result ??\n toErrorResult(\n new AiError({\n code: \"INTERNAL\",\n message: `task \"${task.id}\" completed without a result`,\n })\n ),\n status,\n type,\n }\n}\n\n/** Format a finished task as the parts of a system inject. Layout:\n *\n * <task>{id, type, desc, status: \"done\", durationMs}</task>\n * {result body}\n *\n * The header is the standard `TaskInfo`-shaped JSON so consumers\n * (model, TUI) can parse it the same way they parse `task_list` and\n * heartbeat output — same shape everywhere a task surfaces.\n *\n * The body comes straight from `result.content`. For errors, that\n * already includes the `<error>{code, message, ...}</error>` MetaPart\n * + the formatted `❌ CODE: message` block (baked in by\n * `toErrorResult`), so this function doesn't need to special-case\n * errors — the structured tag and human body ride along with the\n * result content for any tool failure, anywhere.\n *\n * System messages can't carry attachments, so any image/pdf/etc. in\n * the result degrades to a `[image]` placeholder via\n * `stringifyContent` — best-effort, model still sees *something* was\n * there. */\nfunction formatTaskCompletion(task: DoneTaskInfo): (TextPart | MetaPart)[] {\n const { result, ...header } = task\n const parts: (TextPart | MetaPart)[] = [{ data: header, tag: \"task\", type: \"meta\" }]\n const bodyText = stringifyContent(result.content)\n if (bodyText !== \"\") parts.push({ text: bodyText, type: \"text\" })\n return parts\n}\n\n/** Build an `inject`-ready system message for a finished task. */\nexport function taskCompletionMessage(task: DoneTaskInfo): Message<\"system\"> {\n return {\n content: formatTaskCompletion(task),\n meta: { kind: \"task\", taskId: task.id },\n role: \"system\",\n }\n}\n"],"mappings":";;;;AAiBA,MAAM,mBAAmB;;;;;;;;;;;;;;;;;;;AAqHzB,IAAa,QAAb,cAA2B,QAAqB;CAC9C,uBAAgB,IAAI,IAA0B;CAC9C,UAAU;CAEV,SAAoD,CAAC;;;;;CAMrD;CACA;CAEA,IAAI,cAAkC;EACpC,OAAO,KAAK;CACd;CACA,IAAI,YAAY,OAA2B;EACzC,KAAK,eAAe;EACpB,KAAK,eAAe;CACtB;;CAKA,UAA+B;EAC7B,OAAO,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,QAAQ,MAAM,EAAE,WAAW,MAAM,CAAC,CAAC,KAAK,MAAM,WAAW,CAAC,CAAC;CAC5F;;;CAIA,WAAoC;EAClC,OAAO,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,CAAC,CAC3B,QAAQ,MAA8C,EAAE,WAAW,MAAM,CAAC,CAC1E,KAAK,MAAM,WAAW,CAAC,CAAiB;CAC7C;;CAGA,IAAI,IAAkC;EACpC,MAAM,IAAI,KAAK,KAAK,IAAI,EAAE;EAC1B,OAAO,IAAI,WAAW,CAAC,IAAI,KAAA;CAC7B;;CAGA,OAA4B;EAC1B,OAAO,CAAC,GAAG,KAAK,KAAK,OAAO,CAAC,CAAC,CAAC,IAAI,UAAU;CAC/C;CAEA,MAAM,QAAkC;EACtC,OAAO,OAAO,KAAK,WAAW,aAAa,KAAK,OAAO,IAAI,KAAK;CAClE;CAEA,IAAI,OAAO,OAAkD;EAC3D,KAAK,SAAS;CAChB;;;;;;CAOA,aAAa,IAAqB;EAChC,MAAM,IAAI,KAAK,KAAK,IAAI,EAAE;EAC1B,IAAI,GAAG,WAAW,aAAa,CAAC,EAAE,YAAY,OAAO;EACrD,OAAO,EAAE,WAAW,SAAS,KAAK;CACpC;;;;;;;;CASA,WAA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;CAC3E,OAAO;EACL,SAAS,qBAAqB,IAAI;EAClC,MAAM;GAAE,MAAM;GAAQ,QAAQ,KAAK;EAAG;EACtC,MAAM;CACR;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { t as __commonJSMin } from "./rolldown-runtime-
|
|
1
|
+
import { t as __commonJSMin } from "./rolldown-runtime-BVN1G_yT.mjs";
|
|
2
2
|
import { safeStringify } from "@zaly/shared";
|
|
3
3
|
// ../../node_modules/.bun/shell-quote@1.12.0/node_modules/shell-quote/quote.js
|
|
4
4
|
var require_quote = /* @__PURE__ */ __commonJSMin(((exports, module) => {
|
|
@@ -763,4 +763,4 @@ const TOOLS = {
|
|
|
763
763
|
};
|
|
764
764
|
export { parseBash as n, TOOLS as t };
|
|
765
765
|
|
|
766
|
-
//# sourceMappingURL=tools-
|
|
766
|
+
//# sourceMappingURL=tools-Ca7VsMg3.mjs.map
|