@eum-agent/agent-management 1.1.0 → 1.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.
Files changed (3) hide show
  1. package/dist/index.js +529 -252
  2. package/package.json +2 -2
  3. package/ui/ui.js +6586 -1747
package/dist/index.js CHANGED
@@ -1,46 +1,243 @@
1
1
  import { existsSync } from "node:fs";
2
+ import { dirname } from "node:path";
2
3
  import { fileURLToPath } from "node:url";
3
4
  import { z } from "zod";
4
5
  import { randomUUID } from "node:crypto";
6
+ //#region src/body-document.ts
7
+ const LocalBodyRefSchema = z.strictObject({
8
+ bodyId: z.uuid(),
9
+ codec: z.enum([
10
+ "utf8-text",
11
+ "json",
12
+ "opaque"
13
+ ]),
14
+ formatVersion: z.literal(1),
15
+ byteLength: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
16
+ sha256: z.string().regex(/^[a-f0-9]{64}$/)
17
+ });
18
+ async function captureTextBody(text, ctx) {
19
+ ctx.signal.throwIfAborted();
20
+ const writer = await ctx.openBody("utf8-text", ctx.signal);
21
+ const encoder = new TextEncoder();
22
+ let offset = 0;
23
+ let index = 0;
24
+ try {
25
+ while (index < text.length) {
26
+ ctx.signal.throwIfAborted();
27
+ const chunk = /* @__PURE__ */ new Uint8Array(65536);
28
+ let end = Math.min(text.length, index + 32768);
29
+ if (end < text.length && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--;
30
+ const { read, written } = encoder.encodeInto(text.slice(index, end), chunk);
31
+ if (!read) throw new Error("text_encoding_failed");
32
+ await writer.write(offset, chunk.subarray(0, written), ctx.signal);
33
+ offset += written;
34
+ index += read;
35
+ }
36
+ return (await writer.seal(ctx.signal)).body;
37
+ } catch (error) {
38
+ await writer.abort();
39
+ throw error;
40
+ }
41
+ }
42
+ function createTextDocuments(render) {
43
+ const documents = /* @__PURE__ */ new WeakMap();
44
+ const prepare = (value, ctx) => {
45
+ const key = typeof value === "object" && value !== null ? value : void 0;
46
+ const prior = key ? documents.get(key) : void 0;
47
+ if (prior) return prior;
48
+ const work = (async () => {
49
+ const input = render(value);
50
+ const literals = input.nodes.filter((node) => node.kind === "literal");
51
+ const lengths = literals.map((node) => new TextEncoder().encode(node.text).byteLength);
52
+ if (literals.length === input.nodes.length && (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384 || input.nodes.length > 256)) {
53
+ const body = await captureTextBody(literals.map((node) => node.text).join(""), ctx);
54
+ return {
55
+ formatVersion: 1,
56
+ rendererVersion: 1,
57
+ nodes: [{
58
+ id: "text",
59
+ kind: "text-range",
60
+ body,
61
+ startByte: 0,
62
+ endByte: body.byteLength
63
+ }]
64
+ };
65
+ }
66
+ if (lengths.some((length) => length > 4096) || lengths.reduce((sum, length) => sum + length, 0) > 16384) {
67
+ const nodes = [];
68
+ const all = lengths.reduce((sum, length) => sum + length, 0) > 16384;
69
+ for (const node of input.nodes) {
70
+ if (node.kind !== "literal" || !all && new TextEncoder().encode(node.text).byteLength <= 4096) {
71
+ nodes.push(node);
72
+ continue;
73
+ }
74
+ const body = await captureTextBody(node.text, ctx);
75
+ nodes.push({
76
+ id: node.id,
77
+ kind: "text-range",
78
+ body,
79
+ startByte: 0,
80
+ endByte: body.byteLength
81
+ });
82
+ }
83
+ return {
84
+ ...input,
85
+ nodes
86
+ };
87
+ }
88
+ return input;
89
+ })();
90
+ if (key) documents.set(key, work);
91
+ return work;
92
+ };
93
+ return {
94
+ prepare,
95
+ formatModel: prepare
96
+ };
97
+ }
98
+ //#endregion
99
+ //#region src/definition-view.ts
100
+ const AgentDefaultModel = z.strictObject({
101
+ providerId: z.string().min(1).describe("Exact providerId from model_list."),
102
+ model: z.string().min(1).describe("Exact model identifier from model_list.")
103
+ });
104
+ function defaultModelOf(snapshot) {
105
+ const owner = snapshot.extensionData["@eum-agent/llm-capability-chat"];
106
+ if (owner == null) return null;
107
+ if (typeof owner !== "object" || Array.isArray(owner)) throw new Error("Invalid retained Agent default model reference");
108
+ const value = owner.defaultModel;
109
+ if (value == null) return null;
110
+ const parsed = AgentDefaultModel.safeParse(value);
111
+ if (!parsed.success) throw new Error("Invalid retained Agent default model reference");
112
+ return {
113
+ providerId: parsed.data.providerId,
114
+ model: parsed.data.model
115
+ };
116
+ }
117
+ //#endregion
118
+ //#region src/model-document.ts
119
+ function receiptDocument(value) {
120
+ const data = value;
121
+ return {
122
+ formatVersion: 1,
123
+ rendererVersion: 1,
124
+ nodes: [{
125
+ id: "receipt",
126
+ kind: "literal",
127
+ text: data.error ? `${data.error.code}: ${data.error.message}` : `Agent ${data.name ?? ""} (${data.id}); revision ${data.revision}. Changed: ${data.changedFields?.join(", ")}.\nDirect conversations: ${data.startsSessions ? "enabled" : "disabled"}.\n${data.summary ?? ""}`
128
+ }]
129
+ };
130
+ }
131
+ function receiptPresentation(value, type) {
132
+ const data = value;
133
+ return {
134
+ type,
135
+ schemaVersion: 1,
136
+ summary: (data.error?.message ?? `${data.name ?? data.id} \u00b7 ${type === "agent-created" ? "created" : "updated"}`).slice(0, 512),
137
+ state: data.error ? "error" : "ready",
138
+ fields: data.error ? { code: data.error.code } : {
139
+ agentId: data.id,
140
+ revision: data.revision,
141
+ committed: true,
142
+ startsSessions: data.startsSessions ?? true
143
+ },
144
+ actions: [],
145
+ bodyRefs: []
146
+ };
147
+ }
148
+ function pageBusinessResult(result, type) {
149
+ const data = result.data;
150
+ const count = data.items?.length ?? 0;
151
+ return {
152
+ ...result,
153
+ ...data.error ? { error: {
154
+ code: data.error.code,
155
+ retryable: false
156
+ } } : {},
157
+ presentation: {
158
+ type: type === "agent_list" ? "agent-list" : "agent-read",
159
+ schemaVersion: 1,
160
+ summary: (data.error?.message ?? `${count} ${type === "agent_list" ? "agents" : "definition fields"}${data.complete === false ? " \u00b7 partial" : ""}`).slice(0, 512),
161
+ state: result.isError ? "error" : data.complete === false ? "partial" : "ready",
162
+ fields: {
163
+ count,
164
+ complete: data.complete ?? false
165
+ },
166
+ actions: [],
167
+ bodyRefs: data.items?.flatMap((item) => item.body ? [item.body] : []) ?? []
168
+ }
169
+ };
170
+ }
171
+ function pageDocument(value, name) {
172
+ const data = value;
173
+ const nodes = [];
174
+ if (data.error) nodes.push({
175
+ id: "failure",
176
+ kind: "literal",
177
+ text: `${data.error.code}: ${data.error.message}\n`
178
+ });
179
+ for (const [index, item] of (data.items ?? []).entries()) {
180
+ nodes.push({
181
+ id: `identity-${index}`,
182
+ kind: "literal",
183
+ text: item.body ? `Agent ${item.id}; revision ${item.revision}; ${item.field}; code points ${item.offset}..${(item.offset ?? 0) + (item.length ?? 0)}${item.complete ? "" : " (partial)"}.\n` : `${item.name} (${item.id}); revision ${item.revision}; direct conversations ${item.startsSessions ? "enabled" : "disabled"}.\n${item.description}\n`
184
+ });
185
+ if (item.body) nodes.push({
186
+ id: `field-${index}`,
187
+ kind: "text-range",
188
+ body: item.body,
189
+ startByte: item.startByte,
190
+ endByte: item.endByte
191
+ });
192
+ }
193
+ if (!data.error && !data.items?.length) nodes.push({
194
+ id: "empty",
195
+ kind: "literal",
196
+ text: "No matching Agent definitions.\n"
197
+ });
198
+ if (data.next) nodes.push({
199
+ id: "next",
200
+ kind: "literal",
201
+ text: `\nContinue ${name} with ${JSON.stringify(data.next)}\n`
202
+ });
203
+ return {
204
+ formatVersion: 1,
205
+ rendererVersion: 1,
206
+ nodes
207
+ };
208
+ }
209
+ //#endregion
5
210
  //#region src/output-schema.ts
6
- /** Validates complete owner business results and bounded recoverable delivery failures. */
7
- /** Adds the standard failure envelope and bounded text refusals to an owner's result schema. */
8
211
  function toolOutputSchema(body, input, name) {
9
- return z.union([
10
- body,
11
- z.strictObject({
12
- ok: z.literal(false),
13
- error: z.strictObject({
14
- code: z.string().min(1).max(128),
15
- message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 }),
16
- retryable: z.boolean(),
17
- field: z.string().max(256).optional(),
18
- maximum: z.number().finite().optional()
19
- }),
20
- next: z.strictObject({
21
- tool: z.literal(name),
22
- arguments: input
23
- }).nullable(),
24
- execution: z.strictObject({ state: z.enum([
25
- "not-started",
26
- "committed",
27
- "unknown"
28
- ]) }).optional()
212
+ return z.union([body, z.strictObject({
213
+ ok: z.literal(false),
214
+ error: z.strictObject({
215
+ code: z.string().min(1).max(128),
216
+ message: z.string().refine((value) => [...value].length <= 256).meta({ maxLength: 256 }),
217
+ retryable: z.boolean(),
218
+ field: z.string().max(256).optional(),
219
+ maximum: z.number().finite().optional()
29
220
  }),
30
- z.string().max(1024)
31
- ]);
221
+ next: z.strictObject({
222
+ tool: z.literal(name),
223
+ arguments: input
224
+ }).nullable(),
225
+ execution: z.strictObject({ state: z.enum([
226
+ "not-started",
227
+ "committed",
228
+ "unknown"
229
+ ]) }).optional()
230
+ })]);
32
231
  }
33
232
  //#endregion
34
233
  //#region src/cursor-cache.ts
35
- const bytesOf = (value) => 2048 + 2 * (value.content?.length ?? 0);
36
- /** Owns metadata snapshots; each query and all successor positions share one opaque host lease. */
234
+ const bytesOf = (value) => 2048 + 2 * JSON.stringify(value.metadata ?? null).length;
37
235
  var QueryCursorCache = class extends Map {
38
236
  pending = /* @__PURE__ */ new Map();
39
237
  roots = /* @__PURE__ */ new Map();
40
238
  resources;
41
239
  facts;
42
240
  timer;
43
- /** Measures only retained metadata; source IO uses a separate bounded reservation. */
44
241
  constructor(facts, resources) {
45
242
  super();
46
243
  this.facts = facts;
@@ -153,7 +350,6 @@ var QueryCursorCache = class extends Map {
153
350
  this.settle(root);
154
351
  };
155
352
  }
156
- /** Runs source acquisition under the actual authenticated call, releasing only after its cleanup. */
157
353
  async runExclusive(input, call, action, sourceBytes = 4194304) {
158
354
  const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
159
355
  const saved = cursor === void 0 ? void 0 : this.get(cursor);
@@ -173,7 +369,7 @@ var QueryCursorCache = class extends Map {
173
369
  "cursor_invalid"
174
370
  ].includes(error.message)) throw error;
175
371
  return {
176
- content: JSON.stringify({
372
+ data: {
177
373
  ok: false,
178
374
  error: {
179
375
  code: error.message,
@@ -181,14 +377,14 @@ var QueryCursorCache = class extends Map {
181
377
  retryable: false
182
378
  },
183
379
  next: null
184
- }),
380
+ },
381
+ execution: { state: "not-started" },
185
382
  isError: true
186
383
  };
187
384
  } finally {
188
385
  finish?.();
189
386
  }
190
387
  }
191
- /** Joins same-cursor preparation before revalidating and replaying its accepted exact page. */
192
388
  async run(input, call, action, sourceBytes = 4194304) {
193
389
  const cursor = typeof input === "object" && input !== null && "cursor" in input ? input.cursor : void 0;
194
390
  if (cursor === void 0) return this.runExclusive(input, call, action, sourceBytes);
@@ -207,7 +403,6 @@ var QueryCursorCache = class extends Map {
207
403
  if (this.pending.get(cursor) === gate) this.pending.delete(cursor);
208
404
  }
209
405
  }
210
- /** Applies the same resource lifecycle to a native model-tool registration. */
211
406
  wrap(tool, sourceBytes = 4194304) {
212
407
  const execute = tool.execute;
213
408
  return {
@@ -215,12 +410,11 @@ var QueryCursorCache = class extends Map {
215
410
  execute: (input, call) => this.run(input, call, async () => await execute(input, call), sourceBytes)
216
411
  };
217
412
  }
218
- /** Accounts an exact candidate before accepting or retaining its snapshot. */
219
- async prepare(initial, content) {
413
+ async prepare(initial, metadata) {
220
414
  const root = this.roots.get(initial);
221
415
  if (!root || root.closing) throw new Error("cursor_invalid");
222
416
  root.lease.signal.throwIfAborted();
223
- const bytes = 2048 + 2 * content.length;
417
+ const bytes = 2048 + 2 * JSON.stringify(metadata).length;
224
418
  const additional = this.total(root) - root.pendingBytes + bytes - root.heldBytes;
225
419
  if (additional > 0) {
226
420
  await root.lease.grow(root.call, {
@@ -231,7 +425,6 @@ var QueryCursorCache = class extends Map {
231
425
  }
232
426
  root.pendingBytes = bytes;
233
427
  }
234
- /** Awaits metadata admission before installing a new cursor. */
235
428
  async save(key, value) {
236
429
  const root = this.roots.get(this.facts(value).initial);
237
430
  if (!root || root.closing) throw new Error("cursor_invalid");
@@ -257,12 +450,10 @@ var QueryCursorCache = class extends Map {
257
450
  }
258
451
  return deleted;
259
452
  }
260
- /** Drops retained metadata before releasing its shared reservation. */
261
453
  clear() {
262
454
  for (const root of [...this.roots.values()]) this.invalidate(root);
263
455
  }
264
456
  };
265
- /** Applies a tighter owner-local memory ceiling while preserving shared resident accounting. */
266
457
  function trimCursorCache(entries, retained) {
267
458
  let bytes = 0;
268
459
  for (const entry of entries.values()) bytes += bytesOf(retained(entry));
@@ -274,48 +465,93 @@ function trimCursorCache(entries, retained) {
274
465
  }
275
466
  }
276
467
  //#endregion
277
- //#region src/read-pages.ts
278
- /** Agent reads retain bounded page positions, never prompt bodies in the cursor cache. */
279
- const Tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired result tokens; the host may allocate fewer.");
280
- const Cursor = z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque server-generated continuation. Do not alter or combine with initial arguments.");
281
- const ListStart = z.strictObject({
282
- limit: z.number().int().min(1).max(100).default(50).describe("Maximum summaries per call: default 50, hard maximum 100."),
283
- outputTokens: Tokens
468
+ //#region src/data.ts
469
+ const Continue$1 = z.strictObject({
470
+ cursor: z.string(),
471
+ outputTokens: z.number().optional()
284
472
  });
285
- const Continue = z.strictObject({
286
- cursor: Cursor,
287
- outputTokens: Tokens
473
+ const AgentField = z.enum([
474
+ "identity",
475
+ "instructions",
476
+ "style",
477
+ "reminder",
478
+ "tools",
479
+ "defaultModel"
480
+ ]);
481
+ const AgentReceiptSchema = z.strictObject({
482
+ ok: z.literal(true),
483
+ committed: z.literal(true),
484
+ id: z.string(),
485
+ revision: z.string(),
486
+ changedFields: z.array(z.string()),
487
+ summary: z.string().max(512).optional(),
488
+ name: z.string().optional().describe("Replacement display name; omit to retain the current name."),
489
+ startsSessions: z.boolean().optional().describe("Allow direct conversations. Creation defaults to true; update omission retains the current value.")
288
490
  });
289
- const ListInput = z.union([ListStart, Continue]);
290
491
  const Metadata = z.strictObject({
291
492
  id: z.string(),
292
493
  name: z.string(),
293
494
  description: z.string(),
495
+ startsSessions: z.boolean(),
294
496
  revision: z.string()
295
497
  });
296
- const ListOutput = z.strictObject({
498
+ const AgentListDataSchema = z.strictObject({
297
499
  ok: z.literal(true),
298
500
  complete: z.boolean(),
299
501
  items: z.array(Metadata),
300
502
  next: z.strictObject({
301
503
  tool: z.literal("agent_list"),
302
- arguments: Continue
504
+ arguments: Continue$1
303
505
  }).nullable(),
304
506
  effective: z.strictObject({
305
507
  limit: z.number(),
306
508
  outputTokens: z.number()
307
509
  })
308
510
  });
309
- /** Registers a stable summary list in the framework's current readable scope. */
511
+ const Chunk = z.strictObject({
512
+ id: z.string(),
513
+ revision: z.string(),
514
+ field: AgentField,
515
+ body: LocalBodyRefSchema,
516
+ startByte: z.number().int().nonnegative(),
517
+ endByte: z.number().int().nonnegative(),
518
+ offset: z.number().int().nonnegative(),
519
+ length: z.number().int().nonnegative(),
520
+ complete: z.boolean()
521
+ });
522
+ const AgentReadDataSchema = z.strictObject({
523
+ ok: z.literal(true),
524
+ complete: z.boolean(),
525
+ items: z.array(z.union([Metadata, Chunk])),
526
+ next: z.strictObject({
527
+ tool: z.literal("agent_read"),
528
+ arguments: Continue$1
529
+ }).nullable(),
530
+ effective: z.strictObject({ outputTokens: z.number() })
531
+ });
532
+ //#endregion
533
+ //#region src/read-pages.ts
534
+ const Tokens = z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional().describe("Desired result tokens; the host may allocate fewer.");
535
+ const Cursor = z.string().min(1).max(512).regex(/^[\x21-\x7e]+$/).describe("Opaque server-generated continuation. Do not alter or combine with initial arguments.");
536
+ const ListStart = z.strictObject({
537
+ limit: z.number().int().min(1).max(100).default(50).describe("Maximum summaries per call: default 50, hard maximum 100."),
538
+ outputTokens: Tokens
539
+ });
540
+ const Continue = z.strictObject({
541
+ cursor: Cursor,
542
+ outputTokens: Tokens
543
+ });
544
+ const ListInput = z.union([ListStart, Continue]);
310
545
  function registerAgentList(container, agent) {
546
+ const documents = createTextDocuments((value) => pageDocument(value, "agent_list"));
311
547
  const positions = new QueryCursorCache((state) => ({
312
548
  initial: state.query.initial,
313
- content: state.result && "content" in state.result ? state.result.content : void 0
549
+ metadata: state.selection
314
550
  }), container.services.get("query-resources"));
315
551
  container.onDispose?.(() => positions.clear());
316
552
  const address = (ctx) => JSON.stringify(ctx.address);
317
553
  const failure = (code, message, next = null) => ({
318
- content: JSON.stringify({
554
+ data: {
319
555
  ok: false,
320
556
  error: {
321
557
  code,
@@ -323,17 +559,21 @@ function registerAgentList(container, agent) {
323
559
  retryable: next !== null
324
560
  },
325
561
  next
326
- }),
562
+ },
563
+ execution: { state: "not-started" },
327
564
  isError: true
328
565
  });
329
- container.tools.register(positions.wrap({
566
+ registerExact(container, positions, documents.prepare, {
330
567
  name: "agent_list",
331
568
  preload: false,
332
569
  description: "List readable Agent definition summaries in stable id order. Prompt bodies, tools and owner configuration are omitted. Use agent_read for permitted details; follow next.arguments unchanged.",
333
570
  inputSchema: ListInput,
334
- outputSchema: toolOutputSchema(ListOutput, ListInput, "agent_list"),
571
+ outputSchema: toolOutputSchema(AgentListDataSchema, ListInput, "agent_list"),
335
572
  deliveryKind: "exact-page",
573
+ formatModel: documents.formatModel,
336
574
  async execute(input, ctx) {
575
+ const measure = async (result, _signal) => ctx.output.measure(result, await documents.prepare(result.data, ctx), ctx.signal);
576
+ const accept = async (result, _signal) => ctx.output.acceptExact(result, await documents.prepare(result.data, ctx), ctx.signal);
337
577
  ctx.signal.throwIfAborted();
338
578
  const now = performance.now();
339
579
  let position;
@@ -359,51 +599,44 @@ function registerAgentList(container, agent) {
359
599
  tool: "agent_list",
360
600
  arguments: query.initial
361
601
  });
362
- if (position?.result) {
363
- if (ctx.output.measure(position.result) > ctx.output.outputTokens) return failure("page_too_small", "The saved page requires a larger independent allocation.", ctx.output.measure(position.result) <= ctx.output.maximumTokens ? {
364
- tool: "agent_list",
365
- arguments: {
366
- ...input,
367
- outputTokens: ctx.output.measure(position.result)
368
- }
369
- } : null);
370
- position.used = now;
371
- ctx.output.acceptExact(position.result);
372
- return position.result;
373
- }
374
- const cursor = randomUUID();
602
+ const cursor = position?.selection?.cursor ?? randomUUID();
375
603
  const build = (count) => {
376
604
  const complete = count === source.items.length && source.complete;
377
- return { content: JSON.stringify({
378
- ok: true,
379
- complete,
380
- items: source.items.slice(0, count).map(({ agentId, name, description, revision }) => ({
381
- id: agentId,
382
- name,
383
- description,
384
- revision
385
- })),
386
- next: complete ? null : {
387
- tool: "agent_list",
388
- arguments: { cursor }
605
+ return pageBusinessResult({
606
+ data: {
607
+ ok: true,
608
+ complete,
609
+ items: source.items.slice(0, count).map(({ agentId, name, description, startsSessions, revision }) => ({
610
+ id: agentId,
611
+ name,
612
+ description,
613
+ startsSessions,
614
+ revision
615
+ })),
616
+ next: complete ? null : {
617
+ tool: "agent_list",
618
+ arguments: { cursor }
619
+ },
620
+ effective: {
621
+ limit: query.limit,
622
+ outputTokens: position?.selection?.outputTokens ?? ctx.output.outputTokens
623
+ }
389
624
  },
390
- effective: {
391
- limit: query.limit,
392
- outputTokens: ctx.output.outputTokens
393
- }
394
- }) };
625
+ execution: { state: "committed" },
626
+ isError: false
627
+ }, "agent_list");
395
628
  };
396
- let count = source.items.length;
629
+ let count = position?.selection?.count ?? source.items.length;
397
630
  let result = build(count);
398
- while (count > 0 && ctx.output.measure(result) > ctx.output.outputTokens) result = build(--count);
399
- if (count === 0 && source.items.length > 0 || ctx.output.measure(result) > ctx.output.outputTokens) return failure("page_too_small", "One complete summary does not fit this call.", ctx.output.measure(build(Math.min(1, source.items.length))) <= ctx.output.maximumTokens ? {
631
+ while (!position?.selection && count > 0 && await measure(result, ctx.signal) > ctx.output.outputTokens) result = build(--count);
632
+ if (count === 0 && source.items.length > 0 || await measure(result, ctx.signal) > ctx.output.outputTokens) return failure("page_too_small", "One complete summary does not fit this call.", await measure(build(Math.min(1, source.items.length)), ctx.signal) <= ctx.output.maximumTokens ? {
400
633
  tool: "agent_list",
401
634
  arguments: {
402
635
  ...query.initial,
403
- outputTokens: ctx.output.measure(build(Math.min(1, source.items.length)))
636
+ outputTokens: await measure(build(Math.min(1, source.items.length)), ctx.signal)
404
637
  }
405
638
  } : null);
406
- if (!(count === source.items.length && source.complete)) {
639
+ if (!(count === source.items.length && source.complete) && !positions.has(cursor)) {
407
640
  for (const [key, old] of positions) if (now - old.created > 36e5 || old.sessionId === ctx.sessionId && old.generation !== ctx.historyGeneration) positions.delete(key);
408
641
  const roots = [...new Set([...positions.values()].filter((old) => old.sessionId === ctx.sessionId).map((old) => old.query.initial))];
409
642
  if (!roots.includes(query.initial) && roots.length >= 16) {
@@ -425,61 +658,39 @@ function registerAgentList(container, agent) {
425
658
  }
426
659
  });
427
660
  }
428
- await positions.prepare(query.initial, result.content);
429
- ctx.output.acceptExact(result);
661
+ await positions.prepare(query.initial, result.data);
662
+ await accept(result, ctx.signal);
430
663
  if (position) {
431
- position.result = result;
664
+ position.selection ??= {
665
+ count,
666
+ cursor,
667
+ outputTokens: ctx.output.outputTokens
668
+ };
432
669
  position.used = now;
433
670
  }
434
671
  trimCursorCache(positions, (state) => ({
435
672
  initial: state.query.initial,
436
- content: state.result && "content" in state.result ? state.result.content : void 0
673
+ metadata: state.selection
437
674
  }));
438
675
  return result;
439
676
  }
440
- }));
677
+ });
441
678
  }
442
- const Field = z.enum([
443
- "identity",
444
- "instructions",
445
- "style",
446
- "reminder",
447
- "tools",
448
- "extensionData"
449
- ]);
450
679
  const ReadStart = z.strictObject({
451
- fields: z.array(Field).min(1).max(6).optional().describe("Explicit fields to read. Omit for metadata only; large fields return exact text fragments."),
680
+ agentId: z.string().min(1).optional().describe("Exact definition id from agent_list; omission selects the executing definition."),
681
+ fields: z.array(AgentField).min(1).max(6).optional().describe("Explicit fields to read. Omit for metadata only; large fields return exact text fragments."),
452
682
  outputTokens: Tokens
453
683
  });
454
684
  const ReadInput = z.union([ReadStart, Continue]);
455
- const Chunk = z.strictObject({
456
- id: z.string(),
457
- revision: z.string(),
458
- field: Field,
459
- content: z.string(),
460
- offset: z.number().int().nonnegative(),
461
- length: z.number().int().nonnegative(),
462
- complete: z.boolean()
463
- });
464
- const ReadOutput = z.strictObject({
465
- ok: z.literal(true),
466
- complete: z.boolean(),
467
- items: z.array(z.union([Metadata, Chunk])),
468
- next: z.strictObject({
469
- tool: z.literal("agent_read"),
470
- arguments: Continue
471
- }).nullable(),
472
- effective: z.strictObject({ outputTokens: z.number() })
473
- });
474
- /** Reads metadata without prompt IO; explicit fields retain revision-bound fragment positions. */
475
685
  function registerAgentRead(container, agent) {
686
+ const documents = createTextDocuments((value) => pageDocument(value, "agent_read"));
476
687
  const positions = new QueryCursorCache((state) => ({
477
688
  initial: state.query.initial,
478
- content: state.result && "content" in state.result ? state.result.content : void 0
689
+ metadata: state.selection
479
690
  }), container.services.get("query-resources"));
480
691
  container.onDispose?.(() => positions.clear());
481
692
  const failure = (code, message, next = null) => ({
482
- content: JSON.stringify({
693
+ data: {
483
694
  ok: false,
484
695
  error: {
485
696
  code,
@@ -487,22 +698,32 @@ function registerAgentRead(container, agent) {
487
698
  retryable: next !== null
488
699
  },
489
700
  next
490
- }),
701
+ },
702
+ execution: { state: "not-started" },
491
703
  isError: true
492
704
  });
493
- container.tools.register(positions.wrap({
705
+ registerExact(container, positions, documents.prepare, {
494
706
  name: "agent_read",
495
707
  preload: false,
496
- description: "Read your current Agent metadata by default. Explicit fields read exact revision-bound text fragments, including JSON text for tools and extensionData. Follow next.arguments unchanged before claiming a field was read completely. The revision protects later updates.",
708
+ description: "Read metadata for an exact agentId from agent_list, defaulting to the executing definition. Explicit fields read revision-bound text fragments; tools and the explicit defaultModel use JSON text. Arbitrary owner configuration is never returned. Follow next.arguments unchanged to finish a field. The revision protects later updates.",
497
709
  inputSchema: ReadInput,
498
- outputSchema: toolOutputSchema(ReadOutput, ReadInput, "agent_read"),
710
+ outputSchema: toolOutputSchema(AgentReadDataSchema, ReadInput, "agent_read"),
499
711
  deliveryKind: "exact-page",
712
+ formatModel: documents.formatModel,
500
713
  async execute(input, ctx) {
714
+ const measure = async (result, _signal) => ctx.output.measure(result, await documents.prepare(result.data, ctx), ctx.signal);
715
+ const accept = async (result, _signal) => ctx.output.acceptExact(result, await documents.prepare(result.data, ctx), ctx.signal);
501
716
  ctx.signal.throwIfAborted();
502
717
  const now = performance.now(), address = JSON.stringify(ctx.address);
503
718
  let saved;
504
719
  let query;
505
- const metadata = agent.page(ctx, { limit: 1 });
720
+ let fieldSnapshot;
721
+ const requestedId = "cursor" in input ? positions.get(input.cursor)?.query.initial.agentId : input.agentId;
722
+ const metadata = agent.page(ctx, {
723
+ limit: 1,
724
+ current: true,
725
+ agentId: requestedId
726
+ });
506
727
  if ("cursor" in input) {
507
728
  saved = positions.get(input.cursor);
508
729
  if (!saved || saved.sessionId !== ctx.sessionId || saved.address !== address || saved.generation !== ctx.historyGeneration) return failure("cursor_invalid", "This cursor does not belong to the current effective session.");
@@ -511,92 +732,98 @@ function registerAgentRead(container, agent) {
511
732
  tool: "agent_read",
512
733
  arguments: query.initial
513
734
  });
514
- } else query = {
515
- initial: input,
516
- version: metadata.queryVersion,
517
- field: 0,
518
- offset: 0
519
- };
520
- if (metadata.queryVersion !== query.version) return failure("source_changed", "Agent definition changed; restart the field query.", {
735
+ } else {
736
+ fieldSnapshot = input.fields === void 0 ? void 0 : agent.read(ctx, input.agentId);
737
+ query = {
738
+ initial: input,
739
+ version: fieldSnapshot?.revision ?? metadata.queryVersion,
740
+ field: 0,
741
+ offset: 0
742
+ };
743
+ }
744
+ if (query.initial.fields !== void 0 && fieldSnapshot === void 0) fieldSnapshot = agent.read(ctx, query.initial.agentId);
745
+ if ((fieldSnapshot?.revision ?? metadata.queryVersion) !== query.version) return failure("source_changed", "Agent definition changed; restart the field query.", {
521
746
  tool: "agent_read",
522
747
  arguments: query.initial
523
748
  });
524
- if (saved?.result) {
525
- if (ctx.output.measure(saved.result) > ctx.output.outputTokens) return failure("page_too_small", "The saved page needs a larger independent allowance.", ctx.output.measure(saved.result) <= ctx.output.maximumTokens ? {
526
- tool: "agent_read",
527
- arguments: {
528
- ...input,
529
- outputTokens: ctx.output.measure(saved.result)
530
- }
531
- } : null);
532
- ctx.output.acceptExact(saved.result);
533
- saved.used = now;
534
- return saved.result;
535
- }
536
- const effective = { outputTokens: ctx.output.outputTokens };
749
+ const effective = { outputTokens: saved?.selection?.outputTokens ?? ctx.output.outputTokens };
537
750
  if (query.initial.fields === void 0) {
538
- const result = { content: JSON.stringify({
539
- ok: true,
540
- complete: true,
541
- items: metadata.items.map(({ agentId, name, description, revision }) => ({
542
- id: agentId,
543
- name,
544
- description,
545
- revision
546
- })),
547
- next: null,
548
- effective
549
- }) };
550
- if (ctx.output.measure(result) > ctx.output.outputTokens) return failure("page_too_small", "Complete metadata does not fit this call.");
551
- await positions.prepare(query.initial, result.content);
552
- ctx.output.acceptExact(result);
751
+ const result = pageBusinessResult({
752
+ data: {
753
+ ok: true,
754
+ complete: true,
755
+ items: metadata.items.map(({ agentId, name, description, startsSessions, revision }) => ({
756
+ id: agentId,
757
+ name,
758
+ description,
759
+ startsSessions,
760
+ revision
761
+ })),
762
+ next: null,
763
+ effective
764
+ },
765
+ execution: { state: "committed" },
766
+ isError: false
767
+ }, "agent_read");
768
+ if (await measure(result, ctx.signal) > ctx.output.outputTokens) return failure("page_too_small", "Complete metadata does not fit this call.");
769
+ await positions.prepare(query.initial, result.data);
770
+ await accept(result, ctx.signal);
553
771
  trimCursorCache(positions, (state) => ({
554
772
  initial: state.query.initial,
555
- content: state.result && "content" in state.result ? state.result.content : void 0
773
+ metadata: state.selection
556
774
  }));
557
775
  return result;
558
776
  }
559
- const snapshot = agent.read(ctx);
560
- if (snapshot.revision !== metadata.items.find((item) => item.agentId === snapshot.agentId)?.revision) return failure("source_changed", "Agent definition changed during the field read.", {
777
+ const snapshot = fieldSnapshot;
778
+ const field = query.initial.fields[query.field];
779
+ const window = unicodeWindow(field === "tools" ? JSON.stringify(snapshot.tools) : field === "defaultModel" ? JSON.stringify(defaultModelOf(snapshot)) : snapshot.prompts[field], query.offset, saved?.selection?.count ?? Math.min(32768, Math.max(1, ctx.output.outputTokens * 4)));
780
+ const points = window.points;
781
+ const body = await captureTextBody(points.join(""), ctx);
782
+ ctx.signal.throwIfAborted();
783
+ if (agent.read(ctx, query.initial.agentId).revision !== query.version) return failure("source_changed", "Agent definition changed while capturing its original field; restart.", {
561
784
  tool: "agent_read",
562
785
  arguments: query.initial
563
786
  });
564
- if (query.initial.fields.includes("instructions") && snapshot.prompts.failure) return failure("source_unavailable", [...snapshot.prompts.failure].slice(0, 256).join(""));
565
- const field = query.initial.fields[query.field];
566
- const window = unicodeWindow(field === "tools" ? JSON.stringify(snapshot.tools) : field === "extensionData" ? JSON.stringify(snapshot.extensionData) : snapshot.prompts[field], query.offset, Math.min(32768, Math.max(1, ctx.output.outputTokens * 4)));
567
- const points = window.points;
568
- const cursor = randomUUID();
787
+ const byteEnds = [0];
788
+ for (const point of points) byteEnds.push(byteEnds.at(-1) + Buffer.byteLength(point));
789
+ const cursor = saved?.selection?.cursor ?? randomUUID();
569
790
  const build = (count) => {
570
791
  const fieldComplete = window.complete && count === points.length;
571
792
  const complete = fieldComplete && query.field + 1 === query.initial.fields.length;
572
- return { content: JSON.stringify({
573
- ok: true,
574
- complete,
575
- items: [{
576
- id: snapshot.agentId,
577
- revision: snapshot.revision,
578
- field,
579
- content: points.slice(0, count).join(""),
580
- offset: query.offset,
581
- length: count,
582
- complete: fieldComplete
583
- }],
584
- next: complete ? null : {
585
- tool: "agent_read",
586
- arguments: { cursor }
793
+ return pageBusinessResult({
794
+ data: {
795
+ ok: true,
796
+ complete,
797
+ items: [{
798
+ id: snapshot.agentId,
799
+ revision: snapshot.revision,
800
+ field,
801
+ body,
802
+ startByte: 0,
803
+ endByte: byteEnds[count],
804
+ offset: query.offset,
805
+ length: count,
806
+ complete: fieldComplete
807
+ }],
808
+ next: complete ? null : {
809
+ tool: "agent_read",
810
+ arguments: { cursor }
811
+ },
812
+ effective
587
813
  },
588
- effective
589
- }) };
814
+ execution: { state: "committed" },
815
+ isError: false
816
+ }, "agent_read");
590
817
  };
591
- let low = 0, high = points.length;
818
+ let low = saved?.selection?.count ?? 0, high = points.length;
592
819
  while (low < high) {
593
820
  const middle = Math.ceil((low + high) / 2);
594
- if (ctx.output.measure(build(middle)) <= ctx.output.outputTokens) low = middle;
821
+ if (await measure(build(middle), ctx.signal) <= ctx.output.outputTokens) low = middle;
595
822
  else high = middle - 1;
596
823
  }
597
824
  const result = build(low);
598
- if (low === 0 && points.length > 0 || ctx.output.measure(result) > ctx.output.outputTokens) {
599
- const cost = ctx.output.measure(build(Math.min(1, points.length)));
825
+ if (low === 0 && points.length > 0 || await measure(result, ctx.signal) > ctx.output.outputTokens) {
826
+ const cost = await measure(build(Math.min(1, points.length)), ctx.signal);
600
827
  return failure("page_too_small", "The field envelope and one code point do not fit.", cost <= ctx.output.maximumTokens ? {
601
828
  tool: "agent_read",
602
829
  arguments: {
@@ -606,7 +833,7 @@ function registerAgentRead(container, agent) {
606
833
  } : null);
607
834
  }
608
835
  const fieldComplete = window.complete && low === points.length;
609
- if (!(fieldComplete && query.field + 1 === query.initial.fields.length)) {
836
+ if (!(fieldComplete && query.field + 1 === query.initial.fields.length) && !positions.has(cursor)) {
610
837
  for (const [key, old] of positions) if (now - old.created > 36e5 || old.sessionId === ctx.sessionId && old.generation !== ctx.historyGeneration) positions.delete(key);
611
838
  const roots = [...new Set([...positions.values()].filter((old) => old.sessionId === ctx.sessionId).map((old) => old.query.initial))];
612
839
  if (!roots.includes(query.initial) && roots.length >= 16) {
@@ -629,25 +856,28 @@ function registerAgentRead(container, agent) {
629
856
  }
630
857
  });
631
858
  }
632
- await positions.prepare(query.initial, result.content);
633
- ctx.output.acceptExact(result);
859
+ await positions.prepare(query.initial, result.data);
860
+ await accept(result, ctx.signal);
634
861
  if (saved) {
635
- saved.result = result;
862
+ saved.selection ??= {
863
+ count: low,
864
+ cursor,
865
+ outputTokens: ctx.output.outputTokens
866
+ };
636
867
  trimCursorCache(positions, (state) => ({
637
868
  initial: state.query.initial,
638
- content: state.result && "content" in state.result ? state.result.content : void 0
869
+ metadata: state.selection
639
870
  }));
640
871
  saved.used = now;
641
872
  }
642
873
  trimCursorCache(positions, (state) => ({
643
874
  initial: state.query.initial,
644
- content: state.result && "content" in state.result ? state.result.content : void 0
875
+ metadata: state.selection
645
876
  }));
646
877
  return result;
647
878
  }
648
- }));
879
+ });
649
880
  }
650
- /** Builds a bounded Unicode window without allocating an array for the complete source. */
651
881
  function unicodeWindow(text, offset, maximum) {
652
882
  let unit = 0, skipped = 0;
653
883
  while (unit < text.length && skipped < offset) {
@@ -665,9 +895,21 @@ function unicodeWindow(text, offset, maximum) {
665
895
  complete: unit === text.length
666
896
  };
667
897
  }
898
+ function registerExact(container, positions, prepare, tool) {
899
+ const wrapped = positions.wrap(tool);
900
+ container.tools.register({
901
+ ...wrapped,
902
+ async execute(input, ctx) {
903
+ const result = await wrapped.execute(input, ctx);
904
+ if (!("data" in result) || !result.isError) return result;
905
+ const admitted = pageBusinessResult(result, tool.name);
906
+ await ctx.output.acceptExact(admitted, await prepare(admitted.data, ctx), ctx.signal);
907
+ return admitted;
908
+ }
909
+ });
910
+ }
668
911
  //#endregion
669
912
  //#region src/tool-names.ts
670
- /** Canonical names shared by tool registration and browser presentation. */
671
913
  const AGENT_TOOL_NAMES = [
672
914
  "agent_list",
673
915
  "agent_read",
@@ -676,10 +918,6 @@ const AGENT_TOOL_NAMES = [
676
918
  ];
677
919
  //#endregion
678
920
  //#region src/tools.ts
679
- const ModelRef = z.strictObject({
680
- providerId: z.string().min(1).describe("Exact providerId from model_list."),
681
- model: z.string().min(1).describe("Exact model identifier from model_list.")
682
- });
683
921
  const AgentCreateInput = z.strictObject({
684
922
  name: z.string().describe("Agent display name; must be nonblank after trimming."),
685
923
  description: z.string().optional().describe("Short discovery description, at most 500 Unicode code points after trimming."),
@@ -689,10 +927,11 @@ const AgentCreateInput = z.strictObject({
689
927
  style: z.string().optional().describe("Reply style. Omit to retain an existing value on update; empty text clears this field."),
690
928
  reminder: z.string().optional().describe("Reminder repeated on each step. Omit to retain an existing value on update; empty text clears this field.")
691
929
  }).optional().describe("Optional prompt fields; creation starts omitted fields empty, update retains omitted fields."),
692
- defaultModel: ModelRef.nullable().optional().describe("Use model_list to find available providerId/model pairs before choosing an Agent default."),
930
+ defaultModel: AgentDefaultModel.nullable().optional().describe("Use model_list to find available providerId/model pairs before choosing an Agent default."),
693
931
  startsSessions: z.boolean().optional().describe("Allow direct conversations. Creation defaults to true; update omission retains the current value.")
694
932
  });
695
933
  const Update = z.strictObject({
934
+ agentId: z.string().min(1).optional().describe("Exact target id from agent_list; omission selects the executing definition."),
696
935
  name: z.string().optional().describe("Replacement display name; omit to retain the current name."),
697
936
  description: z.string().optional().describe("Short discovery description, at most 500 Unicode code points after trimming."),
698
937
  prompts: z.strictObject({
@@ -701,41 +940,48 @@ const Update = z.strictObject({
701
940
  style: z.string().optional().describe("Reply style. Omit to retain an existing value on update; empty text clears this field."),
702
941
  reminder: z.string().optional().describe("Reminder repeated on each step. Omit to retain an existing value on update; empty text clears this field.")
703
942
  }).optional().describe("Only supplied prompt fields change; empty text clears that field."),
704
- defaultModel: ModelRef.nullable().optional().describe("Use model_list to find available providerId/model pairs before choosing an Agent default."),
943
+ defaultModel: AgentDefaultModel.nullable().optional().describe("Use model_list to find available providerId/model pairs before choosing an Agent default."),
705
944
  startsSessions: z.boolean().optional().describe("Allow direct conversations. Creation defaults to true; update omission retains the current value."),
706
945
  expectedRevision: z.string().optional().describe("Current revision from agent_read; a mismatch refuses the update before a write.")
707
946
  }).refine(({ name, description, prompts, defaultModel, startsSessions }) => name !== void 0 || description !== void 0 || Object.keys(prompts ?? {}).length > 0 || defaultModel !== void 0 || startsSessions !== void 0, "provide at least one field to change");
708
- const Receipt = z.strictObject({
709
- ok: z.literal(true),
710
- committed: z.literal(true),
711
- id: z.string(),
712
- revision: z.string(),
713
- changedFields: z.array(z.string()),
714
- name: z.string().optional().describe("Replacement display name; omit to retain the current name."),
715
- startsSessions: z.boolean().optional().describe("Allow direct conversations. Creation defaults to true; update omission retains the current value.")
947
+ const Created = z.strictObject({
948
+ agentId: z.string().min(1),
949
+ revision: z.string().min(1),
950
+ name: z.string(),
951
+ startsSessions: z.boolean()
716
952
  });
717
- function receipt(result, changedFields) {
718
- if (!("content" in result) || result.isError) return result;
719
- let parsed;
720
- try {
721
- parsed = JSON.parse(result.content);
722
- } catch {
723
- return result;
953
+ function receipt(result, changedFields, schema) {
954
+ if (!("data" in result)) return result;
955
+ if (result.isError) {
956
+ const data = schema.parse(result.data);
957
+ return {
958
+ ...result,
959
+ data,
960
+ presentation: receiptPresentation(data, "agent-created")
961
+ };
724
962
  }
725
- const data = parsed.data;
726
- if (!data?.agentId || !data.revision) return result;
727
- return { content: JSON.stringify({
963
+ const source = Created.parse(result.data);
964
+ const data = AgentReceiptSchema.parse({
728
965
  ok: true,
729
966
  committed: true,
730
- id: data.agentId,
731
- revision: data.revision,
967
+ id: source.agentId,
968
+ revision: source.revision,
732
969
  changedFields,
733
- ...data.name === void 0 ? {} : { name: data.name },
734
- ...data.startsSessions === void 0 ? {} : { startsSessions: data.startsSessions }
735
- }) };
970
+ name: source.name,
971
+ startsSessions: source.startsSessions,
972
+ summary: "Agent created. No session was started. Direct conversation settings do not affect delegation or existing sessions."
973
+ });
974
+ return {
975
+ data: schema.parse(data),
976
+ execution: result.execution,
977
+ isError: false,
978
+ presentation: receiptPresentation(data, "agent-created")
979
+ };
736
980
  }
737
- /** Registers owner-scoped tools and guidance over the ordinary tool source. */
738
981
  function registerAgentTools(container, agent, create) {
982
+ const documents = createTextDocuments(receiptDocument);
983
+ const CreateOutput = toolOutputSchema(AgentReceiptSchema, AgentCreateInput, "agent_create");
984
+ const UpdateOutput = toolOutputSchema(AgentReceiptSchema, Update, "agent_update");
739
985
  registerAgentList(container, agent);
740
986
  const modelConfiguration = () => {
741
987
  const service = container.services.find("agent-model-configuration");
@@ -747,32 +993,63 @@ function registerAgentTools(container, agent, create) {
747
993
  preload: false,
748
994
  description: "Create a new agent after approval. This does not start a session.",
749
995
  inputSchema: AgentCreateInput,
750
- outputSchema: toolOutputSchema(z.union([Receipt, z.string().max(1024)]), AgentCreateInput, "agent_create"),
996
+ outputSchema: CreateOutput,
751
997
  deliveryKind: "receipt",
998
+ formatModel: documents.formatModel,
752
999
  execute: ({ defaultModel, ...input }, exec) => create({
753
1000
  ...input,
754
1001
  ...defaultModel === void 0 ? {} : { extensionData: modelConfiguration().withDefault(defaultModel) }
755
- }, exec).then((result) => receipt(result, [...Object.keys(input), ...defaultModel === void 0 ? [] : ["defaultModel"]]))
1002
+ }, exec).then((result) => receipt(result, [...Object.keys(input), ...defaultModel === void 0 ? [] : ["defaultModel"]], CreateOutput))
756
1003
  });
757
1004
  registerAgentRead(container, agent);
758
1005
  container.tools.register({
759
1006
  name: "agent_update",
760
1007
  preload: false,
761
- description: "Update your own name, description, prompt slots, default model or direct conversation settings after approval. Omitted fields remain unchanged. Tool permissions cannot be changed here.",
1008
+ description: "Update the exact agentId from agent_list, or the executing definition when omitted, after approval. Read the target before editing. Only supplied name, description, prompt slots, default model or direct conversation settings change. Tool permissions cannot be changed here.",
762
1009
  inputSchema: Update,
763
- outputSchema: toolOutputSchema(z.union([Receipt, z.string().max(1024)]), Update, "agent_update"),
1010
+ outputSchema: UpdateOutput,
764
1011
  deliveryKind: "receipt",
765
- execute: ({ expectedRevision, defaultModel, ...patch }, exec) => agent.update(exec, {
766
- ...patch,
767
- ...defaultModel === void 0 ? {} : { extensionData: modelConfiguration().withDefault(defaultModel, agent.read(exec).extensionData) }
768
- }, expectedRevision).then((result) => receipt(result, [...Object.keys(patch), ...defaultModel === void 0 ? [] : ["defaultModel"]]))
1012
+ formatModel: documents.formatModel,
1013
+ async execute({ agentId, expectedRevision, defaultModel, ...patch }, exec) {
1014
+ const before = defaultModel === void 0 ? void 0 : agent.read(exec, agentId);
1015
+ if (before && expectedRevision !== void 0 && expectedRevision !== before.revision) throw new Error("revision-conflict");
1016
+ let saved;
1017
+ const result = await agent.update(exec, {
1018
+ ...patch,
1019
+ ...defaultModel === void 0 ? {} : { extensionData: modelConfiguration().withDefault(defaultModel, before.extensionData) }
1020
+ }, before?.revision ?? expectedRevision, agentId, (snapshot) => {
1021
+ defaultModelOf(snapshot);
1022
+ const data = AgentReceiptSchema.parse({
1023
+ ok: true,
1024
+ committed: true,
1025
+ id: snapshot.agentId,
1026
+ revision: snapshot.revision,
1027
+ changedFields: [...Object.keys(patch), ...defaultModel === void 0 ? [] : ["defaultModel"]],
1028
+ name: snapshot.name,
1029
+ startsSessions: snapshot.startsSessions,
1030
+ summary: "Prompts apply on the next model call. Default models affect only new sessions. Direct conversation settings do not stop existing sessions or delegation."
1031
+ });
1032
+ saved = {
1033
+ data,
1034
+ execution: { state: "committed" },
1035
+ isError: false,
1036
+ presentation: receiptPresentation(data, "agent-updated")
1037
+ };
1038
+ }, defaultModel === void 0 ? void 0 : `defaultModel = ${JSON.stringify(defaultModel)}`);
1039
+ if (result.kind === "tool-result") return "data" in result.result ? {
1040
+ ...result.result,
1041
+ data: UpdateOutput.parse(result.result.data),
1042
+ presentation: receiptPresentation(result.result.data, "agent-updated")
1043
+ } : result.result;
1044
+ return saved;
1045
+ }
769
1046
  });
770
1047
  container.tools.guide({
771
- title: "Your agent definition",
1048
+ title: "Agent definitions",
772
1049
  entries: [
773
1050
  {
774
1051
  tools: ["agent_list"],
775
- text: "List only readable Agent summaries. Follow next.arguments without modifying its cursor; prompts require an explicit agent_read field."
1052
+ text: "Discover all saved definitions independently of delegation. Use exact ids, not names or name fragments; clarify which id the person means when names are duplicated. Follow next.arguments unchanged; prompts require an explicit agent_read field."
776
1053
  },
777
1054
  {
778
1055
  tools: ["agent_create"],
@@ -780,21 +1057,18 @@ function registerAgentTools(container, agent, create) {
780
1057
  },
781
1058
  {
782
1059
  tools: ["agent_read"],
783
- text: "Read your current definition before editing. A rules-file read failure is not an empty rules file."
1060
+ text: "Read the requested agentId from agent_list before editing and retain its revision. Omission selects the executing definition, including delegates. Metadata is the default; select prompt fields, tools or defaultModel explicitly. A rules-file read failure is not an empty rules file."
784
1061
  },
785
1062
  {
786
1063
  tools: ["agent_update"],
787
- text: "Change only the requested fields. Approval mode governs persistence; tool permissions and credentials cannot be changed here. Report the actual result and when it takes effect."
1064
+ text: "Use the requested exact agentId, or omit it only to edit the executing definition. Change only requested fields and use the read revision to detect conflicts. Approval is target-specific; choosing another definition never borrows its permissions. Verify the returned id and report the actual result and effect timing. Tool permissions, credentials, skills and MCP cannot be changed here."
788
1065
  }
789
1066
  ]
790
1067
  });
791
1068
  }
792
1069
  //#endregion
793
1070
  //#region src/index.ts
794
- /** Concrete Agent tools and their guidance, withdrawn together with this extension. */
795
- /** Each tool can be disabled independently without withdrawing Agent framework state. */
796
1071
  const AgentConfig = z.strictObject({ disabled: z.array(z.enum(AGENT_TOOL_NAMES)).default([]) }).default({ disabled: [] });
797
- /** Agent sessions and configuration remain framework-owned after tool withdrawal. */
798
1072
  const agentPlugin = {
799
1073
  name: "@eum-agent/agent-management",
800
1074
  requires: [
@@ -806,7 +1080,10 @@ const agentPlugin = {
806
1080
  configSchema: AgentConfig,
807
1081
  apply(ctx, config) {
808
1082
  const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
809
- if (existsSync(module)) ctx.client.registerUi({ module });
1083
+ if (existsSync(module)) ctx.client.registerPackageFiles({
1084
+ root: dirname(module),
1085
+ entry: "ui.js"
1086
+ });
810
1087
  const disabled = new Set(config.disabled);
811
1088
  const definition = ctx.services.get("agent-definition");
812
1089
  const creation = ctx.services.get("agent-creation");