@eum-agent/extension-catalog 1.1.0 → 1.2.0

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