@eum-agent/extension-catalog 1.0.3 → 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.
package/dist/index.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { DefaultsEnsureDataSchema, DefaultsEnsureParamsSchema, DefaultsStatusSchema } from "./defaults-contract.js";
2
+ import { dirname } from "node:path";
2
3
  import { existsSync } from "node:fs";
3
4
  import { fileURLToPath } from "node:url";
4
5
  import { z } from "zod";
@@ -7,13 +8,9 @@ import semver from "semver";
7
8
  import { performance } from "node:perf_hooks";
8
9
  import { setTimeout as setTimeout$1 } from "node:timers/promises";
9
10
  //#region src/extension-catalog/errors.ts
10
- /** Catalog failures expose a bounded business reason without remote bodies or secrets. */
11
11
  var CatalogError = class extends Error {
12
- /** Stable owner-specific rejection code. */
13
12
  code;
14
- /** Optional bounded retry delay in seconds. */
15
13
  retryAfterSeconds;
16
- /** Creates a failure from already sanitized text. */
17
14
  constructor(code, message, retryAfterSeconds) {
18
15
  super(message);
19
16
  this.name = "CatalogError";
@@ -21,7 +18,6 @@ var CatalogError = class extends Error {
21
18
  this.retryAfterSeconds = retryAfterSeconds;
22
19
  }
23
20
  };
24
- /** Parses JSON with duplicate-key detection before applying a business schema. */
25
21
  function parseJson(content) {
26
22
  let value;
27
23
  try {
@@ -44,7 +40,6 @@ function parseJson(content) {
44
40
  }
45
41
  return value;
46
42
  }
47
- /** Decodes lossless UTF-8; malformed bytes and JSON BOMs are rejected. */
48
43
  function decodeUtf8(bytes) {
49
44
  try {
50
45
  return new TextDecoder("utf-8", {
@@ -55,7 +50,6 @@ function decodeUtf8(bytes) {
55
50
  throw new CatalogError("CATALOG_INVALID", "Invalid catalog UTF-8");
56
51
  }
57
52
  }
58
- /** Maps known framework refusal prefixes without echoing arbitrary exception bodies. */
59
53
  function managementError(error) {
60
54
  if (error instanceof CatalogError) return error;
61
55
  const codes = [
@@ -79,11 +73,8 @@ function managementError(error) {
79
73
  }
80
74
  //#endregion
81
75
  //#region src/extension-catalog/schema.ts
82
- /** Fixed public source; callers cannot override the catalog repository. */
83
76
  const CATALOG_REPOSITORY = "https://github.com/yanxuan-lc/yaoguang-presets";
84
- /** Maximum encoded catalog size before decoding or parsing. */
85
77
  const CATALOG_MAX_BYTES = 8388608;
86
- /** Full Git object identity for commits and trees. */
87
78
  const GitShaSchema = z.string().regex(/^[0-9a-f]{40}$/);
88
79
  const text = (max) => z.string().min(1).max(max).refine((v) => !/[\p{Cc}]/u.test(v), "control characters");
89
80
  const https = z.string().min(1).max(2048).refine((value) => {
@@ -94,7 +85,6 @@ const https = z.string().min(1).max(2048).refine((value) => {
94
85
  return false;
95
86
  }
96
87
  }, "expected public HTTPS URL");
97
- /** Supported actual host targets, independent of the browser platform. */
98
88
  const PlatformTargetSchema = z.object({
99
89
  os: z.enum([
100
90
  "linux",
@@ -103,11 +93,8 @@ const PlatformTargetSchema = z.object({
103
93
  ]),
104
94
  arch: z.enum(["x64", "arm64"])
105
95
  }).strict();
106
- /** Canonical complete SemVer release, never a tag or range. */
107
96
  const VersionSchema = z.string().max(128).refine((v) => semver.valid(v) === v, "expected complete SemVer");
108
- /** Canonical SHA512 SRI over the exact compressed archive bytes. */
109
97
  const IntegritySchema = z.string().regex(/^sha512-[A-Za-z0-9+/]{86}==$/).refine((v) => Buffer.from(v.slice(7), "base64").toString("base64") === v.slice(7), "noncanonical SRI");
110
- /** A maintainer-reviewed exact npm release; trust is never inferred from its name. */
111
98
  const ReleaseSchema = z.object({
112
99
  releaseId: text(256),
113
100
  packageName: z.string().max(214).regex(/^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/),
@@ -160,7 +147,6 @@ const ReleaseSchema = z.object({
160
147
  const targets = value.compatibility.platforms.map((p) => `${p.os}/${p.arch}`);
161
148
  if (new Set(targets).size !== targets.length) issue(["compatibility", "platforms"], "duplicate target");
162
149
  });
163
- /** Entire generated index, validated before any release becomes available. */
164
150
  const CatalogSchema = z.object({ releases: z.array(ReleaseSchema).max(2e3) }).strict().superRefine((value, ctx) => {
165
151
  const ids = /* @__PURE__ */ new Set();
166
152
  for (const [i, release] of value.releases.entries()) {
@@ -176,7 +162,6 @@ const CatalogSchema = z.object({ releases: z.array(ReleaseSchema).max(2e3) }).st
176
162
  ids.add(release.releaseId);
177
163
  }
178
164
  });
179
- /** Immutable complete successful snapshot; revision is assigned at local publication. */
180
165
  const SnapshotSchema = z.object({
181
166
  repository: z.literal(CATALOG_REPOSITORY),
182
167
  commit: GitShaSchema,
@@ -185,30 +170,25 @@ const SnapshotSchema = z.object({
185
170
  revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
186
171
  releases: z.array(ReleaseSchema).max(2e3)
187
172
  }).strict();
188
- /** Client selection binds one displayed commit and exact archive identity. */
189
173
  const SelectionSchema = z.object({
190
174
  snapshotCommit: GitShaSchema,
191
175
  releaseId: text(256),
192
176
  artifactIntegrity: IntegritySchema,
193
177
  expectedInstalledReceiptId: z.uuid().optional()
194
178
  }).strict();
195
- /** Produces stable key-sorted JSON for source and request evidence. */
196
179
  function canonicalJson(value) {
197
180
  if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
198
181
  if (value && typeof value === "object") return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`).join(",")}}`;
199
182
  return JSON.stringify(value);
200
183
  }
201
- /** Binds every record field, including review and compatibility, to one SHA256. */
202
184
  function recordDigest(value) {
203
185
  return createHash("sha256").update(canonicalJson(value)).digest("hex");
204
186
  }
205
- /** Decodes one whole strict release index; duplicate releases reject the entire index. */
206
187
  function decodeReleases(value) {
207
188
  const parsed = CatalogSchema.safeParse(value);
208
189
  if (!parsed.success) throw new CatalogError("CATALOG_INVALID", `Invalid extension catalog: ${parsed.error.issues[0]?.path.join(".") ?? "index"}`);
209
190
  return parsed.data.releases;
210
191
  }
211
- /** Checks the declared product range and actual host target independently of the release version. */
212
192
  function releaseCompatible(release, host) {
213
193
  return semver.satisfies(host.version, release.compatibility.productRange) && release.compatibility.platforms.some((p) => p.os === host.target.os && p.arch === host.target.arch);
214
194
  }
@@ -233,7 +213,6 @@ const CandidateSchema = z.object({
233
213
  ]).optional(),
234
214
  reasonCode: z.string().regex(/^[A-Z][A-Z0-9_]{0,127}$/).optional()
235
215
  }).strict();
236
- /** Entire bounded owner ledger; a corrupt record refuses automatic initialization rather than resetting it. */
237
216
  const DefaultsRecordSchema = z.object({
238
217
  state: z.enum([
239
218
  "pending-snapshot",
@@ -287,7 +266,6 @@ const DefaultsRecordSchema = z.object({
287
266
  });
288
267
  }
289
268
  });
290
- /** Creates a leased SQLite singleton preserving initialization across owner withdrawal. */
291
269
  function createDefaultsStore(storage) {
292
270
  const name = storage.tableName("default_installation");
293
271
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid storage table identity");
@@ -313,2215 +291,7 @@ function createDefaultsStore(storage) {
313
291
  };
314
292
  }
315
293
  //#endregion
316
- //#region ../../core/kernel/src/vocab/address.ts
317
- /**
318
- * A session's address: the `(Agent, Workspace)` pair it belongs to.
319
- * Immutable for the session's whole life — it is set once at session
320
- * creation and carried on every persisted event of that session and on
321
- * the control state folded from them.
322
- */
323
- const SessionAddressSchema = z.object({
324
- agentId: z.string(),
325
- workspaceId: z.string()
326
- });
327
- //#endregion
328
- //#region ../../core/kernel/src/vocab/widgets.ts
329
- /** Returns whether a value is lossless JSON with at most 64 nested containers. */
330
- function isLosslessJson(value) {
331
- const active = /* @__PURE__ */ new Set();
332
- function visit(one, depth) {
333
- if (one === null || typeof one === "boolean") return true;
334
- if (typeof one === "string") return !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(one);
335
- if (typeof one === "number") return Number.isFinite(one) && !Object.is(one, -0);
336
- if (typeof one !== "object" || depth > 64 || active.has(one)) return false;
337
- const array = Array.isArray(one);
338
- if (!array && Object.getPrototypeOf(one) !== Object.prototype && Object.getPrototypeOf(one) !== null) return false;
339
- if (Object.getOwnPropertySymbols(one).length !== 0) return false;
340
- const descriptors = Object.getOwnPropertyDescriptors(one);
341
- if (array && (Object.keys(descriptors).length !== one.length + 1 || !Array.from({ length: one.length }, (_, index) => Object.hasOwn(descriptors, String(index))).every(Boolean))) return false;
342
- active.add(one);
343
- for (const [key, descriptor] of Object.entries(descriptors)) {
344
- if (array && key === "length") continue;
345
- if (!("value" in descriptor) || !descriptor.enumerable || !visit(key, 0) || !visit(descriptor.value, depth + 1)) {
346
- active.delete(one);
347
- return false;
348
- }
349
- }
350
- active.delete(one);
351
- return true;
352
- }
353
- try {
354
- return visit(value, 1);
355
- } catch {
356
- return false;
357
- }
358
- }
359
- /** Pure stored JSON shape; validation requires no owner code. */
360
- const JsonObjectSchema = z.custom((value) => isLosslessJson(value) && value !== null && !Array.isArray(value) && typeof value === "object");
361
- /** Exact, portable widget reference identity. */
362
- const WidgetIdSchema = z.string().regex(/^w_[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
363
- /** Local type names never encode a business catalogue in the host. */
364
- const WidgetTypeSchema = z.string().regex(/^[a-z][a-z0-9-]{0,63}$/);
365
- /** Host-stamped original execution provenance, retained unchanged by forks. */
366
- const WidgetSourceSchema = z.object({
367
- sessionId: z.string().min(1),
368
- messageId: z.string().uuid(),
369
- toolCallId: z.string().min(1),
370
- toolName: z.string().min(1)
371
- }).strict();
372
- /** Complete snapshot stored atomically with its tool result. */
373
- const WidgetInstanceSchema = z.object({
374
- id: WidgetIdSchema,
375
- owner: z.string().min(1),
376
- type: WidgetTypeSchema,
377
- title: z.string().refine((text) => text.trim().length > 0 && [...text].length <= 200),
378
- summary: z.string().refine((text) => text.trim().length > 0 && [...text].length <= 4e3),
379
- data: JsonObjectSchema,
380
- source: WidgetSourceSchema
381
- }).strict().refine((widget) => widgetJsonBytes({
382
- type: widget.type,
383
- title: widget.title,
384
- summary: widget.summary,
385
- data: widget.data
386
- }) <= 262144).transform((widget) => freezeWidget(widget));
387
- /** Fixed diagnostics contain no rejected business data. */
388
- const WidgetIssueCodeSchema = z.enum([
389
- "count-limit",
390
- "invalid-input",
391
- "invalid-json",
392
- "invalid-data",
393
- "item-too-large",
394
- "batch-too-large",
395
- "unknown-type",
396
- "source-unavailable",
397
- "owner-unavailable",
398
- "untrusted-instance",
399
- "error-result"
400
- ]);
401
- /** One item index or one entire-group issue. */
402
- const WidgetIssueSchema = z.object({
403
- code: WidgetIssueCodeSchema,
404
- index: z.number().int().min(0).max(7).optional()
405
- }).strict();
406
- /** Measures complete compact JSON in UTF-8 bytes. */
407
- function widgetJsonBytes(value) {
408
- return new TextEncoder().encode(JSON.stringify(value)).length;
409
- }
410
- /** Copies JSON into a deeply immutable snapshot. */
411
- function freezeWidget(value) {
412
- if (value !== null && typeof value === "object") {
413
- for (const child of Object.values(value)) freezeWidget(child);
414
- Object.freeze(value);
415
- }
416
- return value;
417
- }
418
- //#endregion
419
- //#region ../../core/kernel/src/vocab/owner-context.ts
420
- /** One host-stamped owner fact frozen for a model decision and its derived operations. */
421
- const OwnerContextEntrySchema = z.strictObject({
422
- /** Host-bound capability identity; never supplied by model output. */
423
- owner: z.string().min(1).max(256),
424
- /** Local state name, unique within this owner. */
425
- key: z.string().min(1).max(256),
426
- /** Physical revision of the state selected for this decision. */
427
- revision: z.number().int().nonnegative().safe(),
428
- /** Lossless JSON interpreted only by the owning capability. */
429
- data: z.custom(isLosslessJson)
430
- });
431
- /** Bounded immutable provenance, unique by owner and local key. */
432
- const OwnerContextSchema = z.array(OwnerContextEntrySchema).max(16).superRefine((entries, ctx) => {
433
- const keys = /* @__PURE__ */ new Set();
434
- for (const entry of entries) {
435
- const key = JSON.stringify([entry.owner, entry.key]);
436
- if (keys.has(key)) ctx.addIssue({
437
- code: "custom",
438
- message: "Duplicate owner context key"
439
- });
440
- keys.add(key);
441
- }
442
- if (new TextEncoder().encode(JSON.stringify(entries)).byteLength > 262144) ctx.addIssue({
443
- code: "custom",
444
- message: "Owner context exceeds 256 KiB"
445
- });
446
- }).transform((entries) => freezeWidget(JSON.parse(JSON.stringify(entries))));
447
- //#endregion
448
- //#region ../../core/kernel/src/vocab/message.ts
449
- /**
450
- * The transcript's message shapes: the authoritative history that assembly
451
- * reads. A message is either a plain user/assistant turn of text, an
452
- * assistant reply that also requests tool calls, or a tool-results message
453
- * that answers a batch of those calls. Zod schemas are the source of
454
- * truth; the types are `z.infer`red from them so this vocabulary survives
455
- * the event log round trip once `packages/core/store-sqlite` serializes it.
456
- *
457
- * Tool results are carried in a `role: 'user'` message with `tool-result`
458
- * content parts. Protocol implementations translate this neutral transcript
459
- * into their own request representation.
460
- */
461
- const MessageRoleSchema = z.enum(["user", "assistant"]);
462
- const TextPartSchema = z.object({
463
- type: z.literal("text"),
464
- text: z.string()
465
- });
466
- /** The model's thinking, attached to the same assistant message its reply
467
- * text is. Symmetric with `TextPart` on purpose — it is the recorded
468
- * counterpart of the publish-only `thinking-delta` chunk, carried the
469
- * same way `TextPart` carries the recorded counterpart of `text-delta`.
470
- * Accumulating deltas into this shape, and deciding whether to send it
471
- * back on the next call, is the adapter's job — this package only
472
- * carries it. */
473
- const ThinkingPartSchema = z.object({
474
- type: z.literal("thinking"),
475
- text: z.string(),
476
- /** An opaque token the provider issued with this block and requires back
477
- * **unmodified** on any later turn that continues the same conversation.
478
- * A fabricated or edited value can invalidate replay. Absent for protocols
479
- * that issue no signature. The kernel never reads it; it only
480
- * carries it, so that the adapter that produced it can hand it back. */
481
- signature: z.string().optional(),
482
- /**
483
- * Which endpoint issued that signature.
484
- *
485
- * A signature is only worth anything to whoever signed it, and the product
486
- * cannot tell whether two endpoints are the same signer — two keys against
487
- * one vendor, or a proxy in front of it, look identical from here. So this
488
- * is compared as an endpoint id and the comparison is a deliberate
489
- * over-approximation: an adapter drops a block another endpoint signed,
490
- * which between two endpoints of one vendor costs a block that would have
491
- * replayed. The other way round costs a rejected request.
492
- *
493
- * Absent wherever `signature` is: nothing to attribute. The kernel never
494
- * reads either; it carries them so the adapter that made the block can
495
- * decide.
496
- */
497
- issuer: z.string().optional(),
498
- /** Model identifier that produced this signed thinking block. */
499
- originModel: z.string().optional(),
500
- /**
501
- * Stable compatibility fingerprint for the non-thinking prefix covered by
502
- * the provider signature. Adapters omit a signed block when it does not match
503
- * the request prefix they are about to send.
504
- */
505
- prefix: z.string().optional(),
506
- /**
507
- * Original output-token count used as a conservative upper bound when the
508
- * provider retains more thinking state than the visible text represents.
509
- */
510
- outputTokens: z.number().int().nonnegative().optional(),
511
- /**
512
- * Set on a block the provider returned with no readable text — a protocol's
513
- * `redacted_thinking`. `text` is then empty and `signature` holds the
514
- * provider's opaque `data`, which goes back unmodified in the same place.
515
- */
516
- redacted: z.literal(true).optional()
517
- });
518
- /** A tool call the model requested. `input` is whatever JSON-serializable
519
- * arguments the model produced for it — the kernel does not validate a
520
- * tool's own argument shape, only that the call itself round-trips. */
521
- const ToolUsePartSchema = z.object({
522
- type: z.literal("tool-use"),
523
- id: z.string(),
524
- name: z.string(),
525
- input: z.unknown(),
526
- /** Host-projected execution identity; never changes the model's original call. */
527
- execution: z.object({
528
- name: z.string(),
529
- input: z.unknown(),
530
- definitionFingerprint: z.string()
531
- }).optional()
532
- });
533
- const Sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
534
- /** The copy of a file a model is sent, when it differs from the original:
535
- * a content-addressed variant within every built-in provider type's limits. */
536
- const FileVariantSchema = z.object({
537
- id: Sha256Schema,
538
- mediaType: z.string().min(1),
539
- size: z.number().int().positive(),
540
- width: z.number().int().positive().optional(),
541
- height: z.number().int().positive().optional()
542
- }).strict();
543
- /**
544
- * A reference to a content-addressed file of the session's workspace. Only
545
- * metadata: the bytes live on disk under the workspace's `files/` directory
546
- * and reach a request through `ModelRequest.files` alone, so an event, a
547
- * frame or a snapshot never carries them. `name` belongs to the reference,
548
- * not to the file: the same bytes may be named differently in two messages.
549
- */
550
- const FileRefSchema = z.object({
551
- /** The original's sha256, lower-case hex. */
552
- id: Sha256Schema,
553
- mediaType: z.string().min(1),
554
- name: z.string().min(1).max(200),
555
- size: z.number().int().positive(),
556
- /** Present for an image. */
557
- width: z.number().int().positive().optional(),
558
- height: z.number().int().positive().optional(),
559
- /** The variant a model receives; absent when the original is within limits. */
560
- forModel: FileVariantSchema.optional()
561
- }).strict();
562
- /** A file inside a message, at the place it was written: text and file parts
563
- * interleave in the order a person composed them. */
564
- const FilePartSchema = z.object({
565
- type: z.literal("file"),
566
- file: FileRefSchema
567
- });
568
- /** The host stamps the producing activation before persisting a block. */
569
- const SavedRequiredContextBlockSchema = z.object({
570
- id: z.string().min(1),
571
- scope: z.string().min(1),
572
- version: z.string().min(1),
573
- text: z.string()
574
- }).extend({ stampedSource: z.string().min(1) });
575
- /** Pure delivery facts; live reservation objects never enter the event log. */
576
- const ToolResultDeliverySchema = z.strictObject({
577
- kind: z.enum([
578
- "receipt",
579
- "preview",
580
- "exact-page"
581
- ]),
582
- outputTokens: z.number().int().nonnegative(),
583
- sourceComplete: z.boolean().optional(),
584
- /** Host-bound accepted reply identity; receipt text is not its original source. */
585
- answerRequestId: z.string().min(1).optional(),
586
- execution: z.enum([
587
- "not-started",
588
- "committed",
589
- "partial",
590
- "unknown"
591
- ]).optional()
592
- });
593
- /** The answer to one tool call, matched back to it by `toolUseId`. */
594
- const ToolResultPartSchema = z.object({
595
- /** Immutable host provenance for the decision that admitted this result. */
596
- ownerContext: OwnerContextSchema.optional(),
597
- type: z.literal("tool-result"),
598
- toolUseId: z.string(),
599
- requiredContext: z.array(SavedRequiredContextBlockSchema).optional(),
600
- /** Immutable host-accepted snapshots. */
601
- widgets: z.array(WidgetInstanceSchema).max(8).optional(),
602
- /** Fixed admission diagnostics. */
603
- widgetIssues: z.array(WidgetIssueSchema).max(8).optional(),
604
- content: z.string(),
605
- isError: z.boolean().optional(),
606
- /** Requested preview body tokens; invalid hints are ignored by the host. */
607
- previewTokens: z.number().optional(),
608
- /** Host-admitted delivery metadata; exact pages cannot be silently shortened. */
609
- delivery: ToolResultDeliverySchema.optional(),
610
- /** Files the call handed back, after its text. */
611
- files: z.array(FileRefSchema).optional()
612
- });
613
- const ContentPartSchema = z.discriminatedUnion("type", [
614
- TextPartSchema,
615
- ThinkingPartSchema,
616
- ToolUsePartSchema,
617
- ToolResultPartSchema,
618
- FilePartSchema
619
- ]);
620
- /**
621
- * One volatile contributor's text as a request carried it: the contributor's
622
- * `id` and the strings it gave, joined by a blank line. A request appends a
623
- * note only when it differs from that contributor's last note in the history,
624
- * or at a turn's first step under the default policy. An on-change contributor
625
- * compares values across turn boundaries. The note stays in every later request at the
626
- * place it was first sent.
627
- */
628
- const VolatileNoteSchema = z.object({
629
- id: z.string(),
630
- text: z.string()
631
- }).strict();
632
- /**
633
- * Where a person's message came in, when it came in through a channel that
634
- * names itself: the channel's id and display label, and the speaker the
635
- * channel reported. Written by the gateway's access layer alone; a message
636
- * typed in the product's own client carries none.
637
- */
638
- const MessageViaSchema = z.object({
639
- channel: z.string().min(1),
640
- label: z.string().min(1),
641
- /** Who spoke, as the channel identifies them. `role` is whether they were
642
- * the owner when they sent it; a later change of owner leaves it. */
643
- sender: z.object({
644
- id: z.string().min(1),
645
- name: z.string().min(1).max(64),
646
- role: z.enum(["owner", "member"])
647
- }).strict().optional()
648
- }).strict();
649
- /** Protocol-declared termination, independent of token usage. */
650
- const FinishReasonSchema = z.enum([
651
- "stop",
652
- "tool-calls",
653
- "max-tokens",
654
- "refusal"
655
- ]);
656
- /** Discarded partial calls contain identities only, never executable arguments. */
657
- const OutputTruncationSchema = z.object({
658
- incompleteToolCalls: z.array(z.object({
659
- id: z.string(),
660
- name: z.string().optional()
661
- })),
662
- incompleteThinking: z.literal(true).optional()
663
- });
664
- const MessageSchema = z.object({
665
- finishReason: FinishReasonSchema.optional(),
666
- outputTruncation: OutputTruncationSchema.optional(),
667
- outputContinuation: z.object({
668
- replyId: z.string().uuid(),
669
- attempt: z.number().int().min(1).max(3)
670
- }).optional(),
671
- /** Immutable owner provenance, excluded from all model communication. */
672
- ownerContext: OwnerContextSchema.optional(),
673
- /** UUID assigned when the message first forms and retained by every fork. */
674
- id: z.string().uuid(),
675
- role: MessageRoleSchema,
676
- content: z.array(ContentPartSchema),
677
- /** Present only on a message the model refused to complete — the
678
- * provider's own category for why.
679
- *
680
- * It lives **on the message** rather than only on the `message-appended`
681
- * event that records it, and that distinction is the whole point: `fold`
682
- * rebuilds the transcript out of `event.message`, so a marker carried only
683
- * by the event survives the log and is lost the moment anybody folds it
684
- * back. The transcript needs to remember that a reply was a refusal,
685
- * which means the message has to. Contrast `backfilled`, which stays on
686
- * the event because it describes how that event came to be rather than
687
- * anything about the message. */
688
- refusalCategory: z.string().optional(),
689
- /** Present on a message a composer command produced: what the person
690
- * wrote, and the source that expanded it. `content` holds the expansion,
691
- * which is what the model is sent; the transcript shows `text`. */
692
- invocation: z.object({
693
- text: z.string(),
694
- namespace: z.string()
695
- }).strict().optional(),
696
- /** What a person attached, one entry per leading text block of `content`,
697
- * which holds each attachment's original text. The model-facing envelope is
698
- * added where a request is assembled and is never stored. */
699
- attachments: z.array(z.object({
700
- namespace: z.string(),
701
- group: z.string().optional(),
702
- label: z.string()
703
- }).strict()).optional(),
704
- /** Present only on a model reply: the pair that produced it, stamped by the
705
- * host on the final chunk. On the message rather than the event for the
706
- * reason `refusalCategory` is: `fold` rebuilds the transcript from
707
- * `event.message`, and the latest reply's pair is what names the model a
708
- * compaction after a switch summarizes on. */
709
- model: z.object({
710
- providerId: z.string(),
711
- model: z.string()
712
- }).strict().optional(),
713
- /** Present only on a model reply: the volatile notes the request that
714
- * produced it appended. Adapters render them just before this message, so
715
- * every later request repeats the earlier one byte for byte. Clients do not
716
- * draw them. */
717
- volatile: z.array(VolatileNoteSchema).optional(),
718
- /** Present only on a person's message that arrived through a labelled
719
- * channel. Adapters never see it: the request a model receives carries a
720
- * speaker line instead, added where the request is assembled. */
721
- via: MessageViaSchema.optional(),
722
- /** Durable host attribution, preserved in the transcript when the log is replayed. */
723
- source: z.object({
724
- kind: z.enum([
725
- "delegation-result",
726
- "delegation-task",
727
- "notice",
728
- "trigger",
729
- "trigger-data"
730
- ]),
731
- owner: z.string(),
732
- taskId: z.string(),
733
- deliveryId: z.string().optional(),
734
- /** The trigger definition a `trigger` or `trigger-data` delivery ran for. */
735
- triggerId: z.string().optional(),
736
- /** What a person calls the source: a scheduled task's name. */
737
- label: z.string().optional()
738
- }).strict().optional()
739
- });
740
- //#endregion
741
- //#region ../../core/kernel/src/vocab/human.ts
742
- /**
743
- * The vocabulary of asking a person.
744
- *
745
- * A tool that needs a human decision does not block: it answers a call
746
- * with `{ awaitHuman: HumanRequestInput }` instead of content, the kernel records
747
- * the batch's other results together with the request, and once the
748
- * person has answered, **the same call is executed again** with the reply
749
- * on its context. So a request is addressed by the id of the tool call
750
- * that raised it, and the text a person reads lives on events and on the
751
- * `fold` projection — never on `ControlState`, which carries only the id
752
- * (invariant: control flow does not read message content).
753
- *
754
- * `kind` decides presentation only: a `question` is the model asking, an
755
- * `approval` is an action asking to be allowed. An approval has exactly one
756
- * question whose options are the outcomes the requester accepts.
757
- *
758
- * Zod schemas are the source of truth; the types are inferred from them so
759
- * the shapes survive the event log round trip.
760
- */
761
- const HumanOptionSchema = z.object({
762
- id: z.string().min(1),
763
- label: z.string().min(1),
764
- description: z.string().optional()
765
- });
766
- /** One thing to answer. With `options`, an answer picks by id — one option,
767
- * or several when `multiple` is set — and may add text; with `freeText`, an
768
- * answer may skip the options and give text alone; with no options at all,
769
- * text is the only answer there is. */
770
- const HumanQuestionSchema = z.object({
771
- id: z.string().min(1),
772
- text: z.string().min(1),
773
- options: z.array(HumanOptionSchema),
774
- freeText: z.boolean(),
775
- /** Several options may be chosen; absent means one. */
776
- multiple: z.boolean().optional()
777
- });
778
- const HumanRequestKindSchema = z.enum(["question", "approval"]);
779
- /** One thing an approval would open: a path to read or write, or a host to
780
- * reach. It sits beside the one-line `subject` in `questions[0].text`,
781
- * which consumers that draw no list keep reading. */
782
- const HumanTargetSchema = z.object({
783
- access: z.enum([
784
- "read",
785
- "write",
786
- "network",
787
- "connect",
788
- "listen",
789
- "execute"
790
- ]),
791
- target: z.string().min(1)
792
- });
793
- /** A request as it is recorded and shown: the ask plus who raised it. */
794
- const HumanRequestSchema = z.object({
795
- kind: HumanRequestKindSchema,
796
- /** Why the requester is asking — an approval's justification. */
797
- reason: z.string().optional(),
798
- questions: z.array(HumanQuestionSchema).min(1),
799
- /** An approval's structured objects, in the order the requester lists them. */
800
- targets: z.array(HumanTargetSchema).optional(),
801
- /** A consequence the host states apart from `reason`, drawn above the
802
- * buttons: what a lasting answer opens. */
803
- warning: z.string().optional()
804
- }).extend({
805
- /** The id of the tool call that raised it — one request per call. */
806
- requestId: z.string().min(1),
807
- /** The tool that raised it: the requester a person is told about. */
808
- toolName: z.string().min(1)
809
- });
810
- const HumanAnswerSchema = z.object({
811
- questionId: z.string().min(1),
812
- /** The chosen options: at most one on a single-choice question. Absent
813
- * when none is chosen — never empty. */
814
- optionIds: z.array(z.string().min(1)).min(1).optional(),
815
- text: z.string().optional()
816
- });
817
- /** One person's answer to one request, covering every question in it. */
818
- const HumanReplySchema = z.object({
819
- requestId: z.string().min(1),
820
- answers: z.array(HumanAnswerSchema)
821
- });
822
- z.object({
823
- settled: z.array(ToolResultPartSchema),
824
- requests: z.array(HumanRequestSchema),
825
- replies: z.array(HumanReplySchema),
826
- suspendedCalls: z.array(ToolUsePartSchema)
827
- });
828
- //#endregion
829
- //#region ../../core/kernel/src/vocab/model-failure.ts
830
- /** Bounded, verified facts about a logical model call failure. */
831
- /** Stable failure facts; arbitrary provider text and unknown fields are refused. */
832
- const ModelFailureSchema = z.strictObject({
833
- code: z.enum([
834
- "finish-reason-missing",
835
- "finish-reason-unsupported",
836
- "response-empty",
837
- "final-chunk-missing",
838
- "stream-interrupted",
839
- "stream-idle-timeout",
840
- "http-error",
841
- "request-too-large",
842
- "request-measurement-unsupported",
843
- "authentication-required",
844
- "authentication-expired",
845
- "quota-exceeded",
846
- "model-unavailable",
847
- "context-limit-exceeded",
848
- "provider-error",
849
- "response-invalid",
850
- "unknown"
851
- ]),
852
- stage: z.enum([
853
- "request",
854
- "transport",
855
- "stream",
856
- "response-validation",
857
- "unknown"
858
- ]),
859
- category: z.enum([
860
- "network",
861
- "provider",
862
- "request-too-large",
863
- "protocol",
864
- "unknown"
865
- ]),
866
- source: z.enum([
867
- "protocol",
868
- "transport",
869
- "provider",
870
- "host",
871
- "unknown"
872
- ]),
873
- status: z.number().int().min(100).max(599).optional(),
874
- retryable: z.boolean().optional(),
875
- finishReason: z.enum([
876
- "stop",
877
- "tool-calls",
878
- "max-tokens",
879
- "refusal"
880
- ]).optional(),
881
- providerCode: z.enum([
882
- "usage_not_included",
883
- "usage_limit_reached",
884
- "insufficient_quota",
885
- "context_length_exceeded",
886
- "rate_limit_exceeded",
887
- "overloaded_error",
888
- "api_error",
889
- "rate_limit_error",
890
- "cyber_policy",
891
- "invalid_prompt",
892
- "bio_policy",
893
- "misalignment_policy_violation"
894
- ]).optional(),
895
- attemptCount: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
896
- modelCallId: z.uuid().optional(),
897
- turn: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
898
- step: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()
899
- }).refine((value) => JSON.stringify(value).length <= 2048, "model failure exceeds its size limit");
900
- //#endregion
901
- //#region ../../core/kernel/src/vocab/outcome.ts
902
- /** Turn endings distinguish ordinary completion, cancellation, failures and host execution stops. */
903
- const CompletedReasonSchema = z.enum([
904
- "natural",
905
- "step-limit",
906
- "token-budget",
907
- "refused",
908
- "blocked"
909
- ]);
910
- const CompletedOutcomeSchema = z.object({
911
- kind: z.literal("completed"),
912
- reason: CompletedReasonSchema
913
- });
914
- /** A cancellation landed mid-turn. Carries no reason: what happened next
915
- * (backfilled tool results) is what distinguishes it, not a taxonomy of
916
- * why the cancel was sent. */
917
- const InterruptedOutcomeSchema = z.object({ kind: z.literal("interrupted") });
918
- /** A turn that did not end cleanly — a model call failed with retries
919
- * exhausted, or an effect handler was never implemented. `reason` is a
920
- * short machine-readable code, not a rendered message: the errors table
921
- * has more of these than this change implements transitions for. */
922
- const FailedOutcomeSchema = z.object({
923
- kind: z.literal("failed"),
924
- reason: z.string(),
925
- failure: ModelFailureSchema.optional()
926
- });
927
- /** A verified shared-resource admission failure; no model retry can create capacity. */
928
- const ResourceExhaustionSchema = z.object({
929
- reason: z.literal("resource-exhausted"),
930
- pool: z.literal("query"),
931
- dimension: z.enum([
932
- "session-slots",
933
- "session-bytes",
934
- "resident-bytes",
935
- "session-scratch",
936
- "resident-scratch"
937
- ]),
938
- limit: z.number().int().positive().safe(),
939
- held: z.number().int().nonnegative().safe(),
940
- requested: z.number().int().nonnegative().safe(),
941
- cleanup: z.enum([
942
- "none",
943
- "pending",
944
- "failed"
945
- ]),
946
- recovery: z.enum([
947
- "wait-cleanup",
948
- "owner-recovery",
949
- "expire-resources"
950
- ])
951
- });
952
- /** Successful model output exhausted the fixed continuation budget. */
953
- const ExecutionStopSchema = z.discriminatedUnion("reason", [ResourceExhaustionSchema, z.object({
954
- reason: z.literal("output-limit"),
955
- continuationsUsed: z.literal(3),
956
- continuationLimit: z.literal(3)
957
- })]);
958
- /** A host execution boundary stopped a legal transcript without natural completion. */
959
- const StoppedOutcomeSchema = z.object({
960
- kind: z.literal("stopped"),
961
- stop: ExecutionStopSchema
962
- });
963
- const OutcomeSchema = z.discriminatedUnion("kind", [
964
- CompletedOutcomeSchema,
965
- InterruptedOutcomeSchema,
966
- FailedOutcomeSchema,
967
- StoppedOutcomeSchema
968
- ]);
969
- //#endregion
970
- //#region ../../core/kernel/src/vocab/session-id.ts
971
- /**
972
- * A session's identity: the key of its own event sequence. Distinct from
973
- * `SessionAddress` (vocab/address.ts) — `(Agent, Workspace)` is a scope a
974
- * session lives in, not a session's identity, and any number of sessions
975
- * can share one address while each keeps its own id and its own event
976
- * sequence. `EventStore` addresses events by this, never by address (the
977
- * event table's primary key is `(session_id, seq)`, not
978
- * `(agent_id, workspace_id, seq)`).
979
- */
980
- const SessionIdSchema = z.string().min(1);
981
- //#endregion
982
- //#region ../../core/kernel/src/vocab/state.ts
983
- /**
984
- * Control state: the full input to a control-flow decision. It carries no
985
- * message body — that is what keeps "control flow does not branch on
986
- * message content" a structural fact rather than a discipline. Zod
987
- * schemas are the source of truth; the types are `z.infer`red from them.
988
- *
989
- * `phase` is what `decide`'s transition table (decide.ts) keys on together
990
- * with an incoming event's `kind` — it is the session/turn/step state
991
- * machine's own position, not a general-purpose status flag.
992
- *
993
- * `sessionId` and `address` are two distinct, both-immutable fields:
994
- * `sessionId` is this session's own identity, the key of its event
995
- * sequence; `address` is the `(Agent, Workspace)` scope it lives in,
996
- * shared by any number of sessions. Neither substitutes for the other.
997
- */
998
- const PhaseSchema = z.enum([
999
- "idle",
1000
- "awaiting-model",
1001
- "awaiting-tools",
1002
- "awaiting-human"
1003
- ]);
1004
- /** A tool call requested but not yet answered. Carries the id and name
1005
- * needed to synthesize a "not executed" result for it if the turn ends
1006
- * before it is answered — a bare count cannot do that. */
1007
- const PendingToolCallSchema = z.object({
1008
- id: z.string(),
1009
- name: z.string()
1010
- });
1011
- /** One request a person has not answered yet, by the id of the tool call
1012
- * that raised it. Only the id: the question's text lives on the
1013
- * `human-asked` event and the `fold` projection, never here — control
1014
- * flow does not read message content. */
1015
- const PendingHumanRequestSchema = z.object({ requestId: z.string() });
1016
- /** The two caps a session enforces, and their defaults. `tokenBudget`
1017
- * left unset means the budget is off — a specific default number would
1018
- * be a guess ahead of real usage data. */
1019
- const SessionLimitsSchema = z.strictObject({
1020
- maxSteps: z.number().int().positive(),
1021
- tokenBudget: z.number().int().positive().optional()
1022
- });
1023
- z.object({
1024
- sessionId: SessionIdSchema,
1025
- address: SessionAddressSchema,
1026
- phase: PhaseSchema,
1027
- turn: z.number().int().nonnegative(),
1028
- step: z.number().int().nonnegative(),
1029
- outputContinuationsUsed: z.number().int().min(0).max(3),
1030
- pendingOutputContinuation: z.object({ replyId: z.string().uuid() }).optional(),
1031
- turnTokensUsed: z.number().int().nonnegative(),
1032
- pendingToolCalls: z.array(PendingToolCallSchema),
1033
- pendingHumanRequests: z.array(PendingHumanRequestSchema),
1034
- limits: SessionLimitsSchema
1035
- });
1036
- //#endregion
1037
- //#region ../../core/kernel/src/vocab/event.ts
1038
- /**
1039
- * The event vocabulary: facts that have already happened. Events cannot
1040
- * fail — only effects can. Zod schemas are the source of truth; the types
1041
- * are `z.infer`red from them.
1042
- *
1043
- * Two kinds of event coexist in one union, and `decide` (decide.ts) treats
1044
- * them differently:
1045
- *
1046
- * - **Control-flow events** — `trigger`, `model-replied`,
1047
- * `tool-results-added` — are what a driver feeds into `decide` to
1048
- * advance the session/turn/step state machine. `decide` switches on
1049
- * every one of these by name; adding one without a matching case is a
1050
- * compile error (`assertNeverEventKind`).
1051
- * - **Fact events** — `message-appended`, `turn-ended` — are `decide`'s
1052
- * own output, not something fed back into it in this build. They are
1053
- * listed in `decide`'s switch by name too, explicitly ignored, so they
1054
- * are never mistaken for an unhandled control-flow case and adding a
1055
- * new fact-only variant later never touches `decide` (`Event`'s
1056
- * variants are open).
1057
- *
1058
- * `model-replied` and `tool-results-added` are never recorded — `decide`
1059
- * records the facts it derives from them. Context, human-wait, and history
1060
- * facts can also be appended by their owning host paths. Every such fact
1061
- * belongs to `RecordableEvent` and carries a session identity and address;
1062
- * transient control events do not. `sessionId` is the key
1063
- * `EventStore` addresses a session's events by; `address` rides along as
1064
- * data about the `(Agent, Workspace)` scope that session belongs to — the
1065
- * two are never the same field, because any number of sessions can share
1066
- * one address.
1067
- *
1068
- * Four more control-flow events join the two above, all transient for the
1069
- * same reason: `next-step-inserted` (the interrupting inbox's claim),
1070
- * `cancelled`, `effect-failed` (the single failure-convergence point), and
1071
- * `model-chunk` (a streamed delta — never recorded, only ever published,
1072
- * which is exactly why it is not a member of `RecordableEvent`).
1073
- * `steers-changed` is publish-only the same way, and the driver enqueues it
1074
- * directly rather than through `decide`.
1075
- *
1076
- * `fold` (fold.ts) skips variants it does not recognise rather than
1077
- * throwing — a log a later build appended new variants to must still read
1078
- * on an older one.
1079
- */
1080
- /** Durable owner JSON state and its idempotent operation receipt, ordered by physical sequence. */
1081
- const OwnerStateEventSchema = OwnerContextEntrySchema.extend({
1082
- kind: z.literal("owner-state"),
1083
- sessionId: SessionIdSchema,
1084
- address: SessionAddressSchema,
1085
- operationId: z.string().min(1).max(256),
1086
- requestHash: z.string().min(1).max(256)
1087
- }).superRefine(({ owner, key, revision, data }, ctx) => {
1088
- if (!OwnerContextSchema.safeParse([{
1089
- owner,
1090
- key,
1091
- revision,
1092
- data
1093
- }]).success) ctx.addIssue({
1094
- code: "custom",
1095
- message: "Invalid or oversized owner state"
1096
- });
1097
- });
1098
- const TriggerSourceSchema = z.enum(["human", "plugin"]);
1099
- /** What a model call reported using, in the terms its final chunk gives
1100
- * us. Carried on `model-replied` and folded into `ControlState.turnTokensUsed`
1101
- * via the `message-appended` event `decide` derives from it — usage
1102
- * itself is never persisted directly. */
1103
- const ModelUsageSchema = z.object({
1104
- /** Every input token of the call, cached ones included. */
1105
- inputTokens: z.number().int().nonnegative(),
1106
- outputTokens: z.number().int().nonnegative(),
1107
- /** Input tokens the endpoint served from its prompt cache, when it said. */
1108
- cacheReadTokens: z.number().int().nonnegative().optional(),
1109
- /** Input tokens the endpoint wrote to its prompt cache, when it said. */
1110
- cacheWriteTokens: z.number().int().nonnegative().optional()
1111
- });
1112
- /** What opened this turn. Claimed off the queued inbox at a turn boundary
1113
- * and fed into `decide` as the first event of a turn. Source is recorded
1114
- * as a field, never branched on. */
1115
- const TriggerEventSchema = z.object({
1116
- kind: z.literal("trigger"),
1117
- /** Complete immutable caps selected when this turn was admitted. */
1118
- limits: SessionLimitsSchema,
1119
- sessionId: SessionIdSchema,
1120
- address: SessionAddressSchema,
1121
- source: TriggerSourceSchema,
1122
- /** Which plugin opened the turn when `source` is `plugin`. Absent for a
1123
- * human or scheduled trigger. Recorded as a field, never branched on,
1124
- * like `source` itself. */
1125
- sourceId: z.string().optional(),
1126
- message: MessageSchema
1127
- });
1128
- /** Fed back into `decide` by the call-model effect handler once the model
1129
- * port's stream has produced its final chunk. Transient: never recorded,
1130
- * and so carries no session address (see module comment) — `decide`
1131
- * already knows the address from `ControlState`.
1132
- *
1133
- * `refusalCategory` is present only when the port's final chunk reported
1134
- * `finishReason: 'refusal'` — its presence, not a separate `finishReason`
1135
- * field, is the signal `decide` branches on, the same presence-marks-it
1136
- * idiom `MessageAppendedEvent.backfilled` already uses below. `decide`
1137
- * must judge this before it looks at anything else about the message; the
1138
- * stop/tool-calls/max-tokens paths stay exactly as they were — every one
1139
- * of them is already inferrable from `pendingCallsFrom`/the token budget
1140
- * without needing the full `FinishReason` union carried over the wire. */
1141
- const ModelRepliedEventSchema = z.object({
1142
- kind: z.literal("model-replied"),
1143
- finishReason: FinishReasonSchema,
1144
- outputTruncation: OutputTruncationSchema.optional(),
1145
- message: MessageSchema,
1146
- usage: ModelUsageSchema,
1147
- refusalCategory: z.string().optional()
1148
- });
1149
- /** Fed back into `decide` by the call-tools effect handler once a
1150
- * turn's whole batch of requested tool calls has answered. Transient,
1151
- * same reason as `model-replied`. */
1152
- const ToolResultsAddedEventSchema = z.object({
1153
- kind: z.literal("tool-results-added"),
1154
- ownerStates: z.array(OwnerStateEventSchema).max(16).optional(),
1155
- message: MessageSchema,
1156
- /** Host-verified stop, settled after all admitted calls finish. */
1157
- stop: ExecutionStopSchema.optional()
1158
- });
1159
- /** A message became part of the transcript. */
1160
- const MessageAppendedEventSchema = z.object({
1161
- kind: z.literal("message-appended"),
1162
- sessionId: SessionIdSchema,
1163
- address: SessionAddressSchema,
1164
- message: MessageSchema,
1165
- /** Present only when this message is a model reply — the usage its
1166
- * final chunk reported. Persisting it here (rather than only on the
1167
- * transient `model-replied` event) is what lets `fold` reconstruct
1168
- * `ControlState.turnTokensUsed` from the log alone. */
1169
- usage: ModelUsageSchema.optional(),
1170
- /** `true` only for the "not executed" tool-result message `decide`
1171
- * synthesizes when a turn ends with calls still outstanding
1172
- * (`backfillNotExecuted` in decide.ts). A backfilled message is
1173
- * structurally identical to a genuine `tool-results-added`-derived one
1174
- * (same role, same tool-result content parts), so without this flag
1175
- * `fold` cannot tell "a real round trip completed" from "the turn
1176
- * ended before one did" and over-counts `ControlState.step` for every
1177
- * ending that backfills. Absent (not `false`) on every genuine
1178
- * message, so old logs without it still fold correctly. */
1179
- backfilled: z.literal(true).optional()
1180
- });
1181
- /**
1182
- * The tool set one model request carried, recorded before the request went
1183
- * out. One per step. It is what makes
1184
- * "model-visible means logged" hold once the tool set can change between
1185
- * steps: a replay reads it to know what the model was shown at that step,
1186
- * which nothing else in the log says once tools come and go. `tools` is in
1187
- * name order, so one tool set always records one list.
1188
- */
1189
- const ContextAssembledEventSchema = z.object({
1190
- kind: z.literal("context-assembled"),
1191
- sessionId: SessionIdSchema,
1192
- address: SessionAddressSchema,
1193
- tools: z.array(z.string())
1194
- });
1195
- /** An inclusive message event and half-open content-part range in the raw log. */
1196
- const ContextSourceRangeSchema = z.object({
1197
- messageSeq: z.number().int().nonnegative(),
1198
- startPart: z.number().int().nonnegative(),
1199
- endPart: z.number().int().positive()
1200
- });
1201
- /** The capacity measurement retained with a context decision for replay and audit. */
1202
- const ContextMeasurementSchema = z.object({
1203
- /** No active measurement implementation was supplied. */
1204
- unmeasured: z.literal(true).optional(),
1205
- inputTokens: z.number().int().nonnegative(),
1206
- estimated: z.boolean(),
1207
- contextWindow: z.number().int().positive().optional(),
1208
- inputLimit: z.number().int().positive().optional(),
1209
- outputReserve: z.number().int().nonnegative(),
1210
- fingerprint: z.string(),
1211
- inputBudget: z.number().int().nonnegative().optional(),
1212
- /** Whether the reserve is enforceable upstream or the catalogue capacity. */
1213
- outputReserveSource: z.enum([
1214
- "capacity",
1215
- "enforced",
1216
- "estimated"
1217
- ]).optional(),
1218
- /** Whether the capacity comes from a declaration or the owner's assumed baseline. */
1219
- capacitySource: z.enum(["declared", "assumed"]).optional()
1220
- });
1221
- /** Why the context operation started. */
1222
- const ContextTriggerSchema = z.enum([
1223
- "auto",
1224
- "manual",
1225
- "model-switch"
1226
- ]);
1227
- /** One deterministic replacement of a raw tool-result part. */
1228
- const ContextL1ReplacementSchema = z.object({
1229
- messageSeq: z.number().int().nonnegative(),
1230
- partIndex: z.number().int().nonnegative(),
1231
- replacement: ToolResultPartSchema,
1232
- /** Stable original body reference and bounded preview audit fields. */
1233
- sourceRef: z.string().optional(),
1234
- originalCodePoints: z.number().int().nonnegative().optional(),
1235
- previewTokens: z.number().int().nonnegative().optional(),
1236
- truncated: z.boolean().optional()
1237
- });
1238
- /**
1239
- * A durable change to the model-visible transcript projection. Raw messages
1240
- * remain in the log; replay validates every source before applying this fact.
1241
- */
1242
- const ContextCompactedEventSchema = z.object({
1243
- kind: z.literal("context-compacted"),
1244
- sessionId: SessionIdSchema,
1245
- address: SessionAddressSchema,
1246
- operationId: z.string(),
1247
- baseRevision: z.number().int().nonnegative(),
1248
- revision: z.number().int().positive(),
1249
- trigger: ContextTriggerSchema,
1250
- sourceRanges: z.array(ContextSourceRangeSchema),
1251
- campaignId: z.string().optional(),
1252
- attempt: z.number().int().positive().optional(),
1253
- chunkIndex: z.number().int().nonnegative().optional(),
1254
- before: ContextMeasurementSchema,
1255
- after: ContextMeasurementSchema
1256
- }).extend({
1257
- layer: z.enum([
1258
- "preview",
1259
- "l1",
1260
- "l2"
1261
- ]),
1262
- replacements: z.array(ContextL1ReplacementSchema).optional(),
1263
- summary: MessageSchema.optional()
1264
- }).superRefine((event, ctx) => {
1265
- if (!((event.layer === "l1" || event.layer === "preview") && event.replacements !== void 0 && event.summary === void 0 || event.layer === "l2" && event.summary !== void 0 && event.replacements === void 0)) ctx.addIssue({
1266
- code: "custom",
1267
- message: "context compaction payload must match layer"
1268
- });
1269
- });
1270
- /** Terminal states recorded for context maintenance and auxiliary accounting. */
1271
- const ContextOperationStatusSchema = z.enum([
1272
- "changed",
1273
- "unchanged",
1274
- "failed",
1275
- "cancelled"
1276
- ]);
1277
- /** Durable accounting and outcome for one automatic or explicit context operation. */
1278
- const ContextOperationEventSchema = z.object({
1279
- kind: z.literal("context-operation"),
1280
- sessionId: SessionIdSchema,
1281
- address: SessionAddressSchema,
1282
- operationId: z.string(),
1283
- trigger: ContextTriggerSchema,
1284
- layer: z.enum(["l1", "l2"]).optional(),
1285
- status: ContextOperationStatusSchema.optional(),
1286
- /** Started attempts have no outcome; completed facts carry a status. */
1287
- phase: z.enum(["started", "completed"]).optional(),
1288
- campaignId: z.string().optional(),
1289
- campaignIdentity: z.string().optional(),
1290
- attempt: z.number().int().positive().optional(),
1291
- completedChunks: z.number().int().nonnegative().optional(),
1292
- firstChunkMs: z.number().int().nonnegative().optional(),
1293
- lastProgressMs: z.number().int().nonnegative().optional(),
1294
- candidateKey: z.string(),
1295
- fingerprint: z.string(),
1296
- before: ContextMeasurementSchema.optional(),
1297
- after: ContextMeasurementSchema.optional(),
1298
- summaryModel: z.object({
1299
- providerId: z.string(),
1300
- model: z.string()
1301
- }).strict().optional(),
1302
- usage: ModelUsageSchema.optional(),
1303
- elapsedMs: z.number().int().nonnegative(),
1304
- reason: z.string().optional()
1305
- }).superRefine((event, ctx) => {
1306
- if (event.phase === "started" !== (event.status === void 0)) ctx.addIssue({
1307
- code: "custom",
1308
- message: "started operations have no status; completed operations require one"
1309
- });
1310
- });
1311
- /** A turn reached one of its defined ends. */
1312
- const TurnEndedEventSchema = z.object({
1313
- kind: z.literal("turn-ended"),
1314
- sessionId: SessionIdSchema,
1315
- address: SessionAddressSchema,
1316
- outcome: OutcomeSchema
1317
- });
1318
- /** Marks the end of copied history in a new independent session. */
1319
- const HistorySeededEventSchema = z.object({
1320
- kind: z.literal("history-seeded"),
1321
- sessionId: SessionIdSchema,
1322
- address: SessionAddressSchema,
1323
- sourceSessionId: SessionIdSchema,
1324
- beforeMessageId: z.string().uuid()
1325
- });
1326
- /** Moves the effective transcript to a prior user message without deleting physical events. */
1327
- const HistoryRewoundEventSchema = z.object({
1328
- kind: z.literal("history-rewound"),
1329
- sessionId: SessionIdSchema,
1330
- address: SessionAddressSchema,
1331
- beforeMessageId: z.string().uuid(),
1332
- fromGeneration: z.number().int().nonnegative(),
1333
- toGeneration: z.number().int().positive(),
1334
- operationId: z.string().uuid()
1335
- });
1336
- /** A batch claimed off the interrupting inbox at a step boundary.
1337
- * Transient: the claim itself carries the messages, but only the
1338
- * `message-appended` events `decide` derives from it — one per message,
1339
- * recorded together as one batch — ever reach the log. The claim's
1340
- * *position* in the log (where those derived events land relative to
1341
- * everything else) is what makes replay able to see when the batch was
1342
- * brought in; a separate marker event is not needed for that. */
1343
- const NextStepInsertedEventSchema = z.object({
1344
- kind: z.literal("next-step-inserted"),
1345
- messages: z.array(MessageSchema)
1346
- });
1347
- /** A person's message held for the running turn: `id` names it to
1348
- * `withdraw` and to every listener, `message` is what it becomes once
1349
- * claimed — the same message a send into an idle session would record. */
1350
- const SteerSchema = z.object({
1351
- id: z.string().min(1),
1352
- message: MessageSchema
1353
- });
1354
- /** The held steers changed: one arrived, was claimed into a step, opened
1355
- * the next turn, was withdrawn, or was handed back by a cancellation.
1356
- * Transient and publish-only: the driver enqueues it on the publish queue
1357
- * itself, behind the events of the same claim, so a listener sees a
1358
- * claimed steer's `message-appended` before the list that no longer holds
1359
- * it. `steers` is the whole list still held; `returned` names the steers
1360
- * a cancellation handed back unclaimed, empty otherwise. */
1361
- const SteersChangedEventSchema = z.object({
1362
- kind: z.literal("steers-changed"),
1363
- sessionId: SessionIdSchema,
1364
- address: SessionAddressSchema,
1365
- steers: z.array(SteerSchema),
1366
- returned: z.array(z.string().min(1))
1367
- });
1368
- /** A cancellation requested via `session.cancel()`. Transient —
1369
- * `decide` derives the backfilled tool results and the `interrupted`
1370
- * `TurnEnded` from it. `cause` rides along for logging only; it is never
1371
- * forwarded to `InterruptedOutcome`, which by design carries no reason. */
1372
- const CancelledEventSchema = z.object({
1373
- kind: z.literal("cancelled"),
1374
- cause: z.string().optional()
1375
- });
1376
- /** An effect handler threw. The driver feeds this into `decide` so that
1377
- * the backfill-then-end convergence is one code path regardless of
1378
- * which of the three failure sources produced it — an unimplemented
1379
- * slot, a blocking redaction, or a rejecting record handler. Transient,
1380
- * same reason as `Cancelled`. */
1381
- const EffectFailedEventSchema = z.object({
1382
- kind: z.literal("effect-failed"),
1383
- reason: z.string(),
1384
- failure: ModelFailureSchema.optional()
1385
- });
1386
- /** A non-final chunk from the model port's stream, forwarded by the
1387
- * call-model handler so that `decide` — never the handler itself — is
1388
- * what turns it into a publish-only effect. Streamed deltas are for
1389
- * publishing progress, never for recording; only the final chunk's
1390
- * message becomes `model-replied` and, from there, a recorded
1391
- * `message-appended`. The three chunk shapes are duplicated
1392
- * from `port/model.ts` rather than imported, to avoid a cycle (the port
1393
- * already imports `ModelUsage` from this module) — they are what gets
1394
- * published, which only coincides with the port's transport shape today. */
1395
- const ModelChunkEventSchema = z.object({
1396
- kind: z.literal("model-chunk"),
1397
- ownerContext: OwnerContextSchema.optional(),
1398
- chunk: z.discriminatedUnion("kind", [
1399
- z.object({
1400
- kind: z.literal("text-delta"),
1401
- text: z.string()
1402
- }),
1403
- z.object({
1404
- kind: z.literal("thinking-delta"),
1405
- text: z.string()
1406
- }),
1407
- z.object({
1408
- kind: z.literal("tool-call-delta"),
1409
- id: z.string(),
1410
- name: z.string().optional(),
1411
- inputDelta: z.string()
1412
- }),
1413
- z.object({ kind: z.literal("retract") })
1414
- ])
1415
- });
1416
- /** A batch of tool calls stopped part-way: some calls answered, some asked
1417
- * for a person. Transient — fed back into `decide` by the call-tools
1418
- * handler, which derives the recorded `human-asked` from it. */
1419
- const StepSuspendedEventSchema = z.object({
1420
- kind: z.literal("step-suspended"),
1421
- ownerStates: z.array(OwnerStateEventSchema).max(16).optional(),
1422
- settled: z.array(ToolResultPartSchema),
1423
- requests: z.array(HumanRequestSchema)
1424
- });
1425
- /** Some tool calls of the current step are waiting for a person. Recorded:
1426
- * `settled` holds the batch's already-answered results so that the one
1427
- * tool-results message can be completed after a restart, and `requests`
1428
- * is what a person is asked. `fold` builds its `wait` projection from it. */
1429
- const HumanAskedEventSchema = z.object({
1430
- kind: z.literal("human-asked"),
1431
- sessionId: SessionIdSchema,
1432
- address: SessionAddressSchema,
1433
- settled: z.array(ToolResultPartSchema),
1434
- requests: z.array(HumanRequestSchema)
1435
- });
1436
- /** A person answered one request. Recorded as `{ reply }`; the driver feeds
1437
- * it in carrying `suspended` too — the calls to run again once every
1438
- * request has an answer, read off the `fold` projection — which `decide`
1439
- * puts on the resuming `call-tools` effect and never records. */
1440
- const HumanAnsweredEventSchema = z.object({
1441
- kind: z.literal("human-answered"),
1442
- sessionId: SessionIdSchema,
1443
- address: SessionAddressSchema,
1444
- reply: HumanReplySchema,
1445
- suspended: z.array(ToolUsePartSchema).optional()
1446
- });
1447
- /** Who a session's participants are changed. A fact outside any turn: it
1448
- * moves neither phase nor transcript and never reaches a model request;
1449
- * it is in the log so a session's history says when a person was brought
1450
- * in or let go, and why. */
1451
- const ParticipantChangedEventSchema = z.object({
1452
- kind: z.literal("participant-changed"),
1453
- sessionId: SessionIdSchema,
1454
- address: SessionAddressSchema,
1455
- participant: z.literal("user"),
1456
- change: z.enum(["joined", "left"]),
1457
- by: z.enum(["agent", "user"]),
1458
- reason: z.string().max(500).optional(),
1459
- at: z.number().int().nonnegative()
1460
- });
1461
- /** Complete pure admission facts committed before any call in the batch starts. */
1462
- const ToolCallsAdmittedEventSchema = z.object({
1463
- kind: z.literal("tool-calls-admitted"),
1464
- /** Assistant message whose original calls this fact annotates. */
1465
- messageId: z.string().optional(),
1466
- sessionId: SessionIdSchema,
1467
- address: SessionAddressSchema,
1468
- calls: z.array(z.object({
1469
- callId: z.string(),
1470
- partIndex: z.number().int().nonnegative().optional(),
1471
- entry: z.object({
1472
- name: z.string(),
1473
- input: z.unknown()
1474
- }),
1475
- target: z.object({
1476
- name: z.string(),
1477
- input: z.unknown()
1478
- }).optional(),
1479
- definitionFingerprint: z.string(),
1480
- status: z.enum(["admitted", "rejected"]),
1481
- errorCode: z.string().optional()
1482
- }))
1483
- });
1484
- /** Durable admission of one bounded continuation in the current turn. */
1485
- const OutputContinuationStartedEventSchema = z.object({
1486
- kind: z.literal("output-continuation-started"),
1487
- sessionId: SessionIdSchema,
1488
- address: SessionAddressSchema,
1489
- turn: z.number().int().positive(),
1490
- step: z.number().int().positive(),
1491
- replyId: z.string().uuid(),
1492
- attempt: z.number().int().min(1).max(3)
1493
- });
1494
- const RecordableEventSchema = z.discriminatedUnion("kind", [
1495
- OutputContinuationStartedEventSchema,
1496
- ToolCallsAdmittedEventSchema,
1497
- OwnerStateEventSchema,
1498
- TriggerEventSchema,
1499
- HistorySeededEventSchema,
1500
- HistoryRewoundEventSchema,
1501
- ContextAssembledEventSchema,
1502
- MessageAppendedEventSchema,
1503
- TurnEndedEventSchema,
1504
- HumanAskedEventSchema,
1505
- HumanAnsweredEventSchema,
1506
- ContextCompactedEventSchema,
1507
- ContextOperationEventSchema,
1508
- ParticipantChangedEventSchema
1509
- ]);
1510
- const EventSchema = z.discriminatedUnion("kind", [
1511
- OutputContinuationStartedEventSchema,
1512
- ToolCallsAdmittedEventSchema,
1513
- OwnerStateEventSchema,
1514
- TriggerEventSchema,
1515
- HistorySeededEventSchema,
1516
- HistoryRewoundEventSchema,
1517
- ContextAssembledEventSchema,
1518
- ModelRepliedEventSchema,
1519
- ToolResultsAddedEventSchema,
1520
- MessageAppendedEventSchema,
1521
- TurnEndedEventSchema,
1522
- NextStepInsertedEventSchema,
1523
- SteersChangedEventSchema,
1524
- CancelledEventSchema,
1525
- EffectFailedEventSchema,
1526
- ModelChunkEventSchema,
1527
- StepSuspendedEventSchema,
1528
- HumanAskedEventSchema,
1529
- HumanAnsweredEventSchema,
1530
- ContextCompactedEventSchema,
1531
- ContextOperationEventSchema,
1532
- ParticipantChangedEventSchema
1533
- ]);
1534
- z.enum([
1535
- "call-model",
1536
- "call-tools",
1537
- "wait-human",
1538
- "delegate",
1539
- "publish",
1540
- "record",
1541
- "checkpoint"
1542
- ]);
1543
- /** Assemble context and open one streaming model call. */
1544
- const CallModelEffectSchema = z.object({ kind: z.literal("call-model") });
1545
- /** Execute a batch of capability (tool) calls, concurrently, answered back
1546
- * as one batch.
1547
- *
1548
- * `resume` marks the second half of a batch that parked for a person:
1549
- * `calls` are the calls that asked, now run again with their replies,
1550
- * and the handler merges them with the results already settled on
1551
- * `ctx.wait` into the one message the batch always produces. */
1552
- const CallToolsEffectSchema = z.object({
1553
- kind: z.literal("call-tools"),
1554
- calls: z.array(ToolUsePartSchema),
1555
- resume: z.literal(true).optional()
1556
- });
1557
- /** The turn is now parked for a person: these requests are outstanding.
1558
- * The core's own handler does nothing but name the moment — the driver
1559
- * keeps the turn open by reading the phase, not by anything this
1560
- * effect does. */
1561
- const WaitHumanEffectSchema = z.object({
1562
- kind: z.literal("wait-human"),
1563
- requests: z.array(HumanRequestSchema)
1564
- });
1565
- /** Hand work to another agent. Empty slot until its own task. */
1566
- const DelegateEffectSchema = z.object({ kind: z.literal("delegate") });
1567
- /** Send one event to every channel. `event` is the full `Event` union, not
1568
- * just `RecordableEvent` — a streamed model chunk is published but never
1569
- * recorded, so a publish effect has to be able to carry it. */
1570
- const PublishEffectSchema = z.object({
1571
- kind: z.literal("publish"),
1572
- event: EventSchema
1573
- });
1574
- /** Write a batch of events into the event log, atomically. */
1575
- const RecordEffectSchema = z.object({
1576
- kind: z.literal("record"),
1577
- events: z.array(RecordableEventSchema)
1578
- });
1579
- /** Leave a snapshot for the current session. Empty slot until its own task. */
1580
- const CheckpointEffectSchema = z.object({ kind: z.literal("checkpoint") });
1581
- z.discriminatedUnion("kind", [
1582
- CallModelEffectSchema,
1583
- CallToolsEffectSchema,
1584
- WaitHumanEffectSchema,
1585
- DelegateEffectSchema,
1586
- PublishEffectSchema,
1587
- RecordEffectSchema,
1588
- CheckpointEffectSchema
1589
- ]);
1590
- //#endregion
1591
- //#region ../../core/protocol/src/telemetry.ts
1592
- /** Finite performance stages exclude arbitrary paths, SQL and business text. */
1593
- const TelemetryStage = z.enum([
1594
- "ui.interaction",
1595
- "ui.feedback",
1596
- "ui.commit",
1597
- "ui.frame",
1598
- "ui.stream-display",
1599
- "reading.watch",
1600
- "reading.content",
1601
- "reading.page",
1602
- "reading.queue",
1603
- "reading.worker",
1604
- "reading.projection",
1605
- "reading.ack-wait",
1606
- "reading.loss",
1607
- "reading.source",
1608
- "markdown.parse",
1609
- "markdown.mount",
1610
- "rpc.encode",
1611
- "rpc.send",
1612
- "rpc.receive",
1613
- "rpc.decode",
1614
- "rpc.resolve",
1615
- "rpc.roundtrip",
1616
- "rpc.dispatch",
1617
- "browser.long-task",
1618
- "browser.frame-gap",
1619
- "browser.loss",
1620
- "browser.input-delay",
1621
- "native.bridge",
1622
- "native.command",
1623
- "native.socket.connect",
1624
- "native.socket.queue",
1625
- "native.socket.send",
1626
- "native.socket.receive",
1627
- "native.http.headers",
1628
- "native.http.body",
1629
- "native.file.open",
1630
- "native.file.write",
1631
- "native.file.commit",
1632
- "native.file.cleanup",
1633
- "native.picker.wait",
1634
- "native.loss",
1635
- "gateway.decode",
1636
- "gateway.handler",
1637
- "gateway.encode",
1638
- "gateway.send",
1639
- "runtime.admission",
1640
- "runtime.event-batch",
1641
- "runtime.owner-context",
1642
- "runtime.prepare",
1643
- "runtime.status",
1644
- "runtime.snapshot",
1645
- "runtime.publish",
1646
- "runtime.reading",
1647
- "runtime.turn",
1648
- "model.inspect",
1649
- "model.tokenizer",
1650
- "model.cache",
1651
- "model.call",
1652
- "model.display",
1653
- "context.inspect",
1654
- "context.contributor",
1655
- "tool.call",
1656
- "database.read",
1657
- "database.open",
1658
- "database.close",
1659
- "database.decode",
1660
- "database.statement",
1661
- "database.serialize",
1662
- "database.transaction",
1663
- "database.event-insert",
1664
- "database.reading-projection",
1665
- "database.commit",
1666
- "database.rollback",
1667
- "database.busy",
1668
- "database.checkpoint",
1669
- "file.open",
1670
- "file.write",
1671
- "file.rename",
1672
- "file.close",
1673
- "file.fsync",
1674
- "file.directory-sync",
1675
- "file.publication",
1676
- "file.cleanup",
1677
- "event-loop.delay",
1678
- "event-loop.max",
1679
- "event-loop.p95",
1680
- "event-loop.p99",
1681
- "event-loop.utilization",
1682
- "process.cpu",
1683
- "process.rss",
1684
- "process.heap",
1685
- "process.gc",
1686
- "logging.write"
1687
- ]);
1688
- /** User intent labels contain no user-supplied text. */
1689
- const TelemetryOperation = z.enum([
1690
- "session-switch",
1691
- "send",
1692
- "human-answer",
1693
- "approval",
1694
- "cancel",
1695
- "history-page",
1696
- "heartbeat",
1697
- "generic"
1698
- ]);
1699
- const nonnegative = z.number().finite().nonnegative();
1700
- const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
1701
- const identity = z.string().min(1).max(128).regex(/^[A-Za-z0-9@][A-Za-z0-9@/_.:-]*$/);
1702
- /** Correlation is foreign input; server span and connection identities are host-supplied. */
1703
- const RequestTrace = z.object({
1704
- traceId: z.uuid(),
1705
- parentSpanId: z.uuid().optional(),
1706
- interactionId: z.uuid().optional()
1707
- }).strict();
1708
- /** One same-clock duration, with strictly bounded scalar metadata. */
1709
- const TelemetryObservation = z.object({
1710
- stage: TelemetryStage,
1711
- clockDomain: z.uuid(),
1712
- monotonicStartMs: nonnegative,
1713
- durationMs: nonnegative,
1714
- outcome: z.enum([
1715
- "ok",
1716
- "error",
1717
- "cancelled",
1718
- "timeout",
1719
- "unknown"
1720
- ]).optional(),
1721
- operation: TelemetryOperation.optional(),
1722
- spanId: z.uuid().optional(),
1723
- traceId: z.uuid().optional(),
1724
- parentSpanId: z.uuid().optional(),
1725
- interactionId: z.uuid().optional(),
1726
- sessionId: identity.optional(),
1727
- requestId: identity.optional(),
1728
- visibility: z.enum(["foreground", "background"]).optional(),
1729
- cacheState: z.enum([
1730
- "hit",
1731
- "miss",
1732
- "cold",
1733
- "warm"
1734
- ]).optional(),
1735
- measurementPurpose: z.enum([
1736
- "request",
1737
- "text",
1738
- "catalogue",
1739
- "tool-result",
1740
- "display"
1741
- ]).optional(),
1742
- bytes: counter.optional(),
1743
- count: counter.optional(),
1744
- hits: counter.optional(),
1745
- misses: counter.optional(),
1746
- evictions: counter.optional(),
1747
- inputBytes: counter.optional(),
1748
- retainedBytes: counter.optional()
1749
- }).strict();
1750
- /** Runtime-only capture controls; diagnostic TTL defaults to fifteen minutes. */
1751
- const TelemetryConfigure = z.object({
1752
- mode: z.enum([
1753
- "off",
1754
- "normal",
1755
- "diagnostic"
1756
- ]),
1757
- durationSeconds: z.number().int().min(1).max(3600).optional()
1758
- }).strict();
1759
- /** Bounded client batch; transport additionally checks its serialized byte count. */
1760
- const TelemetryIngest = z.object({
1761
- batchId: z.uuid(),
1762
- pageId: z.uuid(),
1763
- observations: z.array(TelemetryObservation).max(128)
1764
- }).strict();
1765
- z.object({
1766
- mode: z.enum([
1767
- "off",
1768
- "normal",
1769
- "diagnostic"
1770
- ]),
1771
- expiresAt: z.iso.datetime().optional(),
1772
- pendingRecords: counter,
1773
- pendingBytes: counter,
1774
- droppedRecords: counter,
1775
- capabilities: z.object({ eventLoop: z.boolean() }).strict(),
1776
- budgets: z.object({
1777
- targetMs: z.literal(15),
1778
- batchRecords: z.literal(128),
1779
- batchBytes: z.literal(65536),
1780
- recordBytes: z.literal(8192)
1781
- }).strict()
1782
- }).strict();
1783
- /** Authenticated browser and native observation admission. */
1784
- const TelemetryIngestRequest = z.object({
1785
- method: z.literal("gateway.telemetryIngest"),
1786
- params: TelemetryIngest
1787
- });
1788
- /** Authenticated collection status query. */
1789
- const TelemetryStatusRequest = z.object({
1790
- method: z.literal("gateway.telemetryStatus"),
1791
- params: z.object({}).strict().optional()
1792
- });
1793
- /** Authenticated runtime-only collection configuration. */
1794
- const TelemetryConfigureRequest = z.object({
1795
- method: z.literal("gateway.telemetryConfigure"),
1796
- params: TelemetryConfigure
1797
- });
1798
- //#endregion
1799
- //#region ../../core/protocol/src/agent-revisions.ts
1800
- /** Configuration history wire contracts. Shared resource contents are excluded. */
1801
- const AgentId = z.string().min(1);
1802
- const Revision = z.number().int().positive().max(Number.MAX_SAFE_INTEGER);
1803
- /** The exact restore confirmation; reuse the same request id on retry. */
1804
- const AgentRestoreInput = z.strictObject({
1805
- targetRevision: Revision,
1806
- expectedRevision: Revision,
1807
- expectedContentHash: z.string().regex(/^[a-f0-9]{64}$/),
1808
- restoreRequestId: z.string().uuid()
1809
- });
1810
- /** Paginated history request. */
1811
- const ConfigAgentRevisionsRequest = z.object({
1812
- method: z.literal("config.agent.revisions"),
1813
- params: z.strictObject({
1814
- agentId: AgentId,
1815
- limit: z.number().int().min(1).max(100).optional(),
1816
- cursor: z.string().regex(/^[1-9][0-9]*$/).optional()
1817
- })
1818
- });
1819
- /** Compares two immutable saved configurations. */
1820
- const ConfigAgentCompareRevisionsRequest = z.object({
1821
- method: z.literal("config.agent.compareRevisions"),
1822
- params: z.strictObject({
1823
- agentId: AgentId,
1824
- fromRevision: Revision,
1825
- toRevision: Revision
1826
- })
1827
- });
1828
- /** Reads current configuration and validates a historical target. */
1829
- const ConfigAgentPreviewRestoreRequest = z.object({
1830
- method: z.literal("config.agent.previewRestore"),
1831
- params: z.strictObject({
1832
- agentId: AgentId,
1833
- targetRevision: Revision
1834
- })
1835
- });
1836
- /** Restores a version through the ordinary configuration save. */
1837
- const ConfigAgentRestoreRevisionRequest = z.object({
1838
- method: z.literal("config.agent.restoreRevision"),
1839
- params: AgentRestoreInput.extend({ agentId: AgentId })
1840
- });
1841
- //#endregion
1842
- //#region ../../core/protocol/src/authorization.ts
1843
- /** Global resource authorizations and independently controlled sandbox network capabilities. */
1844
- /** A TCP port; `any` is restricted by the host to local network permissions. */
1845
- const AuthorizationPort = z.union([z.number().int().min(1).max(65535), z.literal("any")]);
1846
- /** A resource request. Multiple operations are committed as one batch of single-operation records. */
1847
- const AuthorizationInput = z.discriminatedUnion("kind", [
1848
- z.object({
1849
- kind: z.literal("file"),
1850
- path: z.string().min(1),
1851
- operations: z.array(z.enum(["read", "write"])).min(1)
1852
- }).strict(),
1853
- z.object({
1854
- kind: z.literal("host"),
1855
- host: z.string().min(1),
1856
- port: AuthorizationPort,
1857
- operations: z.array(z.enum(["connect", "listen"])).min(1)
1858
- }).strict(),
1859
- z.object({
1860
- kind: z.literal("command"),
1861
- argv: z.array(z.string()).min(1),
1862
- cwd: z.string().min(1)
1863
- }).strict()
1864
- ]);
1865
- /** The exact executable arguments and resolved working directory approved for one execution. */
1866
- const CommandTarget = z.object({
1867
- argv: z.array(z.string()).min(1),
1868
- cwd: z.string().min(1)
1869
- }).strict();
1870
- /** One real file or directory and its permitted operation. */
1871
- const FileAuthorizationTarget = z.object({
1872
- path: z.string(),
1873
- operation: z.enum(["read", "write"])
1874
- }).strict();
1875
- /** One host pattern, TCP port and independent connection or listening operation. */
1876
- const HostAuthorizationTarget = z.object({
1877
- host: z.string(),
1878
- port: AuthorizationPort,
1879
- operation: z.enum(["connect", "listen"])
1880
- }).strict();
1881
- const resource = {
1882
- id: z.string().min(1),
1883
- source: z.enum(["manual", "approval"]),
1884
- createdAt: z.number(),
1885
- effective: z.boolean(),
1886
- inactiveReason: z.string().optional()
1887
- };
1888
- /** A persisted resource grant, external network approval, or scoped plugin business approval. */
1889
- const AuthorizationRecord = z.discriminatedUnion("kind", [
1890
- z.object({
1891
- ...resource,
1892
- kind: z.literal("file"),
1893
- target: FileAuthorizationTarget
1894
- }),
1895
- z.object({
1896
- ...resource,
1897
- kind: z.literal("host"),
1898
- target: HostAuthorizationTarget
1899
- }),
1900
- z.object({
1901
- ...resource,
1902
- kind: z.literal("command"),
1903
- target: CommandTarget
1904
- }),
1905
- z.object({
1906
- ...resource,
1907
- kind: z.literal("sandbox-network"),
1908
- target: z.object({ capability: z.literal("external") })
1909
- }),
1910
- z.object({
1911
- ...resource,
1912
- kind: z.literal("business-approval"),
1913
- target: z.object({
1914
- owner: z.string(),
1915
- key: z.string(),
1916
- agentId: z.string(),
1917
- workspaceId: z.string(),
1918
- sessionId: z.string().optional(),
1919
- sessionTitle: z.string().optional(),
1920
- label: z.string()
1921
- })
1922
- })
1923
- ]);
1924
- z.enum([
1925
- "image/png",
1926
- "image/jpeg",
1927
- "image/gif",
1928
- "image/webp"
1929
- ]);
1930
- z.object({
1931
- requestBytes: z.number().int().positive(),
1932
- images: z.number().int().positive()
1933
- });
1934
- /** One file a `session.send` places into its text. */
1935
- const MessageFileInput = z.object({
1936
- fileId: z.string().regex(/^[0-9a-f]{64}$/),
1937
- name: z.string().min(1).max(200),
1938
- /** A UTF-16 index into `text`, `0 ≤ at ≤ text.length`, never decreasing
1939
- * along the list. */
1940
- at: z.number().int().nonnegative()
1941
- });
1942
- z.object({ file: FileRefSchema });
1943
- //#endregion
1944
- //#region ../../core/protocol/src/reading.ts
1945
- /** Bounded, disposable conversation reading contracts. Content offsets are UTF-8 bytes. */
1946
- /** A persistent history identity independent of transport frame sequence. */
1947
- const HistoryView = z.object({
1948
- sessionId: z.string(),
1949
- historyGeneration: z.number().int().nonnegative(),
1950
- historyRevision: z.number().int().nonnegative(),
1951
- sourceSeq: z.number().int().min(-1)
1952
- });
1953
- /** Source identity is checked anew on every range read. */
1954
- const ContentScope = z.discriminatedUnion("kind", [
1955
- z.object({
1956
- kind: z.literal("history"),
1957
- sessionId: z.string(),
1958
- historyGeneration: z.number().int().nonnegative()
1959
- }).strict(),
1960
- z.object({
1961
- kind: z.literal("operation"),
1962
- sessionId: z.string(),
1963
- operationId: z.string().uuid()
1964
- }).strict(),
1965
- z.object({
1966
- kind: z.literal("summary"),
1967
- sessionId: z.string(),
1968
- metadataEpoch: z.string()
1969
- }).strict(),
1970
- z.object({
1971
- kind: z.literal("live"),
1972
- sessionId: z.string(),
1973
- processEpoch: z.string(),
1974
- liveEpoch: z.string(),
1975
- streamEpoch: z.string().optional()
1976
- }).strict()
1977
- ]);
1978
- /** Immutable object descriptor; its opaque ID grants no permission. */
1979
- const ContentRef = z.object({
1980
- scope: ContentScope,
1981
- id: z.string().max(256),
1982
- encoding: z.enum(["utf8-text", "canonical-json"]),
1983
- byteLength: z.number().int().nonnegative(),
1984
- sha256: z.string().length(64)
1985
- });
1986
- /** A message identity and bounded display hint; full values live in referenced objects. */
1987
- const ReadingMessageHeader = z.object({
1988
- messageId: z.string(),
1989
- ordinal: z.number().int().nonnegative(),
1990
- role: z.enum(["user", "assistant"]),
1991
- turnId: z.string().optional(),
1992
- introducedSeq: z.number().int().min(-1),
1993
- inherited: z.boolean(),
1994
- kind: z.enum(["message", "tool-results"]),
1995
- sourceKind: MessageSchema.shape.source.unwrap().shape.kind.optional(),
1996
- partCount: z.number().int().nonnegative(),
1997
- metadataRef: ContentRef,
1998
- preview: z.string().refine((v) => new TextEncoder().encode(v).byteLength <= 512)
1999
- });
2000
- /** A stable turn association without a transcript-relative array index. */
2001
- const ReadingTurnHeader = z.object({
2002
- turnId: z.string(),
2003
- openingMessageId: z.string().optional(),
2004
- startedAt: z.number().int(),
2005
- endedAt: z.number().int().optional(),
2006
- status: z.enum([
2007
- "running",
2008
- "completed",
2009
- "cancelled",
2010
- "failed",
2011
- "stopped"
2012
- ]),
2013
- /** Structured framework stop, independent of failed model response diagnostics. */
2014
- stop: ExecutionStopSchema.optional(),
2015
- reason: z.string().max(512).optional(),
2016
- failure: ModelFailureSchema.optional()
2017
- });
2018
- /** A contiguous page, ordered by message ordinal. Cursors are exclusive boundaries. */
2019
- const HistoryWindow = z.object({
2020
- view: HistoryView,
2021
- messages: z.array(ReadingMessageHeader).max(64),
2022
- turns: z.array(ReadingTurnHeader).max(64),
2023
- hasOlder: z.boolean(),
2024
- hasNewer: z.boolean(),
2025
- olderCursor: z.string().max(2048).optional(),
2026
- newerCursor: z.string().max(2048).optional(),
2027
- targetMessageId: z.string().optional()
2028
- });
2029
- /** A part keeps its original position and tool association as pages are loaded. */
2030
- const ReadingPartHeader = z.object({
2031
- partIndex: z.number().int().nonnegative(),
2032
- type: z.string(),
2033
- contentRef: ContentRef,
2034
- metadataRef: ContentRef.optional(),
2035
- callId: z.string().optional(),
2036
- relatedMessageId: z.string().optional(),
2037
- association: z.enum([
2038
- "loaded",
2039
- "unloaded",
2040
- "absent"
2041
- ]).optional()
2042
- });
2043
- /** A bounded descriptor for control and historical annotation collections. */
2044
- const ReadingItemHeader = z.object({
2045
- id: z.string(),
2046
- ordinal: z.number().int().nonnegative(),
2047
- contentRef: ContentRef,
2048
- replyRef: ContentRef.optional(),
2049
- /** Historical answer association, rebound by the host without rewriting saved answer bytes. */
2050
- requestRef: ContentRef.optional(),
2051
- messageId: z.string().optional(),
2052
- turnId: z.string().optional()
2053
- });
2054
- /** Current in-memory or durable control state without embedded request arrays. */
2055
- const ReadingLive = z.object({
2056
- processEpoch: z.string(),
2057
- liveEpoch: z.string(),
2058
- phase: PhaseSchema,
2059
- tokensUsed: z.number().int().nonnegative(),
2060
- recoveryRequired: z.boolean(),
2061
- waitCount: z.number().int().nonnegative(),
2062
- asyncCount: z.number().int().nonnegative(),
2063
- steerCount: z.number().int().nonnegative(),
2064
- waitCollectionId: z.string().optional(),
2065
- wait: ReadingItemHeader.optional(),
2066
- async: ReadingItemHeader.optional(),
2067
- steer: ReadingItemHeader.optional(),
2068
- pending: z.object({
2069
- streamEpoch: z.string(),
2070
- text: ContentRef.optional(),
2071
- thinking: ContentRef.optional()
2072
- }).optional()
2073
- });
2074
- const page = z.number().int().min(1).max(64).default(64);
2075
- /** Reads the latest, adjacent or identity-centered history window. */
2076
- const SessionHistoryPageRequest = z.object({
2077
- method: z.literal("session.historyPage"),
2078
- params: z.object({
2079
- sessionId: z.string(),
2080
- historyGeneration: z.number().int().nonnegative(),
2081
- cursor: z.string().max(2048).optional(),
2082
- aroundMessageId: z.string().optional(),
2083
- limit: page
2084
- }).strict().refine((p) => !(p.cursor && p.aroundMessageId))
2085
- });
2086
- /** Reads original part descriptors, never a complete message payload. */
2087
- const SessionMessagePartsRequest = z.object({
2088
- method: z.literal("session.messageParts"),
2089
- params: z.object({
2090
- sessionId: z.string(),
2091
- historyGeneration: z.number().int().nonnegative(),
2092
- messageId: z.string(),
2093
- cursor: z.string().max(2048).optional(),
2094
- limit: page
2095
- }).strict()
2096
- });
2097
- /** One authorized range consumed by the internal range reader; never a scalar wire entry. */
2098
- const MessageContentInput = z.object({
2099
- scope: ContentScope,
2100
- readingLeaseId: z.string().optional(),
2101
- contentRefId: z.string().max(256),
2102
- offset: z.number().int().nonnegative(),
2103
- maxBytes: z.number().int().min(4).max(262144)
2104
- }).strict();
2105
- /** Reads independent ranges after checking the complete raw and encoded budgets. */
2106
- const SessionMessageContentsRequest = z.object({
2107
- method: z.literal("session.messageContents"),
2108
- params: z.object({
2109
- scope: ContentScope,
2110
- readingLeaseId: z.string().optional(),
2111
- items: z.array(MessageContentInput.omit({
2112
- scope: true,
2113
- readingLeaseId: true
2114
- })).min(1).max(64),
2115
- maxTotalBytes: z.number().int().min(4).max(1048576).default(1048576)
2116
- }).strict().superRefine((value, ctx) => {
2117
- if (value.items.reduce((sum, item) => sum + item.maxBytes, 0) > value.maxTotalBytes) ctx.addIssue({
2118
- code: "custom",
2119
- message: "declared raw content exceeds maxTotalBytes"
2120
- });
2121
- if (value.items.reduce((sum, item) => sum + 4 * Math.ceil(item.maxBytes / 3) + 65536, 8192) > 2097152) ctx.addIssue({
2122
- code: "custom",
2123
- message: "declared encoded result exceeds 2 MiB"
2124
- });
2125
- if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 8388608) ctx.addIssue({
2126
- code: "custom",
2127
- message: "batch input exceeds 8 MiB"
2128
- });
2129
- })
2130
- });
2131
- /** Reads durable annotations or process-local request descriptors. */
2132
- const SessionLivePageRequest = z.object({
2133
- method: z.literal("session.livePage"),
2134
- params: z.object({
2135
- sessionId: z.string(),
2136
- historyGeneration: z.number().int().nonnegative(),
2137
- collection: z.enum([
2138
- "wait",
2139
- "async",
2140
- "steers",
2141
- "turns",
2142
- "answered",
2143
- "participantChanges"
2144
- ]),
2145
- cursor: z.string().max(2048).optional(),
2146
- messageId: z.string().optional(),
2147
- turnId: z.string().optional(),
2148
- messageIds: z.array(z.string()).min(1).max(64).optional(),
2149
- limit: page
2150
- }).strict().refine((value) => [
2151
- value.messageId,
2152
- value.turnId,
2153
- value.messageIds
2154
- ].filter(Boolean).length <= 1, "annotation anchor is ambiguous")
2155
- });
2156
- z.object({
2157
- view: HistoryView,
2158
- parts: z.array(ReadingPartHeader).max(64),
2159
- hasMore: z.boolean(),
2160
- nextCursor: z.string().optional()
2161
- });
2162
- z.object({
2163
- scope: ContentScope,
2164
- contentRefId: z.string(),
2165
- sha256: z.string().length(64),
2166
- offset: z.number().int().nonnegative(),
2167
- nextOffset: z.number().int().nonnegative(),
2168
- byteLength: z.number().int().nonnegative(),
2169
- encoding: z.enum(["utf8-text", "canonical-json"]),
2170
- base64: z.string(),
2171
- complete: z.boolean(),
2172
- historyView: HistoryView.optional(),
2173
- operationSource: z.object({
2174
- sessionId: z.string(),
2175
- operationId: z.string(),
2176
- sha256: z.string()
2177
- }).optional(),
2178
- summarySource: z.object({
2179
- sessionId: z.string(),
2180
- metadataEpoch: z.string()
2181
- }).optional(),
2182
- liveSource: z.object({
2183
- sessionId: z.string(),
2184
- processEpoch: z.string(),
2185
- liveEpoch: z.string()
2186
- }).optional()
2187
- });
2188
- z.object({
2189
- view: HistoryView.optional(),
2190
- liveEpoch: z.string().optional(),
2191
- items: z.array(z.union([ReadingItemHeader, ReadingTurnHeader])).max(64),
2192
- hasMore: z.boolean(),
2193
- nextCursor: z.string().optional()
2194
- });
2195
- //#endregion
2196
- //#region ../../core/protocol/src/index.ts
2197
- /**
2198
- * The wire contract shared by the gateway and every access channel.
2199
- *
2200
- * Both halves import these schemas, so a change here breaks compilation on both
2201
- * sides at once. That is the point: this package is the single source of truth
2202
- * for what may travel over the socket.
2203
- *
2204
- * Methods come in **families, and the family is the first segment of the
2205
- * method name** — `session.*`, `config.*` and `plugin.*`. That is not
2206
- * decoration: a channel translates its own platform's slash command into a
2207
- * `config.*` request, and one look at a frame says which family it belongs to.
2208
- * Authentication grants every family together; the family still describes
2209
- * what the method acts on. They all travel on this one socket, because
2210
- * configuration has to be reachable from every channel — a
2211
- * channel is the user's only surface, and a Feishu adapter sending itself HTTP
2212
- * to change its own configuration would be the shape saying it was cut wrong.
2213
- */
2214
- /**
2215
- * Which model a call uses, as one addressable pair.
2216
- *
2217
- * A session's pin, an agent's default and the installation's default all
2218
- * store this, and `SessionSummary.model` answers with it. It replaces
2219
- * the model entry identifier that used to serve here: that id was minted on
2220
- * one machine and meant nothing on another, and once the list of selectable
2221
- * models became something computed per call rather than a table of rows, an
2222
- * id pointing into that table had nothing left to point at.
2223
- *
2224
- * Both halves are required and neither may be empty. A reference with one
2225
- * half is an endpoint with no model or a model with no endpoint, and
2226
- * accepting it would push the decision about what that means onto every
2227
- * reader.
2228
- */
2229
- const ModelRef = z.object({
2230
- /** The endpoint this model is reached through. */
2231
- providerId: z.string().min(1),
2232
- /** The provider's own name for the model, character for character. */
2233
- model: z.string().min(1)
2234
- });
2235
- /** Framework-owned Agent identity and configuration contributed by extension owners. */
2236
- const AgentSummary = z.object({
2237
- revision: z.number().int().nonnegative().optional(),
2238
- contentHash: z.string().optional(),
2239
- agentId: z.string(),
2240
- name: z.string(),
2241
- createdAt: z.number().int(),
2242
- description: z.string(),
2243
- tools: z.array(z.string()).nullable(),
2244
- startsSessions: z.boolean(),
2245
- avatar: z.string().nullable(),
2246
- /** Each active participant validates its own value; absent owners retain stored data. */
2247
- extensionData: z.record(z.string(), z.unknown())
2248
- });
2249
- z.object({
2250
- identity: z.string(),
2251
- instructions: z.string(),
2252
- style: z.string(),
2253
- reminder: z.string(),
2254
- failure: z.string().optional(),
2255
- /** The rules file's absolute path; absent when the runtime has no work root. */
2256
- path: z.string().optional()
2257
- });
2258
- z.object({
2259
- rev: z.string(),
2260
- mediaType: z.literal("image/png"),
2261
- data: z.string()
2262
- });
2263
- z.enum(["read", "write"]);
2264
- z.enum([
2265
- "once",
2266
- "session",
2267
- "permanent"
2268
- ]);
2269
- /** An authorized workspace tree with its canonical real path and stored access level. */
2270
- const AuthorizedDirectory = z.object({
2271
- path: z.string(),
2272
- access: z.enum(["read", "read-write"])
2273
- });
2274
- /** A workspace: an abstract scope, **bound to no path**. Its authorized
2275
- * directories hang beneath it, zero of them being the normal state for a
2276
- * freshly created one. */
2277
- const WorkspaceSummary = z.object({
2278
- workspaceId: z.string(),
2279
- name: z.string(),
2280
- createdAt: z.number().int(),
2281
- /** The revision of the uploaded picture, or `null` for none — then a
2282
- * client draws the letters face derived from the name. The bytes travel
2283
- * only through `config.workspace.avatars`. */
2284
- avatar: z.string().nullable(),
2285
- /** Already-resolved absolute real paths, the whole tree under each. A
2286
- * summary preserves each authorized tree and its read or read-write level.
2287
- * Additional resource grants are listed by `config.access.list`. */
2288
- directories: z.array(AuthorizedDirectory)
2289
- });
2290
- /** A session as it appears in a list, without loading it. Everything here
2291
- * answers a question a channel asks before opening anything — which is why
2292
- * it carries no transcript.
2293
- *
2294
- * It does carry `phase` and `lastOutcome`, and that half of the original
2295
- * rule was overturned deliberately: a list has to draw what each session is
2296
- * doing, and the only alternative was opening every one of them. The cost is
2297
- * that this is no longer a pure projection of storage — `phase` is live —
2298
- * so two `session.list` calls can differ with the database untouched. */
2299
- /** Who started a session: a person in an interface, or an agent (a
2300
- * scheduled task). Fixed when the session is created. */
2301
- const SessionCreator = z.enum(["user", "agent"]);
2302
- /** The trigger definition or namespaced channel creation key that opened an agent session. */
2303
- const SessionOrigin = z.object({
2304
- kind: z.enum(["trigger", "channel"]),
2305
- ref: z.string().nullable()
2306
- });
2307
- /** One change of who is in a session, placed after `position` transcript
2308
- * messages — the count of messages before it in the log. */
2309
- const ParticipantChange = z.object({
2310
- change: z.enum(["joined", "left"]),
2311
- by: z.enum(["agent", "user"]),
2312
- reason: z.string().max(500).optional(),
2313
- at: z.number().int(),
2314
- position: z.number().int().nonnegative()
2315
- });
2316
- const SessionSummary = z.object({
2317
- /** Persistent compare-and-swap revision for history operations. */
2318
- historyRevision: z.number().int().nonnegative(),
2319
- /** Increments when a replacement history is accepted. */
2320
- historyGeneration: z.number().int().nonnegative(),
2321
- /** The immutable origin of an independent fork, when present. */
2322
- fork: z.object({
2323
- sourceSessionId: z.string(),
2324
- sourceMessageId: z.string().uuid(),
2325
- sourceTitle: z.string(),
2326
- sourceExcerpt: z.string(),
2327
- sourceHistoryRevision: z.number().int().nonnegative(),
2328
- createdAt: z.number().int()
2329
- }).optional(),
2330
- /** Absent before this gateway has loaded the session's context state. */
2331
- /** Native child ancestry; absent on top-level conversations. */
2332
- parentSessionId: z.string().optional(),
2333
- rootSessionId: z.string().optional(),
2334
- depth: z.number().int().positive().optional(),
2335
- sessionId: z.string(),
2336
- agentId: z.string(),
2337
- workspaceId: z.string(),
2338
- /** The topic title: what the session is about, written by the agent in it
2339
- * through `session_note`, or by the first user message before that.
2340
- * `null` until either writes one. */
2341
- title: z.string().nullable(),
2342
- /** The name a person gave the session through `session.setName`, to find
2343
- * it by. Independent of `title`: neither writer touches the other.
2344
- * `null` when nobody named it. */
2345
- name: z.string().nullable(),
2346
- /** What the session is doing, as the agent in it last wrote it. */
2347
- digest: z.object({
2348
- text: z.string(),
2349
- /** Who wrote it: the agent today; a background summary later. */
2350
- author: z.enum(["agent"]),
2351
- updatedAt: z.number()
2352
- }).nullable(),
2353
- /** Filed away. A session's own property rather than this browser's
2354
- * preference, which is what puts it here instead of in `localStorage`
2355
- * beside the brand and the current section: every client agrees about it,
2356
- * and it survives a reload. The archive is a separate view rather than a
2357
- * filter, so an archived session appears on exactly one of the two lists. */
2358
- archived: z.boolean(),
2359
- /** What this session is doing right now. Answered from the live session
2360
- * when the runtime holds one and `idle` when it does not — a session
2361
- * nobody has opened cannot be running. Live state rather than a stored
2362
- * fact, and `session.updated` is what carries a change in it. */
2363
- phase: PhaseSchema,
2364
- /** How the last finished turn ended, or `null` for a session that has not
2365
- * taken one. It is a **projection** of the last turn recorded in the log,
2366
- * kept on the session row only so that a list does not cost one query per
2367
- * session — so **only a list reads it**, and a transcript always reads the
2368
- * log. */
2369
- lastOutcome: OutcomeSchema.nullable(),
2370
- /** The latest committed user or assistant message's visible text — text
2371
- * parts only, whitespace collapsed to single spaces, at most 200 code
2372
- * points — falling back to the most recent earlier message that had text.
2373
- * `null` until a message carries text. A projection stored on the session
2374
- * row under `lastOutcome`'s rule: only a list reads it. */
2375
- preview: z.string().nullable(),
2376
- /** What this session's next turn will call.
2377
- *
2378
- * It is the session's own answer rather than a layer over somebody else's:
2379
- * a session is instantiated from the templates when it is created and
2380
- * carries what it was given from then on, so editing a template does not
2381
- * move it. `null` only when nothing was reachable at the moment it was
2382
- * created, which is a real state on a gateway with nothing configured —
2383
- * and one a person has to resolve by choosing, because nothing fills it in
2384
- * behind them. */
2385
- model: ModelRef.nullable(),
2386
- /** The settings that turn will be made with, for the model above.
2387
- *
2388
- * Opaque here: which of these the endpoint accepts, and what each is
2389
- * called there, is the model plugin's answer from its catalogue. The
2390
- * protocol carries them so one surface can show what a session is using
2391
- * without a second copy of the merge that produced them. */
2392
- params: z.record(z.string(), z.unknown()),
2393
- /** Who started it; never changes. A delegated child reads `user` and stays
2394
- * hidden by its parent id. */
2395
- creator: SessionCreator,
2396
- /** Who else is in it. The person is present in a session they created or
2397
- * one they are a participant of; that decides which list shows it. */
2398
- participants: z.array(z.literal("user")),
2399
- /** Where an agent-created session came from; `null` for a person's. */
2400
- origin: SessionOrigin.nullable(),
2401
- createdAt: z.number().int(),
2402
- updatedAt: z.number().int()
2403
- });
2404
- /** The wire's own statement of what a person is asked and what they answer.
2405
- * Field for field what the kernel records, written here rather than
2406
- * imported because this package is the single writer of wire shapes: the
2407
- * runtime maps one onto the other, and the day the two diverge that
2408
- * mapping is the one place to change. */
2409
- const HumanOption = z.object({
2410
- id: z.string().min(1),
2411
- label: z.string().min(1),
2412
- description: z.string().optional()
2413
- });
2414
- const HumanQuestion = z.object({
2415
- id: z.string().min(1),
2416
- text: z.string().min(1),
2417
- options: z.array(HumanOption),
2418
- /** Whether an answer may skip the options and give text alone. */
2419
- freeText: z.boolean(),
2420
- /** Several options may be chosen; absent means one. */
2421
- multiple: z.boolean().optional()
2422
- });
2423
- const HumanRequestKind = z.enum(["question", "approval"]);
2424
- /** One thing an approval would open — a path to read or write, or a host to
2425
- * reach. A client draws the list when there is one and the one-line
2426
- * `questions[0].text` when there is not. */
2427
- const HumanTarget = z.object({
2428
- access: z.enum([
2429
- "read",
2430
- "write",
2431
- "network",
2432
- "connect",
2433
- "listen",
2434
- "execute"
2435
- ]),
2436
- target: z.string().min(1)
2437
- });
2438
- /** One thing a person is asked. `requestId` is the id of the tool call that
2439
- * raised it and `toolName` is the requester; `kind` decides how a client
2440
- * presents it — a model's question, or an action asking to be allowed, with
2441
- * `reason` as its justification. */
2442
- const HumanRequest = z.object({
2443
- requestId: z.string().min(1),
2444
- toolName: z.string().min(1),
2445
- kind: HumanRequestKind,
2446
- reason: z.string().optional(),
2447
- questions: z.array(HumanQuestion).min(1),
2448
- /** An approval's structured objects, beside the one-line subject. */
2449
- targets: z.array(HumanTarget).optional(),
2450
- /** A consequence the host states apart from `reason`, above the buttons. */
2451
- warning: z.string().optional()
2452
- });
2453
- /** A request a plugin raised outside any tool call. The session does not
2454
- * stop for it: it arrives through `session.asyncAsked`, has a descriptor in
2455
- * `SessionSnapshot.live.async` and remaining descriptors in session.livePage, and is answered through the same
2456
- * `session.answer`. It carries no `toolName`: `plugin` is filled by the
2457
- * host from the caller's handle, never by the plugin, so a client shows
2458
- * the requester by that name. */
2459
- const AsyncHumanRequest = z.object({
2460
- requestId: z.string().min(1),
2461
- plugin: z.string().min(1),
2462
- /** One line saying what is asked, written by the plugin. */
2463
- title: z.string().min(1),
2464
- kind: HumanRequestKind,
2465
- reason: z.string().optional(),
2466
- questions: z.array(HumanQuestion).min(1),
2467
- targets: z.array(HumanTarget).optional(),
2468
- warning: z.string().optional()
2469
- });
2470
- const HumanAnswer = z.object({
2471
- questionId: z.string().min(1),
2472
- /** The chosen options: at most one on a single-choice question. Absent
2473
- * when none is chosen — never empty. */
2474
- optionIds: z.array(z.string().min(1)).min(1).optional(),
2475
- text: z.string().optional()
2476
- });
2477
- /** A person's answer to one request, covering every question in it. */
2478
- const HumanReply = z.object({
2479
- requestId: z.string().min(1),
2480
- answers: z.array(HumanAnswer)
2481
- });
2482
- z.object({
2483
- requests: z.array(HumanRequest),
2484
- replies: z.array(HumanReply)
2485
- });
2486
- z.object({
2487
- request: HumanRequest,
2488
- reply: HumanReply,
2489
- position: z.number().int().nonnegative()
2490
- });
2491
- z.number().int().min(1).max(65535);
2492
- z.object({
2493
- firstMessage: z.number().int().nonnegative(),
2494
- startedAt: z.number().int(),
2495
- endedAt: z.number().int().optional()
2496
- });
2497
- z.object({
2498
- steerId: z.string().min(1),
2499
- message: MessageSchema
2500
- });
2501
- /** Bounded session metadata. Full opaque values are restored from metadataRef. */
2502
- const WatchSessionSummary = SessionSummary.omit({ params: true }).extend({
2503
- metadataRef: ContentRef,
2504
- modelRef: ContentRef.optional(),
2505
- /** Small scalar previews; omitted keys require an explicit original metadata read. */
2506
- parameterHints: z.record(z.string(), z.union([
2507
- z.string(),
2508
- z.number(),
2509
- z.boolean(),
2510
- z.null()
2511
- ])).refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 1024).optional()
2512
- }).refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8192);
2513
- /** Atomic latest reading window and transport frame watermark. */
2514
- const SessionSnapshot = z.object({
2515
- session: WatchSessionSummary,
2516
- window: HistoryWindow,
2517
- live: ReadingLive,
2518
- upToSeq: z.number().int().nonnegative()
2519
- });
2520
- /** Package display name, either shared across languages or keyed by locale. */
2521
- const PluginDisplayName = z.union([z.string().trim().min(1).max(200), z.record(z.string().min(1).max(35), z.string().trim().min(1).max(200))]);
2522
- /** Markdown package description, shared or keyed by 1–32 bounded locale names. */
2523
- const PluginDescription = z.union([z.string().max(64e3), z.record(z.string().min(1).max(35), z.string().min(1).max(64e3).refine((value) => value.trim().length > 0)).refine((value) => Object.keys(value).length > 0 && Object.keys(value).length <= 32)]);
2524
- /** Nonfatal metadata about a completely verified large file; paths are logical, never host paths. */
294
+ //#region src/extension-catalog/artifact-warning.ts
2525
295
  const ArtifactWarningSchema = z.object({
2526
296
  code: z.literal("LARGE_FILE"),
2527
297
  packageName: z.string().min(1).max(4096),
@@ -2529,1754 +299,8 @@ const ArtifactWarningSchema = z.object({
2529
299
  location: z.string().min(1).max(4096).refine((value) => !value.includes("\\") && !/[\p{Cc}]/u.test(value) && !/^(?:\/|[a-z]:)/i.test(value) && value.split("/").every((part) => part !== "" && part !== "." && part !== "..")).optional(),
2530
300
  size: z.number().int().positive().max(268435456)
2531
301
  }).strict();
2532
- /**
2533
- * One plugin, as `plugin list` shows it and as `plugin install` answers.
2534
- *
2535
- * `failed` is a state a plugin *has*, not an error the request returns: a
2536
- * package that will not install, a configuration section its schema refuses,
2537
- * an `apply` that threw — each leaves a line here with the reason on it, and
2538
- * the gateway goes on running. Only a caller's own mistake, a name nothing is
2539
- * installed under, comes back as a failed request.
2540
- */
2541
- const PluginSummary = z.object({
2542
- name: z.string(),
2543
- /** Human-readable package name, distinct from its installation identifier. */
2544
- displayName: PluginDisplayName.optional(),
2545
- /** Localized package description rendered as Markdown without raw HTML. */
2546
- description: PluginDescription.optional(),
2547
- /** What the user asked for, verbatim: `builtin`, `npm:<spec>` or
2548
- * `path:<absolute>`. Held apart from `version` on purpose — comparing the
2549
- * two is how "there is a newer one" gets answered later. */
2550
- origin: z.string(),
2551
- /** `disabled` is a declaration-level fact rather than a container one: a
2552
- * line the person turned off was never handed to the container, so it
2553
- * neither ran nor failed. Reporting it as `failed` would send whoever
2554
- * reads this column looking for a fault that does not exist.
2555
- * `reloading` is a previously active instance temporarily withdrawn by a
2556
- * managed installation while restoration is pending; its capabilities are
2557
- * unavailable until the status returns to `active`. */
2558
- status: z.enum([
2559
- "active",
2560
- "failed",
2561
- "disabled",
2562
- "reloading"
2563
- ]),
2564
- /** Retained user activation choice, independent of an activation failure. */
2565
- enabled: z.boolean().optional(),
2566
- /** Generic admission and observation facts; business provenance remains opaque. */
2567
- installation: z.object({
2568
- revision: z.number().int().nonnegative(),
2569
- receiptId: z.uuid().nullable(),
2570
- /** Complete metadata samples from the current verified package closure; paths are never truncated. */
2571
- warnings: z.array(ArtifactWarningSchema).max(64).optional(),
2572
- /** Total verified warning count, including diagnostic metadata omitted by its byte budget. */
2573
- warningCount: z.number().int().nonnegative().max(1e5).optional(),
2574
- hostRequirements: z.object({
2575
- state: z.enum([
2576
- "satisfied",
2577
- "unsatisfied",
2578
- "unknown"
2579
- ]),
2580
- reasons: z.array(z.string()),
2581
- checkedAt: z.string()
2582
- }),
2583
- provenance: z.object({
2584
- issuer: z.string(),
2585
- record: z.record(z.string(), z.unknown()),
2586
- display: z.object({
2587
- label: z.string(),
2588
- detail: z.string().optional()
2589
- }).optional()
2590
- }).optional()
2591
- }).optional(),
2592
- /** Present whenever `status` is `failed`, and human-readable: the loader
2593
- * constructs it, so nothing here carries a stack or a secret. A
2594
- * `disabled` line carries none — there is no failure to explain. */
2595
- reason: z.string().optional(),
2596
- /** Bounded original installation stderr, returned only for an unsuccessful install. */
2597
- diagnostic: z.string().max(65536).optional(),
2598
- /** The installed package's own `package.json` version, read from the
2599
- * package rather than reported by the plugin, because a hand-written
2600
- * field is the one nobody updates. A built-in reads its own too: it is a
2601
- * package like any other. */
2602
- version: z.string(),
2603
- /** The range the package declares on `@eum-agent/plugin`. Recorded and
2604
- * displayed only — nothing gates on it — and absent when there is no
2605
- * manifest to read it from. */
2606
- contractVersion: z.string().optional()
2607
- });
2608
- /**
2609
- * The two character sets a minted wire name is made of, shared by the method
2610
- * plane and the frame plane.
2611
- *
2612
- * `owner` is the plugin's own name run through the container's sanitiser,
2613
- * which also folds `.` — npm allows it in a package name and it is this
2614
- * rule's own separator, so leaving it would make `plugin.my.plugin.list`
2615
- * unsplittable. `local` is what the plugin passed: one lowerCamel segment,
2616
- * the same shape every core method's last segment has.
2617
- */
2618
- const PluginWireOwner = z.string().regex(/^[a-z0-9_~]+$/);
2619
- const PluginWireLocal = z.string().regex(/^[a-z][a-zA-Z0-9]*$/);
2620
- /** `plugin.<owner>.<local>`, the one name rule both planes obey. */
2621
- const PluginWireName = z.templateLiteral([
2622
- "plugin.",
2623
- PluginWireOwner,
2624
- ".",
2625
- PluginWireLocal
2626
- ]);
2627
- /**
2628
- * A frame a plugin declared with `delivery: 'session'`: it names a session,
2629
- * so it travels the session's own stream and reaches only the connections
2630
- * watching it.
2631
- *
2632
- * It shares `seq` with the core session frames, which is a rule for its
2633
- * readers as much as for its writer: **a client that does not recognise this
2634
- * frame still has to count it.** Counting only the kinds it knows makes `seq`
2635
- * appear to skip, and a client that reads a skip as a dropped frame re-takes
2636
- * a snapshot — a page that reconnects forever because somebody installed a
2637
- * talkative plugin.
2638
- *
2639
- * `payload` is optional **on the envelope** while `SessionFrameDeclaration`
2640
- * still requires a declared schema for it: the envelope only answers "is this
2641
- * a plugin frame", and whether the payload is right is the plugin's own
2642
- * schema's call. A plugin may declare a schema that admits `undefined`, and
2643
- * such a frame JSON-ifies with no `payload` key — a required envelope would
2644
- * refuse it, which is `PluginRequestBody.params`'s trap seen from the other
2645
- * side. The host's envelope MUST NOT be stricter than the declaration.
2646
- */
2647
- const PluginSessionFrame = z.object({
2648
- kind: PluginWireName,
2649
- sessionId: z.string(),
2650
- seq: z.number().int(),
2651
- payload: z.unknown().optional()
2652
- });
2653
- /** A frame a plugin declared with `delivery: 'broadcast'`: every
2654
- * authenticated connection gets it. There is no field a session could
2655
- * travel in, so "a signal carries no session data" is a fact about this
2656
- * shape rather than a discipline. A payload is allowed and is a signal, not
2657
- * data: the recommended plugin declares none and lets its interface re-read
2658
- * through a method. */
2659
- const PluginSignalFrame = z.object({
2660
- kind: PluginWireName,
2661
- payload: z.unknown().optional()
2662
- });
2663
- /**
2664
- * One shape a plugin declared, as JSON Schema.
2665
- *
2666
- * The host exports it through the plugin schema's own `toJSONSchema` method, and
2667
- * this protocol deliberately says nothing about what is inside: it is a
2668
- * description for a person and for a runtime form, not a second validator.
2669
- * The validating one is the plugin's zod, and it runs in the gateway.
2670
- */
2671
- const JsonSchema = z.record(z.string(), z.unknown());
2672
- /** One method a plugin declared. `name` is the minted wire name, ready to
2673
- * send — a client MUST NOT assemble it from `owner` and a local name. */
2674
- const PluginSurfaceMethod = z.object({
2675
- name: z.string(),
2676
- description: z.string().optional(),
2677
- params: JsonSchema,
2678
- result: JsonSchema
2679
- });
2680
- /** One frame a plugin declared. `delivery` was fixed when it was declared and
2681
- * cannot change per emission: `broadcast` reaches every authenticated
2682
- * connection and `session` only the connections watching that session. */
2683
- const PluginSurfaceFrame = z.object({
2684
- name: z.string(),
2685
- delivery: z.enum(["broadcast", "session"]),
2686
- payload: JsonSchema.optional()
2687
- });
2688
- /** The opaque UUID identifying one activation of a client resource or stream owner. */
2689
- const PluginOwnerEpoch = z.uuid();
2690
- /** One owner-scoped HTTP resource and its declared business schemas. */
2691
- const PluginSurfaceResource = z.object({
2692
- owner: z.string(),
2693
- local: z.string(),
2694
- url: z.string(),
2695
- ownerEpoch: PluginOwnerEpoch,
2696
- description: z.string().optional(),
2697
- methods: z.array(z.enum([
2698
- "GET",
2699
- "HEAD",
2700
- "PUT"
2701
- ])).nonempty(),
2702
- params: JsonSchema,
2703
- result: JsonSchema,
2704
- metadata: JsonSchema
2705
- });
2706
- /** The dedicated-stream client envelope; business schemas are applied after authentication. */
2707
- const PluginStreamAuthentication = z.strictObject({
2708
- kind: z.literal("authentication"),
2709
- token: z.string().min(1)
2710
- });
2711
- /** Opening binds an owner activation while leaving business params to that owner's schema. */
2712
- const PluginStreamOpen = z.strictObject({
2713
- kind: z.literal("open"),
2714
- ownerEpoch: PluginOwnerEpoch,
2715
- params: z.unknown().optional()
2716
- });
2717
- /** A dedicated stream's business envelope, validated further by its owner. */
2718
- const PluginStreamData = z.strictObject({
2719
- kind: z.literal("data"),
2720
- payload: z.unknown().optional()
2721
- });
2722
- z.discriminatedUnion("kind", [
2723
- PluginStreamAuthentication,
2724
- PluginStreamOpen,
2725
- PluginStreamData
2726
- ]);
2727
- /** Extension-neutral client IO failure data; status mapping is owned by the transport. */
2728
- const PluginClientError = z.object({
2729
- code: z.string().min(1),
2730
- message: z.string(),
2731
- details: z.unknown().optional()
2732
- });
2733
- z.discriminatedUnion("kind", [
2734
- z.strictObject({ kind: z.literal("authenticated") }),
2735
- z.strictObject({
2736
- kind: z.literal("opened"),
2737
- payload: z.unknown().optional()
2738
- }),
2739
- PluginStreamData,
2740
- z.strictObject({
2741
- kind: z.literal("error"),
2742
- error: PluginClientError
2743
- })
2744
- ]);
2745
- /** One owner-scoped dedicated stream with independent opening, ready and business schemas. */
2746
- const PluginSurfaceStream = z.object({
2747
- owner: z.string(),
2748
- local: z.string(),
2749
- url: z.string(),
2750
- ownerEpoch: PluginOwnerEpoch,
2751
- description: z.string().optional(),
2752
- openParams: JsonSchema,
2753
- ready: JsonSchema,
2754
- input: JsonSchema,
2755
- output: JsonSchema
2756
- });
2757
- /**
2758
- * Everything one plugin put on the client surface.
2759
- *
2760
- * **`ui` is `{ url, rev }` and nothing else.** The registration the host read
2761
- * it from names an absolute path on this machine; that path is of no use to a
2762
- * client — all it can do is `import(url)` — and putting it here would hand
2763
- * every client the local directory layout. There is therefore no field it
2764
- * could travel in.
2765
- */
2766
- const PluginSurfaceEntry = z.object({
2767
- /** The plugin's own name, verbatim. */
2768
- plugin: z.string(),
2769
- /** The minted owner segment: the middle segment of every wire name below. */
2770
- owner: z.string(),
2771
- methods: z.array(PluginSurfaceMethod),
2772
- frames: z.array(PluginSurfaceFrame),
2773
- /** Present when this owner declares HTTP resources. */
2774
- resources: z.array(PluginSurfaceResource).optional(),
2775
- /** Present when this owner declares dedicated streams. */
2776
- streams: z.array(PluginSurfaceStream).optional(),
2777
- /** Only a plugin that declared a browser module has this. */
2778
- ui: z.object({
2779
- url: z.string(),
2780
- rev: z.string()
2781
- }).optional()
2782
- });
2783
- z.object({ plugins: z.array(PluginSurfaceEntry) });
2784
- /** Sent to a single client the moment its socket opens. */
2785
- const HelloFrame = z.object({
2786
- kind: z.literal("connection.hello"),
2787
- clientId: z.string(),
2788
- protocolVersion: z.string(),
2789
- gatewayVersion: z.string()
2790
- });
2791
- /** Broadcast to every authenticated client when the roster changes. Any
2792
- * authenticated channel — CLI, WebUI, App — sees the same frame, which is
2793
- * what makes them peers rather than a primary and its mirrors. */
2794
- const PresenceFrame = z.object({
2795
- kind: z.literal("connection.presence"),
2796
- clientCount: z.number().int()
2797
- });
2798
- /** A session appeared. Broadcast to every authenticated client so no channel
2799
- * has to refresh to see it. */
2800
- const SessionCreatedFrame = z.object({
2801
- kind: z.literal("session.created"),
2802
- session: WatchSessionSummary
2803
- });
2804
- /** A session's summary changed — its title was named by a first message, or
2805
- * its last-active time moved. Without this, a list on another connection
2806
- * keeps showing "new session" until that page reconnects. */
2807
- const SessionUpdatedFrame = z.object({
2808
- kind: z.literal("session.updated"),
2809
- session: WatchSessionSummary
2810
- });
2811
- /** Configuration changed. Broadcast so a change made from any entry point is
2812
- * immediately visible everywhere. */
2813
- const AgentChangedFrame = z.object({
2814
- kind: z.literal("config.agentChanged"),
2815
- agent: AgentSummary
2816
- });
2817
- /** An agent was removed. Broadcast once, after the removal committed, so
2818
- * every list, menu and delegation surface drops it without reloading. It
2819
- * names the agent rather than carrying a summary: there is none left. */
2820
- const AgentRemovedFrame = z.object({
2821
- kind: z.literal("config.agentRemoved"),
2822
- agentIds: z.array(z.string()).min(1).max(64)
2823
- });
2824
- const WorkspaceChangedFrame = z.object({
2825
- kind: z.literal("config.workspaceChanged"),
2826
- workspace: WorkspaceSummary
2827
- });
2828
- /** The set of plugins changed, or one of them changed status. Carries the
2829
- * whole list rather than a delta: a receiver renders what it is given and
2830
- * never has to reconcile, and the list is short enough that a diff would
2831
- * cost more than it saves. */
2832
- const PluginChangedFrame = z.object({
2833
- kind: z.literal("plugin.changed"),
2834
- plugins: z.array(PluginSummary)
2835
- });
2836
- /** Everything below is addressed by `sessionId` and carries `seq` — a
2837
- * per-session counter, monotonic for this gateway process's lifetime, that
2838
- * lets a client assert it missed nothing. It is not the store's `seq`:
2839
- * deltas are never persisted. */
2840
- const sessionFrameBase = {
2841
- sessionId: z.string(),
2842
- seq: z.number().int(),
2843
- historyGeneration: z.number().int().nonnegative(),
2844
- processEpoch: z.string()
2845
- };
2846
- /** Carries no turn number: the number lives in `ControlState`, and the
2847
- * publish slot the frame is built from cannot see it. A client that needs to
2848
- * count turns counts these frames. */
2849
- const TurnStartedFrame = z.object({
2850
- kind: z.literal("session.turnStarted"),
2851
- ...sessionFrameBase,
2852
- /** Who opened the turn: a person, a schedule, or a plugin — and which one. */
2853
- turnId: z.string(),
2854
- openingMessageId: z.string().optional(),
2855
- sourceSeq: z.number().int().min(-1),
2856
- source: TriggerSourceSchema,
2857
- sourceId: z.string().optional(),
2858
- /** When the turn opened, epoch milliseconds — `TurnSpan.startedAt` of the
2859
- * turn whose first message is the next `session.messageAppended`. */
2860
- at: z.number().int()
2861
- });
2862
- const DeltaFrame = z.object({
2863
- kind: z.literal("session.delta"),
2864
- ...sessionFrameBase,
2865
- streamEpoch: z.string(),
2866
- offset: z.number().int().nonnegative(),
2867
- part: z.enum(["text", "thinking"]),
2868
- text: z.string().refine((value) => new TextEncoder().encode(value).length <= 65536)
2869
- });
2870
- /** Every `session.delta` since the turn's last message is void: the model call
2871
- * is being sent again after it broke part way through. A receiver empties the
2872
- * in-flight reply it accumulated; the deltas that follow rebuild it. */
2873
- const DeltaResetFrame = z.object({
2874
- kind: z.literal("session.deltaReset"),
2875
- ...sessionFrameBase,
2876
- streamEpoch: z.string()
2877
- });
2878
- /** A message entered the transcript. Its `thinking`, `tool-use` and
2879
- * `tool-result` content parts carry all thinking and tool activity — there
2880
- * are no separate tool or thinking frames. */
2881
- const SessionMessageFrame = z.object({
2882
- kind: z.literal("session.messageAppended"),
2883
- ...sessionFrameBase,
2884
- /** Everything about the message is on the message, refusal marker included
2885
- * — the frame adds no field of its own, so what a live client renders and
2886
- * what it gets back in a snapshot cannot disagree. */
2887
- message: ReadingMessageHeader,
2888
- sourceSeq: z.number().int().min(-1),
2889
- streamEpoch: z.string().optional()
2890
- });
2891
- /** Committed execution identities annotate existing calls without changing their protocol names. */
2892
- const SessionToolCallsAdmittedFrame = z.object({
2893
- kind: z.literal("session.toolCallsAdmitted"),
2894
- ...sessionFrameBase,
2895
- messageId: z.string(),
2896
- sourceSeq: z.number().int().min(-1)
2897
- });
2898
- /** Replaces the entire effective snapshot after a rewind commits. */
2899
- const SessionHistoryReplacedFrame = z.object({
2900
- kind: z.literal("session.historyReplaced"),
2901
- ...sessionFrameBase,
2902
- snapshot: SessionSnapshot,
2903
- operationId: z.string().uuid()
2904
- });
2905
- const TurnEndedFrame = z.object({
2906
- kind: z.literal("session.turnEnded"),
2907
- ...sessionFrameBase,
2908
- turnId: z.string().optional(),
2909
- sourceSeq: z.number().int().min(-1),
2910
- outcome: OutcomeSchema,
2911
- /** When the turn ended, epoch milliseconds — `TurnSpan.endedAt`. */
2912
- at: z.number().int(),
2913
- /** The session's running total after this turn — the same figure
2914
- * `SessionSnapshot.live.tokensUsed` carries, and its comment says where it
2915
- * comes from and which similarly-named counter it is not.
2916
- *
2917
- * It rides **here rather than on `session.delta`** because usage is only known
2918
- * once a model call comes back (`packages/core/kernel/src/decide.ts` says
2919
- * the same thing about the step) — a number that grew with every delta
2920
- * would be invented. */
2921
- tokensUsed: z.number().int()
2922
- });
2923
- /** The person joined or left the session. Reaches the connections watching
2924
- * it; every list learns the new participants through `session.updated`. */
2925
- const ParticipantChangedFrame = z.object({
2926
- kind: z.literal("session.participantChanged"),
2927
- ...sessionFrameBase,
2928
- ...ParticipantChange.shape
2929
- });
2930
- /** Some tool calls of the current step are waiting for a person. Reaches the
2931
- * connections watching the session — the ones that can answer; everyone
2932
- * else learns only that the phase moved, through `session.updated`. */
2933
- const HumanAskedFrame = z.object({
2934
- kind: z.literal("session.humanAsked"),
2935
- ...sessionFrameBase,
2936
- requests: z.array(ReadingItemHeader).max(64),
2937
- waitCount: z.number().int().nonnegative(),
2938
- waitCollectionId: z.string(),
2939
- liveEpoch: z.string(),
2940
- sourceSeq: z.number().int().min(-1)
2941
- });
2942
- /** A person answered one request. Carries the whole reply so every watcher
2943
- * — including one that was about to answer the same request — sees what
2944
- * actually took effect. Who answered is not on it: every client here is
2945
- * the same person. */
2946
- const HumanAnsweredFrame = z.object({
2947
- kind: z.literal("session.humanAnswered"),
2948
- ...sessionFrameBase,
2949
- requestId: z.string(),
2950
- replyRef: ContentRef.optional(),
2951
- liveEpoch: z.string(),
2952
- sourceSeq: z.number().int().min(-1)
2953
- });
2954
- /** A plugin asked a person something without stopping the session. A
2955
- * client adds it to the session's pending requests and leaves the phase
2956
- * alone — this is why it is not `session.humanAsked`. */
2957
- const AsyncAskedFrame = z.object({
2958
- kind: z.literal("session.asyncAsked"),
2959
- ...sessionFrameBase,
2960
- request: ReadingItemHeader,
2961
- liveEpoch: z.string()
2962
- });
2963
- /** A plugin request left the pending set: with `reply` when an answer took
2964
- * effect, without when the plugin withdrew it, was unloaded, or the
2965
- * gateway stopped. Always after its `session.asyncAsked`; a client ignores
2966
- * one naming a request it does not hold. */
2967
- const AsyncSettledFrame = z.object({
2968
- kind: z.literal("session.asyncSettled"),
2969
- ...sessionFrameBase,
2970
- requestId: z.string().min(1),
2971
- replyRef: ContentRef.optional(),
2972
- liveEpoch: z.string()
2973
- });
2974
- /** The steers waiting for their step changed: one arrived, was claimed into
2975
- * a step, opened the next turn, was withdrawn, or was handed back by a
2976
- * cancellation. `steers` is the whole list still waiting, never a diff; a
2977
- * claimed steer's `session.messageAppended` arrives before the frame that
2978
- * drops it. `returned` names the steers a cancellation handed back
2979
- * unclaimed — the page that sent one puts its words back in the composer —
2980
- * and is empty otherwise. */
2981
- const SteersChangedFrame = z.object({
2982
- kind: z.literal("session.steersChanged"),
2983
- ...sessionFrameBase,
2984
- steers: z.array(ReadingItemHeader).max(64),
2985
- steerCount: z.number().int().nonnegative(),
2986
- liveEpoch: z.string(),
2987
- returned: z.array(z.string().min(1))
2988
- });
2989
- /** The permissions of one (agent, workspace) changed: a person answered one
2990
- * into existence inside a tool call, or revoked one from the settings page.
2991
- * Both go through the one writer of this frame. Broadcast to every client;
2992
- * a client that is not looking at that pair
2993
- * ignores it. */
2994
- const AccessChangedFrame = z.object({
2995
- kind: z.literal("config.accessChanged"),
2996
- grants: z.array(AuthorizationRecord)
2997
- });
2998
- /** How a spawned process ended. Derived rather than reported: a process that
2999
- * took SIGKILL leaves no last words, so `stopped` is told from `signalled`
3000
- * by whether this host asked for it. A client switches on `kind` with a
3001
- * `default` branch — a new kind is an addition. */
3002
- const SubprocessEnding = z.discriminatedUnion("kind", [
3003
- z.object({
3004
- kind: z.literal("exited"),
3005
- code: z.number().int()
3006
- }),
3007
- z.object({
3008
- kind: z.literal("signalled"),
3009
- signal: z.string().min(1)
3010
- }),
3011
- z.object({ kind: z.literal("stopped") }),
3012
- z.object({ kind: z.literal("timed-out") }),
3013
- z.object({ kind: z.literal("cancelled") }),
3014
- z.object({ kind: z.literal("shutdown") })
3015
- ]);
3016
- /** One registered process, as a client reads it.
3017
- *
3018
- * `command` is the one line a person reads, not the argv handed to the
3019
- * sandbox: that argv carries the whole generated profile and every
3020
- * authorized path, and it is recorded nowhere.
3021
- *
3022
- * `held` is what makes the revoke surface possible — the grants this
3023
- * process was planned against. Revoking one of them changes nothing about
3024
- * a process already running, so the interface compares its rows against
3025
- * this list and offers to stop what still holds it.
3026
- *
3027
- * `logs` are absolute paths under the session's workspace directory, which
3028
- * is a work directory: the model reads them with the file tools it has. */
3029
- const SubprocessSummary = z.object({
3030
- processId: z.string().min(1),
3031
- sessionId: z.string().min(1),
3032
- agentId: z.string().min(1),
3033
- workspaceId: z.string().min(1),
3034
- command: z.string(),
3035
- startedAt: z.number().int(),
3036
- state: z.enum([
3037
- "running",
3038
- "ending",
3039
- "ended"
3040
- ]),
3041
- ending: SubprocessEnding.nullable(),
3042
- held: z.array(z.object({
3043
- path: z.string(),
3044
- access: z.enum(["read", "write"])
3045
- })),
3046
- logs: z.object({
3047
- stdout: z.string(),
3048
- stderr: z.string(),
3049
- meta: z.string()
3050
- }),
3051
- notified: z.boolean().nullable()
3052
- });
3053
- /** The subprocess registry changed: something started, something changed
3054
- * state, something ended. Broadcast to every authenticated client, and it
3055
- * carries the whole table rather than a delta — the table holds tens of
3056
- * rows, and at that size a delta only gives a client a second way to be
3057
- * wrong.
3058
- *
3059
- * Most of its causes have no request behind them: a process exits on its
3060
- * own, a timeout fires, the machine is shutting
3061
- * down. One writer, so a request handler broadcasts nothing of its own. */
3062
- const ProcessChangedFrame = z.object({
3063
- kind: z.literal("process.changed"),
3064
- processes: z.array(SubprocessSummary)
3065
- });
3066
- /** Where a run goes: a new session each time, or one existing session. */
3067
- const TriggerTarget = z.discriminatedUnion("kind", [z.object({ kind: z.literal("new-session") }), z.object({
3068
- kind: z.literal("session"),
3069
- sessionId: z.string().min(1)
3070
- })]);
3071
- /** One pre-authorized permission a trigger's new sessions hold: a path read
3072
- * or write (absolute), a command's network (`*`), or a host `web_fetch` may
3073
- * reach. */
3074
- const TriggerScopeItem = z.object({
3075
- kind: z.enum([
3076
- "read",
3077
- "write",
3078
- "network",
3079
- "web-host"
3080
- ]),
3081
- target: z.string().min(1).max(4096)
3082
- });
3083
- const TriggerProblem = z.enum([
3084
- "agent-removed",
3085
- "workspace-removed",
3086
- "session-missing",
3087
- "no-model",
3088
- "source-unavailable"
3089
- ]);
3090
- /** One run of a trigger. `reason` is a code a client words:
3091
- * `previous-running`, `target-busy`, `missed`, `agent-removed`,
3092
- * `workspace-removed`, `session-missing`, `no-model`, `turn-failed`,
3093
- * `turn-interrupted`, `gateway-stopped`. */
3094
- const TriggerRun = z.object({
3095
- id: z.string(),
3096
- triggerId: z.string(),
3097
- kind: z.enum([
3098
- "scheduled",
3099
- "catch-up",
3100
- "fired"
3101
- ]),
3102
- scheduledAt: z.number().int().nullable(),
3103
- startedAt: z.number().int(),
3104
- state: z.enum([
3105
- "running",
3106
- "waiting",
3107
- "completed",
3108
- "failed",
3109
- "skipped"
3110
- ]),
3111
- reason: z.string().nullable(),
3112
- sessionId: z.string().nullable(),
3113
- endedAt: z.number().int().nullable()
3114
- });
3115
- const TriggerCreator = z.discriminatedUnion("kind", [z.object({ kind: z.literal("user") }), z.object({
3116
- kind: z.literal("agent"),
3117
- agentId: z.string(),
3118
- sessionId: z.string()
3119
- })]);
3120
- /** One trigger definition. `source` is a plugin source's minted
3121
- * `plugin:<name>:<kind>`, and `config` is that source's own data — a
3122
- * scheduled task's rule lives there. The core reads none of it. */
3123
- const TriggerSummary = z.object({
3124
- id: z.string(),
3125
- source: z.string(),
3126
- name: z.string(),
3127
- agentId: z.string(),
3128
- workspaceId: z.string(),
3129
- /** The source's own name for itself — 计划任务 for the scheduled-task
3130
- * source — or `null` while the source is not registered. */
3131
- sourceLabel: z.string().nullable(),
3132
- config: z.unknown().nullable(),
3133
- instruction: z.string(),
3134
- target: TriggerTarget,
3135
- scope: z.array(TriggerScopeItem),
3136
- enabled: z.boolean(),
3137
- problem: TriggerProblem.nullable(),
3138
- lastRun: TriggerRun.nullable(),
3139
- createdBy: TriggerCreator,
3140
- createdAt: z.number().int(),
3141
- updatedAt: z.number().int()
3142
- });
3143
- /** What a person or an agent writes to create or change a trigger. */
3144
- const TriggerInput = z.object({
3145
- name: z.string().trim().min(1).max(80),
3146
- agentId: z.string().min(1),
3147
- workspaceId: z.string().min(1),
3148
- config: z.unknown().optional(),
3149
- instruction: z.string().trim().min(1).max(8e3),
3150
- target: TriggerTarget,
3151
- scope: z.array(TriggerScopeItem).max(100)
3152
- });
3153
- /** The trigger table changed; the whole table, like `process.changed`. One
3154
- * writer, `RuntimePort.onTriggersChanged`. */
3155
- const TriggersChangedFrame = z.object({
3156
- kind: z.literal("trigger.changed"),
3157
- triggers: z.array(TriggerSummary)
3158
- });
3159
- /** One run started or moved. One writer, `RuntimePort.onTriggerRunChanged`. */
3160
- const TriggerRunChangedFrame = z.object({
3161
- kind: z.literal("trigger.runChanged"),
3162
- run: TriggerRun
3163
- });
3164
- /** Why a waiting request stopped waiting. `cancelled` is a synchronous
3165
- * request whose turn was cancelled; `session-ended` is one whose session was
3166
- * found no longer waiting when the gateway started. */
3167
- const InboxSettleReason = z.enum([
3168
- "answered",
3169
- "withdrawn",
3170
- "plugin-unloaded",
3171
- "gateway-stopped",
3172
- "session-ended",
3173
- "cancelled"
3174
- ]);
3175
- /**
3176
- * What an inbox item says, by category. Core categories carry structured
3177
- * fields only, because the gateway does not know the reader's language: a
3178
- * client renders each category in its own words. Only a plugin's item
3179
- * carries text, the plugin's own.
3180
- */
3181
- const InboxDetail = z.discriminatedUnion("category", [
3182
- z.object({
3183
- category: z.literal("human-request"),
3184
- source: z.enum(["sync", "async"]),
3185
- request: z.union([HumanRequest, AsyncHumanRequest])
3186
- }),
3187
- z.object({
3188
- category: z.literal("subprocess-ended"),
3189
- processId: z.string().min(1),
3190
- command: z.string(),
3191
- ending: SubprocessEnding
3192
- }),
3193
- z.object({
3194
- category: z.literal("turn-ended"),
3195
- outcome: OutcomeSchema
3196
- }),
3197
- z.object({
3198
- category: z.literal("participant-joined"),
3199
- reason: z.string().max(500)
3200
- }),
3201
- z.object({
3202
- category: z.literal("trigger-run"),
3203
- triggerId: z.string(),
3204
- name: z.string(),
3205
- runId: z.string(),
3206
- state: z.literal("failed"),
3207
- reason: z.string()
3208
- }),
3209
- z.object({
3210
- category: z.literal("plugin"),
3211
- title: z.string().min(1).max(200),
3212
- body: z.string().max(4e3).optional(),
3213
- tone: z.enum([
3214
- "neutral",
3215
- "success",
3216
- "failure"
3217
- ])
3218
- })
3219
- ]);
3220
- /** One notifier's result for one item. */
3221
- const InboxDelivery = z.object({
3222
- /** `<plugin>:<notifier id>`. */
3223
- notifier: z.string().min(1),
3224
- state: z.enum(["delivered", "failed"]),
3225
- reason: z.string().optional(),
3226
- at: z.number().int()
3227
- });
3228
- /**
3229
- * One thing a person should know about or act on, from any session.
3230
- *
3231
- * A `request` waits for an answer given through `session.answer`; it ends
3232
- * `settled`. A `notice` only informs. `owner` is decided by the entrance —
3233
- * `core`, or `plugin:<name>` for what a plugin posted — never by the caller.
3234
- */
3235
- const InboxItem = z.object({
3236
- id: z.string().min(1),
3237
- kind: z.enum(["request", "notice"]),
3238
- owner: z.string().min(1),
3239
- sessionId: z.string().nullable(),
3240
- detail: InboxDetail,
3241
- createdAt: z.number().int(),
3242
- readAt: z.number().int().nullable(),
3243
- settled: z.object({
3244
- at: z.number().int(),
3245
- reason: InboxSettleReason
3246
- }).nullable(),
3247
- deliveries: z.array(InboxDelivery)
3248
- });
3249
- /** The inbox changed: items added or changed, items removed. Broadcast to
3250
- * every authenticated client without `seq`; a client overwrites by id in
3251
- * arrival order and replaces the whole table from `inbox.list` after a
3252
- * reconnect. One writer, `RuntimePort.onInboxChanged`. */
3253
- const InboxChangedFrame = z.object({
3254
- kind: z.literal("inbox.changed"),
3255
- upserted: z.array(InboxItem),
3256
- removed: z.array(z.string())
3257
- });
3258
- /** The allowed-host list changed: an explicit add or remove, or an
3259
- * `allowed-always` approval from inside `web_fetch` with no request behind
3260
- * it — both go through the one writer of this frame. Carries the whole
3261
- * list rather than a delta, so a receiver replaces rather than
3262
- * reconciles. */
3263
- /** A plugin's credentials changed in one scope — a write or a clear through
3264
- * `config.credential.*`. Carries the address and never a value or a hint;
3265
- * a receiver re-reads with `config.credential.status`. Core-owned
3266
- * credentials announce themselves through their own catalog frames. */
3267
- const CredentialChangedFrame = z.object({
3268
- kind: z.literal("config.credentialChanged"),
3269
- plugin: z.string(),
3270
- scopes: z.array(z.string()).min(1).max(64)
3271
- });
3272
- const CoreSessionFrame = z.discriminatedUnion("kind", [
3273
- TurnStartedFrame,
3274
- DeltaFrame,
3275
- DeltaResetFrame,
3276
- SessionToolCallsAdmittedFrame,
3277
- SessionMessageFrame,
3278
- SessionHistoryReplacedFrame,
3279
- TurnEndedFrame,
3280
- HumanAskedFrame,
3281
- HumanAnsweredFrame,
3282
- AsyncAskedFrame,
3283
- AsyncSettledFrame,
3284
- SteersChangedFrame,
3285
- ParticipantChangedFrame
3286
- ]);
3287
- z.union([CoreSessionFrame, PluginSessionFrame]);
3288
- /** Every frame this repository writes, the global ones first and the
3289
- * session-scoped ones after. Still a `discriminatedUnion`: nothing of the
3290
- * core half's exhaustiveness is given up. */
3291
- /** Current confirmed limits after persistence or recovery; this does not certify a particular request. */
3292
- const LimitsChangedFrameSchema = z.strictObject({
3293
- kind: z.literal("config.limitsChanged"),
3294
- limits: SessionLimitsSchema
3295
- });
3296
- const CoreFrame = z.discriminatedUnion("kind", [
3297
- HelloFrame,
3298
- PresenceFrame,
3299
- SessionCreatedFrame,
3300
- SessionUpdatedFrame,
3301
- AgentChangedFrame,
3302
- AgentRemovedFrame,
3303
- WorkspaceChangedFrame,
3304
- PluginChangedFrame,
3305
- AccessChangedFrame,
3306
- LimitsChangedFrameSchema,
3307
- InboxChangedFrame,
3308
- ProcessChangedFrame,
3309
- TriggersChangedFrame,
3310
- TriggerRunChangedFrame,
3311
- CredentialChangedFrame,
3312
- TurnStartedFrame,
3313
- DeltaFrame,
3314
- DeltaResetFrame,
3315
- SessionToolCallsAdmittedFrame,
3316
- SessionMessageFrame,
3317
- SessionHistoryReplacedFrame,
3318
- TurnEndedFrame,
3319
- HumanAskedFrame,
3320
- HumanAnsweredFrame,
3321
- AsyncAskedFrame,
3322
- AsyncSettledFrame,
3323
- SteersChangedFrame,
3324
- ParticipantChangedFrame
3325
- ]);
3326
- /**
3327
- * Every frame the gateway may push, core and plugin alike.
3328
- *
3329
- * A plain union rather than a `discriminatedUnion`, because a plugin's frame
3330
- * name is minted while the gateway runs. The cost is named rather than
3331
- * hidden: every `switch (frame.kind)` now needs a `default`, and
3332
- * exhaustiveness only covers `CoreFrame`. The session-scoped member
3333
- * comes first, so a frame carrying a session is never read as a signal.
3334
- */
3335
- const Frame = z.union([
3336
- CoreFrame,
3337
- PluginSessionFrame,
3338
- PluginSignalFrame
3339
- ]);
3340
- z.strictObject({
3341
- /** Stable lowercase UUID of this installation. */
3342
- gatewayId: z.uuid().refine((id) => id === id.toLowerCase()),
3343
- /** UUID of the actual Gateway process serving this connection. */
3344
- instanceId: z.uuid()
3345
- });
3346
- /** Reads stable installation identity after authentication. */
3347
- const ConnectionInfoRequest = z.object({
3348
- method: z.literal("connection.info"),
3349
- params: z.strictObject({}).optional()
3350
- });
3351
- const PingRequest = z.object({
3352
- method: z.literal("ping"),
3353
- params: z.object({}).optional()
3354
- });
3355
- const StatusRequest = z.object({
3356
- method: z.literal("status"),
3357
- params: z.object({}).optional()
3358
- });
3359
- /** Requests authenticated shutdown of exactly one running gateway instance. */
3360
- const GatewayShutdownRequest = z.strictObject({
3361
- method: z.literal("gateway.shutdown"),
3362
- params: z.strictObject({ instanceId: z.uuid() })
3363
- });
3364
- const SessionListRequest = z.object({
3365
- method: z.literal("session.list"),
3366
- params: z.object({}).optional()
3367
- });
3368
- const SessionCreateRequest = z.object({
3369
- method: z.literal("session.create"),
3370
- params: z.object({
3371
- agentId: z.string(),
3372
- workspaceId: z.string(),
3373
- title: z.string().optional()
3374
- })
3375
- });
3376
- /** The result frame **carries the snapshot itself**. Registering the
3377
- * subscription and reading the snapshot happen in one synchronous step, so
3378
- * nothing can slip between them: no duplicate delivery and no missed frame.
3379
- * A separate `session.snapshot` request would reintroduce exactly the
3380
- * race. */
3381
- const SessionWatchRequest = z.object({
3382
- method: z.literal("session.watch"),
3383
- params: z.object({
3384
- sessionId: z.string(),
3385
- readingLeaseId: z.string().optional()
3386
- }).strict()
3387
- });
3388
- const SessionUnwatchRequest = z.object({
3389
- method: z.literal("session.unwatch"),
3390
- params: z.object({
3391
- sessionId: z.string(),
3392
- readingLeaseId: z.string().optional()
3393
- }).strict()
3394
- });
3395
- /** Takes the message and returns. It does NOT mean the turn started, and
3396
- * certainly not that it finished — a turn can run minutes. Progress arrives
3397
- * as events. The result is deliberately empty of turn content: that is what
3398
- * makes "every channel sees the same stream" free rather than something
3399
- * to maintain. */
3400
- /** The longest a message's text, or one attachment's text, may be. */
3401
- const MESSAGE_TEXT_LIMIT = 262144;
3402
- /** One attachment as the composer sends it: the source, an optional
3403
- * secondary origin, a label, and the text. */
3404
- const MessageAttachmentInput = z.object({
3405
- namespace: z.string().min(1),
3406
- group: z.string().min(1).optional(),
3407
- label: z.string().min(1).max(200),
3408
- text: z.string().min(1).max(MESSAGE_TEXT_LIMIT)
3409
- });
3410
- /** `text` may be empty only when there are attachments; `invocation` records
3411
- * the command a person wrote when `text` is its expansion. */
3412
- const SessionSendRequest = z.object({
3413
- method: z.literal("session.send"),
3414
- params: z.object({
3415
- sessionId: z.string(),
3416
- text: z.string().max(MESSAGE_TEXT_LIMIT),
3417
- invocation: z.object({
3418
- text: z.string().min(1).max(4096),
3419
- namespace: z.string().min(1)
3420
- }).optional(),
3421
- attachments: z.array(MessageAttachmentInput).max(16).optional(),
3422
- /** Files uploaded with `POST /files`, each placed at an index of `text`. */
3423
- files: z.array(MessageFileInput).max(16).optional(),
3424
- operationId: z.string().uuid().optional(),
3425
- rewind: z.object({
3426
- beforeMessageId: z.string().uuid(),
3427
- expectedRevision: z.number().int().nonnegative()
3428
- }).optional()
3429
- })
3430
- }).refine((request) => !request.params.rewind || request.params.operationId !== void 0);
3431
- /** Creates a new independent session before a current user message. */
3432
- const SessionForkRequest = z.object({
3433
- method: z.literal("session.fork"),
3434
- params: z.object({
3435
- sessionId: z.string(),
3436
- beforeMessageId: z.string().uuid(),
3437
- expectedRevision: z.number().int().nonnegative(),
3438
- operationId: z.string().uuid()
3439
- })
3440
- });
3441
- const batchIds = () => z.array(z.string().min(1)).min(1).max(64);
3442
- const queryBudgets = {
3443
- maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
3444
- maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
3445
- };
3446
- const boundedBatchParams = (shape, collection) => z.object(shape).strict().superRefine((value, ctx) => {
3447
- if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 8388608) ctx.addIssue({
3448
- code: "custom",
3449
- message: "batch input exceeds 8 MiB"
3450
- });
3451
- const params = value;
3452
- if (typeof params.maxItemBytes === "number" && typeof params.maxTotalBytes === "number" && Array.isArray(params[collection]) && params.maxItemBytes * params[collection].length + 8192 > params.maxTotalBytes) ctx.addIssue({
3453
- code: "custom",
3454
- message: "declared response budget exceeds maxTotalBytes"
3455
- });
3456
- });
3457
- /** Reads one durable history-operation result after an uncertain response. */
3458
- const SessionOperationsGetRequest = z.object({
3459
- method: z.literal("session.operations.get"),
3460
- params: boundedBatchParams({
3461
- operationIds: z.array(z.uuid()).min(1).max(64),
3462
- ...queryBudgets
3463
- }, "operationIds")
3464
- });
3465
- /** Takes back a message sent while a turn was running, before its step
3466
- * claims it. Answers with the message, so the page that asked can put its
3467
- * words back in the composer; refused once it has reached the
3468
- * conversation. */
3469
- const SessionWithdrawRequest = z.object({
3470
- method: z.literal("session.withdraw"),
3471
- params: z.object({
3472
- sessionId: z.string(),
3473
- steerId: z.string().min(1)
3474
- })
3475
- });
3476
- /** Answers one request a session is waiting on, or one a plugin raised
3477
- * (`SessionSnapshot.live.async`) — the same method for both, told apart
3478
- * by `requestId`. Like `session.send`, the answer is taken and what follows
3479
- * arrives as frames. Not idempotent: a second answer to the same request
3480
- * is refused. */
3481
- const SessionAnswerRequest = z.object({
3482
- method: z.literal("session.answer"),
3483
- params: z.object({
3484
- sessionId: z.string(),
3485
- requestId: z.string().min(1),
3486
- answers: z.array(HumanAnswer)
3487
- })
3488
- });
3489
- /** A no-op when the session is idle, and a no-op when it is not loaded — a
3490
- * session with no driver in this process cannot be running, and cancelling
3491
- * it must not cost a read of its whole log. */
3492
- const SessionCancelRequest = z.object({
3493
- method: z.literal("session.cancel"),
3494
- params: z.object({ sessionId: z.string() })
3495
- });
3496
- /**
3497
- * Moves a session to a model.
3498
- *
3499
- * Not nullable, and that absence is the point: a session is an instance
3500
- * rather than an override, so there is nothing to un-set it back to. A pair
3501
- * this session has not used before is instantiated from the templates as it
3502
- * arrives, and one it has used keeps the settings left on it.
3503
- *
3504
- * Prepares the target context before committing the selection. Preparation
3505
- * may summarize history and is cancellable through session.cancelContext.
3506
- * Refused while a turn or another maintenance operation is running. A session's model is read at every step,
3507
- * so switching mid-turn would send the next step of one conversation to a
3508
- * different endpoint — carrying tool calls the new one never made.
3509
- */
3510
- const SessionSetModelRequest = z.object({
3511
- method: z.literal("session.setModel"),
3512
- params: z.object({
3513
- sessionId: z.string(),
3514
- model: ModelRef
3515
- })
3516
- });
3517
- /**
3518
- * Writes the settings this session will use for one model.
3519
- *
3520
- * Whole rather than a difference: the session is the instance, and this row
3521
- * is what its next turn sends. Writing the settings for a model the session
3522
- * is not currently on is allowed and leaves them there for when it is.
3523
- *
3524
- * Refused while a turn is running, for the reason `session.setModel` is.
3525
- */
3526
- const SessionSetModelParamsRequest = z.object({
3527
- method: z.literal("session.setModelParams"),
3528
- params: z.object({
3529
- sessionId: z.string(),
3530
- model: ModelRef,
3531
- params: z.record(z.string(), z.unknown())
3532
- })
3533
- });
3534
- /** The person joins an agent-created session. A session they created, or
3535
- * one they are already in, answers the current summary unchanged. */
3536
- const SessionJoinRequest = z.object({
3537
- method: z.literal("session.join"),
3538
- params: z.object({ sessionId: z.string() })
3539
- });
3540
- /** The person leaves an agent-created session. Refused for a session they
3541
- * created; one they are not in answers the current summary unchanged. */
3542
- const SessionLeaveRequest = z.object({
3543
- method: z.literal("session.leave"),
3544
- params: z.object({ sessionId: z.string() })
3545
- });
3546
- /** Files a session away, or takes it back out. Idempotent, and it deliberately
3547
- * leaves `updatedAt` alone: filing is not session activity, and a list should
3548
- * not reorder because somebody tidied up. Writing the value it already holds
3549
- * still answers with the summary and still broadcasts once — the same
3550
- * contract `session.setModel` has. It produces no turn and writes no event. */
3551
- const SessionArchiveRequest = z.object({
3552
- method: z.literal("session.archive"),
3553
- params: boundedBatchParams({
3554
- operationId: z.uuid(),
3555
- sessionIds: batchIds(),
3556
- archived: z.boolean()
3557
- }, "sessionIds")
3558
- });
3559
- /** Sets the name a person gives a session, or clears it: trimmed, at most 60
3560
- * characters, and a name holding nothing but whitespace clears it. Leaves
3561
- * the topic title, the digest and `updatedAt` alone, and works whatever the
3562
- * session is doing. Answers the summary and broadcasts `session.updated`
3563
- * once; a name that is too long or an unknown id is refused, nothing
3564
- * written. */
3565
- const SessionSetNameRequest = z.object({
3566
- method: z.literal("session.setName"),
3567
- params: z.object({
3568
- sessionId: z.string(),
3569
- name: z.string()
3570
- })
3571
- });
3572
- /** Reads the latest confirmed global limits; controlled recovery runs before an uncertain value is returned. */
3573
- const ConfigLimitsGetRequest = z.strictObject({
3574
- method: z.literal("config.limits.get"),
3575
- params: z.strictObject({})
3576
- });
3577
- /** Replaces both limits; omitting tokenBudget removes the budget for future turns. */
3578
- const ConfigLimitsSetRequest = z.strictObject({
3579
- method: z.literal("config.limits.set"),
3580
- params: z.strictObject({ limits: SessionLimitsSchema })
3581
- });
3582
- const ConfigAgentListRequest = z.object({
3583
- method: z.literal("config.agent.list"),
3584
- params: z.object({}).optional()
3585
- });
3586
- const ConfigAgentCreateRequest = z.object({
3587
- method: z.literal("config.agent.create"),
3588
- params: z.object({ name: z.string().min(1) })
3589
- });
3590
- /** Changes one agent's definition. An omitted field is left alone; `tools:
3591
- * null` removes the whitelist, and an empty array allows no tool. */
3592
- const ConfigAgentUpdateRequest = z.object({
3593
- method: z.literal("config.agent.update"),
3594
- params: z.object({
3595
- agentId: z.string(),
3596
- expectedRevision: z.number().int().positive(),
3597
- expectedContentHash: z.string().regex(/^[a-f0-9]{64}$/),
3598
- name: z.string().trim().min(1).optional(),
3599
- description: z.string().trim().refine((text) => [...text].length <= 500, "description is longer than 500 characters").optional(),
3600
- tools: z.array(z.string().min(1)).nullable().optional(),
3601
- /** Owner-keyed configuration committed with the Agent definition. */
3602
- extensionData: z.record(z.string(), z.unknown()).optional(),
3603
- startsSessions: z.boolean().optional()
3604
- })
3605
- });
3606
- const ConfigAgentSetPromptSlotRequest = z.object({
3607
- method: z.literal("config.agent.setPromptSlot"),
3608
- params: z.object({
3609
- agentId: z.string(),
3610
- expectedRevision: z.number().int().positive(),
3611
- expectedContentHash: z.string().regex(/^[a-f0-9]{64}$/),
3612
- slot: z.enum([
3613
- "identity",
3614
- "instructions",
3615
- "style",
3616
- "reminder"
3617
- ]),
3618
- text: z.string()
3619
- })
3620
- });
3621
- const ConfigAgentPromptSlotsRequest = z.object({
3622
- method: z.literal("config.agent.promptSlots"),
3623
- params: boundedBatchParams({
3624
- agentIds: batchIds(),
3625
- ...queryBudgets
3626
- }, "agentIds")
3627
- });
3628
- /** Sets an agent's picture, or with `null` returns it to the derived one.
3629
- * The browser crops and encodes; the gateway checks it is a whole 256×256
3630
- * PNG of at most `AVATAR_MAX_BYTES`. */
3631
- const ConfigAgentSetAvatarRequest = z.object({
3632
- method: z.literal("config.agent.setAvatar"),
3633
- params: z.object({
3634
- agentId: z.string(),
3635
- expectedRevision: z.number().int().positive(),
3636
- expectedContentHash: z.string().regex(/^[a-f0-9]{64}$/),
3637
- image: z.string().max(Math.ceil(524288 / 3) * 4).nullable()
3638
- })
3639
- });
3640
- /** The uploaded picture, or `null` when the agent has none. */
3641
- const ConfigAgentAvatarsRequest = z.object({
3642
- method: z.literal("config.agent.avatars"),
3643
- params: boundedBatchParams({
3644
- agentIds: z.array(z.string()).min(1).max(4),
3645
- maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
3646
- }, "agentIds")
3647
- });
3648
- /** Removes a user-created agent: its row, picture, model overrides, access
3649
- * grants and its directory under the work root. Its sessions stay readable
3650
- * and refuse to continue. Refused for the general-purpose agent and while
3651
- * any session of it, or any task delegated to it, is still running. One
3652
- * `config.agentRemoved` follows. */
3653
- const ConfigAgentRemoveRequest = z.object({
3654
- method: z.literal("config.agent.remove"),
3655
- params: boundedBatchParams({
3656
- operationId: z.uuid(),
3657
- agentIds: batchIds()
3658
- }, "agentIds")
3659
- });
3660
- /** One save from the agent editor: every field the person changed, applied
3661
- * together. Everything is validated before anything is written, and the
3662
- * whole batch lands between two steps of any running session, so no step
3663
- * sees half of it. One `config.agentChanged` follows. Omitted fields are
3664
- * left alone; `avatar: null` returns to the derived picture. */
3665
- const ConfigAgentSaveRequest = z.object({
3666
- method: z.literal("config.agent.save"),
3667
- params: ConfigAgentUpdateRequest.shape.params.extend({
3668
- prompts: z.object({
3669
- identity: z.string().optional(),
3670
- instructions: z.string().optional(),
3671
- style: z.string().optional(),
3672
- reminder: z.string().optional()
3673
- }).strict().optional(),
3674
- avatar: ConfigAgentSetAvatarRequest.shape.params.shape.image.optional()
3675
- })
3676
- });
3677
- z.object({
3678
- id: z.enum([
3679
- "identity",
3680
- "instructions",
3681
- "style",
3682
- "reminder"
3683
- ]),
3684
- /** The chapter the slot sits in; `volatile` for the one repeated after the
3685
- * conversation on every step. */
3686
- chapter: z.enum([
3687
- "identity",
3688
- "working-posture",
3689
- "tone",
3690
- "volatile"
3691
- ]),
3692
- /** English, for a client with no translation of its own; a client that has
3693
- * one looks the slot up by `id`. */
3694
- label: z.string(),
3695
- description: z.string(),
3696
- /** Upper bound in Unicode code points, counted after trimming. */
3697
- maxLength: z.number().int().positive()
3698
- });
3699
- const ConfigPromptSlotsRequest = z.object({
3700
- method: z.literal("config.prompt.slots"),
3701
- params: z.object({}).optional()
3702
- });
3703
- z.object({
3704
- agentId: z.string(),
3705
- tools: z.array(z.object({
3706
- name: z.string(),
3707
- description: z.string(),
3708
- plugin: z.string(),
3709
- permitted: z.boolean(),
3710
- preloadDefault: z.boolean()
3711
- }))
3712
- });
3713
- /** Writes nothing, produces no turn, needs no session: safe to retry. An
3714
- * agent that does not exist answers `ok: false`, because an empty list is a
3715
- * real and different answer — "this agent is offered no tools at all". */
3716
- const ConfigToolListRequest = z.object({
3717
- method: z.literal("config.tool.list"),
3718
- params: boundedBatchParams({
3719
- agentIds: batchIds(),
3720
- ...queryBudgets
3721
- }, "agentIds")
3722
- });
3723
- /** What is under a directory, for a client that has to name one.
3724
- *
3725
- * The first method of the `std.*` family: the standard library a client gets
3726
- * from the process hosting it. A browser cannot hand back an absolute path —
3727
- * `webkitdirectory` gives relative ones and `showDirectoryPicker` gives a
3728
- * name — so a client that offers somewhere to *pick* a directory rather than
3729
- * type one cannot do it alone. Omitting `path` starts at the home directory.
3730
- *
3731
- * **It grants no authority that was not already there.** Any connection can
3732
- * already authorize any absolute path through `config.workspace.addDirectory`;
3733
- * this makes an existing power easier to aim rather than adding a new one.
3734
- * It is still a read of the machine, and it is one of the reasons the gateway
3735
- * binds loopback.
3736
- *
3737
- * **It answers file and directory metadata, never file contents**, and that boundary
3738
- * is `index.test.ts`'s to keep rather than this name's — `fs` is the module
3739
- * it belongs to, not a promise about what it will refuse. */
3740
- const StdFsListRequest = z.object({
3741
- method: z.literal("std.fs.list"),
3742
- params: z.object({ path: z.string().min(1).optional() }).optional()
3743
- });
3744
- z.object({
3745
- path: z.string(),
3746
- parent: z.string().nullable(),
3747
- selected: z.string().optional(),
3748
- entries: z.array(z.object({
3749
- name: z.string(),
3750
- path: z.string(),
3751
- kind: z.enum(["file", "directory"]),
3752
- hidden: z.boolean()
3753
- }))
3754
- });
3755
- /** Every registered process, running and recently ended alike. Reads the
3756
- * machine rather than one session: `yaoguang stop` and the revoke surface
3757
- * both need all of them, and filtering by session is the caller's. */
3758
- const ProcessListRequest = z.object({
3759
- method: z.literal("process.list"),
3760
- params: z.object({}).optional()
3761
- });
3762
- /** Every trigger definition, optionally one workspace's. */
3763
- const TriggerListRequest = z.object({
3764
- method: z.literal("trigger.list"),
3765
- params: z.object({ workspaceId: z.string().optional() }).optional()
3766
- });
3767
- /** Creates a definition; a refusal writes nothing. `source` is a registered
3768
- * plugin source, `plugin:<name>:<kind>`, and `config` is checked against
3769
- * that source's `configSchema`. */
3770
- const TriggerCreateRequest = z.object({
3771
- method: z.literal("trigger.create"),
3772
- params: TriggerInput.extend({ source: z.string().min(1) })
3773
- });
3774
- const TriggerUpdateRequest = z.object({
3775
- method: z.literal("trigger.update"),
3776
- params: TriggerInput.extend({ id: z.string().min(1) })
3777
- });
3778
- const TriggerSetEnabledRequest = z.object({
3779
- method: z.literal("trigger.setEnabled"),
3780
- params: boundedBatchParams({
3781
- operationId: z.uuid(),
3782
- ids: batchIds(),
3783
- enabled: z.boolean()
3784
- }, "ids")
3785
- });
3786
- /** Removes a definition, its runs and its pre-authorized scope; sessions it
3787
- * opened stay. */
3788
- const TriggerRemoveRequest = z.object({
3789
- method: z.literal("trigger.remove"),
3790
- params: boundedBatchParams({
3791
- operationId: z.uuid(),
3792
- ids: batchIds()
3793
- }, "ids")
3794
- });
3795
- /** A definition's runs, newest first, at most 200. */
3796
- const TriggerRunsRequest = z.object({
3797
- method: z.literal("trigger.runs"),
3798
- params: boundedBatchParams({
3799
- ids: batchIds(),
3800
- ...queryBudgets
3801
- }, "ids")
3802
- });
3803
- /** Every inbox item that still exists, newest first. No cap: unread notices
3804
- * and waiting requests are never removed on anyone's behalf, so the list
3805
- * hands all of them over. */
3806
- const InboxListRequest = z.object({
3807
- method: z.literal("inbox.list"),
3808
- params: z.object({}).optional()
3809
- });
3810
- /** Marks items read; ids that do not exist are ignored. */
3811
- const InboxReadRequest = z.object({
3812
- method: z.literal("inbox.read"),
3813
- params: z.object({ ids: z.array(z.string().min(1)).min(1).max(1e3) })
3814
- });
3815
- /** Marks every unread notice pointing at one session read — what opening
3816
- * that session does. */
3817
- const InboxReadSessionRequest = z.object({
3818
- method: z.literal("inbox.readSession"),
3819
- params: z.object({ sessionId: z.string().min(1) })
3820
- });
3821
- /** Removes items. A request still waiting cannot be cleared; its id is
3822
- * ignored. */
3823
- const InboxClearRequest = z.object({
3824
- method: z.literal("inbox.clear"),
3825
- params: z.object({ ids: z.array(z.string().min(1)).min(1).max(1e3) })
3826
- });
3827
- /** Removes every read notice and every settled request. */
3828
- const InboxClearReadRequest = z.object({
3829
- method: z.literal("inbox.clearRead"),
3830
- params: z.object({}).optional()
3831
- });
3832
- /** The signal ladder, the same one a timeout walks. A process already gone
3833
- * answers success with no side effect. */
3834
- const ProcessStopRequest = z.object({
3835
- method: z.literal("process.stop"),
3836
- params: boundedBatchParams({ processIds: batchIds() }, "processIds")
3837
- });
3838
- /** One stream's bytes, by range.
3839
- *
3840
- * It reads the log file rather than the in-memory window, so it answers for
3841
- * a process that has already ended — and it takes a range because a stream
3842
- * may hold 64 MB and no caller wants all of it. `total` is what the stream
3843
- * holds now, which is what a caller polls. */
3844
- const ProcessOutputRequest = z.object({
3845
- method: z.literal("process.output"),
3846
- params: z.object({
3847
- processId: z.string().min(1),
3848
- stream: z.enum(["stdout", "stderr"]),
3849
- offset: z.number().int().min(0).optional(),
3850
- limit: z.number().int().min(1).optional()
3851
- })
3852
- });
3853
- z.object({
3854
- bytes: z.string(),
3855
- offset: z.number().int().min(0),
3856
- total: z.number().int().min(0),
3857
- stream: z.enum(["stdout", "stderr"])
3858
- });
3859
- const ConfigWorkspaceListRequest = z.object({
3860
- method: z.literal("config.workspace.list"),
3861
- params: z.object({}).optional()
3862
- });
3863
- const ConfigWorkspaceCreateRequest = z.object({
3864
- method: z.literal("config.workspace.create"),
3865
- params: z.object({ name: z.string().min(1) })
3866
- });
3867
- /** Change what a workspace *is*, as opposed to what it may reach: its name.
3868
- * An omitted field is left alone. The picture has methods of its own. */
3869
- const ConfigWorkspaceUpdateRequest = z.object({
3870
- method: z.literal("config.workspace.update"),
3871
- params: z.object({
3872
- workspaceId: z.string(),
3873
- name: z.string().min(1).optional()
3874
- })
3875
- });
3876
- /** Sets a workspace's picture, or with `null` returns it to the letters face.
3877
- * The browser crops and encodes; the gateway checks it is a whole 256×256
3878
- * PNG of at most `AVATAR_MAX_BYTES`, the same check an agent's picture gets.
3879
- * One `config.workspaceChanged` follows a success. */
3880
- const ConfigWorkspaceSetAvatarRequest = z.object({
3881
- method: z.literal("config.workspace.setAvatar"),
3882
- params: z.object({
3883
- workspaceId: z.string(),
3884
- image: ConfigAgentSetAvatarRequest.shape.params.shape.image
3885
- })
3886
- });
3887
- /** The workspace's uploaded picture, or `null` when it has none. */
3888
- const ConfigWorkspaceAvatarsRequest = z.object({
3889
- method: z.literal("config.workspace.avatars"),
3890
- params: boundedBatchParams({
3891
- workspaceIds: z.array(z.string()).min(1).max(4),
3892
- maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
3893
- }, "workspaceIds")
3894
- });
3895
- /** Adds or updates a bounded directory collection atomically; omitted access is read. */
3896
- const ConfigWorkspaceAddDirectoriesRequest = z.object({
3897
- method: z.literal("config.workspace.addDirectories"),
3898
- params: z.object({
3899
- operationId: z.uuid(),
3900
- workspaceId: z.string(),
3901
- directories: z.array(z.object({
3902
- path: z.string().min(1),
3903
- access: z.enum(["read", "read-write"]).default("read")
3904
- }).strict()).min(1).max(64)
3905
- }).strict().refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8388608, "batch input exceeds 8 MiB")
3906
- });
3907
- /** Removes directory authorizations atomically; already absent paths are successful no-ops. */
3908
- const ConfigWorkspaceRemoveDirectoriesRequest = z.object({
3909
- method: z.literal("config.workspace.removeDirectories"),
3910
- params: z.object({
3911
- operationId: z.uuid(),
3912
- workspaceId: z.string(),
3913
- paths: z.array(z.string().min(1)).min(1).max(64)
3914
- }).strict().refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8388608, "batch input exceeds 8 MiB")
3915
- });
3916
- /** Lists access records with ownership; omitted filters include all scopes. */
3917
- const ConfigAccessListRequest = z.object({
3918
- method: z.literal("config.access.list"),
3919
- params: z.object({}).strict().optional()
3920
- });
3921
- /** Adds a batch of globally reusable resources. */
3922
- const ConfigAccessAddRequest = z.object({
3923
- method: z.literal("config.access.add"),
3924
- params: boundedBatchParams({
3925
- operationId: z.uuid(),
3926
- authorizations: z.array(AuthorizationInput).min(1).max(64)
3927
- }, "authorizations")
3928
- });
3929
- /** Reads whether new shell commands use operating-system confinement. */
3930
- /** Persists the installation-wide switch; repeated writes are no-ops. */
3931
- /** Reads installation-wide independent network strategies. */
3932
- /** Replaces the three strategies atomically without creating an approval record. */
3933
- /** Removes one permission and broadcasts `config.accessChanged`. A permission
3934
- * that was not there answers `revoked: false` rather than failing: a retried
3935
- * revoke says what the first one said. */
3936
- const ConfigAccessRevokeRequest = z.object({
3937
- method: z.literal("config.access.revoke"),
3938
- params: boundedBatchParams({
3939
- operationId: z.uuid(),
3940
- ids: batchIds()
3941
- }, "ids")
3942
- });
3943
- z.object({
3944
- name: z.string(),
3945
- set: z.literal(true),
3946
- hint: z.string()
3947
- });
3948
- /** One scope of one plugin's credentials. `plugin` is the plugin's full
3949
- * name; core-owned credentials are not addressable here and travel in their
3950
- * own create/update requests. */
3951
- const CredentialScopeParams = z.object({
3952
- plugin: z.string().min(1),
3953
- scope: z.string().min(1)
3954
- });
3955
- /** The set credentials of one scope, ordered by name. A name that is not
3956
- * set is absent: the plugin, not the core, knows what it expects. */
3957
- const ConfigCredentialStatusRequest = z.object({
3958
- method: z.literal("config.credential.status"),
3959
- params: CredentialScopeParams
3960
- });
3961
- /** Writes one plugin credential. The value is trimmed before it is sealed;
3962
- * a value of only whitespace clears the name. Answers the scope's status
3963
- * and broadcasts `config.credentialChanged`. The plaintext travels inbound
3964
- * only. */
3965
- const ConfigCredentialSetRequest = z.object({
3966
- method: z.literal("config.credential.set"),
3967
- params: boundedBatchParams({
3968
- operationId: z.uuid(),
3969
- plugin: z.string().min(1),
3970
- scope: z.string().min(1),
3971
- items: z.array(z.object({
3972
- name: z.string().min(1),
3973
- value: z.string()
3974
- }).strict()).min(1).max(64)
3975
- }, "items")
3976
- });
3977
- /** Clears one name, or the whole scope when `name` is omitted. Clearing
3978
- * something absent succeeds and answers the current status. */
3979
- const ConfigCredentialClearRequest = z.object({
3980
- method: z.literal("config.credential.clear"),
3981
- params: boundedBatchParams({
3982
- operationId: z.uuid(),
3983
- plugin: z.string().min(1),
3984
- items: z.array(z.discriminatedUnion("mode", [z.object({
3985
- scope: z.string().min(1),
3986
- mode: z.literal("names"),
3987
- names: batchIds()
3988
- }).strict(), z.object({
3989
- scope: z.string().min(1),
3990
- mode: z.literal("all")
3991
- }).strict()])).min(1).max(64)
3992
- }, "items")
3993
- });
3994
- /** Reads the hosts `web_fetch` may reach without asking. */
3995
- /** Adds a bare host and broadcasts `config.webChanged`. With `includeSubdomains`, the
3996
- * stored `*.host` rule covers the base and all descendant labels; otherwise it is exact. */
3997
- /** Removes one host and broadcasts `config.webChanged`; a host not on the list
3998
- * still answers and still broadcasts. */
3999
- /**
4000
- * Installs a package and loads what it exports, in one request.
4001
- *
4002
- * `spec` is npm's own: a package name with an optional version, or a
4003
- * directory. A relative directory is resolved by the caller before it is
4004
- * sent — the gateway is a daemon and its working directory is not the
4005
- * user's.
4006
- *
4007
- * `config` is the plugin's own section, unread here: the plugin declares a
4008
- * zod schema and the container validates against it, so a shape this
4009
- * protocol pinned would be a second opinion about someone else's
4010
- * configuration.
4011
- */
4012
- /** Installs the selected roots in one shared physical mutation and reports every root result. */
4013
- const PluginInstallBatchRequest = z.object({
4014
- method: z.literal("plugin.installBatch"),
4015
- params: z.object({ items: z.array(z.object({
4016
- spec: z.string().min(1),
4017
- config: z.record(z.string(), z.unknown()).optional()
4018
- })).min(1).max(64) })
4019
- });
4020
- /** Requested roots and their complete confirmed lifecycle closure. */
4021
- const PluginRemovalBatchPlan = z.object({
4022
- names: z.array(z.string().min(1)).min(1).max(64),
4023
- affectedNames: z.array(z.string().min(1)),
4024
- token: z.string().min(1)
4025
- });
4026
- /** Previews a shared uninstall closure without changing state. */
4027
- const PluginRemoveBatchPreviewRequest = z.object({
4028
- method: z.literal("plugin.removeBatchPreview"),
4029
- params: z.object({ names: z.array(z.string().min(1)).min(1).max(64) })
4030
- });
4031
- /** Removes the confirmed union with one physical mutation. */
4032
- const PluginRemoveBatchRequest = z.object({
4033
- method: z.literal("plugin.removeBatch"),
4034
- params: PluginRemoveBatchPreviewRequest.shape.params.extend({ token: z.string().min(1) })
4035
- });
4036
- PluginRemovalBatchPlan.extend({ enabled: z.boolean() });
4037
- /** Previews one combined enable or disable closure. */
4038
- const PluginSetEnabledBatchPreviewRequest = z.object({
4039
- method: z.literal("plugin.setEnabledBatchPreview"),
4040
- params: PluginRemoveBatchPreviewRequest.shape.params.extend({ enabled: z.boolean() })
4041
- });
4042
- /** Commits the confirmed activation union, retaining already active owner instances. */
4043
- const PluginSetEnabledBatchRequest = z.object({
4044
- method: z.literal("plugin.setEnabledBatch"),
4045
- params: PluginSetEnabledBatchPreviewRequest.shape.params.extend({ token: z.string().min(1) })
4046
- });
4047
- z.object({
4048
- name: z.string().min(1),
4049
- names: z.array(z.string().min(1)),
4050
- token: z.string().min(1)
4051
- });
4052
- z.object({
4053
- /** Installed target extension. */
4054
- name: z.string().min(1),
4055
- /** True enables dependencies; false disables consumers. */
4056
- enabled: z.boolean(),
4057
- /** Owners whose declaration changes or whose activation is retried. */
4058
- names: z.array(z.string().min(1)),
4059
- /** Binds the operation to current manifests, declarations and owner statuses. */
4060
- token: z.string().min(1)
4061
- });
4062
- /** Previews activation changes without importing modules or modifying state. */
4063
- /** Changes activation; a supplied stale preview token rejects before mutation. */
4064
- /** Reads the declared configuration without including it in catalogue broadcasts. */
4065
- const PluginGetConfigsRequest = z.object({
4066
- method: z.literal("plugin.getConfigs"),
4067
- params: boundedBatchParams({
4068
- names: batchIds(),
4069
- ...queryBudgets
4070
- }, "names")
4071
- });
4072
- /** Replaces configuration and reloads enabled plugins and their active dependants. */
4073
- const PluginSetConfigRequest = z.object({
4074
- method: z.literal("plugin.setConfig"),
4075
- params: z.object({
4076
- name: z.string().min(1),
4077
- config: z.record(z.string(), z.unknown())
4078
- })
4079
- });
4080
- const PluginListRequest = z.object({
4081
- method: z.literal("plugin.list"),
4082
- params: z.object({}).optional()
4083
- });
4084
- /** Reads the whole plugin client surface in one call: every declared method,
4085
- * every declared frame, and the address of every browser module. One call
4086
- * rather than three, because an install can land between two of them and
4087
- * leave a client holding a surface that contradicts itself. */
4088
- const PluginSurfaceRequest = z.object({
4089
- method: z.literal("plugin.surface"),
4090
- params: z.object({}).optional()
4091
- });
4092
- /** Reads framework-managed instruction sources for the current Agent address. */
4093
- const SessionInstructionsRequest = z.object({
4094
- method: z.literal("session.instructions"),
4095
- params: z.object({ sessionId: z.string() })
4096
- });
4097
- const RequestBody = z.discriminatedUnion("method", [
4098
- TelemetryIngestRequest,
4099
- TelemetryStatusRequest,
4100
- TelemetryConfigureRequest,
4101
- SessionInstructionsRequest,
4102
- PingRequest,
4103
- ConnectionInfoRequest,
4104
- StatusRequest,
4105
- GatewayShutdownRequest,
4106
- SessionListRequest,
4107
- SessionCreateRequest,
4108
- SessionWatchRequest,
4109
- SessionHistoryPageRequest,
4110
- SessionMessagePartsRequest,
4111
- SessionMessageContentsRequest,
4112
- SessionLivePageRequest,
4113
- SessionUnwatchRequest,
4114
- SessionSendRequest,
4115
- SessionForkRequest,
4116
- SessionOperationsGetRequest,
4117
- SessionAnswerRequest,
4118
- SessionWithdrawRequest,
4119
- SessionCancelRequest,
4120
- SessionSetModelRequest,
4121
- SessionSetModelParamsRequest,
4122
- SessionArchiveRequest,
4123
- SessionSetNameRequest,
4124
- SessionJoinRequest,
4125
- SessionLeaveRequest,
4126
- ConfigLimitsGetRequest,
4127
- ConfigLimitsSetRequest,
4128
- ConfigAgentListRequest,
4129
- ConfigAgentCreateRequest,
4130
- ConfigPromptSlotsRequest,
4131
- ConfigAgentUpdateRequest,
4132
- ConfigAgentSetPromptSlotRequest,
4133
- ConfigAgentPromptSlotsRequest,
4134
- ConfigAgentSetAvatarRequest,
4135
- ConfigAgentAvatarsRequest,
4136
- ConfigAgentSaveRequest,
4137
- ConfigAgentRevisionsRequest,
4138
- ConfigAgentCompareRevisionsRequest,
4139
- ConfigAgentPreviewRestoreRequest,
4140
- ConfigAgentRestoreRevisionRequest,
4141
- ConfigAgentRemoveRequest,
4142
- ConfigToolListRequest,
4143
- InboxListRequest,
4144
- InboxReadRequest,
4145
- InboxReadSessionRequest,
4146
- InboxClearRequest,
4147
- InboxClearReadRequest,
4148
- TriggerListRequest,
4149
- TriggerCreateRequest,
4150
- TriggerUpdateRequest,
4151
- TriggerSetEnabledRequest,
4152
- TriggerRemoveRequest,
4153
- TriggerRunsRequest,
4154
- ProcessListRequest,
4155
- ProcessStopRequest,
4156
- ProcessOutputRequest,
4157
- ConfigWorkspaceListRequest,
4158
- ConfigWorkspaceCreateRequest,
4159
- ConfigWorkspaceUpdateRequest,
4160
- ConfigWorkspaceSetAvatarRequest,
4161
- ConfigWorkspaceAvatarsRequest,
4162
- ConfigWorkspaceAddDirectoriesRequest,
4163
- ConfigWorkspaceRemoveDirectoriesRequest,
4164
- ConfigAccessListRequest,
4165
- ConfigAccessAddRequest,
4166
- ConfigAccessRevokeRequest,
4167
- ConfigCredentialStatusRequest,
4168
- ConfigCredentialSetRequest,
4169
- ConfigCredentialClearRequest,
4170
- StdFsListRequest,
4171
- PluginInstallBatchRequest,
4172
- PluginSetEnabledBatchPreviewRequest,
4173
- PluginSetEnabledBatchRequest,
4174
- PluginRemoveBatchPreviewRequest,
4175
- PluginRemoveBatchRequest,
4176
- PluginListRequest,
4177
- PluginGetConfigsRequest,
4178
- PluginSetConfigRequest,
4179
- PluginSurfaceRequest
4180
- ]);
4181
- /**
4182
- * A request naming a method some plugin declared while this gateway was
4183
- * running.
4184
- *
4185
- * The name is checked against the minting rule and **the parameters are not
4186
- * read at all**: their shape is the plugin's zod, validated in the gateway,
4187
- * and a second opinion here would be a second writer of someone else's
4188
- * contract.
4189
- *
4190
- * `method` is a template literal type rather than a bare `string`, and that is
4191
- * load-bearing: one `string` discriminant in this union and
4192
- * `body.method === 'session.send'` stops narrowing, which takes every `switch`
4193
- * that reads `body.params` afterwards down with it.
4194
- *
4195
- * `params` is optional because a call that takes none sends no key —
4196
- * `JSON.stringify` drops an `undefined` — and a frame this schema refuses is
4197
- * dropped in silence rather than answered. Bare `z.unknown()` would not
4198
- * serve: zod 4 treats it as a required key, which would refuse exactly the
4199
- * paramsless calls this field is meant to admit.
4200
- */
4201
- const PluginRequestBody = z.object({
4202
- method: PluginWireName,
4203
- params: z.unknown().optional()
4204
- });
4205
- /** One business request from a client. Authentication is a separate control
4206
- * frame.
4207
- *
4208
- * The body is widened one layer out rather than `RequestBody` itself: the
4209
- * core union stays a `discriminatedUnion` of names known at compile time,
4210
- * and a plugin's runtime-minted name sits beside it. */
4211
- const RequestFrame = z.object({
4212
- kind: z.literal("request"),
4213
- id: z.string(),
4214
- trace: RequestTrace.optional(),
4215
- body: z.union([RequestBody, PluginRequestBody])
4216
- });
4217
- /** Supplies the credential for one WebSocket connection. */
4218
- const AuthenticationFrame = z.object({
4219
- kind: z.literal("authentication"),
4220
- id: z.string().min(1).max(128),
4221
- token: z.string().max(256)
4222
- });
4223
- z.discriminatedUnion("kind", [RequestFrame, AuthenticationFrame]);
4224
- z.object({ authenticated: z.literal(true) });
4225
- z.enum(["auth-required", "auth-failed"]);
4226
- z.enum([
4227
- "history_conflict",
4228
- "session_busy",
4229
- "cut_unavailable",
4230
- "source_unavailable",
4231
- "file_unavailable",
4232
- "operation_conflict",
4233
- "history_preparing",
4234
- "history_unavailable",
4235
- "history_invalid",
4236
- "history_stale",
4237
- "history_cursor_invalid",
4238
- "history_worker_unavailable",
4239
- "reading_lease_invalid",
4240
- "content_unavailable",
4241
- "content_stale",
4242
- "message_unavailable",
4243
- "invalid_range"
4244
- ]);
4245
- z.enum(["configuration_write_rejected", "configuration_recovery_required"]);
4246
- /** A bounded machine-readable refusal identifier; owner business codes are not enumerated by core. */
4247
- const RequestErrorCode = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/);
4248
- /** Gateway -> client: the answer to one request, addressed by its id. */
4249
- const ResultFrame = z.object({
4250
- kind: z.literal("result"),
4251
- id: z.string(),
4252
- ok: z.boolean(),
4253
- data: z.unknown().optional(),
4254
- error: z.string().optional(),
4255
- errorCode: RequestErrorCode.optional(),
4256
- /** Recoverable reading preparation lease and suggested polling interval. */
4257
- readingDetails: z.object({
4258
- readingLeaseId: z.string().optional(),
4259
- retryAfterMs: z.number().int().positive().optional()
4260
- }).optional()
4261
- });
4262
- /** Gateway -> the connections that care: something happened. Carries no id,
4263
- * because no one asked for it. */
4264
- const EventFrame = z.object({
4265
- kind: z.literal("event"),
4266
- event: Frame
4267
- });
4268
- z.discriminatedUnion("kind", [ResultFrame, EventFrame]);
4269
- z.object({
4270
- instanceId: z.uuid(),
4271
- gatewayVersion: z.string(),
4272
- protocolVersion: z.string(),
4273
- clientCount: z.number().int(),
4274
- uptimeMs: z.number().int(),
4275
- pid: z.number().int()
4276
- });
4277
302
  //#endregion
4278
303
  //#region src/extension-catalog/projection.ts
4279
- /** Minimal historical commit identity retained with a release admission. */
4280
304
  const AcceptedSnapshotSchema = z.object({
4281
305
  repository: z.literal(CATALOG_REPOSITORY),
4282
306
  commit: GitShaSchema,
@@ -4287,7 +311,6 @@ z.object({
4287
311
  release: ReleaseSchema,
4288
312
  releaseDigest: z.string().regex(/^[0-9a-f]{64}$/)
4289
313
  }).strict();
4290
- /** Current directory source and actual host compatibility are independent of activation status. */
4291
314
  const InstalledRowSchema = z.object({
4292
315
  packageName: z.string(),
4293
316
  distribution: z.enum([
@@ -4307,7 +330,6 @@ const InstalledRowSchema = z.object({
4307
330
  }).strict(),
4308
331
  updates: z.array(ReleaseSchema)
4309
332
  }).strict();
4310
- /** Uses current directory publisher markers while retaining actual saved host requirement facts. */
4311
333
  function projectInstalled(observations, snapshot, host) {
4312
334
  return observations.map((observation) => {
4313
335
  const builtin = (observation.summary?.origin ?? observation.declared.origin) === "builtin";
@@ -4331,7 +353,6 @@ function projectInstalled(observations, snapshot, host) {
4331
353
  }
4332
354
  //#endregion
4333
355
  //#region src/extension-catalog/views.ts
4334
- /** Explicit catalog synchronization result, independent of snapshot availability. */
4335
356
  const SyncSchema = z.object({
4336
357
  state: z.enum([
4337
358
  "idle",
@@ -4343,14 +364,12 @@ const SyncSchema = z.object({
4343
364
  error: z.string().max(4096).optional(),
4344
365
  retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4345
366
  }).strict();
4346
- /** Pure cache-only list response; an empty catalog is a valid successful snapshot. */
4347
367
  const ListSchema = z.object({
4348
368
  revision: z.number().int().nonnegative(),
4349
369
  snapshot: SnapshotSchema.omit({ releases: true }).nullable(),
4350
370
  releases: z.array(ReleaseSchema).max(2e3),
4351
371
  sync: SyncSchema
4352
372
  }).strict();
4353
- /** Short invalidation carrying no configuration, credentials, or archive bytes. */
4354
373
  const CatalogChangedSchema = z.object({
4355
374
  revision: z.number().int().nonnegative(),
4356
375
  snapshot: z.object({
@@ -4359,7 +378,6 @@ const CatalogChangedSchema = z.object({
4359
378
  }).strict().optional(),
4360
379
  sync: SyncSchema
4361
380
  }).strict();
4362
- /** Confirmation response for a fixed exact extension dependency closure. */
4363
381
  const PreviewSchema = z.object({
4364
382
  previewToken: z.string().min(1).max(8192),
4365
383
  expiresAt: z.iso.datetime({ offset: true }),
@@ -4378,7 +396,6 @@ const PreviewSchema = z.object({
4378
396
  affectedOwners: z.array(z.string()).max(2e3),
4379
397
  warnings: z.array(ArtifactWarningSchema).max(64)
4380
398
  }).strict();
4381
- /** Durable installation operation facts returned by the generic owner-bound service. */
4382
399
  const OperationSchema = z.object({
4383
400
  operationId: z.uuid(),
4384
401
  attemptId: z.uuid(),
@@ -4448,7 +465,6 @@ const OperationSchema = z.object({
4448
465
  ownerWithdrawn: z.boolean().optional()
4449
466
  }).strict()).max(2e3)
4450
467
  }).strict();
4451
- /** Installation progress invalidation; clients query the durable attempt after reconnecting. */
4452
468
  const InstallChangedSchema = z.object({
4453
469
  operationId: z.uuid(),
4454
470
  phase: OperationSchema.shape.phase,
@@ -4457,12 +473,10 @@ const InstallChangedSchema = z.object({
4457
473
  cleanup: OperationSchema.shape.cleanup,
4458
474
  revision: z.number().int().nonnegative()
4459
475
  }).strict();
4460
- /** Current directory source markers and installed metadata for unique package names. */
4461
476
  const InstalledSchema = z.object({
4462
477
  observedAt: z.iso.datetime({ offset: true }),
4463
478
  rows: z.array(InstalledRowSchema).max(2e3)
4464
479
  }).strict();
4465
- /** Existing owner RPC success/failure convention; sanitized errors remain actionable. */
4466
480
  function resultSchema(data) {
4467
481
  return z.union([z.object({
4468
482
  ok: z.literal(true),
@@ -4476,7 +490,6 @@ function resultSchema(data) {
4476
490
  }
4477
491
  //#endregion
4478
492
  //#region src/extension-catalog/operations.ts
4479
- /** Nonempty operation identities with per-member and complete encoded-response byte budgets. */
4480
493
  const OperationQueriesParams = z.object({
4481
494
  operationIds: z.array(z.uuid()).min(1).max(64),
4482
495
  maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
@@ -4487,7 +500,6 @@ const OperationQueriesParams = z.object({
4487
500
  message: "declared operation response exceeds byte budget"
4488
501
  });
4489
502
  });
4490
- /** Safe operation facts in the original request order. */
4491
503
  const OperationQueriesData = z.object({ results: z.array(z.discriminatedUnion("ok", [z.object({
4492
504
  index: z.number().int().nonnegative().max(63),
4493
505
  target: z.uuid(),
@@ -4505,7 +517,6 @@ const OperationQueriesData = z.object({ results: z.array(z.discriminatedUnion("o
4505
517
  }).strict()])).min(1).max(64) }).strict();
4506
518
  //#endregion
4507
519
  //#region src/defaults/service.ts
4508
- /** Creates one shared initialization attempt scoped to this catalog owner. */
4509
520
  function createDefaultsService(options) {
4510
521
  const controller = new AbortController();
4511
522
  const signal = AbortSignal.any([options.signal, controller.signal]);
@@ -4678,7 +689,6 @@ function createDefaultsService(options) {
4678
689
  await applyOperation(record, operation);
4679
690
  }
4680
691
  return {
4681
- /** Starts one shared bounded attempt immediately; completed initialization performs no network work. */
4682
692
  async ensure(input) {
4683
693
  signal.throwIfAborted();
4684
694
  const params = DefaultsEnsureParamsSchema.parse(input);
@@ -4719,9 +729,7 @@ function createDefaultsService(options) {
4719
729
  status: await status()
4720
730
  };
4721
731
  },
4722
- /** Projects current readonly installation facts over retained history; never enrolls or installs. */
4723
732
  status,
4724
- /** Cancels this automatic attempt and joins all work before releasing the owner's resources. */
4725
733
  async dispose() {
4726
734
  controller.abort(/* @__PURE__ */ new Error("Default installation owner is draining"));
4727
735
  await active?.work;
@@ -4730,17 +738,10 @@ function createDefaultsService(options) {
4730
738
  }
4731
739
  //#endregion
4732
740
  //#region src/extension-catalog/sync.ts
4733
- /** Git smart HTTP ref advertisement for the catalog repository. */
4734
741
  const CATALOG_REFS_URL = "https://github.com/yanxuan-lc/yaoguang-presets.git/info/refs?service=git-upload-pack";
4735
- /** Raw content URL of the extension index pinned to one commit. */
4736
742
  const catalogIndexUrl = (commit) => `https://raw.githubusercontent.com/yanxuan-lc/yaoguang-presets/${commit}/extensions/index.json`;
4737
743
  const REFS_MAX_BYTES = 1048576;
4738
744
  const headers = { "User-Agent": "YaoGuang-extensions" };
4739
- /**
4740
- * Returns the commit of `refs/heads/main` from a Git smart HTTP upload-pack advertisement.
4741
- * Requires the leading service announcement and well-formed pkt-lines; any other shape,
4742
- * including a missing main branch, is rejected as an invalid catalog.
4743
- */
4744
745
  function parseMainCommit(bytes) {
4745
746
  const text = Buffer.from(bytes).toString("latin1");
4746
747
  const lines = [];
@@ -4766,12 +767,6 @@ function parseMainCommit(bytes) {
4766
767
  }
4767
768
  throw new CatalogError("CATALOG_INVALID", "Catalog repository has no main branch");
4768
769
  }
4769
- /**
4770
- * Reads a bounded response without credentials, redirects, or remote-body diagnostics.
4771
- * A failed status becomes `SYNC_FAILED`, with a retry delay (at most one day) taken from
4772
- * `retry-after`, or from `x-ratelimit-reset` for 429 and exhausted-quota 403 responses.
4773
- * A 404 throws the error built by `notFound` when it is supplied.
4774
- */
4775
770
  async function readBoundedResponse(network, url, signal, maxBytes, headers = {}, notFound) {
4776
771
  signal.throwIfAborted();
4777
772
  const response = await network.fetch(url, {
@@ -4810,11 +805,6 @@ async function readBoundedResponse(network, url, signal, maxBytes, headers = {},
4810
805
  reader.releaseLock();
4811
806
  }
4812
807
  }
4813
- /**
4814
- * Resolves the catalog's main commit with one ref advertisement request, then reads the complete
4815
- * extension index pinned to that commit. An unchanged commit reuses `previous` with a new fetch
4816
- * time. Requests carry no credentials, refuse redirects and share an 8 MiB budget and 30 s limit.
4817
- */
4818
808
  async function synchronize(network, ownerSignal, previous) {
4819
809
  const controller = new AbortController();
4820
810
  const signal = AbortSignal.any([ownerSignal, controller.signal]);
@@ -4845,7 +835,6 @@ async function synchronize(network, ownerSignal, previous) {
4845
835
  }
4846
836
  //#endregion
4847
837
  //#region src/extension-catalog/service.ts
4848
- /** Creates local catalog reads and explicit synchronization, preview, and operation management. */
4849
838
  function createCatalogService(options) {
4850
839
  let snapshot = null;
4851
840
  let sync = { state: "idle" };
@@ -4951,7 +940,6 @@ function createCatalogService(options) {
4951
940
  consumerSignal.removeEventListener("abort", onAbort);
4952
941
  }
4953
942
  }
4954
- /** Prepares exact roots and one shared extension closure without imports or activation. */
4955
943
  async function preview(inputs, enableNames = [], batch = false, attempt, automatic = false) {
4956
944
  const preparationSignal = attempt ? AbortSignal.any([signal, attempt.signal]) : signal;
4957
945
  preparationSignal.throwIfAborted();
@@ -5086,15 +1074,12 @@ function createCatalogService(options) {
5086
1074
  return defaults;
5087
1075
  }
5088
1076
  return {
5089
- /** Starts or shares this owner's one-shot bounded automatic installation task. */
5090
1077
  defaultsEnsure(input) {
5091
1078
  return requireDefaults().ensure(input);
5092
1079
  },
5093
- /** Returns passive initialization facts without refreshing or enrolling. */
5094
1080
  defaultsStatus() {
5095
1081
  return requireDefaults().status();
5096
1082
  },
5097
- /** Returns cached data only; first use and failure never trigger network work. */
5098
1083
  list() {
5099
1084
  signal.throwIfAborted();
5100
1085
  if (!snapshot) return {
@@ -5111,14 +1096,12 @@ function createCatalogService(options) {
5111
1096
  sync: { ...sync }
5112
1097
  };
5113
1098
  },
5114
- /** Joins the active fresh synchronization; manual work survives automatic attempt cancellation. */
5115
1099
  refresh() {
5116
1100
  return {
5117
1101
  taskId: sharedSynchronization(true).taskId,
5118
1102
  sync: { ...sync }
5119
1103
  };
5120
1104
  },
5121
- /** Previews installation with target enablement and joins owned preparation before disposal. */
5122
1105
  preview(input) {
5123
1106
  const task = preview([input]);
5124
1107
  ownedTasks.add(task);
@@ -5129,14 +1112,12 @@ function createCatalogService(options) {
5129
1112
  });
5130
1113
  return task;
5131
1114
  },
5132
- /** Prepares one approved union of exact roots and existing owners to enable. */
5133
1115
  previewBatch(inputs, enableNames = []) {
5134
1116
  const task = preview(inputs, enableNames, true);
5135
1117
  ownedTasks.add(task);
5136
1118
  task.then(() => ownedTasks.delete(task), () => ownedTasks.delete(task));
5137
1119
  return task;
5138
1120
  },
5139
- /** Delegates deduplication before any token or current-snapshot validation. */
5140
1121
  install(operationId, previewToken) {
5141
1122
  signal.throwIfAborted();
5142
1123
  return options.installer.install({
@@ -5144,15 +1125,12 @@ function createCatalogService(options) {
5144
1125
  token: previewToken
5145
1126
  });
5146
1127
  },
5147
- /** Reads an existing durable attempt without restarting work. */
5148
1128
  operation(operationId) {
5149
1129
  return options.installer.operation(operationId);
5150
1130
  },
5151
- /** Retries only cleanup still owned by the queried attempt. */
5152
1131
  retryCleanup(operationId) {
5153
1132
  return options.installer.retryCleanup(operationId);
5154
1133
  },
5155
- /** Projects installed metadata against the current cached directory without reading files. */
5156
1134
  async installed() {
5157
1135
  signal.throwIfAborted();
5158
1136
  const observations = await options.installer.observe();
@@ -5161,7 +1139,6 @@ function createCatalogService(options) {
5161
1139
  rows: projectInstalled(observations, snapshot, options.hostIdentity)
5162
1140
  };
5163
1141
  },
5164
- /** Joins all discovery work before owner disposal completes. */
5165
1142
  async dispose() {
5166
1143
  controller.abort(/* @__PURE__ */ new Error("Catalog owner withdrawn"));
5167
1144
  await Promise.all([defaults?.dispose(), Promise.allSettled([...ownedTasks])]);
@@ -5170,7 +1147,6 @@ function createCatalogService(options) {
5170
1147
  }
5171
1148
  //#endregion
5172
1149
  //#region src/extension-catalog/store.ts
5173
- /** Persists the last complete validated catalog snapshot in this owner's storage lease. */
5174
1150
  function createCatalogStore(storage) {
5175
1151
  const name = storage.tableName("catalog_snapshot");
5176
1152
  if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid storage table identity");
@@ -5183,7 +1159,6 @@ function createCatalogStore(storage) {
5183
1159
  return value;
5184
1160
  }
5185
1161
  return {
5186
- /** Reads validated last-success data without network activity; corruption refuses availability. */
5187
1162
  read() {
5188
1163
  const row = storage.db.prepare(`SELECT snapshot_json FROM ${table} WHERE id=1`).get();
5189
1164
  if (!row) return null;
@@ -5193,7 +1168,6 @@ function createCatalogStore(storage) {
5193
1168
  throw new CatalogError("CATALOG_INVALID", "Catalog cache is unavailable; refresh to repair it");
5194
1169
  }
5195
1170
  },
5196
- /** Atomically replaces the complete snapshot and advances its successful revision. */
5197
1171
  save(input) {
5198
1172
  const snapshot = validate(input);
5199
1173
  storage.db.exec("SAVEPOINT catalog_snapshot_commit");
@@ -5223,7 +1197,6 @@ function createCatalogStore(storage) {
5223
1197
  }
5224
1198
  //#endregion
5225
1199
  //#region src/extension-catalog/register.ts
5226
- /** Registers authenticated catalog methods and owner-lifetime invalidation frames. */
5227
1200
  function registerExtensionCatalog(ctx) {
5228
1201
  const changed = ctx.client.registerFrame({
5229
1202
  name: "extensionCatalogChanged",
@@ -5389,7 +1362,6 @@ function registerExtensionCatalog(ctx) {
5389
1362
  }
5390
1363
  //#endregion
5391
1364
  //#region src/index.ts
5392
- /** Owns extension-catalog capabilities independently from bootstrap resources. */
5393
1365
  const plugin = {
5394
1366
  name: "@eum-agent/extension-catalog",
5395
1367
  requires: [
@@ -5401,7 +1373,10 @@ const plugin = {
5401
1373
  apply(ctx) {
5402
1374
  registerExtensionCatalog(ctx);
5403
1375
  const module = fileURLToPath(new URL("../ui/ui.js", import.meta.url));
5404
- if (existsSync(module)) ctx.client.registerUi({ module });
1376
+ if (existsSync(module)) ctx.client.registerPackageFiles({
1377
+ root: dirname(module),
1378
+ entry: "ui.js"
1379
+ });
5405
1380
  }
5406
1381
  };
5407
1382
  //#endregion