@zaly/agent 0.1.1 → 0.2.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.
@@ -1 +1 @@
1
- {"version":3,"file":"src-C04Qk9KE.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 { 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?.effort ?? \"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() {\n return 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 void this.emit(\"reasoning\", { effort: r, 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 this.#model = m\n void this.emit(\"model\", { model: m, prev })\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 { AnyContent, AnyPart, AnyType, Attachment, Message, Tool } from \"@zaly/ai\"\nimport type { Prompt } from \"../prompt/registry.ts\"\n\nimport { stringifyContent } from \"@zaly/ai\"\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\nexport function estimatePart(p: AnyPart): TokenCount {\n switch (p.type) {\n case \"reasoning\":\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)\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) : 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(content: AnyContent): 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)\n tokens += partStats.tokens\n children.push(partStats)\n }\n return children\n}\n\nfunction estimateMessage(m: Message): TokenCount {\n const type = m.role\n const children = estimateContent(m.content)\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(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 } = {}\n): TokenStats {\n const root: TokenStats = { children: new Map(), count: 0, key: \"TOTAL\", tokens: 0 }\n const counts: TokenCount[] = []\n if (opts.prompt) counts.push(estimatePrompt(opts.prompt, opts.tools))\n counts.push(...msgs.map(estimateMessage))\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":";;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,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
+ {"version":3,"file":"src-DJoqT9yP.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 { 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?.effort ?? \"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() {\n return 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 void this.emit(\"reasoning\", { effort: r, 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 this.#model = m\n void this.emit(\"model\", { model: m, prev })\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 { AnyContent, AnyPart, AnyType, Attachment, Message, Tool } from \"@zaly/ai\"\nimport type { Prompt } from \"../prompt/registry.ts\"\n\nimport { stringifyContent } from \"@zaly/ai\"\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\nexport function estimatePart(p: AnyPart): TokenCount {\n switch (p.type) {\n case \"reasoning\":\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)\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) : 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(content: AnyContent): 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)\n tokens += partStats.tokens\n children.push(partStats)\n }\n return children\n}\n\nfunction estimateMessage(m: Message): TokenCount {\n const type = m.role\n const children = estimateContent(m.content)\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(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 } = {}\n): TokenStats {\n const root: TokenStats = { children: new Map(), count: 0, key: \"TOTAL\", tokens: 0 }\n const counts: TokenCount[] = []\n if (opts.prompt) counts.push(estimatePrompt(opts.prompt, opts.tools))\n counts.push(...msgs.map(estimateMessage))\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":";;;;;;;;;;;;;;;;;;;AA+BA,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,WAAW,UAAU;EACrD,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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,CAAC,CAAC,QAAQ,MAAM,GAAG;AACpD"}
@@ -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-C8zqqbPE.mjs").then((n) => n.n);
25
+ const { Session } = await import("./session-CUE48QWX.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-BbcxLzgC.mjs.map
135
+ //# sourceMappingURL=subagent-D-TYaX38.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;EAC3B,MAAM,EAAE,YAAY,MAAM,OAAO,yBAAwB,CAAA,MAAA,MAAA,EAAA,CAAA;EAKzD,MAAM,QAAQ,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AO,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-D-TYaX38.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;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@zaly/agent",
3
- "version": "0.1.1",
3
+ "version": "0.2.0",
4
4
  "description": "Agent runtime, sessions, tools, permissions, compaction, and tasks for zaly.",
5
5
  "keywords": [
6
6
  "agent",
@@ -33,8 +33,8 @@
33
33
  "access": "public"
34
34
  },
35
35
  "dependencies": {
36
- "@zaly/ai": "0.1.1",
37
- "@zaly/shared": "0.1.1",
36
+ "@zaly/ai": "0.2.0",
37
+ "@zaly/shared": "0.2.0",
38
38
  "pathe": "^2.0.3"
39
39
  },
40
40
  "devDependencies": {
@@ -1 +0,0 @@
1
- {"version":3,"file":"agent-BRENvuvx.mjs","names":[],"sources":["../src/utils/usage.ts","../src/stop.ts","../src/agent.ts"],"sourcesContent":["import type { Message, TokenCount, Usage } from \"@zaly/ai\"\n\n/** Sum two Usages. Optional fields are only present in the result\n * when at least one input had them set, so callers can tell \"no\n * reasoning happened this turn\" apart from \"0 reasoning tokens.\" */\nexport function addUsage(a: Usage, b: Usage): Usage {\n const out: Usage = {\n input: a.input + b.input,\n output: a.output + b.output,\n }\n if (a.cacheRead !== undefined || b.cacheRead !== undefined) {\n out.cacheRead = (a.cacheRead ?? 0) + (b.cacheRead ?? 0)\n }\n if (a.cacheWrite !== undefined || b.cacheWrite !== undefined) {\n out.cacheWrite = (a.cacheWrite ?? 0) + (b.cacheWrite ?? 0)\n }\n if (a.reasoning !== undefined || b.reasoning !== undefined) {\n out.reasoning = (a.reasoning ?? 0) + (b.reasoning ?? 0)\n }\n if (a.cost || b.cost) out.cost = addUsage(a.cost ?? empty(), b.cost ?? empty())\n return out\n}\n\nexport class TokenUsage implements Usage {\n #last: Usage = empty()\n #total: Usage = empty()\n\n constructor(messages?: readonly Message[]) {\n for (const m of messages ?? [])\n if (m.role === \"assistant\" && m.meta?.usage) this.add(m.meta.usage)\n }\n\n get cost(): Usage {\n return this.total.cost ?? empty()\n }\n\n get input(): number {\n return this.last.input\n }\n\n get output(): number {\n return this.last.output\n }\n\n get cacheRead(): number {\n return this.last.cacheRead ?? 0\n }\n\n get cacheWrite(): number {\n return this.last.cacheWrite ?? 0\n }\n\n get reasoning(): number {\n return this.last.reasoning ?? 0\n }\n\n add(count: Usage): void {\n this.#last = count\n this.#total = addUsage(this.#total, count)\n }\n\n resetLast(): void {\n this.#last = empty()\n }\n\n get last(): Usage {\n return this.#last\n }\n\n get total(): Usage {\n return this.#total\n }\n\n get contextSize(): number {\n return (\n this.last.input + this.last.output + (this.last.cacheRead ?? 0) + (this.last.cacheWrite ?? 0)\n )\n }\n}\n\nfunction empty(): TokenCount {\n return { input: 0, output: 0 }\n}\n","import type { TokenCount, ToolCallPart } from \"@zaly/ai\"\nimport type { Emitter, Envelope } from \"@zaly/shared\"\nimport type { AgentEvents, AgentStopKind } from \"./events.ts\"\n\nimport { safeStringify } from \"@zaly/shared\"\nimport { addUsage } from \"./utils/usage.ts\"\n\n/** Caps + heuristics that can end a run early. Wired into the\n * `AgentSession` loop via a single `detect()` call after each step. */\nexport interface StopOptions {\n /** Hard ceiling on provider round-trips per `run()`. Default: 50. */\n maxSteps?: number\n /** Cumulative token cap across the whole `run()`\n * (`totalUsage.input + totalUsage.output`). */\n tokenBudget?: number\n /** Bail after this many consecutive failing tool calls. A successful\n * tool result resets the streak. */\n maxToolErrors?: number\n\n // ── Loop detection ──────────────────────────────────────────────────\n // Two cheap heuristics over the running tool-call history. Hash is\n // `name + JSON.stringify(params)`; property order matters (rare false\n // negative if the model alternates key order on the same logical call,\n // accepted in exchange for a much cheaper hash). Set either limit to\n // `Infinity` to disable that arm.\n\n /** Same `(name, params)` appearing N times in a row → loop. Catches\n * the most common failure mode: re-calling `read_file` with the same\n * path expecting different output. Default 3. */\n loopConsecutive?: number\n /** Bounded window for duplicate detection. Default 10. */\n loopWindow?: number\n /** Within the window, this many duplicates of one call → loop.\n * Catches alternation patterns (`A B A B …`) the consecutive arm\n * alone won't see. Default 4. */\n loopWindowRepeats?: number\n}\n\n/**\n * Subscribes to an `AgentEvent` stream, accumulates the bookkeeping\n * the loop needs to make stop-or-continue decisions, and exposes a\n * single `detect()` to consult after each step.\n *\n * Lives outside `AgentSession` so concerns separate cleanly:\n * - the session owns conversation, queues, status, and loop control;\n * - the policy owns counters and the rules that act on them.\n *\n * Wire it up via `attach(session)` (returns an unsubscribe), or feed\n * events manually with `handle(event)` for custom drivers.\n */\nexport class StopPolicy {\n readonly #opts: StopOptions\n\n #steps = 0\n #consecutiveErrors = 0\n #calls: ToolCallPart[] = []\n #usage: TokenCount = { input: 0, output: 0 }\n #totalUsage: TokenCount = { input: 0, output: 0 }\n\n constructor(opts: StopOptions = {}) {\n this.#opts = opts\n }\n\n // ── Read ──────────────────────────────────────────────────────────────\n\n /** Token usage from the most recent step's response. */\n get usage(): TokenCount {\n return this.#usage\n }\n /** Cumulative token usage across every step in the current run. */\n get totalUsage(): TokenCount {\n return this.#totalUsage\n }\n get steps(): number {\n return this.#steps\n }\n get consecutiveErrors(): number {\n return this.#consecutiveErrors\n }\n /** Tool-call history fed to the loop detector. Read-only. */\n get calls(): readonly ToolCallPart[] {\n return this.#calls\n }\n\n // ── Wiring ────────────────────────────────────────────────────────────\n\n /** Subscribe to an emitter. To detach later, register the listener\n * yourself and pass the same fn to `emitter.off(fn)`:\n *\n * const handler = (e) => policy.handle(e)\n * emitter.all(handler)\n * // later:\n * emitter.off(handler) */\n attach(emitter: Emitter<AgentEvents>): void {\n emitter.onAny((event) => this.handle(event))\n }\n\n /** Feed a single event into the policy. Public so custom drivers\n * can drive it without going through `attach`. */\n handle(event: Envelope<AgentEvents>): void {\n switch (event.type) {\n case \"step-end\": {\n this.#steps++\n break\n }\n case \"tool-call\": {\n this.#calls.push(event.call)\n break\n }\n case \"tool-result\": {\n this.#consecutiveErrors = event.result.isError ? this.#consecutiveErrors + 1 : 0\n break\n }\n case \"stream-event\": {\n if (event.event.type === \"finish\") {\n this.#usage = event.event.usage\n this.#totalUsage = addUsage(this.#totalUsage, event.event.usage)\n }\n break\n }\n // status / stop — no policy state to update.\n }\n }\n\n /** Reset per-run counters. Token totals (`usage` / `totalUsage`)\n * persist unless `keepUsage: false` is passed — billing-style\n * displays usually want them sticky across resets. */\n reset(opts: { keepUsage?: boolean } = {}): void {\n this.#steps = 0\n this.#consecutiveErrors = 0\n this.#calls = []\n if (opts.keepUsage === false) {\n this.#usage = { input: 0, output: 0 }\n this.#totalUsage = { input: 0, output: 0 }\n }\n }\n\n /** Decide whether the loop should stop. Returns the stop reason or\n * `undefined` to continue. Order matters — `loop-detected` wins\n * over `max-tool-errors` if both fire, since a model in a tight\n * loop is the more pressing thing to surface. */\n detect(): AgentStopKind | undefined {\n if (this.#opts.maxSteps !== undefined && this.#steps >= this.#opts.maxSteps) {\n return \"max-steps\"\n }\n if (this.#detectLoop()) {\n return \"loop-detected\"\n }\n if (\n this.#opts.maxToolErrors !== undefined &&\n this.#consecutiveErrors >= this.#opts.maxToolErrors\n ) {\n return \"max-tool-errors\"\n }\n if (\n this.#opts.tokenBudget !== undefined &&\n this.#totalUsage.input + this.#totalUsage.output > this.#opts.tokenBudget\n ) {\n return \"token-budget\"\n }\n return undefined\n }\n\n // ── Loop detection internals ─────────────────────────────────────────\n\n #detectLoop(): boolean {\n const calls = this.#calls\n if (calls.length === 0) return false\n\n const consecutive = this.#opts.loopConsecutive ?? 3\n if (Number.isFinite(consecutive) && calls.length >= consecutive) {\n const last = hashCall(calls[calls.length - 1])\n let run = 1\n for (let i = calls.length - 2; i >= 0 && run < consecutive; i--) {\n if (hashCall(calls[i]) === last) run++\n else break\n }\n if (run >= consecutive) return true\n }\n\n const window = this.#opts.loopWindow ?? 10\n const windowRepeats = this.#opts.loopWindowRepeats ?? 4\n if (Number.isFinite(windowRepeats) && calls.length >= windowRepeats) {\n const slice = calls.slice(Math.max(0, calls.length - window))\n const counts = new Map<string, number>()\n for (const call of slice) {\n const h = hashCall(call)\n const next = (counts.get(h) ?? 0) + 1\n if (next >= windowRepeats) return true\n counts.set(h, next)\n }\n }\n\n return false\n }\n}\n\nfunction hashCall(call: ToolCallPart): string {\n return `${call.name}\\0${safeStringify(call.params)}`\n}\n","// oxlint-disable no-await-in-loop\nimport type {\n AssistantMessage,\n Content,\n Context,\n Message,\n MetaOf,\n MetaPart,\n Model,\n ModelStreamOptions,\n ParamsOf,\n TokenCount,\n Tool,\n ToolCallPart,\n ToolContext,\n ToolResult,\n} from \"@zaly/ai\"\nimport type { CompactionOptions } from \"./compaction/compactions.ts\"\nimport type { AgentContext } from \"./ctx.ts\"\nimport type { AgentEvents, AgentStatus, AgentStop, AgentStopKind } from \"./events.ts\"\nimport type { Session } from \"./session/session.ts\"\nimport type { AgentOptions, ContextPressure, SendMode, StepResult, TurnResult } from \"./types.ts\"\n\nimport { AiError, isContextOverflow, runTool } from \"@zaly/ai\"\nimport { Emitter, toValue, toError } from \"@zaly/shared\"\nimport { StopPolicy } from \"./stop.ts\"\nimport { Tasks, taskCompletionMessage, taskInfoPart } from \"./tasks.ts\"\nimport { TokenUsage } from \"./utils/usage.ts\"\nimport { uuidv7 } from \"./utils/uuid.ts\"\n\nconst PRESSURE_LEVELS = [0.75, 0.85, 0.95] as const\n\n/**\n * Long-lived agent — drives the multi-turn loop, owns the run-time\n * status / queues, and delegates conversation state to a `Session`.\n *\n * Typical interactive use:\n *\n * ```ts\n * const agent = await Agent.load({ model, tools })\n * agent.session.on(\"node\", (e) => render(e))\n * agent.send({ role: \"user\", content: \"hi\" }) // auto-runs\n * // …user types again later…\n * agent.send({ role: \"user\", content: \"follow-up\" }) // queues if running\n * ```\n *\n * Headless / one-shot use is just a thin wrapper on top — see\n * `runAgent` in the test helpers.\n */\nexport class Agent extends Emitter<AgentEvents> {\n readonly #opts: AgentOptions\n readonly #ctx: AgentContext\n readonly #stopPolicy: StopPolicy\n readonly #tasks: Tasks\n /** Nesting depth — see `AgentOptions.depth`. Read-only; subagents pass\n * `parent.depth + 1` when constructing their child. */\n readonly depth: number\n /** Cap on `depth` — see `AgentOptions.maxDepth`. */\n readonly maxDepth: number\n #started = false\n\n #parent?: Agent\n\n #injectQueue: Message[] = []\n #appendQueue: Message[][] = []\n #notifyQueue: MetaPart[] = []\n\n #status: AgentStatus = \"idle\"\n #abortController?: AbortController\n #pauseRequested?: string\n #running?: Promise<AgentStopKind>\n #usage: TokenUsage\n\n /** Pending future-injects scheduled via `scheduleWakeup`. Cleared\n * whenever the loop becomes active for any reason — the scheduled\n * inject was a fallback \"wake me up at time T if nothing else does,\"\n * and once something else has, the timer is moot. Hints from cancelled\n * wakeups carry over as a system message so the intent doesn't\n * evaporate. */\n readonly #wakeups = new Map<string, { timer: ReturnType<typeof setTimeout>; hint?: string }>()\n\n #lastStop?: AgentStop\n\n /** Synchronous, low-level constructor. Prefer `Agent.load(opts)` —\n * it runs the same construction *plus* any async setup (resolving\n * `session: SessionOptions` to a built `Session`, skills discovery,\n * future warm-ups). The constructor is `protected` so test doubles /\n * subclasses can still call `super(init)` directly; they're\n * responsible for providing a pre-built `Session` on `init.session`. */\n public constructor(ctx: AgentContext) {\n super()\n const opts = ctx.opts\n this.#ctx = ctx\n this.#opts = ctx.opts\n this.depth = opts.depth ?? 0\n this.maxDepth = opts.maxDepth ?? 2\n\n // Note: session.update() + initial messages are committed\n // asynchronously from `Agent.load`, NOT here. Constructors can't\n // be async; deferring those writes until after construction also\n // gives consumers a window to subscribe to session events before\n // the first node fires.\n\n this.#tasks = new Tasks()\n this.#tasks.$tools = async () => this.tools\n this.#tasks.heartbeatMs = opts.heartbeatMs\n this.#tasks.onEmitError = (error) => opts.logger?.child(\"tasks\").error(error)\n // Post-round task completions inject a system message into the next\n // step, surfacing the result to the model. Round-internal completions\n // are folded into the round's returned parts and don't fire here.\n this.#tasks.on(\"task-done\", ({ task }) => {\n this.send(taskCompletionMessage(task))\n })\n // Heartbeats keep the agent loop alive while long-running tasks are\n // in flight. Each pulse injects a small system note listing what's\n // still going. Tasks with incremental output ready to read get a\n // `*new*` marker so the model knows to call `task_poll` if it cares.\n this.#tasks.on(\"heartbeat\", ({ running }) => {\n this.send({\n content: [{ content: [taskInfoPart(running)], tag: \"heartbeat\", type: \"meta\" }],\n role: \"system\",\n })\n })\n\n this.#stopPolicy = new StopPolicy(opts.stop)\n this.#stopPolicy.attach(this)\n this.onEmitError = (error) => opts.logger?.child(\"events\").error(error)\n this.#ctx.attach(this)\n\n // Seed usage\n this.#usage = new TokenUsage(this.messages)\n this.#ctx.on(\"session\", () => this.reset())\n }\n\n async reset(): Promise<void> {\n this.stop({ abort: true, reason: \"reset\" })\n await this.waitIdle()\n await this.#tasks.killAll()\n this.#cancelAllWakeups()\n this.#usage = new TokenUsage(this.messages)\n this.#stopPolicy.reset({ keepUsage: false })\n this.#injectQueue = []\n this.#appendQueue = []\n this.#notifyQueue = []\n this.#wakeups.clear()\n this.#stop(\"natural\")\n }\n\n /** Spawn a child agent that inherits this agent's runtime defaults —\n * cwd, model, permissions, full effective tool list (user tools +\n * the loaded skill tool), `depth + 1`, and `maxDepth`. Pass\n * `overrides` to specialize: typical ones are `prompt` (the child\n * has its own role), `session` (the child writes to its own JSONL),\n * and `tools` (curated subset).\n *\n * Used by the `subagent` tool for delegation; equally useful for\n * ad-hoc parallel-agent patterns (multiple children working on\n * pieces of a task in parallel).\n *\n * Depth cap: when the child would be at `maxDepth`, the `subagent`\n * tool is filtered out of its inherited tool list so recursion\n * bottoms out cleanly. The model just doesn't see the tool — no\n * error path. */\n async child(overrides: Partial<AgentOptions> = {}): Promise<Agent> {\n const childDepth = overrides.depth ?? this.depth + 1\n // Inherit the *effective* step tool list (includes the loaded\n // `skill` tool). The child opts out of its own skill scan since\n // the catalog is shared.\n\n let tools = [...this.tools].filter((t) => t.name !== \"skill\")\n if (childDepth >= this.maxDepth) tools = tools.filter((t) => t.name !== \"subagent\")\n const { createAgent } = await import(\"./ctx.ts\")\n\n const ret = await createAgent({\n cwd: this.cwd,\n depth: childDepth,\n mask: this.#opts.mask,\n maxDepth: this.maxDepth,\n model: this.model,\n // Inherit the parent's `notify` setting so test roots that\n // disable the notifier (`notify: false`) propagate that to\n // children — otherwise spawning a child would silently re-enable\n // session-started / time / etc. injections that the harness\n // explicitly opted out of.\n notify: this.#opts.notify,\n permissions: await this.ctx.permissions(),\n skills: this.#ctx.skills, // shared catalog; child doesn't reload\n // Propagate the swarm so the child + every grandchild address\n // each other through the same registry. Override-able via\n // `overrides.swarm` if a caller wants the child outside the\n // tree (rare).\n swarm: await this.#ctx.swarm(),\n tools,\n ...overrides,\n })\n ret.#parent = this\n // Children are spawned ready — subagent dispatch typically calls\n // `.send()` immediately after, and inspecting `child.tools` /\n // `child.prompt` before sending should just work.\n await ret.start()\n return ret\n }\n\n // ── Read ──────────────────────────────────────────────────────────────\n\n /** Active conversation — delegates to the underlying `Session`. */\n get messages(): readonly Message[] {\n return this.session.messages\n }\n\n get status(): AgentStatus {\n return this.#status\n }\n\n get cwd(): string {\n return this.#ctx.cwd\n }\n\n get model(): Model | undefined {\n return this.#ctx.model\n }\n\n get session(): Session {\n return this.#ctx.session\n }\n\n get signal(): AbortSignal | undefined {\n return this.#abortController?.signal\n }\n\n /** Token usage from the most recent step's response. Drives\n * `contextSize` and any \"this turn used N tokens\" UI. */\n get usage(): TokenUsage {\n return this.#usage\n }\n\n /** Cumulative token usage across every step in the current run.\n * Useful for billing-style displays. */\n get totalUsage(): TokenCount {\n return this.#usage.total\n }\n /** Logical size of the current conversation in tokens — what the\n * next request will send as input. Equals the last step's\n * `input + output` (since the model's reply becomes part of the\n * next prompt). Returns 0 before any step has run. */\n get contextSize(): number {\n return this.#usage.contextSize\n }\n\n get pressure(): ContextPressure {\n const used = this.contextSize\n const limit = this.model?.spec.contextSize ?? 0\n const ratio = limit > 0 ? used / limit : 0\n const level = PRESSURE_LEVELS.findLast((t) => ratio >= t) ?? 0\n return { level, limit, ratio, used }\n }\n\n get lastStop(): AgentStop | undefined {\n return this.#lastStop\n }\n\n get steps(): number {\n return this.#stopPolicy.steps\n }\n\n get parent(): Agent | undefined {\n return this.#parent\n }\n\n get tools() {\n return this.#ctx.tools\n }\n\n get prompt() {\n return this.#ctx.prompt\n }\n\n get ctx(): AgentContext {\n return this.#ctx\n }\n\n /** Long-running task registry — exposed for the TUI / introspection\n * tools (`task_list`, etc.). Mutating directly is a foot-gun;\n * prefer the agent's higher-level surface. */\n get tasks(): Tasks {\n return this.#tasks\n }\n\n // ── Input ────────────────────────────────────────────────────────────\n\n #enqueue(message: Message | Message[], opts: { mode?: SendMode } = {}): void {\n const messages = Array.isArray(message) ? message : [message]\n if (!messages.length) return\n for (const m of messages) m.id ??= uuidv7()\n if (opts.mode === \"append\") this.#appendQueue.push(messages)\n else this.#injectQueue.push(...messages)\n void this.emit(\"pending\", { messages })\n }\n\n /** Queue messages and start/resume the loop when idle or paused.\n * `inject` (default) delivers before the next model step without\n * interrupting an active response or tool batch. `append` waits until\n * the current turn finishes naturally and no injections remain.\n * Injections batch in queue order; appends run one send() submission\n * at a time, keeping each submission's messages together.\n * With `run: false`, only enqueue; omit messages to start/resume\n * processing already queued work. */\n send(message?: Message | Message[], opts: { mode?: SendMode; run?: boolean } = {}): void {\n this.#enqueue(message ?? [], opts)\n if (opts.run === false) return\n if (this.#status === \"idle\" || this.#status === \"paused\") void this.run()\n }\n\n async useTool<T extends Tool = Tool>(\n name: T[\"name\"],\n params: ParamsOf<T>,\n msg: string,\n opts: { hidden?: boolean } = {}\n ): Promise<{\n call: ToolCallPart<T[\"name\"], ParamsOf<T>>\n result: ToolResult<MetaOf<T>>\n messages: [Message<\"system\">, Message<\"assistant\">, Message<\"tool\">]\n }> {\n const tool = this.tools.find((t) => t.name === name) as T | undefined\n if (!tool) throw new Error(`cannot inject tool use: no tool named \"${name}\"`)\n\n const id = uuidv7()\n const call: ToolCallPart = { id, name, params, type: \"tool-call\" }\n const result = await runTool(tool, params, await this.#toolContext(), { preflight: false })\n const messages: [Message<\"system\">, Message<\"assistant\">, Message<\"tool\">] = [\n {\n content: [\n {\n content: msg,\n data: { tool: name },\n tag: \"user-tool-use\",\n type: \"meta\",\n },\n ],\n role: \"system\",\n },\n {\n content: [call],\n role: \"assistant\",\n },\n {\n content: [\n {\n content: result.content,\n error: result.error,\n id,\n isError: result.isError,\n meta: result.meta,\n name,\n type: \"tool-result\",\n },\n ],\n role: \"tool\",\n },\n ]\n\n if (opts.hidden) for (const m of messages) m.hidden = true\n\n return { call, messages, result: result as ToolResult<MetaOf<T>> }\n }\n\n notify(type: string, data: Content | Record<string, unknown>): void {\n const meta: MetaPart =\n typeof data === \"string\" || Array.isArray(data)\n ? { content: data, tag: type, type: \"meta\" }\n : { data, tag: type, type: \"meta\" }\n this.#notifyQueue.push(meta)\n }\n\n /** Schedule a one-shot wake-up at `delayMs` from now. The agent will\n * receive a system message at that time IF nothing else has woken\n * the loop in the meantime — task-done injects, heartbeats, and user\n * messages all auto-cancel pending wakeups (their job was to ensure\n * the agent gets a turn; if it's already getting one, the timer is\n * redundant).\n *\n * Cancelled wakeups don't silently disappear — their `hint`s, if any,\n * are folded into a system message that lands in the next step\n * alongside whatever woke the loop. The model sees the hints with a\n * `status=\"cancelled\"` marker so it knows the timer didn't fire.\n *\n * Returns the wakeup id (mostly for telemetry / TUI display — the\n * model can't usefully cancel it later, since by the time it has a\n * turn to call cancel, the wakeup has either fired or been cancelled\n * for it). */\n scheduleWakeup(opts: { delayMs: number; hint?: string }): string {\n const id = uuidv7()\n const timer = setTimeout(() => {\n this.#wakeups.delete(id)\n this.send({\n content: [{ data: { hint: opts.hint, id }, tag: \"wakeup\", type: \"meta\" }],\n role: \"system\",\n })\n }, opts.delayMs)\n timer.unref()\n this.#wakeups.set(id, { hint: opts.hint, timer })\n return id\n }\n\n /** Cancel all pending wakeups, surfacing their hints as a single\n * system message so the model can see what was queued. Called from\n * `#setStatus` whenever the agent transitions to `streaming` — that's\n * the unambiguous \"loop is active\" signal. */\n #cancelAllWakeups(): void {\n if (this.#wakeups.size === 0) return\n const carried: { id: string; hint: string }[] = []\n for (const [id, { hint, timer }] of this.#wakeups) {\n clearTimeout(timer)\n if (hint) carried.push({ hint, id })\n }\n this.#wakeups.clear()\n if (carried.length > 0) {\n const parts: MetaPart[] = carried.map((c) => ({\n data: { hint: c.hint, id: c.id, status: \"cancelled\" as const },\n tag: \"wakeup\",\n type: \"meta\",\n }))\n this.#injectQueue.push({ content: parts, role: \"system\" })\n }\n }\n\n // ── Loop control ─────────────────────────────────────────────────────\n\n /** Drive steps until the agent goes idle (no queued messages and\n * the model stopped naturally) or hits a non-recoverable stop.\n * Doubles as a resume from `paused` — drains queued messages and\n * picks the loop back up. If a run is already in flight, returns\n * the existing promise. */\n run(): Promise<AgentStopKind> {\n if (this.#running) return this.#running\n this.#pauseRequested = undefined\n this.#abortController = undefined\n this.#running = this.#loop()\n .catch((error) => {\n this.#opts.logger?.child(\"run\").error(error)\n return this.#stop(\n error instanceof Error && error.name === \"AbortError\" ? \"aborted\" : \"error\",\n error\n )\n })\n .finally(() => {\n this.#abortController = undefined\n this.#running = undefined\n })\n return this.#running\n }\n\n async #collect() {\n this.#abortController = new AbortController()\n const context = {\n cacheKey: this.ctx.session.id,\n messages: [...this.ctx.messages],\n prompt: this.prompt,\n sessionId: this.ctx.session.id,\n tools: this.tools,\n } satisfies Context\n await this.emitSerial(\"context\", context)\n const model = this.model\n if (!model) throw new Error(\"model must be loaded to collect\")\n return model.stream(context, this.#streamOpts())\n }\n\n #shouldAutoCompact(): boolean {\n const opts = toValue(this.#opts.compaction)\n const auto = opts?.enabled ?? true\n if (!auto) return false\n const threshold = opts?.threshold ?? 0.95\n return this.pressure.ratio >= threshold\n }\n\n #streamOpts(): ModelStreamOptions {\n const base = this.#opts.request ?? {}\n return {\n ...base,\n onEvent: (event) => {\n void this.emit(\"stream-event\", { event })\n try {\n void this.#opts.onEvent?.(event)\n } catch (error) {\n this.#opts.logger?.child(\"stream\").error(error)\n }\n },\n onUpdate: this.#opts.onUpdate,\n reasoning: { ...base.reasoning, effort: this.#ctx.reasoning },\n signal: this.#abortController?.signal,\n }\n }\n\n /** Run exactly one step. Useful for tests and custom drivers\n * that want to interleave logic between steps. */\n async step(): Promise<StepResult> {\n if (this.#shouldAutoCompact()) await this.compact()\n // Drain the notify queue into the inject queue as a single system message\n if (this.#notifyQueue.length > 0) {\n this.#injectQueue.push({\n content: this.#notifyQueue.splice(0),\n role: \"system\",\n })\n }\n\n // Drain injections from send(), notifications, wakeups, and hooks.\n // Sequential await preserves queue order in the session.\n for (const m of this.#injectQueue.splice(0)) await this.session.add(m)\n\n this.#setStatus(\"streaming\")\n\n let collected: AssistantMessage\n\n try {\n collected = await this.#collect()\n } catch (error) {\n const err = toError(error)\n const overflow = isContextOverflow({ message: err.message })\n if (overflow) this.#opts.logger?.warn(\"Context overflow detected:\", err)\n return {\n error: err,\n finishReason: overflow ? \"length\" : \"error\",\n kind: overflow ? \"context-overflow\" : \"error\",\n usage: { input: 0, output: 0 },\n }\n }\n\n this.#usage.add(collected.meta.usage)\n\n const result: Omit<StepResult, \"kind\"> = {\n finishReason: collected.meta.finishReason,\n message: collected,\n usage: collected.meta.usage,\n }\n\n // Silent-overflow check BEFORE committing the message — gives the\n // session a chance to drop it and retry on a compacted history.\n if (\n this.#opts.contextLimit !== undefined &&\n isContextOverflow({\n contextLimit: this.#opts.contextLimit,\n // Total prompt size = uncached input + cached reads + cached\n // writes. `usage.input` is uncached-only; the cache fields are\n // separate billing tiers that still occupy the context window.\n usageInput:\n result.usage.input + (result.usage.cacheRead ?? 0) + (result.usage.cacheWrite ?? 0),\n })\n )\n return { kind: \"context-overflow\", ...result }\n\n const calls = await this.#parseToolCalls(collected)\n await this.session.add(collected)\n\n if (calls.length === 0) return { kind: \"natural\", ...result }\n\n return {\n kind: \"tool-calls\",\n toolMessage: await this.#runTools(calls),\n ...result,\n }\n }\n\n async #parseToolCalls(message: Message): Promise<ToolCallPart[]> {\n if (typeof message.content === \"string\") return []\n const calls = message.content.filter((p): p is ToolCallPart => p.type === \"tool-call\")\n for (const call of calls) {\n const tool = this.tools.find((t) => t.name === call.name)\n if (!tool) continue\n try {\n call.params = (await tool.validator.cleanParams(call.params)) ?? call.params\n } catch {}\n }\n return calls\n }\n\n async compact(): Promise<void> {\n const prev = this.#status\n const pressure = this.pressure\n this.#setStatus(\"compacting\")\n this.#usage.resetLast()\n try {\n const { Compaction } = await import(\"./compaction/compactions.ts\")\n const opts: Partial<CompactionOptions> = {\n ...toValue(this.#opts.compaction),\n signal: this.#abortController?.signal,\n }\n const compactor = new Compaction(this, opts)\n await compactor.compact(pressure)\n } finally {\n this.#setStatus(prev)\n }\n }\n\n async #runTools(calls: ToolCallPart[]) {\n this.#setStatus(\"running-tools\")\n void this.emit(\"tool-calls\", { calls })\n for (const call of calls) void this.emit(\"tool-call\", { call })\n\n const emitted = new Set<string>()\n // The whole batch — including streamable promotion, parallel chains,\n // grace timing, and ownerRound suppression — lives in Tasks.run().\n // What lands back here is a 1:1 array of result parts ready to commit.\n // The skill tool (when active) is passed via `extraTools` so dispatch\n // can resolve `name: \"skill\"` calls without polluting `tasks.tools`.\n const resultParts = await this.#tasks.run(calls, await this.#toolContext(), {\n onResult: (call, result) => {\n emitted.add(call.id)\n void this.emit(\"tool-result\", { call, result })\n },\n })\n\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i]\n const part = resultParts[i]\n if (emitted.has(call.id)) continue\n void this.emit(\"tool-result\", {\n call,\n result: {\n content: part.content,\n error: part.error,\n isError: part.isError ?? false,\n meta: part.meta,\n },\n })\n }\n const message: Message<\"tool\"> = { content: resultParts, role: \"tool\" }\n await this.session.add(message)\n return message\n }\n\n /** Resolve when the agent is in a quiescent state — `idle` or\n * `paused`. If a run is currently in flight (or was just kicked off\n * synchronously by `send` / `inject` / a wakeup), waits for it to\n * settle before returning the final status. If no run is in flight,\n * resolves immediately with the current status.\n *\n * Use this in REPL-style drivers to await the loop without racing\n * with internally-triggered runs (the wakeup timer, heartbeat, or\n * task-completion injects all spawn `void this.run()` independently\n * of caller-driven `await agent.run()`). The `#running` promise is\n * set synchronously inside `run()` before any await point, so this\n * catches every kicked-off cycle including the one `send` just fired.\n *\n * Errors from the loop are swallowed — callers read `agent.lastError`\n * / `agent.lastStopReason` for diagnostics. The point of `waitIdle`\n * is just to know \"the loop is no longer driving.\" */\n async waitIdle(timeout?: number): Promise<AgentStatus> {\n if (!this.#running) return this.#status\n const wait = [this.#running.catch(() => undefined)]\n if (timeout !== undefined) wait.push(new Promise((resolve) => setTimeout(resolve, timeout)))\n await Promise.race(wait)\n return this.#status\n }\n\n /** Stop the loop with a custom reason.\n * When `abort: true` (the default), also trigger the abort signal so any\n * in-flight stream or tool calls can react to the stop.\n * When `abort: false`, the agent still stops immediately, but any active\n * stream or tool calls are left to run to completion */\n stop(opts: { abort?: boolean; reason?: string } = {}): void {\n this.#pauseRequested ??= opts.reason ?? \"stop\"\n if (opts.abort ?? true) this.#abortController?.abort(opts.reason)\n }\n\n async start() {\n if (this.#started) return\n this.#started = true\n await this.emit(\"start\")\n }\n\n get started() {\n return this.#started\n }\n\n // ── Internals ────────────────────────────────────────────────────────\n\n async #turn(): Promise<TurnResult> {\n for (let step = 1; ; step++) {\n if (this.#abortController?.signal.aborted)\n return { kind: \"aborted\", reason: this.#abortController.signal.reason }\n if (this.#pauseRequested !== undefined)\n return { kind: \"paused\", reason: this.#pauseRequested }\n\n void this.emit(\"step-start\", { step })\n const outcome = await this.step()\n void this.emit(\"step-end\", { outcome: outcome.kind, step })\n\n if (outcome.kind === \"error\") {\n return {\n kind: outcome.error?.name === \"AbortError\" ? \"aborted\" : \"error\",\n reason: outcome.error,\n }\n }\n\n if (outcome.kind === \"natural\") {\n return { kind: \"natural\" }\n }\n\n if (outcome.kind === \"context-overflow\") {\n // Auto-compaction also gates the overflow recovery path. With\n // `auto: false`, overflow stops cleanly instead of attempting\n // a recovery the user explicitly opted out of.\n if (toValue(this.#opts.compaction)?.enabled === false) return { kind: \"context-overflow\" }\n // Compactor mutates the conversation; the rejected message is\n // not committed — next step retries on the compacted state.\n this.#opts.logger\n ?.child(\"compaction\")\n .warn(\n `context overflow detected (size ${this.contextSize}, limit ${this.pressure.limit}); running compaction`\n )\n await this.compact()\n continue\n }\n\n // outcome.kind === \"tool-calls\" — consult the policy.\n const stop = this.#stopPolicy.detect()\n if (stop) return { kind: stop }\n }\n }\n\n async #loop(): Promise<AgentStopKind> {\n if (!this.#started) await this.start()\n // Reset per-run counters (steps, consecutive errors, call history).\n // Token totals stay sticky across resets — they're billing-style\n // displays, not per-turn caps.\n this.#stopPolicy.reset()\n for (let turn = 1; ; turn++) {\n // Start one append submission only after pending injections have settled.\n if (this.#injectQueue.length === 0)\n for (const m of this.#appendQueue.shift() ?? []) await this.session.add(m)\n\n void this.emit(\"turn-start\", { turn })\n const result = await this.#turn()\n const reason = result.reason ? toError(result.reason).message : undefined\n void this.emit(\"turn-end\", { outcome: result.kind, reason, turn })\n\n // If the model stopped naturally but there are still queued messages,\n // keep the loop alive to process them.\n if (\n result.kind === \"natural\" &&\n (this.#injectQueue.length > 0 || this.#appendQueue.length > 0)\n )\n continue\n\n return this.#stop(result.kind, result.reason)\n }\n }\n\n #stop(kind: AgentStopKind, reason?: unknown): AgentStopKind {\n this.#lastStop = {\n error: reason instanceof Error ? reason : undefined,\n kind,\n reason: reason === undefined ? undefined : toError(reason).message,\n }\n this.#setStatus(kind === \"natural\" ? \"idle\" : \"paused\")\n void this.emit(\"stop\", {\n status: this.#status,\n usage: this.usage,\n ...this.#lastStop,\n })\n return kind\n }\n\n /** Build the per-step `ToolContext` handed to each tool. The session\n * cwd, an abort signal scoped to the in-flight stream, and the\n * long-running spawn registry are all surfaced here. */\n async #toolContext(): Promise<ToolContext> {\n const masker = await this.#ctx.masker()\n return {\n agent: this,\n bash: this.#opts.bash,\n cwd: this.cwd,\n isMasked: (msgId: string, partIdx?: number) => masker?.isMasked(msgId, partIdx) ?? false,\n messages: this.session.messages,\n need: (scope, input) => this.#need(scope, input),\n perms: await this.ctx.permissions(),\n sessionDir: this.session.dir,\n signal: this.#abortController?.signal,\n swarm: () => this.#ctx.swarm(),\n tasks: this.#tasks,\n }\n }\n\n /** Implementation of `ctx.need(scope, input)`. Resolves on `allow`,\n * throws a `PERMISSION_DENIED` `AiError` on `deny`, and escalates\n * `ask` to `AgentOptions.allow` (treating it as `deny` when no\n * callback is configured). */\n async #need(scope: string, input: string): Promise<void> {\n const perms = await this.ctx.permissions()\n const r = perms.validate(scope, input)\n if (r.verdict === \"allow\") return\n if (r.verdict === \"ask\" && this.#opts.allow) {\n const ok = await this.#opts.allow({\n ask: r.ask,\n input,\n reason: r.reason,\n scope,\n suggestions: r.suggestions,\n })\n if (ok) return\n }\n throw new AiError({\n code: \"PERMISSION_DENIED\",\n data: { input, scope, suggestions: r.suggestions, verdict: r.verdict },\n message: r.reason,\n // `ask` verdicts that the user denied this turn are retryable —\n // they may add a rule later. Hard `deny` is not.\n retryable: r.verdict === \"ask\",\n })\n }\n\n /** Tear down session-scoped resources. Called on agent disposal — the\n * agent doesn't auto-dispose today, so callers (TUI on quit, headless\n * runner on completion) should invoke this explicitly. */\n async dispose(): Promise<void> {\n this.clearListeners()\n this.#cancelAllWakeups()\n await this.#tasks.killAll()\n }\n\n #setStatus(status: AgentStatus): void {\n const prev = this.#status\n if (prev === status) return\n // Cancel wakeups only when an EXTERNAL wake-up brings the loop back\n // to active (idle/paused → streaming). Mid-turn transitions\n // (running-tools → streaming) are the same turn continuing — a\n // wakeup the model just scheduled mid-tool-call would otherwise be\n // killed before it ever fires. The \"external wake-up\" cases that\n // *should* cancel: a `task-done` inject, a heartbeat, a user\n // message — all route through `inject` → `send` → `run` from the\n // idle/paused state, hitting this branch correctly.\n if (status === \"streaming\" && (prev === \"idle\" || prev === \"paused\")) {\n this.#cancelAllWakeups()\n }\n this.#status = status\n void this.emit(\"status\", { status })\n }\n}\n"],"mappings":";;;;;;;;AAKA,SAAgB,SAAS,GAAU,GAAiB;CAClD,MAAM,MAAa;EACjB,OAAO,EAAE,QAAQ,EAAE;EACnB,QAAQ,EAAE,SAAS,EAAE;CACvB;CACA,IAAI,EAAE,cAAc,KAAA,KAAa,EAAE,c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AAO,UAAU,KAAK,MAAM,OAAO,KAAK;GAC/C,OAAO,MAAM,KAAK,IAAI,YAAY;GAClC,YAAY,KAAK,QAAQ;GACzB,QAAQ,KAAK,kBAAkB;GAC/B,aAAa,KAAK,KAAK,MAAM;GAC7B,OAAO,KAAK;EACd;CACF;;;;;CAMA,MAAM,MAAM,OAAe,OAA8B;EAEvD,MAAM,KAAI,MADU,KAAK,IAAI,YAAY,EAAA,CACzB,SAAS,OAAO,KAAK;EACrC,IAAI,EAAE,YAAY,SAAS;EAC3B,IAAI,EAAE,YAAY,SAAS,KAAK,MAAM,OAQhC;OAAA,MAPa,KAAK,MAAM,MAAM;IAChC,KAAK,EAAE;IACP;IACA,QAAQ,EAAE;IACV;IACA,aAAa,EAAE;GACjB,CAAC,GACO;EAAA;EAEV,MAAM,IAAI,QAAQ;GAChB,MAAM;GACN,MAAM;IAAE;IAAO;IAAO,aAAa,EAAE;IAAa,SAAS,EAAE;GAAQ;GACrE,SAAS,EAAE;GAGX,WAAW,EAAE,YAAY;EAC3B,CAAC;CACH;;;;CAKA,MAAM,UAAyB;EAC7B,KAAK,eAAe;EACpB,KAAK,kBAAkB;EACvB,MAAM,KAAK,OAAO,QAAQ;CAC5B;CAEA,WAAW,QAA2B;EACpC,MAAM,OAAO,KAAK;EAClB,IAAI,SAAS,QAAQ;EASrB,IAAI,WAAW,gBAAgB,SAAS,UAAU,SAAS,WACzD,KAAK,kBAAkB;EAEzB,KAAK,UAAU;EACf,KAAU,KAAK,UAAU,EAAE,OAAO,CAAC;CACrC;AACF"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"compactions-HFjEgrv3.mjs","names":[],"sources":["../src/compaction/prompt.ts","../src/compaction/compactions.ts"],"sourcesContent":["/* Prompts for generating a checkpoint and framing it for the resumed agent. */\n\nexport const SYSTEM_PROMPT = `Summarize the supplied conversation into a structured context checkpoint for your future self to resume the work. Do not continue the conversation or answer questions in it.\n\nUse this format, omitting empty sections:\n\n## Goal\nWhat the user is trying to accomplish and what they have authorized.\n\n## Constraints & Preferences\nImportant requirements, boundaries, and user corrections.\n\n## Progress\nCompleted work, work in progress, and blockers. Include outstanding tasks or tool results needed to resume.\n\n## Key Decisions\nWhat was chosen or rejected, with brief rationale.\n\n## Next Steps\nWhat remains to be done, in order. Do not invent work if the task is complete.\n\n## Critical Context\nEssential data, references, and artifact paths, with a brief explanation of why they matter.\n\nBe concise and readable. Preserve exact paths, identifiers, commands, and errors when needed to continue accurately. Distinguish verified results from proposals and uncertainty; do not infer missing tool results.\n\nSummarize user intent rather than listing every message. File and command usage tables are included separately: do not reproduce their inventories or infer outcomes from them. Mention only files and commands whose significance needs explaining.\n\nConsolidate previous summaries with newer evidence, removing repetition and superseded state while retaining relevant constraints and decisions.`\n\nexport const SUMMARY_PROMPT = `Create the context checkpoint summary now, using the format above. Output only the summary.`\n\nexport const PREVIOUS_SUMMARY_PROMPT = `Incorporate this prior summary into the new checkpoint, retaining relevant context and updating superseded state from the conversation.`\n\n/** Shown to the resumed agent, not the summarizer. */\nexport const SUMMARY_HEADER = `The older conversation has been compacted into the summary below. Recent messages follow verbatim and may supersede it. Use both to continue where the conversation left off without repeating completed work.\n\nFile and command usage tables cover the full conversation and are navigation aids, not evidence of results. If necessary information is missing, consult the referenced artifacts or ask rather than guess.`\n","import type { Message, ReasoningEffort } from \"@zaly/ai\"\nimport type { Agent } from \"../agent.ts\"\nimport type { ContextPressure } from \"../types.ts\"\nimport type { ToolStatOptions } from \"./utils.ts\"\n\nimport { toXml } from \"@zaly/ai\"\nimport { SUMMARY_HEADER, SUMMARY_PROMPT, SYSTEM_PROMPT } from \"./prompt.ts\"\nimport {\n extractBashUsage,\n extractConversation,\n extractFileUsage,\n formatBashUsage,\n formatFileUsage,\n messageTail,\n} from \"./utils.ts\"\n\nexport type CompactionOptions = {\n enabled: boolean\n threshold?: number\n /** Existing messages up to this many tokens will be preserved in the context */\n keepTokens: number\n maxToolResultLen: number\n summaryTokens: number\n bash: ToolStatOptions\n files: ToolStatOptions\n signal?: AbortSignal\n reasoning?: ReasoningEffort\n trigger?: \"manual\" | \"auto\"\n}\n\nconst defaults: CompactionOptions = {\n bash: { limit: 50, minCount: 2, minScore: 0.5, sort: \"score\" },\n enabled: true,\n files: { limit: 50, minCount: 1, minScore: 0.5, sort: \"score\" },\n keepTokens: 20_000,\n maxToolResultLen: 2000,\n reasoning: \"low\",\n summaryTokens: 10_000,\n threshold: 0.95,\n}\n\nexport class Compaction {\n #opts: CompactionOptions\n #agent: Agent\n\n constructor(agent: Agent, opts: Partial<CompactionOptions> = {}) {\n this.#agent = agent\n this.#opts = { ...defaults, ...opts }\n }\n\n async compact(pressure: ContextPressure): Promise<void> {\n const { session } = this.#agent\n\n const masker = await this.#agent.ctx.masker()\n\n const messages = masker ? await masker.mask(session.messages, pressure) : session.messages\n\n const now = performance.now()\n\n const tail = messageTail(messages, { keepTokens: this.#opts.keepTokens })\n const older = tail.length > 0 ? messages.slice(0, -tail.length) : messages\n\n if (older.length === 0) return\n\n const conversation = extractConversation(\n // Conversation summary is based on the older messages, not the tail — the tail is what we keep\n older,\n { maxToolResultLen: this.#opts.maxToolResultLen }\n )\n\n const bashUsage = formatBashUsage(extractBashUsage(messages, this.#opts.bash))\n const fileUsage = formatFileUsage(extractFileUsage(messages, this.#opts.files))\n\n const request: Message<\"user\"> = {\n content: [\n { text: conversation, type: \"text\" },\n { text: fileUsage, type: \"text\" },\n { text: bashUsage, type: \"text\" },\n { text: SUMMARY_PROMPT, type: \"text\" },\n ],\n role: \"user\",\n }\n\n const summary = await this.#summarize(request)\n // The bash + file usage tables are deterministic, ground-truth signals\n // — pricier to ask the model to reproduce than to copy verbatim. Carry\n // them through to the resumed agent so it has the same working-set\n // visibility the summarizer had, without paying for output tokens.\n const summaryMessage: Message<\"system\"> = {\n content: [\n { text: SUMMARY_HEADER, type: \"text\" },\n { text: toXml(summary, \"compaction-summary\", { indent: false }), type: \"text\" },\n { text: fileUsage, type: \"text\" },\n { text: bashUsage, type: \"text\" },\n ],\n meta: { kind: \"compaction-summary\" },\n role: \"system\",\n }\n await session.compact({\n durationMs: Math.round(performance.now() - now),\n preTokens: this.#agent.contextSize,\n summary: summaryMessage,\n tail: tail.length,\n trigger: this.#opts.trigger,\n })\n masker?.reset()\n }\n\n async #summarize(message: Message<\"user\">): Promise<string> {\n const model = this.#agent.model\n if (!model) throw new Error(\"model must be loaded to compact\")\n const m = await model.stream(\n {\n messages: [message],\n prompt: [SYSTEM_PROMPT],\n sessionId: this.#agent.session.id,\n },\n {\n caching: false,\n maxTokens: this.#opts.summaryTokens,\n reasoning: this.#opts.reasoning ? { effort: this.#opts.reasoning } : undefined,\n signal: this.#opts.signal,\n }\n )\n if (typeof m.content === \"string\") return m.content\n const parts = m.content.filter((p) => p.type === \"text\").map((p) => p.text)\n return parts.join(\"\\n\")\n }\n}\n"],"mappings":";;;AAEA,MAAa,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4B7B,MAAa,iBAAiB;;AAK9B,MAAa,iBAAiB;;;;ACL9B,MAAM,WAA8B;CAClC,MAAM;EAAE,OAAO;EAAI,UAAU;EAAG,UAAU;EAAK,MAAM;CAAQ;CAC7D,SAAS;CACT,OAAO;EAAE,OAAO;EAAI,UAAU;EAAG,UAAU;EAAK,MAAM;CAAQ;CAC9D,YAAY;CACZ,kBAAkB;CAClB,WAAW;CACX,eAAe;CACf,WAAW;AACb;AAEA,IAAa,aAAb,MAAwB;CACtB;CACA;CAEA,YAAY,OAAc,OAAmC,CAAC,GAAG;EAC/D,KAAK,SAAS;EACd,KAAK,QAAQ;GAAE,GAAG;GAAU,GAAG;EAAK;CACtC;CAEA,MAAM,QAAQ,UAA0C;EACtD,MAAM,EAAE,YAAY,KAAK;EAEzB,MAAM,SAAS,MAAM,KAAK,OAAO,IAAI,OAAO;EAE5C,MAAM,WAAW,SAAS,MAAM,OAAO,KAAK,QAAQ,UAAU,QAAQ,IAAI,QAAQ;EAElF,MAAM,MAAM,YAAY,IAAI;EAE5B,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