@zaly/agent 0.0.5 → 0.0.9

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