@zaly/agent 0.0.6 → 0.0.10

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.
Files changed (47) hide show
  1. package/dist/{agent-BaD2kax9.mjs → agent-B7cQOuMZ.mjs} +2 -2
  2. package/dist/agent-B7cQOuMZ.mjs.map +1 -0
  3. package/dist/{agent-DirSoZjM.mjs → agent-D3wVIibN.mjs} +3 -3
  4. package/dist/{agent-DirSoZjM.mjs.map → agent-D3wVIibN.mjs.map} +1 -1
  5. package/dist/{compactions-3AjPqjeZ.mjs → compactions-B8VdZJoU.mjs} +2 -2
  6. package/dist/{compactions-3AjPqjeZ.mjs.map → compactions-B8VdZJoU.mjs.map} +1 -1
  7. package/dist/{edit-Qxl4w1C2.mjs → edit-D4yaBK1K.mjs} +9 -17
  8. package/dist/edit-D4yaBK1K.mjs.map +1 -0
  9. package/dist/{fetch-DXuxAg_t.mjs → fetch-VKhSWdEh.mjs} +2 -2
  10. package/dist/{fetch-DXuxAg_t.mjs.map → fetch-VKhSWdEh.mjs.map} +1 -1
  11. package/dist/{find-Bah9SKWX.mjs → find-CimUGn-L.mjs} +6 -20
  12. package/dist/find-CimUGn-L.mjs.map +1 -0
  13. package/dist/{grep-B4GF0svc.mjs → grep-6O3mjSvV.mjs} +10 -78
  14. package/dist/grep-6O3mjSvV.mjs.map +1 -0
  15. package/dist/{index-node-esm-DAnl9SaE.mjs → index-node-esm-CJsN8G51.mjs} +5 -3
  16. package/dist/index-node-esm-CJsN8G51.mjs.map +1 -0
  17. package/dist/index.d.mts +20 -37
  18. package/dist/index.d.mts.map +1 -1
  19. package/dist/index.mjs +3 -953
  20. package/dist/{manager-DHBfEtge.mjs → manager-BqlbCGYV.mjs} +2 -2
  21. package/dist/{manager-DHBfEtge.mjs.map → manager-BqlbCGYV.mjs.map} +1 -1
  22. package/dist/{masker-Bv9KjkDF.mjs → masker-DRFztUwc.mjs} +2 -2
  23. package/dist/{masker-Bv9KjkDF.mjs.map → masker-DRFztUwc.mjs.map} +1 -1
  24. package/dist/{read-Djsx2NZl.mjs → read-CSL_8nAk.mjs} +47 -63
  25. package/dist/read-CSL_8nAk.mjs.map +1 -0
  26. package/dist/{registry-Bao6L4Ue.mjs → registry-L9GDccS0.mjs} +2 -2
  27. package/dist/{registry-Bao6L4Ue.mjs.map → registry-L9GDccS0.mjs.map} +1 -1
  28. package/dist/{session-B1lXSWhT.mjs → session-BSvUrr12.mjs} +2 -2
  29. package/dist/{session-B1lXSWhT.mjs.map → session-BSvUrr12.mjs.map} +1 -1
  30. package/dist/session.mjs +1 -1
  31. package/dist/src-fK6DL2bg.mjs +953 -0
  32. package/dist/src-fK6DL2bg.mjs.map +1 -0
  33. package/dist/{subagent-Zz-MQHk2.mjs → subagent-C8XCEecM.mjs} +2 -2
  34. package/dist/{subagent-Zz-MQHk2.mjs.map → subagent-C8XCEecM.mjs.map} +1 -1
  35. package/dist/{tools-CZvBFp-v.mjs → tools-wvkkuXWH.mjs} +2 -2
  36. package/dist/{tools-CZvBFp-v.mjs.map → tools-wvkkuXWH.mjs.map} +1 -1
  37. package/dist/{write-D3L-92vj.mjs → write-DwGiDNeG.mjs} +3 -11
  38. package/dist/write-DwGiDNeG.mjs.map +1 -0
  39. package/package.json +6 -6
  40. package/dist/agent-BaD2kax9.mjs.map +0 -1
  41. package/dist/edit-Qxl4w1C2.mjs.map +0 -1
  42. package/dist/find-Bah9SKWX.mjs.map +0 -1
  43. package/dist/grep-B4GF0svc.mjs.map +0 -1
  44. package/dist/index-node-esm-DAnl9SaE.mjs.map +0 -1
  45. package/dist/index.mjs.map +0 -1
  46. package/dist/read-Djsx2NZl.mjs.map +0 -1
  47. package/dist/write-D3L-92vj.mjs.map +0 -1
@@ -0,0 +1,953 @@
1
+ import { i as __exportAll, n as parseBash, t as TOOLS } from "./tools-wvkkuXWH.mjs";
2
+ import "./registry-L9GDccS0.mjs";
3
+ import { Emitter, formatDuration, isInstance, normPath, prettyPath, safeReadFile, safeStatAsync, safeStringify, toError } from "@zaly/shared";
4
+ import { LazyCache } from "@zaly/shared/cache";
5
+ import { BaseCollection } from "@zaly/shared/collection";
6
+ import { createRegistry } from "@zaly/shared/registry";
7
+ import { basename, dirname } from "pathe";
8
+ import { AiError, ContentTransform, attachmentToMeta, defineTool, errorToMeta, extractToolCalls, extractToolResults, metaToText, safeParseToolParams, sanitizeText, stringifyContent, toXml } from "@zaly/ai";
9
+ import { glob } from "@zaly/shared/glob";
10
+ import { readFile } from "node:fs/promises";
11
+ import { isDeepStrictEqual } from "node:util";
12
+ import { Type } from "typebox";
13
+ //#region src/ctx.ts
14
+ var ctx_exports = /* @__PURE__ */ __exportAll({
15
+ AgentContext: () => AgentContext,
16
+ createAgent: () => createAgent,
17
+ createAgentContext: () => createAgentContext
18
+ });
19
+ var AgentContext = class extends Emitter {
20
+ #agent;
21
+ #opts;
22
+ #model;
23
+ #session;
24
+ #reasoning;
25
+ #cwd;
26
+ #cache = new LazyCache();
27
+ #tools;
28
+ #skills;
29
+ #prompt;
30
+ constructor(opts) {
31
+ super();
32
+ this.#opts = opts;
33
+ this.#cwd = normPath(opts.cwd);
34
+ this.#reasoning = opts.request?.reasoning?.effort ?? "medium";
35
+ this.#session = opts.session;
36
+ this.#model = opts.model;
37
+ this.#skills = opts.skills;
38
+ this.#prompt = opts.prompt ?? [];
39
+ this.#tools = opts.tools ?? [];
40
+ this.onEmitError = (error) => this.#opts.logger?.child("context").error(error);
41
+ this.on("model", async ({ model }) => {
42
+ if (!this.#session.started) return;
43
+ if (model) await this.session.update({ modelId: model.id });
44
+ }).on("reasoning", async ({ effort }) => {
45
+ if (!this.#session.started) return;
46
+ await this.session.update({ reasoning: effort });
47
+ }).on("cwd", ({ cwd }) => {
48
+ if (!this.#session.started) return;
49
+ this.#cache.forget("permissions");
50
+ this.session.update({ cwd });
51
+ });
52
+ }
53
+ async start() {
54
+ const [_masker, notifier] = await Promise.all([this.masker(), this.notifier()]);
55
+ if (!this.model) throw new Error("model is required to start agent session");
56
+ if (notifier) notifier.attach(this.agent);
57
+ await this.session.start({
58
+ cwd: this.cwd,
59
+ modelId: this.model.id,
60
+ reasoning: this.reasoning
61
+ });
62
+ for (const m of this.#opts.messages ?? []) await this.session.add(m);
63
+ }
64
+ attach(agent) {
65
+ if (this.#agent === agent) return;
66
+ if (this.#agent) throw new Error("agent already attached to context");
67
+ if (agent.started) throw new Error("cannot attach agent that has already started");
68
+ this.#agent = agent;
69
+ agent.once("start", () => this.start());
70
+ }
71
+ get messages() {
72
+ return this.session.messages;
73
+ }
74
+ get status() {
75
+ return this.#agent?.status;
76
+ }
77
+ get opts() {
78
+ return this.#opts;
79
+ }
80
+ get cwd() {
81
+ return this.#cwd;
82
+ }
83
+ set cwd(c) {
84
+ if (c === this.#cwd) return;
85
+ const prev = this.#cwd;
86
+ this.#cwd = normPath(c);
87
+ this.emit("cwd", {
88
+ cwd: this.#cwd,
89
+ prev
90
+ });
91
+ }
92
+ get signal() {
93
+ return this.#agent?.signal;
94
+ }
95
+ get agent() {
96
+ if (!this.#agent) throw new Error("agent not attached to context");
97
+ return this.#agent;
98
+ }
99
+ get reasoning() {
100
+ return this.#reasoning;
101
+ }
102
+ set reasoning(r) {
103
+ if (r === this.#reasoning) return;
104
+ const prev = this.#reasoning;
105
+ this.#reasoning = r;
106
+ this.emit("reasoning", {
107
+ effort: r,
108
+ prev
109
+ });
110
+ }
111
+ get session() {
112
+ return this.#session;
113
+ }
114
+ async useSession(s) {
115
+ const prev = this.#session;
116
+ this.#session = s;
117
+ const modelId = s.settings.modelId;
118
+ if (modelId && modelId !== this.model?.id) {
119
+ if (this.#opts.loadModel) this.model = await this.#opts.loadModel(modelId);
120
+ else {
121
+ const { loadModel } = await import("@zaly/ai");
122
+ this.model = await loadModel(modelId);
123
+ }
124
+ }
125
+ this.cwd = s.settings.cwd ?? this.cwd;
126
+ this.reasoning = s.settings.reasoning ?? this.reasoning;
127
+ await this.emit("session", {
128
+ prev,
129
+ session: s
130
+ });
131
+ if (this.#agent?.started) await s.start({
132
+ cwd: this.cwd,
133
+ modelId: this.model?.id,
134
+ reasoning: this.reasoning
135
+ });
136
+ }
137
+ get model() {
138
+ return this.#model;
139
+ }
140
+ set model(m) {
141
+ if (m === this.#model) return;
142
+ const prev = this.#model;
143
+ this.#model = m;
144
+ this.emit("model", {
145
+ model: m,
146
+ prev
147
+ });
148
+ }
149
+ set tools(tools) {
150
+ this.#tools = tools;
151
+ }
152
+ get tools() {
153
+ return [...this.#tools, ...this.skills?.tool ? [this.skills.tool] : []];
154
+ }
155
+ get prompt() {
156
+ return this.#prompt;
157
+ }
158
+ set prompt(p) {
159
+ this.#prompt = p;
160
+ }
161
+ async swarm() {
162
+ return this.#cache.need("swarm", async () => {
163
+ const { Swarm } = await import("./swarm-BJ3gQA1Z.mjs");
164
+ return new Swarm();
165
+ }, this.#opts.swarm);
166
+ }
167
+ set skills(s) {
168
+ if (s === this.#skills) return;
169
+ this.#skills = s;
170
+ this.emit("skills", { skills: s });
171
+ }
172
+ get skills() {
173
+ return this.#skills;
174
+ }
175
+ async notifier() {
176
+ return this.#cache.want("notifier", async (opts) => {
177
+ const { Notifier } = await import("./notify-DpG_m9iP.mjs");
178
+ return new Notifier(opts);
179
+ }, this.#opts.notify);
180
+ }
181
+ async masker() {
182
+ return this.#cache.want("masker", async (opts) => {
183
+ const { Masker } = await import("./masker-DRFztUwc.mjs");
184
+ return new Masker(this.agent, opts);
185
+ }, this.#opts.mask);
186
+ }
187
+ async permissions() {
188
+ return this.#cache.need("permissions", async (opts) => {
189
+ const { PermissionManager } = await import("./manager-BqlbCGYV.mjs");
190
+ return new PermissionManager({
191
+ ...opts,
192
+ cwd: this.cwd
193
+ });
194
+ }, this.#opts.permissions);
195
+ }
196
+ };
197
+ async function loadSession(spec) {
198
+ if (isInstance(spec)) return spec;
199
+ else {
200
+ const { Session } = await import("./session-BSvUrr12.mjs").then((n) => n.n);
201
+ return await Session.load({ ...spec });
202
+ }
203
+ }
204
+ async function createAgentContext(opts) {
205
+ const session = await loadSession(opts.session);
206
+ return new AgentContext({
207
+ ...opts,
208
+ session
209
+ });
210
+ }
211
+ async function createAgent(opts) {
212
+ const [{ Agent }, ctx] = await Promise.all([import("./agent-D3wVIibN.mjs"), createAgentContext(opts)]);
213
+ return new Agent(ctx);
214
+ }
215
+ const promptRegistry = createRegistry("prompt").from({
216
+ "AGENTS.md": (ctx) => import("./markdown-Bv4J8cg3.mjs").then((m) => m.agentsMdPrompt(ctx)),
217
+ "MEMORY.md": (ctx) => import("./markdown-Bv4J8cg3.mjs").then((m) => m.memoryMdPrompt(ctx)),
218
+ agent: () => import("./agent-B7cQOuMZ.mjs").then((m) => m.agentPrompt),
219
+ env: (ctx) => import("./env-UUFv5Mye.mjs").then((m) => m.prompt(ctx)),
220
+ model: (ctx) => import("./model-_3ZA2xqm.mjs").then((m) => m.prompt(ctx))
221
+ });
222
+ var PromptCollection = class extends BaseCollection {
223
+ list() {
224
+ const ret = /* @__PURE__ */ new Map();
225
+ for (const k of promptRegistry.keys()) ret.set(k, {
226
+ name: k,
227
+ text: (ctx) => promptRegistry.load(k, ctx)
228
+ });
229
+ for (const r of this.registered) ret.set(r.name, r);
230
+ return [...ret.values()];
231
+ }
232
+ async render(ctx) {
233
+ const all = new Map(this.list().map((p) => [p.name, p]));
234
+ return (await Promise.all((ctx.prompts ?? this.active).map(async (p) => {
235
+ const def = all.get(p);
236
+ if (!def) throw new Error(`Unknown prompt: ${p}`);
237
+ return {
238
+ name: def.name,
239
+ text: typeof def.text === "string" ? def.text : await def.text(ctx)
240
+ };
241
+ }))).map((p) => ({
242
+ name: p.name,
243
+ text: p.text.trim()
244
+ })).filter((p) => p.text.length > 0);
245
+ }
246
+ };
247
+ async function promptCollection() {
248
+ return new PromptCollection([
249
+ "agent",
250
+ "env",
251
+ "model",
252
+ "AGENTS.md",
253
+ "MEMORY.md"
254
+ ]);
255
+ }
256
+ const toolRegistry = createRegistry("tool").from({
257
+ agent_send: () => import("./swarm-BuFx_xeY.mjs").then((m) => m.agentSendTool),
258
+ agent_spawn: () => import("./swarm-BuFx_xeY.mjs").then((m) => m.agentSpawnTool),
259
+ bash: () => import("./bash-COgq4W7U.mjs").then((m) => m.bashTool),
260
+ edit: () => import("./edit-D4yaBK1K.mjs").then((m) => m.editTool),
261
+ fetch: () => import("./fetch-VKhSWdEh.mjs").then((m) => m.fetchTool),
262
+ find: () => import("./find-CimUGn-L.mjs").then((m) => m.findTool),
263
+ grep: () => import("./grep-6O3mjSvV.mjs").then((m) => m.grepTool),
264
+ read: () => import("./read-CSL_8nAk.mjs").then((m) => m.readTool),
265
+ search: () => import("./search-CRw247ES.mjs").then((m) => m.searchTool),
266
+ subagent: () => import("./subagent-C8XCEecM.mjs").then((m) => m.subagentTool),
267
+ task_list: () => import("./tasks-BA-PCeGa.mjs").then((m) => m.taskListTool),
268
+ task_poll: () => import("./tasks-BA-PCeGa.mjs").then((m) => m.taskPollTool),
269
+ task_stop: () => import("./tasks-BA-PCeGa.mjs").then((m) => m.taskStopTool),
270
+ wakeup: () => import("./wakeup-BYqTnfSp.mjs").then((m) => m.wakeupTool),
271
+ write: () => import("./write-DwGiDNeG.mjs").then((m) => m.writeTool)
272
+ });
273
+ var ToolCollection = class extends BaseCollection {
274
+ list() {
275
+ const ret = new Set(toolRegistry.keys());
276
+ for (const r of this.registered) ret.add(r.name);
277
+ return [...ret];
278
+ }
279
+ async load(tools) {
280
+ const load = async (t) => this.registered.findLast((r) => r.name === t) ?? toolRegistry.load(t);
281
+ return await Promise.all((tools ?? this.active).map((t) => load(t)));
282
+ }
283
+ };
284
+ async function toolCollection() {
285
+ return new ToolCollection([]);
286
+ }
287
+ //#endregion
288
+ //#region src/commands.ts
289
+ const BASH_RE = /^!`(.*)`$/;
290
+ var Commands = class {
291
+ #opts;
292
+ catalog = /* @__PURE__ */ new Map();
293
+ #logger;
294
+ constructor(opts = {}) {
295
+ this.#opts = opts;
296
+ this.#logger = opts.logger;
297
+ }
298
+ async load() {
299
+ const paths = this.#opts.paths ?? [];
300
+ await Promise.all(paths.map(async (path) => await this.add(path)));
301
+ return this;
302
+ }
303
+ async add(path) {
304
+ path = normPath(path);
305
+ const name = basename(path, ".md");
306
+ const { parseFrontmatter } = await import("@zaly/shared/yaml");
307
+ try {
308
+ const content = await safeReadFile(path);
309
+ if (!content) throw new Error(`Failed to read command file at ${path}`);
310
+ const { fm, body } = await parseFrontmatter(content);
311
+ const args = {};
312
+ const fmArgs = fm.args ?? {};
313
+ for (const [o, opt] of Object.entries(fmArgs)) {
314
+ if (opt.type === "boolean") opt.default ??= false;
315
+ else if (opt.type === "string") opt.required ??= opt.default === void 0;
316
+ else {
317
+ this.#logger?.warn(`Unsupported argument type for \`--${o}\` in command **${name}** at \`${prettyPath(path)}\`\nOnly \`string\` and \`boolean\` are supported. Skipping this argument.`);
318
+ continue;
319
+ }
320
+ args[o] = opt;
321
+ }
322
+ const cmd = {
323
+ ...fm,
324
+ args,
325
+ body,
326
+ name,
327
+ path
328
+ };
329
+ if (this.catalog.has(name)) return;
330
+ this.catalog.set(name, cmd);
331
+ } catch (error) {
332
+ this.#logger?.error(`Error loading **command** from ${path}: ${error.message}`);
333
+ }
334
+ }
335
+ get(name) {
336
+ return this.catalog.get(name);
337
+ }
338
+ async format(input, cmd) {
339
+ let args;
340
+ if (typeof input === "string") {
341
+ const { argsParse } = await import("@zaly/shared/args");
342
+ args = await argsParse(input, cmd.args);
343
+ } else args = input;
344
+ const { createTemplate } = await import("@zaly/shared/template");
345
+ const rendered = createTemplate(cmd.body, {
346
+ expr: this.#opts.expr,
347
+ format: (value) => {
348
+ if (value === args._) return args._.join(" ");
349
+ },
350
+ name: cmd.name
351
+ })({
352
+ ...args,
353
+ args: args._,
354
+ raw: args.$
355
+ });
356
+ if (this.#opts.bash === false) return rendered;
357
+ const bash = Array.isArray(this.#opts.bash) ? this.#opts.bash : ["bash"];
358
+ const lines = rendered.split("\n");
359
+ const ret = [];
360
+ for (const token of this.#tokenize(lines, cmd)) {
361
+ let text;
362
+ if (token.type === "script") text = await exec(token.value, { bash });
363
+ else if (token.type === "block" && /^bash\s*!$/.test(token.lang ?? "")) text = await exec(token.body, { bash });
364
+ ret.push(text ?? token.value);
365
+ }
366
+ return ret.join("\n");
367
+ }
368
+ *#tokenize(lines, cmd) {
369
+ let block = [];
370
+ let marker = void 0;
371
+ let lang = void 0;
372
+ for (const line of lines) {
373
+ const m = line.match(/^\s*(`{3,}|~{3,})(.*)$/);
374
+ const script = line.match(BASH_RE);
375
+ if (marker && line.match(marker)) {
376
+ block.push(line);
377
+ yield {
378
+ body: block.slice(1, -1).join("\n"),
379
+ lang,
380
+ type: "block",
381
+ value: block.join("\n")
382
+ };
383
+ marker = void 0;
384
+ } else if (!marker && m) {
385
+ marker = new RegExp(`^\\s*${m[1]}\\s*$`);
386
+ lang = m[2].trim() || void 0;
387
+ block = [line];
388
+ } else if (marker) block.push(line);
389
+ else if (script) yield {
390
+ type: "script",
391
+ value: script[1]
392
+ };
393
+ else yield {
394
+ type: "text",
395
+ value: line
396
+ };
397
+ }
398
+ if (marker) throw new Error(`Unclosed code block in command **${cmd.name}**`);
399
+ }
400
+ };
401
+ async function exec(script, opts = {}) {
402
+ if (!script.trim()) return;
403
+ const { spawnCmd } = await import("@zaly/shared/process");
404
+ let result;
405
+ try {
406
+ result = (await spawnCmd(script, {
407
+ bash: opts.bash ?? true,
408
+ throw: true
409
+ }))?.trim() ?? "";
410
+ } catch (error) {
411
+ result = toError(error).message.trim();
412
+ }
413
+ const md = [];
414
+ if (script.includes("\n")) {
415
+ md.push("```bash");
416
+ md.push(script);
417
+ md.push("```");
418
+ md.push("");
419
+ md.push("```shellsession");
420
+ md.push(result);
421
+ md.push("```");
422
+ } else {
423
+ md.push("```shellsession");
424
+ md.push(`$ ${script}`);
425
+ md.push(result);
426
+ md.push("```");
427
+ }
428
+ md.push("");
429
+ return md.join("\n");
430
+ }
431
+ //#endregion
432
+ //#region src/skills.ts
433
+ var Skills = class Skills {
434
+ catalog = /* @__PURE__ */ new Map();
435
+ #tool;
436
+ #opts;
437
+ constructor(opts = {}) {
438
+ this.#opts = opts;
439
+ }
440
+ static async load(opts) {
441
+ return new Skills(opts).reload();
442
+ }
443
+ /** (Re)scan project + user `.agent/skills/` directories. Wipes the
444
+ * current catalog and the cached tool, then repopulates. Safe to
445
+ * call mid-session — agent uses `this.tool` per-step so the next
446
+ * request after reload picks up the change. */
447
+ async reload() {
448
+ this.catalog.clear();
449
+ this.#tool = void 0;
450
+ const paths = this.#opts.paths ?? [];
451
+ const skills = await Promise.all(paths.map(async (path) => await this.#load(path)));
452
+ for (const skill of skills) if (skill && !this.catalog.has(skill.name)) this.catalog.set(skill.name, skill);
453
+ return this;
454
+ }
455
+ async #load(path) {
456
+ if (!path.endsWith("SKILL.md")) return;
457
+ const dir = dirname(path);
458
+ try {
459
+ const { meta, mtime, body } = await readSkill(path);
460
+ if (!meta.name || !meta.description || this.catalog.has(meta.name)) return;
461
+ return {
462
+ body,
463
+ desc: meta.description,
464
+ dir,
465
+ mtime,
466
+ name: meta.name,
467
+ path
468
+ };
469
+ } catch {}
470
+ }
471
+ async #update(entry) {
472
+ const updated = await this.#load(entry.path) ?? entry;
473
+ if (isDeepStrictEqual(updated, entry)) return entry;
474
+ this.catalog.set(entry.name, updated);
475
+ this.#tool = void 0;
476
+ return updated;
477
+ }
478
+ /** Skill base directories — pass each to `agent.permissions.addWorkspace`
479
+ * so the model can read bundled `references/` files without tripping
480
+ * permission asks. */
481
+ get dirs() {
482
+ return [...this.catalog.values()].map((s) => s.dir);
483
+ }
484
+ /** The activation tool. Returns `undefined` when the catalog is empty
485
+ * (the agent then omits skills entirely from the model's tool list,
486
+ * per the spec). Lazily built on first access; invalidated by
487
+ * `load()`. */
488
+ get tool() {
489
+ if (this.catalog.size === 0) return void 0;
490
+ return this.#tool ??= this.#buildTool();
491
+ }
492
+ #buildTool() {
493
+ const names = [...this.catalog.keys()];
494
+ return defineTool({
495
+ name: "skill",
496
+ desc: this.#buildCatalogDesc(),
497
+ parallel: true,
498
+ params: Type.Object({ name: Type.Union(names.map((n) => Type.Literal(n)), { description: "Name of the skill to activate. The full SKILL.md instructions are loaded as the tool result; bundled files in the skill's directory are listed but not read — fetch them via the `read` tool when the skill's instructions require them." }) }),
499
+ call: (args, ctx) => this.#call(args.name, ctx)
500
+ });
501
+ }
502
+ async #call(requested, ctx) {
503
+ let skill = this.catalog.get(requested);
504
+ if (!skill) {
505
+ const available = [...this.catalog.keys()];
506
+ throw new AiError({
507
+ code: "UNKNOWN_SKILL",
508
+ data: {
509
+ available,
510
+ name: requested
511
+ },
512
+ message: `no skill named "${requested}". Available: ${available.join(", ")}`
513
+ });
514
+ }
515
+ skill = await this.#update(skill);
516
+ ctx.meta = {
517
+ desc: skill.desc,
518
+ mtime: skill.mtime,
519
+ name: skill.name,
520
+ path: skill.path
521
+ };
522
+ if (await this.isActivated(skill, ctx)) {
523
+ ctx.meta.unchanged = true;
524
+ return [{
525
+ content: `skill "${skill.name}" unchanged since last read: ${skill.path}`,
526
+ tag: "unchanged",
527
+ type: "meta"
528
+ }];
529
+ }
530
+ const references = await listReferences(skill.dir);
531
+ return [{
532
+ data: {
533
+ dir: skill.dir,
534
+ name: skill.name,
535
+ references
536
+ },
537
+ tag: "skill",
538
+ type: "meta"
539
+ }, {
540
+ text: skill.body,
541
+ type: "text"
542
+ }];
543
+ }
544
+ async isActivated(skill, ctx) {
545
+ const messages = ctx.messages ?? [];
546
+ for (const { m, $p, p } of extractToolResults(messages, ["skill"])) {
547
+ const id = m.id;
548
+ if (!id || !p.meta || ctx.isMasked?.(id, $p)) continue;
549
+ if (p.meta.unchanged) continue;
550
+ if (p.meta.name === skill.name) return p.meta.mtime === skill.mtime;
551
+ }
552
+ return false;
553
+ }
554
+ async activate(name, agent) {
555
+ const ret = await agent.useTool("skill", { name }, `Skill "${name}" was activated by the user.`);
556
+ if (ret.result.meta?.unchanged) return;
557
+ return ret;
558
+ }
559
+ #buildCatalogDesc() {
560
+ return `Activate one of the available skills below. The skill's full SKILL.md instructions are loaded as the tool result; the model should follow them directly. Bundled files are listed in the result but not eagerly read — fetch the ones the skill's instructions reference via the \`read\` tool.\n\nAvailable skills:\n${[...this.catalog.values()].map((s) => `- ${s.name}: ${s.desc}`).join("\n")}`;
561
+ }
562
+ };
563
+ async function readSkill(path) {
564
+ const s = await safeStatAsync(path);
565
+ if (!s?.isFile()) throw new Error(`Skill file not found at ${path}`);
566
+ const raw = await readFile(path, "utf8");
567
+ const { parseFrontmatter } = await import("@zaly/shared/yaml");
568
+ const { fm, body } = await parseFrontmatter(raw);
569
+ return {
570
+ body,
571
+ meta: fm,
572
+ mtime: s.mtimeMs
573
+ };
574
+ }
575
+ async function listReferences(dir) {
576
+ const out = [];
577
+ for await (const rel of glob("**", {
578
+ cwd: dir,
579
+ depth: 4,
580
+ type: "file"
581
+ })) {
582
+ if (rel === "SKILL.md" || rel.endsWith("/SKILL.md")) continue;
583
+ out.push(rel);
584
+ if (out.length >= 200) break;
585
+ }
586
+ return out.toSorted();
587
+ }
588
+ //#endregion
589
+ //#region src/compaction/utils.ts
590
+ const LAMBDA = Math.LN2 / 60;
591
+ const KIND_WEIGHTS = {
592
+ edit: 2,
593
+ read: 1,
594
+ write: 3
595
+ };
596
+ const sorters = {
597
+ count: (a, b) => b[1].count - a[1].count,
598
+ key: (a, b) => a[0].localeCompare(b[0]),
599
+ score: (a, b) => b[1].score - a[1].score
600
+ };
601
+ function turnInfo(messages) {
602
+ const weights = [];
603
+ const turns = [];
604
+ let turn = 0;
605
+ for (let i = messages.length - 1; i >= 0; i--) {
606
+ if (messages[i].role === "assistant") turn++;
607
+ weights[i] = Math.exp(-LAMBDA * turn);
608
+ turns[i] = turn;
609
+ }
610
+ return {
611
+ turns,
612
+ weights
613
+ };
614
+ }
615
+ function toolStats(map, opts = {}) {
616
+ const limit = opts.limit ?? 50;
617
+ const sorter = sorters[opts.sort ?? "score"];
618
+ return [...map.entries()].toSorted(sorter).map(([, stat]) => stat).filter((stat) => stat.count >= (opts.minCount ?? 1)).filter((stat) => stat.score >= (opts.minScore ?? 0)).slice(0, limit);
619
+ }
620
+ /** Walk assistant tool-calls for `read` / `write` / `edit` and tally
621
+ * per-path activity with frecency-weighted scoring. Returns the top-N
622
+ * by score. Each entry carries the per-kind breakdown so the
623
+ * summarizer can describe the *kind* of activity ("heavily edited",
624
+ * "read once, then written", "iteratively refined").
625
+ *
626
+ * Paths are canonicalized via the cwd recorded on each call's session
627
+ * node — relative paths are resolved against the cwd that was active
628
+ * when the call ran, and `~` is expanded. Calls under different cwds
629
+ * that target the same file thus collapse into one bucket. */
630
+ function extractFileUsage(messages, opts = {}) {
631
+ opts = {
632
+ minScore: .5,
633
+ ...opts
634
+ };
635
+ const map = /* @__PURE__ */ new Map();
636
+ const { turns, weights } = turnInfo(messages);
637
+ for (const { m, p, $m: idx } of extractToolResults(messages, [
638
+ "read",
639
+ "write",
640
+ "edit"
641
+ ])) {
642
+ const path = p.meta?.path;
643
+ if (!path) continue;
644
+ const entry = map.get(path) ?? {
645
+ count: 0,
646
+ edits: 0,
647
+ lastTs: 0,
648
+ lastTurn: Infinity,
649
+ path,
650
+ reads: 0,
651
+ score: 0,
652
+ writes: 0
653
+ };
654
+ if (p.name === "read") entry.reads++;
655
+ else if (p.name === "write") entry.writes++;
656
+ else entry.edits++;
657
+ entry.count++;
658
+ entry.score += weights[idx] * KIND_WEIGHTS[p.name];
659
+ if (turns[idx] < entry.lastTurn) entry.lastTurn = turns[idx];
660
+ if (m.ts && m.ts > entry.lastTs) entry.lastTs = m.ts;
661
+ map.set(path, entry);
662
+ }
663
+ return toolStats(map, opts);
664
+ }
665
+ /** Walk assistant tool-calls for `bash`, parse each command line, and
666
+ * tally per-command frecency. Plumbing commands (cat, head, grep, awk,
667
+ * sed, …) are filtered out — they dominate raw counts but carry no
668
+ * operational signal a summarizer would describe. Returns the top-N
669
+ * by frecency `score`. */
670
+ function extractBashUsage(messages, opts = {}) {
671
+ opts = {
672
+ minCount: 2,
673
+ minScore: .5,
674
+ ...opts
675
+ };
676
+ const { turns, weights } = turnInfo(messages);
677
+ const map = /* @__PURE__ */ new Map();
678
+ for (const { m, p, $m: idx } of extractToolCalls(messages, ["bash"])) {
679
+ const cmd = safeParseToolParams(p.params)?.command;
680
+ if (!cmd) continue;
681
+ const result = parseBash(cmd);
682
+ if (!result.ok) continue;
683
+ const w = weights[idx] ?? 0;
684
+ const t = turns[idx] ?? Infinity;
685
+ for (const seg of result.segments) {
686
+ if (TOOLS[seg.cmd]) continue;
687
+ const key = `${seg.cmd} ${seg.args.join(" ")}`;
688
+ if (key.includes("\n")) continue;
689
+ const entry = map.get(key) ?? {
690
+ command: key,
691
+ count: 0,
692
+ lastTs: 0,
693
+ lastTurn: Infinity,
694
+ score: 0
695
+ };
696
+ entry.count++;
697
+ entry.score += w;
698
+ if (t < entry.lastTurn) entry.lastTurn = t;
699
+ if (m.ts && m.ts > entry.lastTs) entry.lastTs = m.ts;
700
+ map.set(key, entry);
701
+ }
702
+ }
703
+ return toolStats(map, opts);
704
+ }
705
+ function truncate(text, len) {
706
+ return text.length <= len ? text : `${text.slice(0, len)}…`;
707
+ }
708
+ /** Flatten a list of messages into a single tagged transcript. */
709
+ function extractConversation(messages, opts = {}) {
710
+ const transform = ContentTransform.create().drop("reasoning").map("tool-call", (part) => ({
711
+ content: [{
712
+ text: `${part.name}(${safeStringify(part.params)})`,
713
+ type: "text"
714
+ }],
715
+ tag: "tool-call",
716
+ type: "meta"
717
+ })).map("tool-result", (part) => {
718
+ const text = truncate(stringifyContent(part.content), opts.maxToolResultLen ?? 2e3);
719
+ return {
720
+ content: text === "" ? void 0 : [{
721
+ text,
722
+ type: "text"
723
+ }],
724
+ data: {
725
+ tool: part.name,
726
+ ...part.isError ? { error: true } : {}
727
+ },
728
+ tag: "tool-result",
729
+ type: "meta"
730
+ };
731
+ }).pipe(attachmentToMeta("image", "pdf", "audio", "video")).pipe(errorToMeta()).pipe(metaToText()).pipe(sanitizeText());
732
+ const blocks = [];
733
+ let role = void 0;
734
+ for (const m of messages) {
735
+ const parts = typeof m.content === "string" ? [{
736
+ text: m.content,
737
+ type: "text"
738
+ }] : m.content;
739
+ const transformed = transform.runSync(parts);
740
+ const text = stringifyContent(transformed).trim();
741
+ if (!text) continue;
742
+ let currentRole = m.role.charAt(0).toUpperCase() + m.role.slice(1);
743
+ currentRole = currentRole === "Tool" ? "Assistant" : currentRole;
744
+ blocks.push(role === currentRole ? text : `\n[${currentRole}]: ${text}`);
745
+ role = currentRole;
746
+ }
747
+ const text = blocks.join("\n").replace(/^\s+$/gm, "").trim();
748
+ return toXml(text, "conversation", { indent: false });
749
+ }
750
+ function messageTail(messages, opts) {
751
+ const maxTokens = opts.keepTokens ?? 2e4;
752
+ messages = messages.toReversed();
753
+ const tail = [];
754
+ const queue = [];
755
+ let used = 0;
756
+ let last = void 0;
757
+ for (const m of messages) {
758
+ queue.unshift(m);
759
+ const usage = m.role === "assistant" ? m.meta?.usage : void 0;
760
+ if (!usage) continue;
761
+ const current = usage.input + usage.output + (usage.cacheRead ?? 0) + (usage.cacheWrite ?? 0);
762
+ const delta = Math.max(0, (last ?? current) - current);
763
+ if (used + delta > maxTokens) break;
764
+ used += delta;
765
+ last = current;
766
+ tail.unshift(...queue.splice(0));
767
+ }
768
+ return tail;
769
+ }
770
+ const lastCol = (lastTurn, lastTs) => {
771
+ return `${lastTurn === Infinity ? "?" : `${lastTurn}t`} / ${lastTs > 0 ? formatDuration(lastTs) : "?"}`;
772
+ };
773
+ function formatBashUsage(commands) {
774
+ if (commands.length === 0) return "(no bash commands found)";
775
+ const lines = [];
776
+ lines.push("=== Top bash commands (sorted by frecency) ===");
777
+ lines.push(` ${"score".padStart(7)} ${"count".padStart(5)} ${"last".padEnd(14)} command`);
778
+ for (const c of commands) lines.push(` ${c.score.toFixed(2).padStart(7)} ${String(c.count).padStart(5)} ${lastCol(c.lastTurn, c.lastTs).padEnd(14)} ${c.command}`);
779
+ const text = lines.join("\n");
780
+ return toXml(text, "bash-commands", { indent: false });
781
+ }
782
+ function formatFileUsage(files) {
783
+ if (files.length === 0) return "(no file ops found)";
784
+ const lines = [];
785
+ lines.push("=== Top files touched (sorted by frecency) ===");
786
+ lines.push(` ${"score".padStart(7)} ${"total".padStart(5)} r/w/e ${"last".padEnd(14)} path`);
787
+ for (const f of files) {
788
+ const rwe = `${f.reads}/${f.writes}/${f.edits}`.padEnd(12);
789
+ lines.push(` ${f.score.toFixed(2).padStart(7)} ${String(f.count).padStart(5)} ${rwe} ${lastCol(f.lastTurn, f.lastTs).padEnd(14)} ${f.path}`);
790
+ }
791
+ const text = lines.join("\n");
792
+ return toXml(text, "files", { indent: false });
793
+ }
794
+ //#endregion
795
+ //#region src/context/tokens.ts
796
+ const CHARS_PER_TOKEN = 4;
797
+ const ATTACHMENT_TOKENS = {
798
+ audio: 3e3,
799
+ image: 1500,
800
+ pdf: 8e3,
801
+ video: 5e3
802
+ };
803
+ function fromText(text) {
804
+ return Math.ceil(text.length / CHARS_PER_TOKEN);
805
+ }
806
+ function sumTokens(stats) {
807
+ return stats.reduce((sum, s) => sum + s.tokens, 0);
808
+ }
809
+ function estimatePart(p) {
810
+ switch (p.type) {
811
+ case "reasoning":
812
+ case "text": return {
813
+ tokens: fromText(p.text),
814
+ type: p.type
815
+ };
816
+ case "tool-call": return {
817
+ kind: p.name,
818
+ tokens: fromText(p.name) + fromText(JSON.stringify(p.params ?? {})),
819
+ type: p.type
820
+ };
821
+ case "tool-result": {
822
+ const children = estimateContent(p.content);
823
+ return {
824
+ children,
825
+ kind: p.name,
826
+ tokens: fromText(p.name) + sumTokens(children),
827
+ type: p.type
828
+ };
829
+ }
830
+ case "image":
831
+ case "pdf":
832
+ case "audio":
833
+ case "video": return {
834
+ tokens: ATTACHMENT_TOKENS[p.type],
835
+ type: p.type
836
+ };
837
+ case "meta": return {
838
+ children: p.content ? estimateContent(p.content) : void 0,
839
+ kind: p.tag,
840
+ tokens: fromText(stringifyContent(p)),
841
+ type: p.type
842
+ };
843
+ case "error": return {
844
+ tokens: fromText(stringifyContent(p)),
845
+ type: p.type
846
+ };
847
+ default: throw new Error(`Unknown part type: ${p.type}`);
848
+ }
849
+ }
850
+ function estimateContent(content) {
851
+ if (typeof content === "string") return [{
852
+ tokens: fromText(content),
853
+ type: "text"
854
+ }];
855
+ let tokens = 0;
856
+ const children = [];
857
+ for (const p of content) {
858
+ const partStats = estimatePart(p);
859
+ tokens += partStats.tokens;
860
+ children.push(partStats);
861
+ }
862
+ return children;
863
+ }
864
+ function estimateMessage(m) {
865
+ const type = m.role;
866
+ const children = estimateContent(m.content);
867
+ return {
868
+ children,
869
+ kind: m.role === "system" ? m.meta?.kind : void 0,
870
+ tokens: sumTokens(children),
871
+ type
872
+ };
873
+ }
874
+ function estimatePrompt(prompt, tools) {
875
+ const children = prompt.map((p) => ({
876
+ kind: typeof p === "string" ? void 0 : p.name,
877
+ tokens: fromText(typeof p === "string" ? p : p.text),
878
+ type: "prompt"
879
+ }));
880
+ children.push(...tools?.map((t) => ({
881
+ kind: t.name,
882
+ tokens: fromText(t.name) + fromText(JSON.stringify(t.params ?? {})),
883
+ type: "tool-schema"
884
+ })) ?? []);
885
+ return {
886
+ children,
887
+ tokens: sumTokens(children),
888
+ type: "system-prompt"
889
+ };
890
+ }
891
+ function addCount(stat, parent, expand) {
892
+ const keys = stat.kind ? [stat.type, stat.kind] : [stat.type];
893
+ let child;
894
+ for (const key of keys) {
895
+ parent.children ??= /* @__PURE__ */ new Map();
896
+ child = parent.children.get(key);
897
+ if (!child) {
898
+ child = {
899
+ children: /* @__PURE__ */ new Map(),
900
+ count: 0,
901
+ key,
902
+ tokens: 0
903
+ };
904
+ parent.children.set(key, child);
905
+ }
906
+ child.tokens += stat.tokens;
907
+ child.count++;
908
+ parent = child;
909
+ }
910
+ if (stat.children && child && (!expand || expand(stat))) for (const c of stat.children) addCount(c, child, expand);
911
+ }
912
+ function tokenStats(msgs, opts = {}) {
913
+ const root = {
914
+ children: /* @__PURE__ */ new Map(),
915
+ count: 0,
916
+ key: "TOTAL",
917
+ tokens: 0
918
+ };
919
+ const counts = [];
920
+ if (opts.prompt) counts.push(estimatePrompt(opts.prompt, opts.tools));
921
+ counts.push(...msgs.map(estimateMessage));
922
+ for (const stats of counts) {
923
+ root.tokens += stats.tokens;
924
+ root.count++;
925
+ addCount(stats, root, opts.expand);
926
+ }
927
+ return root;
928
+ }
929
+ function fmtStats(s, indent = 0) {
930
+ return `${(" ".repeat(indent) + s.key).padEnd(28)} ${fmt(s.count).padStart(6)}x ${fmt(s.tokens).padStart(14)}`;
931
+ }
932
+ function formatTokenStats(s, indent = 0) {
933
+ const ret = [];
934
+ const children = s.children ? [...s.children.values()].toSorted((a, b) => b.tokens - a.tokens) : [];
935
+ for (const c of children) {
936
+ ret.push(fmtStats(c, indent));
937
+ if (c.children?.size) ret.push(formatTokenStats(c, indent + 1));
938
+ if (indent === 0) ret.push("─".repeat(51));
939
+ }
940
+ if (indent === 0) {
941
+ ret.unshift("─".repeat(51));
942
+ ret.push(fmtStats(s, indent));
943
+ ret.push("─".repeat(51));
944
+ }
945
+ return ret.join("\n");
946
+ }
947
+ function fmt(n) {
948
+ return n.toLocaleString("en-US").replace(/,/g, "_");
949
+ }
950
+ //#endregion
951
+ export { ctx_exports as _, extractConversation as a, formatFileUsage as c, Commands as d, toolCollection as f, createAgent as g, promptRegistry as h, extractBashUsage as i, messageTail as l, promptCollection as m, formatTokenStats as n, extractFileUsage as o, toolRegistry as p, tokenStats as r, formatBashUsage as s, estimatePart as t, Skills as u };
952
+
953
+ //# sourceMappingURL=src-fK6DL2bg.mjs.map