@eum-agent/extension-catalog 1.0.1 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +2249 -1673
  2. package/package.json +6 -6
  3. package/ui/ui.js +9 -6
package/dist/index.js CHANGED
@@ -180,7 +180,6 @@ const CatalogSchema = z.object({ releases: z.array(ReleaseSchema).max(2e3) }).st
180
180
  const SnapshotSchema = z.object({
181
181
  repository: z.literal(CATALOG_REPOSITORY),
182
182
  commit: GitShaSchema,
183
- treeSha: GitShaSchema,
184
183
  contentDigest: z.string().regex(/^[0-9a-f]{64}$/),
185
184
  fetchedAt: z.iso.datetime({ offset: true }),
186
185
  revision: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
@@ -314,1234 +313,593 @@ function createDefaultsStore(storage) {
314
313
  };
315
314
  }
316
315
  //#endregion
317
- //#region src/defaults/service.ts
318
- /** Creates one shared initialization attempt scoped to this catalog owner. */
319
- function createDefaultsService(options) {
320
- const controller = new AbortController();
321
- const signal = AbortSignal.any([options.signal, controller.signal]);
322
- let active = null;
323
- function initial() {
324
- return {
325
- state: "pending-snapshot",
326
- enrolledAt: (/* @__PURE__ */ new Date()).toISOString(),
327
- candidates: []
328
- };
329
- }
330
- async function status() {
331
- const before = options.store.read() ?? initial();
332
- const observations = before.candidates.length ? await options.installer.observe(before.candidates.map((candidate) => candidate.packageName)) : [];
333
- const record = options.store.read() ?? initial();
334
- const candidates = record.candidates.map(({ artifactIntegrity: _integrity, receiptId, ...candidate }) => {
335
- const observed = observations.find((item) => item.packageName === candidate.packageName);
336
- const captured = before.candidates.find((item) => item.packageName === candidate.packageName);
337
- const matchesCapturedResult = captured?.state === "installed" && captured.receiptId === receiptId && captured.operationId === candidate.operationId && captured.releaseId === candidate.releaseId;
338
- if (candidate.state === "installed" && matchesCapturedResult && observed) {
339
- if (!observed.declared.installed || !observed.declared.enabled || receiptId && observed.receipt?.receiptId !== receiptId) {
340
- candidate.state = "user-managed";
341
- candidate.reasonCode = "USER_DECLARATION_PRESERVED";
342
- delete candidate.activation;
343
- } else {
344
- const activation = observed.activation ?? (observed.summary?.status === "active" ? "active" : observed.summary?.status === "failed" ? "failed" : void 0);
345
- if (activation) candidate.activation = activation;
346
- }
347
- }
348
- return candidate;
349
- });
350
- return DefaultsStatusSchema.parse({
351
- state: active ? "working" : record.state === "complete" ? "complete" : record.state === "pending-snapshot" ? "pending-snapshot" : "pending",
352
- taskId: active?.id ?? null,
353
- operationId: record.currentOperationId ?? null,
354
- counts: {
355
- installed: candidates.filter((c) => c.state === "installed").length,
356
- pending: candidates.filter((c) => c.state === "pending").length,
357
- skipped: candidates.filter((c) => c.state === "skipped" || c.state === "user-managed").length
358
- },
359
- activationDeferred: candidates.filter((c) => c.state === "installed" && c.activation === "deferred").length,
360
- candidates,
361
- ...record.lastReasonCode ? { reasonCode: record.lastReasonCode } : {},
362
- ...record.retryNotBefore ? { retryAfterSeconds: Math.min(86400, Math.max(0, Math.ceil((Date.parse(record.retryNotBefore) - Date.now()) / 1e3))) } : {}
363
- });
364
- }
365
- function persist(record) {
366
- if (record.snapshot) record.state = record.candidates.some((c) => c.state === "pending") ? "pending" : "complete";
367
- return options.store.save(record);
368
- }
369
- async function applyOperation(record, operation) {
370
- for (const candidate of record.candidates.filter((c) => c.operationId === operation.operationId && c.state === "pending")) {
371
- const packageResult = operation.packages.find((p) => p.packageName === candidate.packageName);
372
- const rootResult = operation.rootResults?.find((r) => r.packageName === candidate.packageName);
373
- if (packageResult?.receiptId) {
374
- candidate.state = "installed";
375
- candidate.receiptId = packageResult.receiptId;
376
- candidate.activation = rootResult?.status === "active" ? "active" : rootResult?.status === "deferred" ? "deferred" : "failed";
377
- delete candidate.reasonCode;
378
- } else if (operation.phase === "settled" && operation.outcome !== "pending") {
379
- candidate.reasonCode = "INSTALL_FAILED";
380
- record.lastReasonCode = "INSTALL_FAILED";
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;
381
348
  }
382
349
  }
383
- if (record.lastReasonCode === "INSTALL_FAILED" && !record.candidates.some((candidate) => candidate.state === "pending")) delete record.lastReasonCode;
384
- persist(record);
350
+ active.delete(one);
351
+ return true;
385
352
  }
386
- async function joinOperation(operationId) {
387
- let operation = await options.installer.join(operationId);
388
- while (operation.cleanup === "failed" || operation.cleanup === "pending") {
389
- try {
390
- operation = await options.installer.retryCleanup(operationId);
391
- } catch {
392
- await setTimeout$1(250);
393
- continue;
394
- }
395
- if (operation.cleanup === "failed" || operation.cleanup === "pending") await setTimeout$1(250);
396
- }
397
- return operation;
353
+ try {
354
+ return visit(value, 1);
355
+ } catch {
356
+ return false;
398
357
  }
399
- async function recover(record) {
400
- const operationIds = [...new Set(record.candidates.filter((c) => c.state === "pending").map((c) => c.operationId).filter((id) => !!id))];
401
- for (const id of operationIds) {
402
- let operation;
403
- try {
404
- operation = await options.installer.operation(id);
405
- } catch (error) {
406
- if (managementError(error).code !== "OPERATION_NOT_FOUND") throw error;
407
- continue;
408
- }
409
- operation = await joinOperation(id);
410
- await applyOperation(record, operation);
411
- if (operation.phase !== "settled" || operation.outcome === "pending") throw new CatalogError("RECOVERY_PENDING", "The original default installation attempt is not settled");
412
- }
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);
413
415
  }
414
- async function run(attempt) {
415
- let record = options.store.read() ?? options.store.save(initial());
416
- delete record.lastReasonCode;
417
- delete record.retryNotBefore;
418
- await recover(record);
419
- if (record.state === "complete") return;
420
- const snapshot = await options.acquireSnapshot(attempt);
421
- attempt.signal.throwIfAborted();
422
- if (!record.snapshot) {
423
- const chosen = /* @__PURE__ */ new Map();
424
- for (const release of snapshot.releases) {
425
- if (release.defaultInstall !== true || !releaseCompatible(release, options.identity)) continue;
426
- const before = chosen.get(release.packageName);
427
- if (!before || semver.gt(release.version, before.version)) chosen.set(release.packageName, release);
428
- }
429
- if (chosen.size > 64) throw new CatalogError("LIMIT_EXCEEDED", "Default extension cohort exceeds 64 roots");
430
- record = await options.installer.coordinate(() => options.store.save({
431
- ...record,
432
- state: chosen.size ? "frozen" : "complete",
433
- snapshot: {
434
- commit: snapshot.commit,
435
- contentDigest: snapshot.contentDigest
436
- },
437
- host: {
438
- version: options.identity.version,
439
- ...options.identity.target
440
- },
441
- candidates: [...chosen.values()].sort((a, b) => a.packageName < b.packageName ? -1 : a.packageName > b.packageName ? 1 : 0).map((r) => ({
442
- packageName: r.packageName,
443
- releaseId: r.releaseId,
444
- artifactIntegrity: r.artifact.integrity,
445
- state: "pending"
446
- }))
447
- }));
448
- }
449
- if (record.state === "complete") return;
450
- const observations = await options.installer.observe();
451
- for (const candidate of record.candidates.filter((c) => c.state === "pending")) if (observations.some((o) => o.packageName === candidate.packageName && o.declared.origin !== void 0)) {
452
- candidate.state = "user-managed";
453
- candidate.reasonCode = "USER_DECLARATION_PRESERVED";
454
- } else {
455
- const release = snapshot.releases.find((r) => r.releaseId === candidate.releaseId && r.artifact.integrity === candidate.artifactIntegrity);
456
- if (!release || release.defaultInstall !== true || !releaseCompatible(release, options.identity)) {
457
- candidate.state = "skipped";
458
- candidate.reasonCode = "RELEASE_REVOKED";
459
- }
460
- }
461
- persist(record);
462
- const roots = record.candidates.filter((c) => c.state === "pending");
463
- if (!roots.length) return;
464
- const plan = await options.preview(roots.map((c) => ({
465
- snapshotCommit: snapshot.commit,
466
- releaseId: c.releaseId,
467
- artifactIntegrity: c.artifactIntegrity
468
- })), attempt);
469
- attempt.signal.throwIfAborted();
470
- const operationId = randomUUID();
471
- record.currentOperationId = operationId;
472
- record.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
473
- for (const candidate of roots) candidate.operationId = operationId;
474
- persist(record);
475
- try {
476
- await options.installer.install({
477
- operationId,
478
- token: plan.previewToken
479
- }, attempt);
480
- } catch (error) {
481
- try {
482
- await options.installer.operation(operationId);
483
- } catch {
484
- throw error;
485
- }
486
- }
487
- const operation = await joinOperation(operationId);
488
- await applyOperation(record, operation);
489
- }
490
- return {
491
- /** Starts one shared bounded attempt immediately; completed initialization performs no network work. */
492
- async ensure(input) {
493
- signal.throwIfAborted();
494
- const params = DefaultsEnsureParamsSchema.parse(input);
495
- if (params.expectedProductVersion !== options.identity.version) throw new CatalogError("PRODUCT_VERSION_MISMATCH", "Default installation requires the current product version");
496
- const record = options.store.read() ?? initial();
497
- if (active) return {
498
- taskId: active.id,
499
- status: await status()
500
- };
501
- if (record.state === "complete" || record.retryNotBefore && Date.parse(record.retryNotBefore) > Date.now()) return {
502
- taskId: null,
503
- status: await status()
504
- };
505
- const id = randomUUID(), deadline = performance.now() + Math.min(18e4, params.remainingWorkMs);
506
- const timerController = new AbortController();
507
- const timer = setTimeout(() => timerController.abort(/* @__PURE__ */ new Error("Default installation work budget exhausted")), Math.max(1, deadline - performance.now()));
508
- const attempt = {
509
- signal: AbortSignal.any([signal, timerController.signal]),
510
- remainingWorkMs: () => Math.max(0, deadline - performance.now())
511
- };
512
- const work = Promise.resolve().then(() => run(attempt)).catch((error) => {
513
- const record = options.store.read() ?? initial(), failure = managementError(error);
514
- record.lastReasonCode = attempt.signal.aborted ? "ATTEMPT_CANCELLED" : failure.code;
515
- for (const candidate of record.candidates.filter((c) => c.state === "pending")) candidate.reasonCode = record.lastReasonCode;
516
- if (failure.retryAfterSeconds !== void 0) record.retryNotBefore = new Date(Date.now() + failure.retryAfterSeconds * 1e3).toISOString();
517
- persist(record);
518
- }).finally(() => {
519
- clearTimeout(timer);
520
- active = null;
521
- });
522
- work.catch(() => {});
523
- active = {
524
- id,
525
- work
526
- };
527
- return {
528
- taskId: id,
529
- status: await status()
530
- };
531
- },
532
- /** Projects current readonly installation facts over retained history; never enrolls or installs. */
533
- status,
534
- /** Cancels this automatic attempt and joins all work before releasing the owner's resources. */
535
- async dispose() {
536
- controller.abort(/* @__PURE__ */ new Error("Default installation owner is draining"));
537
- await active?.work;
538
- }
539
- };
416
+ return value;
540
417
  }
541
418
  //#endregion
542
- //#region src/extension-catalog/projection.ts
543
- /** Minimal historical commit identity retained with a release admission. */
544
- const AcceptedSnapshotSchema = z.object({
545
- repository: z.literal(CATALOG_REPOSITORY),
546
- commit: GitShaSchema,
547
- treeSha: GitShaSchema,
548
- contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
419
+ //#region ../../core/kernel/src/vocab/owner-context.ts
420
+ /** One host-stamped owner fact frozen for a model decision and its derived operations. */
421
+ const OwnerContextEntrySchema = z.strictObject({
422
+ /** Host-bound capability identity; never supplied by model output. */
423
+ owner: z.string().min(1).max(256),
424
+ /** Local state name, unique within this owner. */
425
+ key: z.string().min(1).max(256),
426
+ /** Physical revision of the state selected for this decision. */
427
+ revision: z.number().int().nonnegative().safe(),
428
+ /** Lossless JSON interpreted only by the owning capability. */
429
+ data: z.custom(isLosslessJson)
430
+ });
431
+ /** Bounded immutable provenance, unique by owner and local key. */
432
+ const OwnerContextSchema = z.array(OwnerContextEntrySchema).max(16).superRefine((entries, ctx) => {
433
+ const keys = /* @__PURE__ */ new Set();
434
+ for (const entry of entries) {
435
+ const key = JSON.stringify([entry.owner, entry.key]);
436
+ if (keys.has(key)) ctx.addIssue({
437
+ code: "custom",
438
+ message: "Duplicate owner context key"
439
+ });
440
+ keys.add(key);
441
+ }
442
+ if (new TextEncoder().encode(JSON.stringify(entries)).byteLength > 262144) ctx.addIssue({
443
+ code: "custom",
444
+ message: "Owner context exceeds 256 KiB"
445
+ });
446
+ }).transform((entries) => freezeWidget(JSON.parse(JSON.stringify(entries))));
447
+ //#endregion
448
+ //#region ../../core/kernel/src/vocab/message.ts
449
+ /**
450
+ * The transcript's message shapes: the authoritative history that assembly
451
+ * reads. A message is either a plain user/assistant turn of text, an
452
+ * assistant reply that also requests tool calls, or a tool-results message
453
+ * that answers a batch of those calls. Zod schemas are the source of
454
+ * truth; the types are `z.infer`red from them so this vocabulary survives
455
+ * the event log round trip once `packages/core/store-sqlite` serializes it.
456
+ *
457
+ * Tool results are carried in a `role: 'user'` message with `tool-result`
458
+ * content parts. Protocol implementations translate this neutral transcript
459
+ * into their own request representation.
460
+ */
461
+ const MessageRoleSchema = z.enum(["user", "assistant"]);
462
+ const TextPartSchema = z.object({
463
+ type: z.literal("text"),
464
+ text: z.string()
465
+ });
466
+ /** The model's thinking, attached to the same assistant message its reply
467
+ * text is. Symmetric with `TextPart` on purpose — it is the recorded
468
+ * counterpart of the publish-only `thinking-delta` chunk, carried the
469
+ * same way `TextPart` carries the recorded counterpart of `text-delta`.
470
+ * Accumulating deltas into this shape, and deciding whether to send it
471
+ * back on the next call, is the adapter's job — this package only
472
+ * carries it. */
473
+ const ThinkingPartSchema = z.object({
474
+ type: z.literal("thinking"),
475
+ text: z.string(),
476
+ /** An opaque token the provider issued with this block and requires back
477
+ * **unmodified** on any later turn that continues the same conversation.
478
+ * A fabricated or edited value can invalidate replay. Absent for protocols
479
+ * that issue no signature. The kernel never reads it; it only
480
+ * carries it, so that the adapter that produced it can hand it back. */
481
+ signature: z.string().optional(),
482
+ /**
483
+ * Which endpoint issued that signature.
484
+ *
485
+ * A signature is only worth anything to whoever signed it, and the product
486
+ * cannot tell whether two endpoints are the same signer — two keys against
487
+ * one vendor, or a proxy in front of it, look identical from here. So this
488
+ * is compared as an endpoint id and the comparison is a deliberate
489
+ * over-approximation: an adapter drops a block another endpoint signed,
490
+ * which between two endpoints of one vendor costs a block that would have
491
+ * replayed. The other way round costs a rejected request.
492
+ *
493
+ * Absent wherever `signature` is: nothing to attribute. The kernel never
494
+ * reads either; it carries them so the adapter that made the block can
495
+ * decide.
496
+ */
497
+ issuer: z.string().optional(),
498
+ /** Model identifier that produced this signed thinking block. */
499
+ originModel: z.string().optional(),
500
+ /**
501
+ * Stable compatibility fingerprint for the non-thinking prefix covered by
502
+ * the provider signature. Adapters omit a signed block when it does not match
503
+ * the request prefix they are about to send.
504
+ */
505
+ prefix: z.string().optional(),
506
+ /**
507
+ * Original output-token count used as a conservative upper bound when the
508
+ * provider retains more thinking state than the visible text represents.
509
+ */
510
+ outputTokens: z.number().int().nonnegative().optional(),
511
+ /**
512
+ * Set on a block the provider returned with no readable text — a protocol's
513
+ * `redacted_thinking`. `text` is then empty and `signature` holds the
514
+ * provider's opaque `data`, which goes back unmodified in the same place.
515
+ */
516
+ redacted: z.literal(true).optional()
517
+ });
518
+ /** A tool call the model requested. `input` is whatever JSON-serializable
519
+ * arguments the model produced for it — the kernel does not validate a
520
+ * tool's own argument shape, only that the call itself round-trips. */
521
+ const ToolUsePartSchema = z.object({
522
+ type: z.literal("tool-use"),
523
+ id: z.string(),
524
+ name: z.string(),
525
+ input: z.unknown(),
526
+ /** Host-projected execution identity; never changes the model's original call. */
527
+ execution: z.object({
528
+ name: z.string(),
529
+ input: z.unknown(),
530
+ definitionFingerprint: z.string()
531
+ }).optional()
532
+ });
533
+ const Sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
534
+ /** The copy of a file a model is sent, when it differs from the original:
535
+ * a content-addressed variant within every built-in provider type's limits. */
536
+ const FileVariantSchema = z.object({
537
+ id: Sha256Schema,
538
+ mediaType: z.string().min(1),
539
+ size: z.number().int().positive(),
540
+ width: z.number().int().positive().optional(),
541
+ height: z.number().int().positive().optional()
549
542
  }).strict();
550
- z.object({
551
- snapshot: AcceptedSnapshotSchema,
552
- release: ReleaseSchema,
553
- releaseDigest: z.string().regex(/^[0-9a-f]{64}$/)
543
+ /**
544
+ * A reference to a content-addressed file of the session's workspace. Only
545
+ * metadata: the bytes live on disk under the workspace's `files/` directory
546
+ * and reach a request through `ModelRequest.files` alone, so an event, a
547
+ * frame or a snapshot never carries them. `name` belongs to the reference,
548
+ * not to the file: the same bytes may be named differently in two messages.
549
+ */
550
+ const FileRefSchema = z.object({
551
+ /** The original's sha256, lower-case hex. */
552
+ id: Sha256Schema,
553
+ mediaType: z.string().min(1),
554
+ name: z.string().min(1).max(200),
555
+ size: z.number().int().positive(),
556
+ /** Present for an image. */
557
+ width: z.number().int().positive().optional(),
558
+ height: z.number().int().positive().optional(),
559
+ /** The variant a model receives; absent when the original is within limits. */
560
+ forModel: FileVariantSchema.optional()
554
561
  }).strict();
555
- /** Current directory source and actual host compatibility are independent of activation status. */
556
- const InstalledRowSchema = z.object({
557
- packageName: z.string(),
558
- distribution: z.enum([
559
- "builtin",
560
- "verified",
561
- "custom"
562
+ /** A file inside a message, at the place it was written: text and file parts
563
+ * interleave in the order a person composed them. */
564
+ const FilePartSchema = z.object({
565
+ type: z.literal("file"),
566
+ file: FileRefSchema
567
+ });
568
+ /** The host stamps the producing activation before persisting a block. */
569
+ const SavedRequiredContextBlockSchema = z.object({
570
+ id: z.string().min(1),
571
+ scope: z.string().min(1),
572
+ version: z.string().min(1),
573
+ text: z.string()
574
+ }).extend({ stampedSource: z.string().min(1) });
575
+ /** Pure delivery facts; live reservation objects never enter the event log. */
576
+ const ToolResultDeliverySchema = z.strictObject({
577
+ kind: z.enum([
578
+ "receipt",
579
+ "preview",
580
+ "exact-page"
562
581
  ]),
563
- publisherKind: z.enum(["official", "third-party"]).optional(),
564
- compatibility: z.object({
565
- state: z.enum([
566
- "compatible",
567
- "incompatible",
568
- "unknown"
569
- ]),
570
- reasons: z.array(z.string()),
571
- assessedAt: z.string()
572
- }).strict(),
573
- updates: z.array(ReleaseSchema)
582
+ outputTokens: z.number().int().nonnegative(),
583
+ sourceComplete: z.boolean().optional(),
584
+ /** Host-bound accepted reply identity; receipt text is not its original source. */
585
+ answerRequestId: z.string().min(1).optional(),
586
+ execution: z.enum([
587
+ "not-started",
588
+ "committed",
589
+ "partial",
590
+ "unknown"
591
+ ]).optional()
592
+ });
593
+ /** The answer to one tool call, matched back to it by `toolUseId`. */
594
+ const ToolResultPartSchema = z.object({
595
+ /** Immutable host provenance for the decision that admitted this result. */
596
+ ownerContext: OwnerContextSchema.optional(),
597
+ type: z.literal("tool-result"),
598
+ toolUseId: z.string(),
599
+ requiredContext: z.array(SavedRequiredContextBlockSchema).optional(),
600
+ /** Immutable host-accepted snapshots. */
601
+ widgets: z.array(WidgetInstanceSchema).max(8).optional(),
602
+ /** Fixed admission diagnostics. */
603
+ widgetIssues: z.array(WidgetIssueSchema).max(8).optional(),
604
+ content: z.string(),
605
+ isError: z.boolean().optional(),
606
+ /** Requested preview body tokens; invalid hints are ignored by the host. */
607
+ previewTokens: z.number().optional(),
608
+ /** Host-admitted delivery metadata; exact pages cannot be silently shortened. */
609
+ delivery: ToolResultDeliverySchema.optional(),
610
+ /** Files the call handed back, after its text. */
611
+ files: z.array(FileRefSchema).optional()
612
+ });
613
+ const ContentPartSchema = z.discriminatedUnion("type", [
614
+ TextPartSchema,
615
+ ThinkingPartSchema,
616
+ ToolUsePartSchema,
617
+ ToolResultPartSchema,
618
+ FilePartSchema
619
+ ]);
620
+ /**
621
+ * One volatile contributor's text as a request carried it: the contributor's
622
+ * `id` and the strings it gave, joined by a blank line. A request appends a
623
+ * note only when it differs from that contributor's last note in the history,
624
+ * or at a turn's first step under the default policy. An on-change contributor
625
+ * compares values across turn boundaries. The note stays in every later request at the
626
+ * place it was first sent.
627
+ */
628
+ const VolatileNoteSchema = z.object({
629
+ id: z.string(),
630
+ text: z.string()
574
631
  }).strict();
575
- /** Uses current directory publisher markers while retaining actual saved host requirement facts. */
576
- function projectInstalled(observations, snapshot, host) {
577
- return observations.map((observation) => {
578
- const builtin = (observation.summary?.origin ?? observation.declared.origin) === "builtin";
579
- const listed = snapshot?.releases.filter((release) => release.packageName === observation.packageName).sort((a, b) => semver.rcompare(a.version, b.version))[0];
580
- const currentVersion = observation.summary?.version ?? observation.declared.version ?? observation.receipt?.version ?? "";
581
- const requirements = observation.hostRequirements;
582
- const compatibility = {
583
- state: requirements.state === "satisfied" ? "compatible" : requirements.state === "unsatisfied" ? "incompatible" : "unknown",
584
- reasons: [...requirements.reasons],
585
- assessedAt: requirements.checkedAt
586
- };
587
- const updates = !builtin && host && semver.valid(currentVersion) ? (snapshot?.releases ?? []).filter((release) => release.packageName === observation.packageName && semver.gt(release.version, currentVersion) && releaseCompatible(release, host)).sort((a, b) => semver.rcompare(a.version, b.version)) : [];
588
- return {
589
- packageName: observation.packageName,
590
- distribution: builtin ? "builtin" : listed ? "verified" : "custom",
591
- ...!builtin && listed ? { publisherKind: listed.publisher.kind } : {},
592
- compatibility,
593
- updates
594
- };
595
- });
596
- }
632
+ /**
633
+ * Where a person's message came in, when it came in through a channel that
634
+ * names itself: the channel's id and display label, and the speaker the
635
+ * channel reported. Written by the gateway's access layer alone; a message
636
+ * typed in the product's own client carries none.
637
+ */
638
+ const MessageViaSchema = z.object({
639
+ channel: z.string().min(1),
640
+ label: z.string().min(1),
641
+ /** Who spoke, as the channel identifies them. `role` is whether they were
642
+ * the owner when they sent it; a later change of owner leaves it. */
643
+ sender: z.object({
644
+ id: z.string().min(1),
645
+ name: z.string().min(1).max(64),
646
+ role: z.enum(["owner", "member"])
647
+ }).strict().optional()
648
+ }).strict();
649
+ /** Protocol-declared termination, independent of token usage. */
650
+ const FinishReasonSchema = z.enum([
651
+ "stop",
652
+ "tool-calls",
653
+ "max-tokens",
654
+ "refusal"
655
+ ]);
656
+ /** Discarded partial calls contain identities only, never executable arguments. */
657
+ const OutputTruncationSchema = z.object({
658
+ incompleteToolCalls: z.array(z.object({
659
+ id: z.string(),
660
+ name: z.string().optional()
661
+ })),
662
+ incompleteThinking: z.literal(true).optional()
663
+ });
664
+ const MessageSchema = z.object({
665
+ finishReason: FinishReasonSchema.optional(),
666
+ outputTruncation: OutputTruncationSchema.optional(),
667
+ outputContinuation: z.object({
668
+ replyId: z.string().uuid(),
669
+ attempt: z.number().int().min(1).max(3)
670
+ }).optional(),
671
+ /** Immutable owner provenance, excluded from all model communication. */
672
+ ownerContext: OwnerContextSchema.optional(),
673
+ /** UUID assigned when the message first forms and retained by every fork. */
674
+ id: z.string().uuid(),
675
+ role: MessageRoleSchema,
676
+ content: z.array(ContentPartSchema),
677
+ /** Present only on a message the model refused to complete — the
678
+ * provider's own category for why.
679
+ *
680
+ * It lives **on the message** rather than only on the `message-appended`
681
+ * event that records it, and that distinction is the whole point: `fold`
682
+ * rebuilds the transcript out of `event.message`, so a marker carried only
683
+ * by the event survives the log and is lost the moment anybody folds it
684
+ * back. The transcript needs to remember that a reply was a refusal,
685
+ * which means the message has to. Contrast `backfilled`, which stays on
686
+ * the event because it describes how that event came to be rather than
687
+ * anything about the message. */
688
+ refusalCategory: z.string().optional(),
689
+ /** Present on a message a composer command produced: what the person
690
+ * wrote, and the source that expanded it. `content` holds the expansion,
691
+ * which is what the model is sent; the transcript shows `text`. */
692
+ invocation: z.object({
693
+ text: z.string(),
694
+ namespace: z.string()
695
+ }).strict().optional(),
696
+ /** What a person attached, one entry per leading text block of `content`,
697
+ * which holds each attachment's original text. The model-facing envelope is
698
+ * added where a request is assembled and is never stored. */
699
+ attachments: z.array(z.object({
700
+ namespace: z.string(),
701
+ group: z.string().optional(),
702
+ label: z.string()
703
+ }).strict()).optional(),
704
+ /** Present only on a model reply: the pair that produced it, stamped by the
705
+ * host on the final chunk. On the message rather than the event for the
706
+ * reason `refusalCategory` is: `fold` rebuilds the transcript from
707
+ * `event.message`, and the latest reply's pair is what names the model a
708
+ * compaction after a switch summarizes on. */
709
+ model: z.object({
710
+ providerId: z.string(),
711
+ model: z.string()
712
+ }).strict().optional(),
713
+ /** Present only on a model reply: the volatile notes the request that
714
+ * produced it appended. Adapters render them just before this message, so
715
+ * every later request repeats the earlier one byte for byte. Clients do not
716
+ * draw them. */
717
+ volatile: z.array(VolatileNoteSchema).optional(),
718
+ /** Present only on a person's message that arrived through a labelled
719
+ * channel. Adapters never see it: the request a model receives carries a
720
+ * speaker line instead, added where the request is assembled. */
721
+ via: MessageViaSchema.optional(),
722
+ /** Durable host attribution, preserved in the transcript when the log is replayed. */
723
+ source: z.object({
724
+ kind: z.enum([
725
+ "delegation-result",
726
+ "delegation-task",
727
+ "notice",
728
+ "trigger",
729
+ "trigger-data"
730
+ ]),
731
+ owner: z.string(),
732
+ taskId: z.string(),
733
+ deliveryId: z.string().optional(),
734
+ /** The trigger definition a `trigger` or `trigger-data` delivery ran for. */
735
+ triggerId: z.string().optional(),
736
+ /** What a person calls the source: a scheduled task's name. */
737
+ label: z.string().optional()
738
+ }).strict().optional()
739
+ });
597
740
  //#endregion
598
- //#region src/extension-catalog/sync.ts
599
- const api = "https://api.github.com/repos/yanxuan-lc/yaoguang-presets";
600
- const commitSchema = z.object({
601
- sha: GitShaSchema,
602
- commit: z.object({ tree: z.object({ sha: GitShaSchema }) })
603
- });
604
- const treeSchema = z.object({
605
- sha: GitShaSchema,
606
- truncated: z.literal(false),
607
- tree: z.array(z.object({
608
- path: z.string().max(4096),
609
- mode: z.string(),
610
- type: z.string(),
611
- sha: GitShaSchema
612
- })).max(2e4)
613
- });
614
- const blobSha = (bytes) => createHash("sha1").update(`blob ${bytes.length}\0`).update(bytes).digest("hex");
615
- /** Reads a bounded response without credentials, redirects, or remote-body diagnostics. */
616
- async function readBoundedResponse(network, url, signal, maxBytes, headers = {}) {
617
- signal.throwIfAborted();
618
- const response = await network.fetch(url, {
619
- signal,
620
- redirect: "error",
621
- headers
622
- });
623
- if (!response.ok) {
624
- await response.body?.cancel().catch(() => {});
625
- const retry = Number(response.headers.get("retry-after"));
626
- throw new CatalogError("SYNC_FAILED", `Request failed (HTTP ${response.status})`, Number.isFinite(retry) && retry > 0 ? Math.min(86400, retry) : void 0);
627
- }
628
- if (Number(response.headers.get("content-length")) > maxBytes) {
629
- await response.body?.cancel().catch(() => {});
630
- throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
631
- }
632
- const reader = response.body?.getReader();
633
- if (!reader) return /* @__PURE__ */ new Uint8Array();
634
- const chunks = [];
635
- let size = 0;
636
- try {
637
- for (;;) {
638
- signal.throwIfAborted();
639
- const chunk = await reader.read();
640
- if (chunk.done) break;
641
- size += chunk.value.length;
642
- if (size > maxBytes) throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
643
- chunks.push(chunk.value);
644
- }
645
- signal.throwIfAborted();
646
- return Buffer.concat(chunks, size);
647
- } finally {
648
- await reader.cancel().catch(() => {});
649
- reader.releaseLock();
650
- }
651
- }
652
- /** Fetches and verifies a whole index and all release files pinned to one Git tree. */
653
- async function synchronize(network, ownerSignal, previous) {
654
- const controller = new AbortController();
655
- const signal = AbortSignal.any([ownerSignal, controller.signal]);
656
- const timer = setTimeout(() => controller.abort(new CatalogError("SYNC_FAILED", "Catalog synchronization exceeded 30 seconds")), 3e4);
657
- let remaining = CATALOG_MAX_BYTES;
658
- async function read(path, raw = false) {
659
- const bytes = await readBoundedResponse(network, `${api}/${path}`, signal, remaining, {
660
- Accept: raw ? "application/vnd.github.raw+json" : "application/vnd.github+json",
661
- "X-GitHub-Api-Version": "2026-03-10",
662
- "User-Agent": "YaoGuang-extensions"
663
- });
664
- remaining -= bytes.length;
665
- if (remaining < 0) throw new CatalogError("LIMIT_EXCEEDED", "Whole catalog exceeds 8 MiB");
666
- return bytes;
667
- }
668
- try {
669
- const commit = commitSchema.parse(parseJson(decodeUtf8(await read("commits/main"))));
670
- if (previous?.commit === commit.sha && previous.treeSha === commit.commit.tree.sha) return {
671
- ...previous,
672
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
673
- };
674
- const tree = treeSchema.parse(parseJson(decodeUtf8(await read(`git/trees/${commit.commit.tree.sha}?recursive=1`))));
675
- if (tree.sha !== commit.commit.tree.sha) throw new CatalogError("CATALOG_INVALID", "Commit tree mismatch");
676
- const paths = /* @__PURE__ */ new Set();
677
- for (const item of tree.tree) {
678
- if (paths.has(item.path)) throw new CatalogError("CATALOG_INVALID", "Duplicate tree path");
679
- paths.add(item.path);
680
- if (item.path === "extensions" || item.path.startsWith("extensions/")) {
681
- if (item.path.split("/").some((p) => !p || p === "." || p === "..") || item.path.includes("\\") || !(item.mode === "100644" && item.type === "blob" || item.mode === "040000" && item.type === "tree")) throw new CatalogError("CATALOG_INVALID", "Catalog contains unsafe tree entry");
682
- }
683
- }
684
- const index = tree.tree.find((item) => item.path === "extensions/index.json");
685
- if (!index || index.mode !== "100644") throw new CatalogError("CATALOG_UNAVAILABLE", "No extension index is available");
686
- const bytes = await read(`git/blobs/${index.sha}`, true);
687
- if (blobSha(bytes) !== index.sha) throw new CatalogError("CATALOG_INVALID", "Index Git blob digest mismatch");
688
- const releases = decodeReleases(parseJson(decodeUtf8(bytes)));
689
- const files = tree.tree.filter((item) => item.type === "blob" && item.path.startsWith("extensions/releases/"));
690
- if (files.length !== releases.length || files.some((item) => !/^extensions\/releases\/[^/]+\.json$/.test(item.path))) throw new CatalogError("CATALOG_INVALID", "Release file coverage mismatch");
691
- let next = 0;
692
- const records = /* @__PURE__ */ new Map();
693
- const failed = (await Promise.allSettled(Array.from({ length: Math.min(4, files.length) }, async () => {
694
- try {
695
- for (;;) {
696
- const item = files[next++];
697
- if (!item) return;
698
- const content = await read(`git/blobs/${item.sha}`, true);
699
- if (blobSha(content) !== item.sha) throw new CatalogError("CATALOG_INVALID", "Release Git blob digest mismatch");
700
- const release = ReleaseSchema.parse(parseJson(decodeUtf8(content)));
701
- if (records.has(release.releaseId)) throw new CatalogError("CATALOG_INVALID", "Duplicate release file");
702
- records.set(release.releaseId, recordDigest(release));
703
- }
704
- } catch (error) {
705
- controller.abort(error);
706
- throw error;
707
- }
708
- }))).find((result) => result.status === "rejected");
709
- if (failed?.status === "rejected") throw failed.reason;
710
- if (releases.some((release) => records.get(release.releaseId) !== recordDigest(release))) throw new CatalogError("CATALOG_INVALID", "Index and release contents differ");
711
- return {
712
- repository: CATALOG_REPOSITORY,
713
- commit: commit.sha,
714
- treeSha: tree.sha,
715
- contentDigest: recordDigest({ releases }),
716
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
717
- revision: previous?.revision ?? 0,
718
- releases
719
- };
720
- } catch (error) {
721
- controller.abort(error);
722
- if (error instanceof CatalogError) throw error;
723
- if (ownerSignal.aborted) throw ownerSignal.reason;
724
- throw new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful snapshot is retained");
725
- } finally {
726
- clearTimeout(timer);
727
- }
728
- }
741
+ //#region ../../core/kernel/src/vocab/human.ts
742
+ /**
743
+ * The vocabulary of asking a person.
744
+ *
745
+ * A tool that needs a human decision does not block: it answers a call
746
+ * with `{ awaitHuman: HumanRequestInput }` instead of content, the kernel records
747
+ * the batch's other results together with the request, and once the
748
+ * person has answered, **the same call is executed again** with the reply
749
+ * on its context. So a request is addressed by the id of the tool call
750
+ * that raised it, and the text a person reads lives on events and on the
751
+ * `fold` projection — never on `ControlState`, which carries only the id
752
+ * (invariant: control flow does not read message content).
753
+ *
754
+ * `kind` decides presentation only: a `question` is the model asking, an
755
+ * `approval` is an action asking to be allowed. An approval has exactly one
756
+ * question whose options are the outcomes the requester accepts.
757
+ *
758
+ * Zod schemas are the source of truth; the types are inferred from them so
759
+ * the shapes survive the event log round trip.
760
+ */
761
+ const HumanOptionSchema = z.object({
762
+ id: z.string().min(1),
763
+ label: z.string().min(1),
764
+ description: z.string().optional()
765
+ });
766
+ /** One thing to answer. With `options`, an answer picks by id — one option,
767
+ * or several when `multiple` is set — and may add text; with `freeText`, an
768
+ * answer may skip the options and give text alone; with no options at all,
769
+ * text is the only answer there is. */
770
+ const HumanQuestionSchema = z.object({
771
+ id: z.string().min(1),
772
+ text: z.string().min(1),
773
+ options: z.array(HumanOptionSchema),
774
+ freeText: z.boolean(),
775
+ /** Several options may be chosen; absent means one. */
776
+ multiple: z.boolean().optional()
777
+ });
778
+ const HumanRequestKindSchema = z.enum(["question", "approval"]);
779
+ /** One thing an approval would open: a path to read or write, or a host to
780
+ * reach. It sits beside the one-line `subject` in `questions[0].text`,
781
+ * which consumers that draw no list keep reading. */
782
+ const HumanTargetSchema = z.object({
783
+ access: z.enum([
784
+ "read",
785
+ "write",
786
+ "network",
787
+ "connect",
788
+ "listen",
789
+ "execute"
790
+ ]),
791
+ target: z.string().min(1)
792
+ });
793
+ /** A request as it is recorded and shown: the ask plus who raised it. */
794
+ const HumanRequestSchema = z.object({
795
+ kind: HumanRequestKindSchema,
796
+ /** Why the requester is asking — an approval's justification. */
797
+ reason: z.string().optional(),
798
+ questions: z.array(HumanQuestionSchema).min(1),
799
+ /** An approval's structured objects, in the order the requester lists them. */
800
+ targets: z.array(HumanTargetSchema).optional(),
801
+ /** A consequence the host states apart from `reason`, drawn above the
802
+ * buttons: what a lasting answer opens. */
803
+ warning: z.string().optional()
804
+ }).extend({
805
+ /** The id of the tool call that raised it — one request per call. */
806
+ requestId: z.string().min(1),
807
+ /** The tool that raised it: the requester a person is told about. */
808
+ toolName: z.string().min(1)
809
+ });
810
+ const HumanAnswerSchema = z.object({
811
+ questionId: z.string().min(1),
812
+ /** The chosen options: at most one on a single-choice question. Absent
813
+ * when none is chosen — never empty. */
814
+ optionIds: z.array(z.string().min(1)).min(1).optional(),
815
+ text: z.string().optional()
816
+ });
817
+ /** One person's answer to one request, covering every question in it. */
818
+ const HumanReplySchema = z.object({
819
+ requestId: z.string().min(1),
820
+ answers: z.array(HumanAnswerSchema)
821
+ });
822
+ z.object({
823
+ settled: z.array(ToolResultPartSchema),
824
+ requests: z.array(HumanRequestSchema),
825
+ replies: z.array(HumanReplySchema),
826
+ suspendedCalls: z.array(ToolUsePartSchema)
827
+ });
729
828
  //#endregion
730
- //#region src/extension-catalog/service.ts
731
- /** Creates local catalog reads and explicit synchronization, preview, and operation management. */
732
- function createCatalogService(options) {
733
- let snapshot = null;
734
- let sync = { state: "idle" };
735
- try {
736
- snapshot = options.store.read();
737
- } catch {
738
- sync = {
739
- state: "failed",
740
- error: "Catalog cache is damaged; refresh to repair it"
741
- };
742
- }
743
- const controller = new AbortController();
744
- const signal = AbortSignal.any([options.signal, controller.signal]);
745
- const ownedTasks = /* @__PURE__ */ new Set();
746
- let synchronization = null;
747
- function notifySynchronization() {
748
- if (!signal.aborted) options.notify?.({
749
- revision: snapshot?.revision ?? 0,
750
- ...snapshot ? { snapshot: {
751
- commit: snapshot.commit,
752
- contentDigest: snapshot.contentDigest
753
- } } : {},
754
- sync: { ...sync }
755
- });
756
- }
757
- function sharedSynchronization(manual = false) {
758
- signal.throwIfAborted();
759
- if (synchronization) {
760
- if (manual) synchronization.manual = true;
761
- return synchronization;
762
- }
763
- const taskId = randomUUID(), taskController = new AbortController(), taskSignal = AbortSignal.any([signal, taskController.signal]);
764
- sync = {
765
- state: "syncing",
766
- taskId
767
- };
768
- const work = Promise.resolve().then(async () => {
769
- try {
770
- const acquired = await synchronize(options.network, taskSignal, snapshot);
771
- const saved = await options.installer.coordinate(() => {
772
- taskSignal.throwIfAborted();
773
- snapshot = options.store.save(acquired);
774
- return snapshot;
775
- });
776
- sync = {
777
- state: "succeeded",
778
- taskId
779
- };
780
- return saved;
781
- } catch (error) {
782
- const failure = error instanceof CatalogError ? error : new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful data is retained");
783
- sync = {
784
- state: "failed",
785
- taskId,
786
- error: failure.message,
787
- ...failure.retryAfterSeconds === void 0 ? {} : { retryAfterSeconds: failure.retryAfterSeconds }
788
- };
789
- throw failure;
790
- } finally {
791
- synchronization = null;
792
- notifySynchronization();
793
- }
794
- });
795
- synchronization = {
796
- taskId,
797
- controller: taskController,
798
- manual,
799
- consumers: /* @__PURE__ */ new Set(),
800
- work
801
- };
802
- ownedTasks.add(work);
803
- work.then(() => ownedTasks.delete(work), () => ownedTasks.delete(work));
804
- notifySynchronization();
805
- return synchronization;
806
- }
807
- async function acquireFreshSnapshot(attempt) {
808
- const consumerSignal = AbortSignal.any([signal, attempt.signal]);
809
- consumerSignal.throwIfAborted();
810
- const task = sharedSynchronization(), consumer = Symbol();
811
- task.consumers.add(consumer);
812
- let onAbort;
813
- const cancelled = new Promise((_resolve, reject) => {
814
- onAbort = () => {
815
- task.consumers.delete(consumer);
816
- if (!task.manual && !task.consumers.size) task.controller.abort(consumerSignal.reason);
817
- reject(consumerSignal.reason);
818
- };
819
- consumerSignal.addEventListener("abort", onAbort, { once: true });
820
- if (consumerSignal.aborted) onAbort();
821
- });
822
- try {
823
- const acquired = await Promise.race([task.work, cancelled]);
824
- consumerSignal.throwIfAborted();
825
- return acquired;
826
- } catch (error) {
827
- if (consumerSignal.aborted && !task.manual && !task.consumers.size) {
828
- task.controller.abort(consumerSignal.reason);
829
- await Promise.allSettled([task.work]);
830
- }
831
- throw error;
832
- } finally {
833
- task.consumers.delete(consumer);
834
- consumerSignal.removeEventListener("abort", onAbort);
835
- }
836
- }
837
- /** Prepares exact roots and one shared extension closure without imports or activation. */
838
- async function preview(inputs, enableNames = [], batch = false, attempt, automatic = false) {
839
- const preparationSignal = attempt ? AbortSignal.any([signal, attempt.signal]) : signal;
840
- preparationSignal.throwIfAborted();
841
- const selections = inputs.map((input) => SelectionSchema.parse(input)), selectedSnapshot = snapshot;
842
- if (!selections.length || selections.length > 64 || enableNames.length > 2e3) throw new CatalogError("LIMIT_EXCEEDED", "Select between one and 64 exact extension roots");
843
- if (!selectedSnapshot) throw new CatalogError("CATALOG_UNAVAILABLE", "Refresh the extension catalog before selecting a release");
844
- const accepted = structuredClone(selectedSnapshot);
845
- const selectedHost = options.hostIdentity;
846
- if (!selectedHost) throw new CatalogError("RELEASE_INCOMPATIBLE", "Current product and host target are unavailable");
847
- const host = selectedHost;
848
- const observations = await options.installer.observe();
849
- const roots = [];
850
- for (const selection of selections) {
851
- if (selection.snapshotCommit !== accepted.commit) throw new CatalogError("STALE_PREVIEW", "Selected catalog commit is no longer current");
852
- const release = accepted.releases.find((r) => r.releaseId === selection.releaseId);
853
- if (!release || release.artifact.integrity !== selection.artifactIntegrity) throw new CatalogError("RELEASE_UNLISTED", "Selected exact release is not listed");
854
- if (!releaseCompatible(release, host)) throw new CatalogError("RELEASE_INCOMPATIBLE", "Selected release does not accept the current product and host target");
855
- const existing = observations.find((o) => o.packageName === release.packageName);
856
- if (automatic && existing?.declared.origin !== void 0) throw new CatalogError("STALE_PREVIEW", "A user declaration now owns this default extension");
857
- if (selection.expectedInstalledReceiptId !== void 0 && existing?.receipt?.receiptId !== selection.expectedInstalledReceiptId) throw new CatalogError("STALE_PREVIEW", "Current installed receipt differs from the displayed selection");
858
- const prior = roots.find((r) => r.packageName === release.packageName);
859
- if (prior && recordDigest(prior) !== recordDigest(release)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension roots select conflicting exact releases");
860
- if (!prior) roots.push(release);
861
- }
862
- const resolved = [], chosen = new Map(roots.map((root) => [root.packageName, root])), expanded = /* @__PURE__ */ new Set();
863
- async function expand(candidate) {
864
- const prior = chosen.get(candidate.packageName);
865
- if (prior) {
866
- if (prior.releaseId !== candidate.releaseId) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension requirements select conflicting exact releases");
867
- if (expanded.has(candidate.packageName)) return;
868
- }
869
- if (!prior && chosen.size >= 64) throw new CatalogError("LIMIT_EXCEEDED", "Extension closure exceeds 64 packages");
870
- chosen.set(candidate.packageName, candidate);
871
- expanded.add(candidate.packageName);
872
- resolved.push(candidate);
873
- const raw = (await options.installer.inspect({
874
- expectedName: candidate.packageName,
875
- expectedVersion: candidate.version,
876
- ...candidate.artifact
877
- }, preparationSignal, attempt)).yaoguang?.dependencies ?? {};
878
- if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).length > 64) throw new CatalogError("ARTIFACT_INVALID", "Invalid extension dependency declaration");
879
- for (const [name, range] of Object.entries(raw)) {
880
- if (typeof range !== "string" || semver.validRange(range) === null) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension dependency has an invalid version range");
881
- const selected = chosen.get(name);
882
- if (selected) {
883
- if (!semver.satisfies(selected.version, range)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Exact closure cannot satisfy all extension requirements");
884
- continue;
885
- }
886
- const installed = observations.find((o) => o.packageName === name && o.declared.origin !== void 0);
887
- if (automatic && installed && (!installed.declared.installed || !installed.declared.enabled)) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency declaration does not permit default installation");
888
- const installedVersion = installed?.receipt?.version ?? installed?.declared.version ?? installed?.summary?.version;
889
- if (installedVersion && semver.valid(installedVersion) && semver.satisfies(installedVersion, range)) continue;
890
- if (automatic && installed) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency version cannot be replaced by default installation");
891
- const choices = accepted.releases.filter((r) => r.packageName === name && semver.satisfies(r.version, range) && releaseCompatible(r, host));
892
- if (choices.length !== 1) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Missing extension dependency has no unique compatible exact release");
893
- await expand(choices[0]);
894
- }
895
- }
896
- for (const root of roots) await expand(root);
897
- function evidence(candidate) {
898
- return {
899
- expectedName: candidate.packageName,
900
- expectedVersion: candidate.version,
901
- ...candidate.artifact,
902
- sourceRecord: {
903
- snapshot: {
904
- repository: accepted.repository,
905
- commit: accepted.commit,
906
- treeSha: accepted.treeSha,
907
- contentDigest: accepted.contentDigest
908
- },
909
- release: candidate,
910
- releaseDigest: recordDigest(candidate)
911
- },
912
- activationConstraints: {
913
- hostVersionRange: candidate.compatibility.productRange,
914
- platformTargets: candidate.compatibility.platforms
915
- },
916
- display: {
917
- label: typeof candidate.displayName === "string" ? candidate.displayName : candidate.displayName["en-US"],
918
- detail: "Historical catalog admission"
919
- }
920
- };
921
- }
922
- const validate = () => {
923
- if (snapshot?.commit !== accepted.commit || snapshot.contentDigest !== accepted.contentDigest || snapshot.revision !== accepted.revision || resolved.some((r) => !snapshot.releases.some((current) => current.releaseId === r.releaseId && recordDigest(current) === recordDigest(r)))) throw new CatalogError("STALE_PREVIEW", "Catalog changed after preview; select the new exact release explicitly");
924
- };
925
- preparationSignal.throwIfAborted();
926
- validate();
927
- const rootNames = new Set(roots.map((root) => root.packageName));
928
- const dependencies = resolved.filter((record) => !rootNames.has(record.packageName)).map(evidence);
929
- const preview = batch ? await options.installer.previewBatch({
930
- roots: roots.map(evidence),
931
- dependencies,
932
- enabled: true,
933
- enableNames
934
- }, validate, attempt) : await options.installer.preview({
935
- ...evidence(roots[0]),
936
- enabled: true,
937
- dependencies
938
- }, validate, attempt);
939
- preparationSignal.throwIfAborted();
940
- if (automatic && preview.replacing.length) throw new CatalogError("STALE_PREVIEW", "Default installation cannot replace existing extensions");
941
- return {
942
- previewToken: preview.token,
943
- expiresAt: preview.expiresAt,
944
- snapshot: {
945
- commit: accepted.commit,
946
- contentDigest: accepted.contentDigest
947
- },
948
- graphRevision: preview.graphRevision,
949
- resolvedSelections: resolved,
950
- dependencies: preview.selections.filter((selection) => !rootNames.has(selection.expectedName)).map((s) => ({
951
- packageName: s.expectedName,
952
- version: s.expectedVersion
953
- })),
954
- willEnable: [...preview.willEnable],
955
- replacing: [...preview.replacing],
956
- affectedOwners: [...preview.affectedOwners],
957
- warnings: []
958
- };
959
- }
960
- const defaults = options.defaultsStore && options.hostIdentity ? createDefaultsService({
961
- store: options.defaultsStore,
962
- identity: options.hostIdentity,
963
- installer: options.installer,
964
- signal,
965
- preview: (selections, attempt) => preview(selections, [], true, attempt, true),
966
- acquireSnapshot: acquireFreshSnapshot
967
- }) : null;
968
- function requireDefaults() {
969
- if (!defaults) throw new CatalogError("DEFAULTS_UNAVAILABLE", "Default extension initialization is unavailable for this host");
970
- return defaults;
971
- }
972
- return {
973
- /** Starts or shares this owner's one-shot bounded automatic installation task. */
974
- defaultsEnsure(input) {
975
- return requireDefaults().ensure(input);
976
- },
977
- /** Returns passive initialization facts without refreshing or enrolling. */
978
- defaultsStatus() {
979
- return requireDefaults().status();
980
- },
981
- /** Returns cached data only; first use and failure never trigger network work. */
982
- list() {
983
- signal.throwIfAborted();
984
- if (!snapshot) return {
985
- revision: 0,
986
- snapshot: null,
987
- releases: [],
988
- sync: { ...sync }
989
- };
990
- const { releases, ...metadata } = snapshot;
991
- return {
992
- revision: snapshot.revision,
993
- snapshot: metadata,
994
- releases,
995
- sync: { ...sync }
996
- };
997
- },
998
- /** Joins the active fresh synchronization; manual work survives automatic attempt cancellation. */
999
- refresh() {
1000
- return {
1001
- taskId: sharedSynchronization(true).taskId,
1002
- sync: { ...sync }
1003
- };
1004
- },
1005
- /** Previews installation with target enablement and joins owned preparation before disposal. */
1006
- preview(input) {
1007
- const task = preview([input]);
1008
- ownedTasks.add(task);
1009
- task.then(() => {
1010
- ownedTasks.delete(task);
1011
- }, () => {
1012
- ownedTasks.delete(task);
1013
- });
1014
- return task;
1015
- },
1016
- /** Prepares one approved union of exact roots and existing owners to enable. */
1017
- previewBatch(inputs, enableNames = []) {
1018
- const task = preview(inputs, enableNames, true);
1019
- ownedTasks.add(task);
1020
- task.then(() => ownedTasks.delete(task), () => ownedTasks.delete(task));
1021
- return task;
1022
- },
1023
- /** Delegates deduplication before any token or current-snapshot validation. */
1024
- install(operationId, previewToken) {
1025
- signal.throwIfAborted();
1026
- return options.installer.install({
1027
- operationId,
1028
- token: previewToken
1029
- });
1030
- },
1031
- /** Reads an existing durable attempt without restarting work. */
1032
- operation(operationId) {
1033
- return options.installer.operation(operationId);
1034
- },
1035
- /** Retries only cleanup still owned by the queried attempt. */
1036
- retryCleanup(operationId) {
1037
- return options.installer.retryCleanup(operationId);
1038
- },
1039
- /** Projects installed metadata against the current cached directory without reading files. */
1040
- async installed() {
1041
- signal.throwIfAborted();
1042
- const observations = await options.installer.observe();
1043
- return {
1044
- observedAt: (/* @__PURE__ */ new Date()).toISOString(),
1045
- rows: projectInstalled(observations, snapshot, options.hostIdentity)
1046
- };
1047
- },
1048
- /** Joins all discovery work before owner disposal completes. */
1049
- async dispose() {
1050
- controller.abort(/* @__PURE__ */ new Error("Catalog owner withdrawn"));
1051
- await Promise.all([defaults?.dispose(), Promise.allSettled([...ownedTasks])]);
1052
- }
1053
- };
1054
- }
1055
- //#endregion
1056
- //#region src/extension-catalog/store.ts
1057
- /** Persists the last complete validated catalog snapshot in this owner's storage lease. */
1058
- function createCatalogStore(storage) {
1059
- const name = storage.tableName("catalog_snapshot");
1060
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid storage table identity");
1061
- const table = `"${name}"`;
1062
- storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK(id=1), snapshot_json TEXT NOT NULL)`);
1063
- function validate(input) {
1064
- const value = SnapshotSchema.parse(input);
1065
- if (recordDigest({ releases: value.releases }) !== value.contentDigest) throw new CatalogError("CATALOG_INVALID", "Cached snapshot digest differs from its complete records");
1066
- if (new Set(value.releases.map((r) => r.releaseId)).size !== value.releases.length) throw new CatalogError("CATALOG_INVALID", "Duplicate cached release");
1067
- return value;
1068
- }
1069
- return {
1070
- /** Reads validated last-success data without network activity; corruption refuses availability. */
1071
- read() {
1072
- const row = storage.db.prepare(`SELECT snapshot_json FROM ${table} WHERE id=1`).get();
1073
- if (!row) return null;
1074
- try {
1075
- return validate(JSON.parse(row.snapshot_json));
1076
- } catch {
1077
- throw new CatalogError("CATALOG_INVALID", "Catalog cache is unavailable; refresh to repair it");
1078
- }
1079
- },
1080
- /** Atomically replaces the complete snapshot and advances its successful revision. */
1081
- save(input) {
1082
- const snapshot = validate(input);
1083
- storage.db.exec("SAVEPOINT catalog_snapshot_commit");
1084
- try {
1085
- let before = null;
1086
- try {
1087
- before = this.read();
1088
- } catch {}
1089
- const revision = (before?.revision ?? 0) + 1;
1090
- if (!Number.isSafeInteger(revision)) throw new CatalogError("LIMIT_EXCEEDED", "Catalog revision is exhausted");
1091
- const saved = {
1092
- ...snapshot,
1093
- revision
1094
- };
1095
- const json = canonicalJson(saved);
1096
- if (Buffer.byteLength(json) > 8388608) throw new CatalogError("LIMIT_EXCEEDED", "Encoded catalog exceeds 8 MiB");
1097
- storage.db.prepare(`INSERT INTO ${table}(id,snapshot_json) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET snapshot_json=excluded.snapshot_json`).run(json);
1098
- storage.db.exec("RELEASE catalog_snapshot_commit");
1099
- return saved;
1100
- } catch (error) {
1101
- storage.db.exec("ROLLBACK TO catalog_snapshot_commit");
1102
- storage.db.exec("RELEASE catalog_snapshot_commit");
1103
- throw error;
1104
- }
1105
- }
1106
- };
1107
- }
1108
- //#endregion
1109
- //#region ../../core/kernel/src/vocab/widgets.ts
1110
- /** Returns whether a value is lossless JSON with at most 64 nested containers. */
1111
- function isLosslessJson(value) {
1112
- const active = /* @__PURE__ */ new Set();
1113
- function visit(one, depth) {
1114
- if (one === null || typeof one === "boolean") return true;
1115
- if (typeof one === "string") return !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(one);
1116
- if (typeof one === "number") return Number.isFinite(one) && !Object.is(one, -0);
1117
- if (typeof one !== "object" || depth > 64 || active.has(one)) return false;
1118
- const array = Array.isArray(one);
1119
- if (!array && Object.getPrototypeOf(one) !== Object.prototype && Object.getPrototypeOf(one) !== null) return false;
1120
- if (Object.getOwnPropertySymbols(one).length !== 0) return false;
1121
- const descriptors = Object.getOwnPropertyDescriptors(one);
1122
- if (array && (Object.keys(descriptors).length !== one.length + 1 || !Array.from({ length: one.length }, (_, index) => Object.hasOwn(descriptors, String(index))).every(Boolean))) return false;
1123
- active.add(one);
1124
- for (const [key, descriptor] of Object.entries(descriptors)) {
1125
- if (array && key === "length") continue;
1126
- if (!("value" in descriptor) || !descriptor.enumerable || !visit(key, 0) || !visit(descriptor.value, depth + 1)) {
1127
- active.delete(one);
1128
- return false;
1129
- }
1130
- }
1131
- active.delete(one);
1132
- return true;
1133
- }
1134
- try {
1135
- return visit(value, 1);
1136
- } catch {
1137
- return false;
1138
- }
1139
- }
1140
- /** Pure stored JSON shape; validation requires no owner code. */
1141
- const JsonObjectSchema = z.custom((value) => isLosslessJson(value) && value !== null && !Array.isArray(value) && typeof value === "object");
1142
- /** Exact, portable widget reference identity. */
1143
- 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}$/);
1144
- /** Local type names never encode a business catalogue in the host. */
1145
- const WidgetTypeSchema = z.string().regex(/^[a-z][a-z0-9-]{0,63}$/);
1146
- /** Host-stamped original execution provenance, retained unchanged by forks. */
1147
- const WidgetSourceSchema = z.object({
1148
- sessionId: z.string().min(1),
1149
- messageId: z.string().uuid(),
1150
- toolCallId: z.string().min(1),
1151
- toolName: z.string().min(1)
1152
- }).strict();
1153
- /** Complete snapshot stored atomically with its tool result. */
1154
- const WidgetInstanceSchema = z.object({
1155
- id: WidgetIdSchema,
1156
- owner: z.string().min(1),
1157
- type: WidgetTypeSchema,
1158
- title: z.string().refine((text) => text.trim().length > 0 && [...text].length <= 200),
1159
- summary: z.string().refine((text) => text.trim().length > 0 && [...text].length <= 4e3),
1160
- data: JsonObjectSchema,
1161
- source: WidgetSourceSchema
1162
- }).strict().refine((widget) => widgetJsonBytes({
1163
- type: widget.type,
1164
- title: widget.title,
1165
- summary: widget.summary,
1166
- data: widget.data
1167
- }) <= 262144).transform((widget) => freezeWidget(widget));
1168
- /** Fixed diagnostics contain no rejected business data. */
1169
- const WidgetIssueCodeSchema = z.enum([
1170
- "count-limit",
1171
- "invalid-input",
1172
- "invalid-json",
1173
- "invalid-data",
1174
- "item-too-large",
1175
- "batch-too-large",
1176
- "unknown-type",
1177
- "source-unavailable",
1178
- "owner-unavailable",
1179
- "untrusted-instance",
1180
- "error-result"
1181
- ]);
1182
- /** One item index or one entire-group issue. */
1183
- const WidgetIssueSchema = z.object({
1184
- code: WidgetIssueCodeSchema,
1185
- index: z.number().int().min(0).max(7).optional()
1186
- }).strict();
1187
- /** Measures complete compact JSON in UTF-8 bytes. */
1188
- function widgetJsonBytes(value) {
1189
- return new TextEncoder().encode(JSON.stringify(value)).length;
1190
- }
1191
- /** Copies JSON into a deeply immutable snapshot. */
1192
- function freezeWidget(value) {
1193
- if (value !== null && typeof value === "object") {
1194
- for (const child of Object.values(value)) freezeWidget(child);
1195
- Object.freeze(value);
1196
- }
1197
- return value;
1198
- }
1199
- //#endregion
1200
- //#region ../../core/kernel/src/vocab/address.ts
1201
- /**
1202
- * A session's address: the `(Agent, Workspace)` pair it belongs to.
1203
- * Immutable for the session's whole life — it is set once at session
1204
- * creation and carried on every persisted event of that session and on
1205
- * the control state folded from them.
1206
- */
1207
- const SessionAddressSchema = z.object({
1208
- agentId: z.string(),
1209
- workspaceId: z.string()
1210
- });
1211
- //#endregion
1212
- //#region ../../core/kernel/src/vocab/message.ts
1213
- /**
1214
- * The transcript's message shapes: the authoritative history that assembly
1215
- * reads. A message is either a plain user/assistant turn of text, an
1216
- * assistant reply that also requests tool calls, or a tool-results message
1217
- * that answers a batch of those calls. Zod schemas are the source of
1218
- * truth; the types are `z.infer`red from them so this vocabulary survives
1219
- * the event log round trip once `packages/core/store-sqlite` serializes it.
1220
- *
1221
- * Tool results are carried in a `role: 'user'` message with `tool-result`
1222
- * content parts. Protocol implementations translate this neutral transcript
1223
- * into their own request representation.
1224
- */
1225
- const MessageRoleSchema = z.enum(["user", "assistant"]);
1226
- const TextPartSchema = z.object({
1227
- type: z.literal("text"),
1228
- text: z.string()
1229
- });
1230
- /** The model's thinking, attached to the same assistant message its reply
1231
- * text is. Symmetric with `TextPart` on purpose — it is the recorded
1232
- * counterpart of the publish-only `thinking-delta` chunk, carried the
1233
- * same way `TextPart` carries the recorded counterpart of `text-delta`.
1234
- * Accumulating deltas into this shape, and deciding whether to send it
1235
- * back on the next call, is the adapter's job — this package only
1236
- * carries it. */
1237
- const ThinkingPartSchema = z.object({
1238
- type: z.literal("thinking"),
1239
- text: z.string(),
1240
- /** An opaque token the provider issued with this block and requires back
1241
- * **unmodified** on any later turn that continues the same conversation.
1242
- * A fabricated or edited value can invalidate replay. Absent for protocols
1243
- * that issue no signature. The kernel never reads it; it only
1244
- * carries it, so that the adapter that produced it can hand it back. */
1245
- signature: z.string().optional(),
1246
- /**
1247
- * Which endpoint issued that signature.
1248
- *
1249
- * A signature is only worth anything to whoever signed it, and the product
1250
- * cannot tell whether two endpoints are the same signer — two keys against
1251
- * one vendor, or a proxy in front of it, look identical from here. So this
1252
- * is compared as an endpoint id and the comparison is a deliberate
1253
- * over-approximation: an adapter drops a block another endpoint signed,
1254
- * which between two endpoints of one vendor costs a block that would have
1255
- * replayed. The other way round costs a rejected request.
1256
- *
1257
- * Absent wherever `signature` is: nothing to attribute. The kernel never
1258
- * reads either; it carries them so the adapter that made the block can
1259
- * decide.
1260
- */
1261
- issuer: z.string().optional(),
1262
- /** Model identifier that produced this signed thinking block. */
1263
- originModel: z.string().optional(),
1264
- /**
1265
- * Stable compatibility fingerprint for the non-thinking prefix covered by
1266
- * the provider signature. Adapters omit a signed block when it does not match
1267
- * the request prefix they are about to send.
1268
- */
1269
- prefix: z.string().optional(),
1270
- /**
1271
- * Original output-token count used as a conservative upper bound when the
1272
- * provider retains more thinking state than the visible text represents.
1273
- */
1274
- outputTokens: z.number().int().nonnegative().optional(),
1275
- /**
1276
- * Set on a block the provider returned with no readable text — a protocol's
1277
- * `redacted_thinking`. `text` is then empty and `signature` holds the
1278
- * provider's opaque `data`, which goes back unmodified in the same place.
1279
- */
1280
- redacted: z.literal(true).optional()
1281
- });
1282
- /** A tool call the model requested. `input` is whatever JSON-serializable
1283
- * arguments the model produced for it — the kernel does not validate a
1284
- * tool's own argument shape, only that the call itself round-trips. */
1285
- const ToolUsePartSchema = z.object({
1286
- type: z.literal("tool-use"),
1287
- id: z.string(),
1288
- name: z.string(),
1289
- input: z.unknown()
1290
- });
1291
- const Sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
1292
- /** The copy of a file a model is sent, when it differs from the original:
1293
- * a content-addressed variant within every built-in provider type's limits. */
1294
- const FileVariantSchema = z.object({
1295
- id: Sha256Schema,
1296
- mediaType: z.string().min(1),
1297
- size: z.number().int().positive(),
1298
- width: z.number().int().positive().optional(),
1299
- height: z.number().int().positive().optional()
1300
- }).strict();
1301
- /**
1302
- * A reference to a content-addressed file of the session's workspace. Only
1303
- * metadata: the bytes live on disk under the workspace's `files/` directory
1304
- * and reach a request through `ModelRequest.files` alone, so an event, a
1305
- * frame or a snapshot never carries them. `name` belongs to the reference,
1306
- * not to the file: the same bytes may be named differently in two messages.
1307
- */
1308
- const FileRefSchema = z.object({
1309
- /** The original's sha256, lower-case hex. */
1310
- id: Sha256Schema,
1311
- mediaType: z.string().min(1),
1312
- name: z.string().min(1).max(200),
1313
- size: z.number().int().positive(),
1314
- /** Present for an image. */
1315
- width: z.number().int().positive().optional(),
1316
- height: z.number().int().positive().optional(),
1317
- /** The variant a model receives; absent when the original is within limits. */
1318
- forModel: FileVariantSchema.optional()
1319
- }).strict();
1320
- /** A file inside a message, at the place it was written: text and file parts
1321
- * interleave in the order a person composed them. */
1322
- const FilePartSchema = z.object({
1323
- type: z.literal("file"),
1324
- file: FileRefSchema
1325
- });
1326
- /** The answer to one tool call, matched back to it by `toolUseId`. */
1327
- const ToolResultPartSchema = z.object({
1328
- type: z.literal("tool-result"),
1329
- toolUseId: z.string(),
1330
- /** Immutable host-accepted snapshots. */
1331
- widgets: z.array(WidgetInstanceSchema).max(8).optional(),
1332
- /** Fixed admission diagnostics. */
1333
- widgetIssues: z.array(WidgetIssueSchema).max(8).optional(),
1334
- content: z.string(),
1335
- isError: z.boolean().optional(),
1336
- /** Requested preview body tokens; invalid hints are ignored by the host. */
1337
- previewTokens: z.number().optional(),
1338
- /** First-delivery instructions kept whole; ordinary history reduction remains allowed. */
1339
- previewProtected: z.boolean().optional(),
1340
- /** Files the call handed back, after its text. */
1341
- files: z.array(FileRefSchema).optional()
1342
- });
1343
- const ContentPartSchema = z.discriminatedUnion("type", [
1344
- TextPartSchema,
1345
- ThinkingPartSchema,
1346
- ToolUsePartSchema,
1347
- ToolResultPartSchema,
1348
- FilePartSchema
1349
- ]);
1350
- /**
1351
- * One volatile contributor's text as a request carried it: the contributor's
1352
- * `id` and the strings it gave, joined by a blank line. A request appends a
1353
- * note only when it differs from that contributor's last note in the history,
1354
- * or at a turn's first step, and the note stays in every later request at the
1355
- * place it was first sent.
1356
- */
1357
- const VolatileNoteSchema = z.object({
1358
- id: z.string(),
1359
- text: z.string()
1360
- }).strict();
1361
- /**
1362
- * Where a person's message came in, when it came in through a channel that
1363
- * names itself: the channel's id and display label, and the speaker the
1364
- * channel reported. Written by the gateway's access layer alone; a message
1365
- * typed in the product's own client carries none.
1366
- */
1367
- const MessageViaSchema = z.object({
1368
- channel: z.string().min(1),
1369
- label: z.string().min(1),
1370
- /** Who spoke, as the channel identifies them. `role` is whether they were
1371
- * the owner when they sent it; a later change of owner leaves it. */
1372
- sender: z.object({
1373
- id: z.string().min(1),
1374
- name: z.string().min(1).max(64),
1375
- role: z.enum(["owner", "member"])
1376
- }).strict().optional()
1377
- }).strict();
1378
- const MessageSchema = z.object({
1379
- /** UUID assigned when the message first forms and retained by every fork. */
1380
- id: z.string().uuid(),
1381
- role: MessageRoleSchema,
1382
- content: z.array(ContentPartSchema),
1383
- /** Present only on a message the model refused to complete — the
1384
- * provider's own category for why.
1385
- *
1386
- * It lives **on the message** rather than only on the `message-appended`
1387
- * event that records it, and that distinction is the whole point: `fold`
1388
- * rebuilds the transcript out of `event.message`, so a marker carried only
1389
- * by the event survives the log and is lost the moment anybody folds it
1390
- * back. The transcript needs to remember that a reply was a refusal,
1391
- * which means the message has to. Contrast `backfilled`, which stays on
1392
- * the event because it describes how that event came to be rather than
1393
- * anything about the message. */
1394
- refusalCategory: z.string().optional(),
1395
- /** Present on a message a composer command produced: what the person
1396
- * wrote, and the source that expanded it. `content` holds the expansion,
1397
- * which is what the model is sent; the transcript shows `text`. */
1398
- invocation: z.object({
1399
- text: z.string(),
1400
- namespace: z.string()
1401
- }).strict().optional(),
1402
- /** What a person attached, one entry per leading text block of `content`,
1403
- * which holds each attachment's original text. The model-facing envelope is
1404
- * added where a request is assembled and is never stored. */
1405
- attachments: z.array(z.object({
1406
- namespace: z.string(),
1407
- group: z.string().optional(),
1408
- label: z.string()
1409
- }).strict()).optional(),
1410
- /** Present only on a model reply: the pair that produced it, stamped by the
1411
- * host on the final chunk. On the message rather than the event for the
1412
- * reason `refusalCategory` is: `fold` rebuilds the transcript from
1413
- * `event.message`, and the latest reply's pair is what names the model a
1414
- * compaction after a switch summarizes on. */
1415
- model: z.object({
1416
- providerId: z.string(),
1417
- model: z.string()
1418
- }).strict().optional(),
1419
- /** Present only on a model reply: the volatile notes the request that
1420
- * produced it appended. Adapters render them just before this message, so
1421
- * every later request repeats the earlier one byte for byte. Clients do not
1422
- * draw them. */
1423
- volatile: z.array(VolatileNoteSchema).optional(),
1424
- /** Present only on a person's message that arrived through a labelled
1425
- * channel. Adapters never see it: the request a model receives carries a
1426
- * speaker line instead, added where the request is assembled. */
1427
- via: MessageViaSchema.optional(),
1428
- /** Durable host attribution, preserved in the transcript when the log is replayed. */
1429
- source: z.object({
1430
- kind: z.enum([
1431
- "delegation-result",
1432
- "delegation-task",
1433
- "notice",
1434
- "trigger",
1435
- "trigger-data"
1436
- ]),
1437
- owner: z.string(),
1438
- taskId: z.string(),
1439
- deliveryId: z.string().optional(),
1440
- /** The trigger definition a `trigger` or `trigger-data` delivery ran for. */
1441
- triggerId: z.string().optional(),
1442
- /** What a person calls the source: a scheduled task's name. */
1443
- label: z.string().optional()
1444
- }).strict().optional()
1445
- });
1446
- //#endregion
1447
- //#region ../../core/kernel/src/vocab/human.ts
1448
- /**
1449
- * The vocabulary of asking a person.
1450
- *
1451
- * A tool that needs a human decision does not block: it answers a call
1452
- * with `{ awaitHuman: HumanRequestInput }` instead of content, the kernel records
1453
- * the batch's other results together with the request, and once the
1454
- * person has answered, **the same call is executed again** with the reply
1455
- * on its context. So a request is addressed by the id of the tool call
1456
- * that raised it, and the text a person reads lives on events and on the
1457
- * `fold` projection — never on `ControlState`, which carries only the id
1458
- * (invariant: control flow does not read message content).
1459
- *
1460
- * `kind` decides presentation only: a `question` is the model asking, an
1461
- * `approval` is an action asking to be allowed. An approval has exactly one
1462
- * question whose options are the outcomes the requester accepts.
1463
- *
1464
- * Zod schemas are the source of truth; the types are inferred from them so
1465
- * the shapes survive the event log round trip.
1466
- */
1467
- const HumanOptionSchema = z.object({
1468
- id: z.string().min(1),
1469
- label: z.string().min(1),
1470
- description: z.string().optional()
1471
- });
1472
- /** One thing to answer. With `options`, an answer picks by id — one option,
1473
- * or several when `multiple` is set — and may add text; with `freeText`, an
1474
- * answer may skip the options and give text alone; with no options at all,
1475
- * text is the only answer there is. */
1476
- const HumanQuestionSchema = z.object({
1477
- id: z.string().min(1),
1478
- text: z.string().min(1),
1479
- options: z.array(HumanOptionSchema),
1480
- freeText: z.boolean(),
1481
- /** Several options may be chosen; absent means one. */
1482
- multiple: z.boolean().optional()
1483
- });
1484
- const HumanRequestKindSchema = z.enum(["question", "approval"]);
1485
- /** One thing an approval would open: a path to read or write, or a host to
1486
- * reach. It sits beside the one-line `subject` in `questions[0].text`,
1487
- * which consumers that draw no list keep reading. */
1488
- const HumanTargetSchema = z.object({
1489
- access: z.enum([
1490
- "read",
1491
- "write",
1492
- "network",
1493
- "connect",
1494
- "listen",
1495
- "execute"
1496
- ]),
1497
- target: z.string().min(1)
1498
- });
1499
- /** A request as it is recorded and shown: the ask plus who raised it. */
1500
- const HumanRequestSchema = z.object({
1501
- kind: HumanRequestKindSchema,
1502
- /** Why the requester is asking — an approval's justification. */
1503
- reason: z.string().optional(),
1504
- questions: z.array(HumanQuestionSchema).min(1),
1505
- /** An approval's structured objects, in the order the requester lists them. */
1506
- targets: z.array(HumanTargetSchema).optional(),
1507
- /** A consequence the host states apart from `reason`, drawn above the
1508
- * buttons: what a lasting answer opens. */
1509
- warning: z.string().optional()
1510
- }).extend({
1511
- /** The id of the tool call that raised it — one request per call. */
1512
- requestId: z.string().min(1),
1513
- /** The tool that raised it: the requester a person is told about. */
1514
- toolName: z.string().min(1)
1515
- });
1516
- const HumanAnswerSchema = z.object({
1517
- questionId: z.string().min(1),
1518
- /** The chosen options: at most one on a single-choice question. Absent
1519
- * when none is chosen — never empty. */
1520
- optionIds: z.array(z.string().min(1)).min(1).optional(),
1521
- text: z.string().optional()
1522
- });
1523
- /** One person's answer to one request, covering every question in it. */
1524
- const HumanReplySchema = z.object({
1525
- requestId: z.string().min(1),
1526
- answers: z.array(HumanAnswerSchema)
1527
- });
1528
- z.object({
1529
- settled: z.array(ToolResultPartSchema),
1530
- requests: z.array(HumanRequestSchema),
1531
- replies: z.array(HumanReplySchema),
1532
- suspendedCalls: z.array(ToolUsePartSchema)
1533
- });
829
+ //#region ../../core/kernel/src/vocab/model-failure.ts
830
+ /** Bounded, verified facts about a logical model call failure. */
831
+ /** Stable failure facts; arbitrary provider text and unknown fields are refused. */
832
+ const ModelFailureSchema = z.strictObject({
833
+ code: z.enum([
834
+ "finish-reason-missing",
835
+ "finish-reason-unsupported",
836
+ "response-empty",
837
+ "final-chunk-missing",
838
+ "stream-interrupted",
839
+ "stream-idle-timeout",
840
+ "http-error",
841
+ "request-too-large",
842
+ "request-measurement-unsupported",
843
+ "authentication-required",
844
+ "authentication-expired",
845
+ "quota-exceeded",
846
+ "model-unavailable",
847
+ "context-limit-exceeded",
848
+ "provider-error",
849
+ "response-invalid",
850
+ "unknown"
851
+ ]),
852
+ stage: z.enum([
853
+ "request",
854
+ "transport",
855
+ "stream",
856
+ "response-validation",
857
+ "unknown"
858
+ ]),
859
+ category: z.enum([
860
+ "network",
861
+ "provider",
862
+ "request-too-large",
863
+ "protocol",
864
+ "unknown"
865
+ ]),
866
+ source: z.enum([
867
+ "protocol",
868
+ "transport",
869
+ "provider",
870
+ "host",
871
+ "unknown"
872
+ ]),
873
+ status: z.number().int().min(100).max(599).optional(),
874
+ retryable: z.boolean().optional(),
875
+ finishReason: z.enum([
876
+ "stop",
877
+ "tool-calls",
878
+ "max-tokens",
879
+ "refusal"
880
+ ]).optional(),
881
+ providerCode: z.enum([
882
+ "usage_not_included",
883
+ "usage_limit_reached",
884
+ "insufficient_quota",
885
+ "context_length_exceeded",
886
+ "rate_limit_exceeded",
887
+ "overloaded_error",
888
+ "api_error",
889
+ "rate_limit_error",
890
+ "cyber_policy",
891
+ "invalid_prompt",
892
+ "bio_policy",
893
+ "misalignment_policy_violation"
894
+ ]).optional(),
895
+ attemptCount: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
896
+ modelCallId: z.uuid().optional(),
897
+ turn: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
898
+ step: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()
899
+ }).refine((value) => JSON.stringify(value).length <= 2048, "model failure exceeds its size limit");
1534
900
  //#endregion
1535
901
  //#region ../../core/kernel/src/vocab/outcome.ts
1536
- /**
1537
- * How a turn ended: an exhaustive union at the top level (`completed` /
1538
- * `interrupted` / `failed`), open underneath it in `completed`'s reason
1539
- * (more reasons to stop are a pure addition, the three top-level kinds
1540
- * are closed). `completed` means the turn ended cleanly, not that it
1541
- * achieved a goal: hitting a limit, being
1542
- * refused and being policy-blocked all land here because each of them
1543
- * leaves a legal transcript with nothing broken.
1544
- */
902
+ /** Turn endings distinguish ordinary completion, cancellation, failures and host execution stops. */
1545
903
  const CompletedReasonSchema = z.enum([
1546
904
  "natural",
1547
905
  "step-limit",
@@ -1563,12 +921,50 @@ const InterruptedOutcomeSchema = z.object({ kind: z.literal("interrupted") });
1563
921
  * has more of these than this change implements transitions for. */
1564
922
  const FailedOutcomeSchema = z.object({
1565
923
  kind: z.literal("failed"),
1566
- reason: z.string()
924
+ reason: z.string(),
925
+ failure: ModelFailureSchema.optional()
926
+ });
927
+ /** A verified shared-resource admission failure; no model retry can create capacity. */
928
+ const ResourceExhaustionSchema = z.object({
929
+ reason: z.literal("resource-exhausted"),
930
+ pool: z.literal("query"),
931
+ dimension: z.enum([
932
+ "session-slots",
933
+ "session-bytes",
934
+ "resident-bytes",
935
+ "session-scratch",
936
+ "resident-scratch"
937
+ ]),
938
+ limit: z.number().int().positive().safe(),
939
+ held: z.number().int().nonnegative().safe(),
940
+ requested: z.number().int().nonnegative().safe(),
941
+ cleanup: z.enum([
942
+ "none",
943
+ "pending",
944
+ "failed"
945
+ ]),
946
+ recovery: z.enum([
947
+ "wait-cleanup",
948
+ "owner-recovery",
949
+ "expire-resources"
950
+ ])
951
+ });
952
+ /** Successful model output exhausted the fixed continuation budget. */
953
+ const ExecutionStopSchema = z.discriminatedUnion("reason", [ResourceExhaustionSchema, z.object({
954
+ reason: z.literal("output-limit"),
955
+ continuationsUsed: z.literal(3),
956
+ continuationLimit: z.literal(3)
957
+ })]);
958
+ /** A host execution boundary stopped a legal transcript without natural completion. */
959
+ const StoppedOutcomeSchema = z.object({
960
+ kind: z.literal("stopped"),
961
+ stop: ExecutionStopSchema
1567
962
  });
1568
963
  const OutcomeSchema = z.discriminatedUnion("kind", [
1569
964
  CompletedOutcomeSchema,
1570
965
  InterruptedOutcomeSchema,
1571
- FailedOutcomeSchema
966
+ FailedOutcomeSchema,
967
+ StoppedOutcomeSchema
1572
968
  ]);
1573
969
  //#endregion
1574
970
  //#region ../../core/kernel/src/vocab/session-id.ts
@@ -1630,6 +1026,8 @@ z.object({
1630
1026
  phase: PhaseSchema,
1631
1027
  turn: z.number().int().nonnegative(),
1632
1028
  step: z.number().int().nonnegative(),
1029
+ outputContinuationsUsed: z.number().int().min(0).max(3),
1030
+ pendingOutputContinuation: z.object({ replyId: z.string().uuid() }).optional(),
1633
1031
  turnTokensUsed: z.number().int().nonnegative(),
1634
1032
  pendingToolCalls: z.array(PendingToolCallSchema),
1635
1033
  pendingHumanRequests: z.array(PendingHumanRequestSchema),
@@ -1679,6 +1077,24 @@ z.object({
1679
1077
  * throwing — a log a later build appended new variants to must still read
1680
1078
  * on an older one.
1681
1079
  */
1080
+ /** Durable owner JSON state and its idempotent operation receipt, ordered by physical sequence. */
1081
+ const OwnerStateEventSchema = OwnerContextEntrySchema.extend({
1082
+ kind: z.literal("owner-state"),
1083
+ sessionId: SessionIdSchema,
1084
+ address: SessionAddressSchema,
1085
+ operationId: z.string().min(1).max(256),
1086
+ requestHash: z.string().min(1).max(256)
1087
+ }).superRefine(({ owner, key, revision, data }, ctx) => {
1088
+ if (!OwnerContextSchema.safeParse([{
1089
+ owner,
1090
+ key,
1091
+ revision,
1092
+ data
1093
+ }]).success) ctx.addIssue({
1094
+ code: "custom",
1095
+ message: "Invalid or oversized owner state"
1096
+ });
1097
+ });
1682
1098
  const TriggerSourceSchema = z.enum(["human", "plugin"]);
1683
1099
  /** What a model call reported using, in the terms its final chunk gives
1684
1100
  * us. Carried on `model-replied` and folded into `ControlState.turnTokensUsed`
@@ -1724,6 +1140,8 @@ const TriggerEventSchema = z.object({
1724
1140
  * without needing the full `FinishReason` union carried over the wire. */
1725
1141
  const ModelRepliedEventSchema = z.object({
1726
1142
  kind: z.literal("model-replied"),
1143
+ finishReason: FinishReasonSchema,
1144
+ outputTruncation: OutputTruncationSchema.optional(),
1727
1145
  message: MessageSchema,
1728
1146
  usage: ModelUsageSchema,
1729
1147
  refusalCategory: z.string().optional()
@@ -1733,7 +1151,10 @@ const ModelRepliedEventSchema = z.object({
1733
1151
  * same reason as `model-replied`. */
1734
1152
  const ToolResultsAddedEventSchema = z.object({
1735
1153
  kind: z.literal("tool-results-added"),
1736
- message: MessageSchema
1154
+ ownerStates: z.array(OwnerStateEventSchema).max(16).optional(),
1155
+ message: MessageSchema,
1156
+ /** Host-verified stop, settled after all admitted calls finish. */
1157
+ stop: ExecutionStopSchema.optional()
1737
1158
  });
1738
1159
  /** A message became part of the transcript. */
1739
1160
  const MessageAppendedEventSchema = z.object({
@@ -1789,7 +1210,13 @@ const ContextMeasurementSchema = z.object({
1789
1210
  fingerprint: z.string(),
1790
1211
  inputBudget: z.number().int().nonnegative().optional(),
1791
1212
  /** Whether the reserve is enforceable upstream or the catalogue capacity. */
1792
- outputReserveSource: z.enum(["capacity", "enforced"]).optional()
1213
+ outputReserveSource: z.enum([
1214
+ "capacity",
1215
+ "enforced",
1216
+ "estimated"
1217
+ ]).optional(),
1218
+ /** Whether the capacity comes from a declaration or the owner's assumed baseline. */
1219
+ capacitySource: z.enum(["declared", "assumed"]).optional()
1793
1220
  });
1794
1221
  /** Why the context operation started. */
1795
1222
  const ContextTriggerSchema = z.enum([
@@ -1953,7 +1380,8 @@ const CancelledEventSchema = z.object({
1953
1380
  * same reason as `Cancelled`. */
1954
1381
  const EffectFailedEventSchema = z.object({
1955
1382
  kind: z.literal("effect-failed"),
1956
- reason: z.string()
1383
+ reason: z.string(),
1384
+ failure: ModelFailureSchema.optional()
1957
1385
  });
1958
1386
  /** A non-final chunk from the model port's stream, forwarded by the
1959
1387
  * call-model handler so that `decide` — never the handler itself — is
@@ -1966,6 +1394,7 @@ const EffectFailedEventSchema = z.object({
1966
1394
  * published, which only coincides with the port's transport shape today. */
1967
1395
  const ModelChunkEventSchema = z.object({
1968
1396
  kind: z.literal("model-chunk"),
1397
+ ownerContext: OwnerContextSchema.optional(),
1969
1398
  chunk: z.discriminatedUnion("kind", [
1970
1399
  z.object({
1971
1400
  kind: z.literal("text-delta"),
@@ -1989,6 +1418,7 @@ const ModelChunkEventSchema = z.object({
1989
1418
  * handler, which derives the recorded `human-asked` from it. */
1990
1419
  const StepSuspendedEventSchema = z.object({
1991
1420
  kind: z.literal("step-suspended"),
1421
+ ownerStates: z.array(OwnerStateEventSchema).max(16).optional(),
1992
1422
  settled: z.array(ToolResultPartSchema),
1993
1423
  requests: z.array(HumanRequestSchema)
1994
1424
  });
@@ -2028,7 +1458,43 @@ const ParticipantChangedEventSchema = z.object({
2028
1458
  reason: z.string().max(500).optional(),
2029
1459
  at: z.number().int().nonnegative()
2030
1460
  });
1461
+ /** Complete pure admission facts committed before any call in the batch starts. */
1462
+ const ToolCallsAdmittedEventSchema = z.object({
1463
+ kind: z.literal("tool-calls-admitted"),
1464
+ /** Assistant message whose original calls this fact annotates. */
1465
+ messageId: z.string().optional(),
1466
+ sessionId: SessionIdSchema,
1467
+ address: SessionAddressSchema,
1468
+ calls: z.array(z.object({
1469
+ callId: z.string(),
1470
+ partIndex: z.number().int().nonnegative().optional(),
1471
+ entry: z.object({
1472
+ name: z.string(),
1473
+ input: z.unknown()
1474
+ }),
1475
+ target: z.object({
1476
+ name: z.string(),
1477
+ input: z.unknown()
1478
+ }).optional(),
1479
+ definitionFingerprint: z.string(),
1480
+ status: z.enum(["admitted", "rejected"]),
1481
+ errorCode: z.string().optional()
1482
+ }))
1483
+ });
1484
+ /** Durable admission of one bounded continuation in the current turn. */
1485
+ const OutputContinuationStartedEventSchema = z.object({
1486
+ kind: z.literal("output-continuation-started"),
1487
+ sessionId: SessionIdSchema,
1488
+ address: SessionAddressSchema,
1489
+ turn: z.number().int().positive(),
1490
+ step: z.number().int().positive(),
1491
+ replyId: z.string().uuid(),
1492
+ attempt: z.number().int().min(1).max(3)
1493
+ });
2031
1494
  const RecordableEventSchema = z.discriminatedUnion("kind", [
1495
+ OutputContinuationStartedEventSchema,
1496
+ ToolCallsAdmittedEventSchema,
1497
+ OwnerStateEventSchema,
2032
1498
  TriggerEventSchema,
2033
1499
  HistorySeededEventSchema,
2034
1500
  HistoryRewoundEventSchema,
@@ -2042,6 +1508,9 @@ const RecordableEventSchema = z.discriminatedUnion("kind", [
2042
1508
  ParticipantChangedEventSchema
2043
1509
  ]);
2044
1510
  const EventSchema = z.discriminatedUnion("kind", [
1511
+ OutputContinuationStartedEventSchema,
1512
+ ToolCallsAdmittedEventSchema,
1513
+ OwnerStateEventSchema,
2045
1514
  TriggerEventSchema,
2046
1515
  HistorySeededEventSchema,
2047
1516
  HistoryRewoundEventSchema,
@@ -2119,6 +1588,214 @@ z.discriminatedUnion("kind", [
2119
1588
  CheckpointEffectSchema
2120
1589
  ]);
2121
1590
  //#endregion
1591
+ //#region ../../core/protocol/src/telemetry.ts
1592
+ /** Finite performance stages exclude arbitrary paths, SQL and business text. */
1593
+ const TelemetryStage = z.enum([
1594
+ "ui.interaction",
1595
+ "ui.feedback",
1596
+ "ui.commit",
1597
+ "ui.frame",
1598
+ "ui.stream-display",
1599
+ "reading.watch",
1600
+ "reading.content",
1601
+ "reading.page",
1602
+ "reading.queue",
1603
+ "reading.worker",
1604
+ "reading.projection",
1605
+ "reading.ack-wait",
1606
+ "reading.loss",
1607
+ "reading.source",
1608
+ "markdown.parse",
1609
+ "markdown.mount",
1610
+ "rpc.encode",
1611
+ "rpc.send",
1612
+ "rpc.receive",
1613
+ "rpc.decode",
1614
+ "rpc.resolve",
1615
+ "rpc.roundtrip",
1616
+ "rpc.dispatch",
1617
+ "browser.long-task",
1618
+ "browser.frame-gap",
1619
+ "browser.loss",
1620
+ "browser.input-delay",
1621
+ "native.bridge",
1622
+ "native.command",
1623
+ "native.socket.connect",
1624
+ "native.socket.queue",
1625
+ "native.socket.send",
1626
+ "native.socket.receive",
1627
+ "native.http.headers",
1628
+ "native.http.body",
1629
+ "native.file.open",
1630
+ "native.file.write",
1631
+ "native.file.commit",
1632
+ "native.file.cleanup",
1633
+ "native.picker.wait",
1634
+ "native.loss",
1635
+ "gateway.decode",
1636
+ "gateway.handler",
1637
+ "gateway.encode",
1638
+ "gateway.send",
1639
+ "runtime.admission",
1640
+ "runtime.event-batch",
1641
+ "runtime.owner-context",
1642
+ "runtime.prepare",
1643
+ "runtime.status",
1644
+ "runtime.snapshot",
1645
+ "runtime.publish",
1646
+ "runtime.reading",
1647
+ "runtime.turn",
1648
+ "model.inspect",
1649
+ "model.tokenizer",
1650
+ "model.cache",
1651
+ "model.call",
1652
+ "model.display",
1653
+ "context.inspect",
1654
+ "context.contributor",
1655
+ "tool.call",
1656
+ "database.read",
1657
+ "database.open",
1658
+ "database.close",
1659
+ "database.decode",
1660
+ "database.statement",
1661
+ "database.serialize",
1662
+ "database.transaction",
1663
+ "database.event-insert",
1664
+ "database.reading-projection",
1665
+ "database.commit",
1666
+ "database.rollback",
1667
+ "database.busy",
1668
+ "database.checkpoint",
1669
+ "file.open",
1670
+ "file.write",
1671
+ "file.rename",
1672
+ "file.close",
1673
+ "file.fsync",
1674
+ "file.directory-sync",
1675
+ "file.publication",
1676
+ "file.cleanup",
1677
+ "event-loop.delay",
1678
+ "event-loop.max",
1679
+ "event-loop.p95",
1680
+ "event-loop.p99",
1681
+ "event-loop.utilization",
1682
+ "process.cpu",
1683
+ "process.rss",
1684
+ "process.heap",
1685
+ "process.gc",
1686
+ "logging.write"
1687
+ ]);
1688
+ /** User intent labels contain no user-supplied text. */
1689
+ const TelemetryOperation = z.enum([
1690
+ "session-switch",
1691
+ "send",
1692
+ "human-answer",
1693
+ "approval",
1694
+ "cancel",
1695
+ "history-page",
1696
+ "heartbeat",
1697
+ "generic"
1698
+ ]);
1699
+ const nonnegative = z.number().finite().nonnegative();
1700
+ const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
1701
+ const identity = z.string().min(1).max(128).regex(/^[A-Za-z0-9@][A-Za-z0-9@/_.:-]*$/);
1702
+ /** Correlation is foreign input; server span and connection identities are host-supplied. */
1703
+ const RequestTrace = z.object({
1704
+ traceId: z.uuid(),
1705
+ parentSpanId: z.uuid().optional(),
1706
+ interactionId: z.uuid().optional()
1707
+ }).strict();
1708
+ /** One same-clock duration, with strictly bounded scalar metadata. */
1709
+ const TelemetryObservation = z.object({
1710
+ stage: TelemetryStage,
1711
+ clockDomain: z.uuid(),
1712
+ monotonicStartMs: nonnegative,
1713
+ durationMs: nonnegative,
1714
+ outcome: z.enum([
1715
+ "ok",
1716
+ "error",
1717
+ "cancelled",
1718
+ "timeout",
1719
+ "unknown"
1720
+ ]).optional(),
1721
+ operation: TelemetryOperation.optional(),
1722
+ spanId: z.uuid().optional(),
1723
+ traceId: z.uuid().optional(),
1724
+ parentSpanId: z.uuid().optional(),
1725
+ interactionId: z.uuid().optional(),
1726
+ sessionId: identity.optional(),
1727
+ requestId: identity.optional(),
1728
+ visibility: z.enum(["foreground", "background"]).optional(),
1729
+ cacheState: z.enum([
1730
+ "hit",
1731
+ "miss",
1732
+ "cold",
1733
+ "warm"
1734
+ ]).optional(),
1735
+ measurementPurpose: z.enum([
1736
+ "request",
1737
+ "text",
1738
+ "catalogue",
1739
+ "tool-result",
1740
+ "display"
1741
+ ]).optional(),
1742
+ bytes: counter.optional(),
1743
+ count: counter.optional(),
1744
+ hits: counter.optional(),
1745
+ misses: counter.optional(),
1746
+ evictions: counter.optional(),
1747
+ inputBytes: counter.optional(),
1748
+ retainedBytes: counter.optional()
1749
+ }).strict();
1750
+ /** Runtime-only capture controls; diagnostic TTL defaults to fifteen minutes. */
1751
+ const TelemetryConfigure = z.object({
1752
+ mode: z.enum([
1753
+ "off",
1754
+ "normal",
1755
+ "diagnostic"
1756
+ ]),
1757
+ durationSeconds: z.number().int().min(1).max(3600).optional()
1758
+ }).strict();
1759
+ /** Bounded client batch; transport additionally checks its serialized byte count. */
1760
+ const TelemetryIngest = z.object({
1761
+ batchId: z.uuid(),
1762
+ pageId: z.uuid(),
1763
+ observations: z.array(TelemetryObservation).max(128)
1764
+ }).strict();
1765
+ z.object({
1766
+ mode: z.enum([
1767
+ "off",
1768
+ "normal",
1769
+ "diagnostic"
1770
+ ]),
1771
+ expiresAt: z.iso.datetime().optional(),
1772
+ pendingRecords: counter,
1773
+ pendingBytes: counter,
1774
+ droppedRecords: counter,
1775
+ capabilities: z.object({ eventLoop: z.boolean() }).strict(),
1776
+ budgets: z.object({
1777
+ targetMs: z.literal(15),
1778
+ batchRecords: z.literal(128),
1779
+ batchBytes: z.literal(65536),
1780
+ recordBytes: z.literal(8192)
1781
+ }).strict()
1782
+ }).strict();
1783
+ /** Authenticated browser and native observation admission. */
1784
+ const TelemetryIngestRequest = z.object({
1785
+ method: z.literal("gateway.telemetryIngest"),
1786
+ params: TelemetryIngest
1787
+ });
1788
+ /** Authenticated collection status query. */
1789
+ const TelemetryStatusRequest = z.object({
1790
+ method: z.literal("gateway.telemetryStatus"),
1791
+ params: z.object({}).strict().optional()
1792
+ });
1793
+ /** Authenticated runtime-only collection configuration. */
1794
+ const TelemetryConfigureRequest = z.object({
1795
+ method: z.literal("gateway.telemetryConfigure"),
1796
+ params: TelemetryConfigure
1797
+ });
1798
+ //#endregion
2122
1799
  //#region ../../core/protocol/src/agent-revisions.ts
2123
1800
  /** Configuration history wire contracts. Shared resource contents are excluded. */
2124
1801
  const AgentId = z.string().min(1);
@@ -2330,8 +2007,13 @@ const ReadingTurnHeader = z.object({
2330
2007
  "running",
2331
2008
  "completed",
2332
2009
  "cancelled",
2333
- "failed"
2334
- ])
2010
+ "failed",
2011
+ "stopped"
2012
+ ]),
2013
+ /** Structured framework stop, independent of failed model response diagnostics. */
2014
+ stop: ExecutionStopSchema.optional(),
2015
+ reason: z.string().max(512).optional(),
2016
+ failure: ModelFailureSchema.optional()
2335
2017
  });
2336
2018
  /** A contiguous page, ordered by message ordinal. Cursors are exclusive boundaries. */
2337
2019
  const HistoryWindow = z.object({
@@ -2412,16 +2094,39 @@ const SessionMessagePartsRequest = z.object({
2412
2094
  limit: page
2413
2095
  }).strict()
2414
2096
  });
2415
- /** Reads at most 256KiB from one authorized source object. */
2416
- const SessionMessageContentRequest = z.object({
2417
- method: z.literal("session.messageContent"),
2097
+ /** One authorized range consumed by the internal range reader; never a scalar wire entry. */
2098
+ const MessageContentInput = z.object({
2099
+ scope: ContentScope,
2100
+ readingLeaseId: z.string().optional(),
2101
+ contentRefId: z.string().max(256),
2102
+ offset: z.number().int().nonnegative(),
2103
+ maxBytes: z.number().int().min(4).max(262144)
2104
+ }).strict();
2105
+ /** Reads independent ranges after checking the complete raw and encoded budgets. */
2106
+ const SessionMessageContentsRequest = z.object({
2107
+ method: z.literal("session.messageContents"),
2418
2108
  params: z.object({
2419
2109
  scope: ContentScope,
2420
2110
  readingLeaseId: z.string().optional(),
2421
- contentRefId: z.string().max(256),
2422
- offset: z.number().int().nonnegative(),
2423
- maxBytes: z.number().int().min(4).max(262144)
2424
- }).strict()
2111
+ items: z.array(MessageContentInput.omit({
2112
+ scope: true,
2113
+ readingLeaseId: true
2114
+ })).min(1).max(64),
2115
+ maxTotalBytes: z.number().int().min(4).max(1048576).default(1048576)
2116
+ }).strict().superRefine((value, ctx) => {
2117
+ if (value.items.reduce((sum, item) => sum + item.maxBytes, 0) > value.maxTotalBytes) ctx.addIssue({
2118
+ code: "custom",
2119
+ message: "declared raw content exceeds maxTotalBytes"
2120
+ });
2121
+ if (value.items.reduce((sum, item) => sum + 4 * Math.ceil(item.maxBytes / 3) + 65536, 8192) > 2097152) ctx.addIssue({
2122
+ code: "custom",
2123
+ message: "declared encoded result exceeds 2 MiB"
2124
+ });
2125
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 8388608) ctx.addIssue({
2126
+ code: "custom",
2127
+ message: "batch input exceeds 8 MiB"
2128
+ });
2129
+ })
2425
2130
  });
2426
2131
  /** Reads durable annotations or process-local request descriptors. */
2427
2132
  const SessionLivePageRequest = z.object({
@@ -2561,11 +2266,11 @@ z.enum([
2561
2266
  "session",
2562
2267
  "permanent"
2563
2268
  ]);
2564
- /** One work directory, as `workspace list` shows it and as a search reads it:
2565
- * an absolute real path, resolved when it was added. It carries no mode —
2566
- * every work directory is readable, and what may be *changed* is a grant,
2567
- * answered by a person when a tool asked. */
2568
- const AuthorizedDirectory = z.object({ path: z.string() });
2269
+ /** An authorized workspace tree with its canonical real path and stored access level. */
2270
+ const AuthorizedDirectory = z.object({
2271
+ path: z.string(),
2272
+ access: z.enum(["read", "read-write"])
2273
+ });
2569
2274
  /** A workspace: an abstract scope, **bound to no path**. Its authorized
2570
2275
  * directories hang beneath it, zero of them being the normal state for a
2571
2276
  * freshly created one. */
@@ -2575,11 +2280,11 @@ const WorkspaceSummary = z.object({
2575
2280
  createdAt: z.number().int(),
2576
2281
  /** The revision of the uploaded picture, or `null` for none — then a
2577
2282
  * client draws the letters face derived from the name. The bytes travel
2578
- * only through `config.workspace.avatar`. */
2283
+ * only through `config.workspace.avatars`. */
2579
2284
  avatar: z.string().nullable(),
2580
2285
  /** Already-resolved absolute real paths, the whole tree under each. A
2581
- * summary says which trees this workspace may see and read; what may be
2582
- * changed under one of them is a grant, listed by `config.access.list`. */
2286
+ * summary preserves each authorized tree and its read or read-write level.
2287
+ * Additional resource grants are listed by `config.access.list`. */
2583
2288
  directories: z.array(AuthorizedDirectory)
2584
2289
  });
2585
2290
  /** A session as it appears in a list, without loading it. Everything here
@@ -3114,7 +2819,7 @@ const AgentChangedFrame = z.object({
3114
2819
  * names the agent rather than carrying a summary: there is none left. */
3115
2820
  const AgentRemovedFrame = z.object({
3116
2821
  kind: z.literal("config.agentRemoved"),
3117
- agentId: z.string()
2822
+ agentIds: z.array(z.string()).min(1).max(64)
3118
2823
  });
3119
2824
  const WorkspaceChangedFrame = z.object({
3120
2825
  kind: z.literal("config.workspaceChanged"),
@@ -3183,6 +2888,13 @@ const SessionMessageFrame = z.object({
3183
2888
  sourceSeq: z.number().int().min(-1),
3184
2889
  streamEpoch: z.string().optional()
3185
2890
  });
2891
+ /** Committed execution identities annotate existing calls without changing their protocol names. */
2892
+ const SessionToolCallsAdmittedFrame = z.object({
2893
+ kind: z.literal("session.toolCallsAdmitted"),
2894
+ ...sessionFrameBase,
2895
+ messageId: z.string(),
2896
+ sourceSeq: z.number().int().min(-1)
2897
+ });
3186
2898
  /** Replaces the entire effective snapshot after a rewind commits. */
3187
2899
  const SessionHistoryReplacedFrame = z.object({
3188
2900
  kind: z.literal("session.historyReplaced"),
@@ -3555,12 +3267,13 @@ const InboxChangedFrame = z.object({
3555
3267
  const CredentialChangedFrame = z.object({
3556
3268
  kind: z.literal("config.credentialChanged"),
3557
3269
  plugin: z.string(),
3558
- scope: z.string()
3270
+ scopes: z.array(z.string()).min(1).max(64)
3559
3271
  });
3560
3272
  const CoreSessionFrame = z.discriminatedUnion("kind", [
3561
3273
  TurnStartedFrame,
3562
3274
  DeltaFrame,
3563
3275
  DeltaResetFrame,
3276
+ SessionToolCallsAdmittedFrame,
3564
3277
  SessionMessageFrame,
3565
3278
  SessionHistoryReplacedFrame,
3566
3279
  TurnEndedFrame,
@@ -3599,6 +3312,7 @@ const CoreFrame = z.discriminatedUnion("kind", [
3599
3312
  TurnStartedFrame,
3600
3313
  DeltaFrame,
3601
3314
  DeltaResetFrame,
3315
+ SessionToolCallsAdmittedFrame,
3602
3316
  SessionMessageFrame,
3603
3317
  SessionHistoryReplacedFrame,
3604
3318
  TurnEndedFrame,
@@ -3724,10 +3438,29 @@ const SessionForkRequest = z.object({
3724
3438
  operationId: z.string().uuid()
3725
3439
  })
3726
3440
  });
3441
+ const batchIds = () => z.array(z.string().min(1)).min(1).max(64);
3442
+ const queryBudgets = {
3443
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
3444
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
3445
+ };
3446
+ const boundedBatchParams = (shape, collection) => z.object(shape).strict().superRefine((value, ctx) => {
3447
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 8388608) ctx.addIssue({
3448
+ code: "custom",
3449
+ message: "batch input exceeds 8 MiB"
3450
+ });
3451
+ const params = value;
3452
+ if (typeof params.maxItemBytes === "number" && typeof params.maxTotalBytes === "number" && Array.isArray(params[collection]) && params.maxItemBytes * params[collection].length + 8192 > params.maxTotalBytes) ctx.addIssue({
3453
+ code: "custom",
3454
+ message: "declared response budget exceeds maxTotalBytes"
3455
+ });
3456
+ });
3727
3457
  /** Reads one durable history-operation result after an uncertain response. */
3728
- const SessionOperationGetRequest = z.object({
3729
- method: z.literal("session.operation.get"),
3730
- params: z.object({ operationId: z.string().uuid() })
3458
+ const SessionOperationsGetRequest = z.object({
3459
+ method: z.literal("session.operations.get"),
3460
+ params: boundedBatchParams({
3461
+ operationIds: z.array(z.uuid()).min(1).max(64),
3462
+ ...queryBudgets
3463
+ }, "operationIds")
3731
3464
  });
3732
3465
  /** Takes back a message sent while a turn was running, before its step
3733
3466
  * claims it. Answers with the message, so the page that asked can put its
@@ -3817,10 +3550,11 @@ const SessionLeaveRequest = z.object({
3817
3550
  * contract `session.setModel` has. It produces no turn and writes no event. */
3818
3551
  const SessionArchiveRequest = z.object({
3819
3552
  method: z.literal("session.archive"),
3820
- params: z.object({
3821
- sessionId: z.string(),
3553
+ params: boundedBatchParams({
3554
+ operationId: z.uuid(),
3555
+ sessionIds: batchIds(),
3822
3556
  archived: z.boolean()
3823
- })
3557
+ }, "sessionIds")
3824
3558
  });
3825
3559
  /** Sets the name a person gives a session, or clears it: trimmed, at most 60
3826
3560
  * characters, and a name holding nothing but whitespace clears it. Leaves
@@ -3886,7 +3620,10 @@ const ConfigAgentSetPromptSlotRequest = z.object({
3886
3620
  });
3887
3621
  const ConfigAgentPromptSlotsRequest = z.object({
3888
3622
  method: z.literal("config.agent.promptSlots"),
3889
- params: z.object({ agentId: z.string() })
3623
+ params: boundedBatchParams({
3624
+ agentIds: batchIds(),
3625
+ ...queryBudgets
3626
+ }, "agentIds")
3890
3627
  });
3891
3628
  /** Sets an agent's picture, or with `null` returns it to the derived one.
3892
3629
  * The browser crops and encodes; the gateway checks it is a whole 256×256
@@ -3901,9 +3638,12 @@ const ConfigAgentSetAvatarRequest = z.object({
3901
3638
  })
3902
3639
  });
3903
3640
  /** The uploaded picture, or `null` when the agent has none. */
3904
- const ConfigAgentAvatarRequest = z.object({
3905
- method: z.literal("config.agent.avatar"),
3906
- params: z.object({ agentId: z.string() })
3641
+ const ConfigAgentAvatarsRequest = z.object({
3642
+ method: z.literal("config.agent.avatars"),
3643
+ params: boundedBatchParams({
3644
+ agentIds: z.array(z.string()).min(1).max(4),
3645
+ maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
3646
+ }, "agentIds")
3907
3647
  });
3908
3648
  /** Removes a user-created agent: its row, picture, model overrides, access
3909
3649
  * grants and its directory under the work root. Its sessions stay readable
@@ -3912,7 +3652,10 @@ const ConfigAgentAvatarRequest = z.object({
3912
3652
  * `config.agentRemoved` follows. */
3913
3653
  const ConfigAgentRemoveRequest = z.object({
3914
3654
  method: z.literal("config.agent.remove"),
3915
- params: z.object({ agentId: z.string().min(1) })
3655
+ params: boundedBatchParams({
3656
+ operationId: z.uuid(),
3657
+ agentIds: batchIds()
3658
+ }, "agentIds")
3916
3659
  });
3917
3660
  /** One save from the agent editor: every field the person changed, applied
3918
3661
  * together. Everything is validated before anything is written, and the
@@ -3963,7 +3706,8 @@ z.object({
3963
3706
  name: z.string(),
3964
3707
  description: z.string(),
3965
3708
  plugin: z.string(),
3966
- permitted: z.boolean()
3709
+ permitted: z.boolean(),
3710
+ preloadDefault: z.boolean()
3967
3711
  }))
3968
3712
  });
3969
3713
  /** Writes nothing, produces no turn, needs no session: safe to retry. An
@@ -3971,7 +3715,10 @@ z.object({
3971
3715
  * real and different answer — "this agent is offered no tools at all". */
3972
3716
  const ConfigToolListRequest = z.object({
3973
3717
  method: z.literal("config.tool.list"),
3974
- params: z.object({ agentId: z.string().min(1) })
3718
+ params: boundedBatchParams({
3719
+ agentIds: batchIds(),
3720
+ ...queryBudgets
3721
+ }, "agentIds")
3975
3722
  });
3976
3723
  /** What is under a directory, for a client that has to name one.
3977
3724
  *
@@ -4030,21 +3777,28 @@ const TriggerUpdateRequest = z.object({
4030
3777
  });
4031
3778
  const TriggerSetEnabledRequest = z.object({
4032
3779
  method: z.literal("trigger.setEnabled"),
4033
- params: z.object({
4034
- id: z.string().min(1),
3780
+ params: boundedBatchParams({
3781
+ operationId: z.uuid(),
3782
+ ids: batchIds(),
4035
3783
  enabled: z.boolean()
4036
- })
3784
+ }, "ids")
4037
3785
  });
4038
3786
  /** Removes a definition, its runs and its pre-authorized scope; sessions it
4039
3787
  * opened stay. */
4040
3788
  const TriggerRemoveRequest = z.object({
4041
3789
  method: z.literal("trigger.remove"),
4042
- params: z.object({ id: z.string().min(1) })
3790
+ params: boundedBatchParams({
3791
+ operationId: z.uuid(),
3792
+ ids: batchIds()
3793
+ }, "ids")
4043
3794
  });
4044
3795
  /** A definition's runs, newest first, at most 200. */
4045
3796
  const TriggerRunsRequest = z.object({
4046
3797
  method: z.literal("trigger.runs"),
4047
- params: z.object({ id: z.string().min(1) })
3798
+ params: boundedBatchParams({
3799
+ ids: batchIds(),
3800
+ ...queryBudgets
3801
+ }, "ids")
4048
3802
  });
4049
3803
  /** Every inbox item that still exists, newest first. No cap: unread notices
4050
3804
  * and waiting requests are never removed on anyone's behalf, so the list
@@ -4079,7 +3833,7 @@ const InboxClearReadRequest = z.object({
4079
3833
  * answers success with no side effect. */
4080
3834
  const ProcessStopRequest = z.object({
4081
3835
  method: z.literal("process.stop"),
4082
- params: z.object({ processId: z.string().min(1) })
3836
+ params: boundedBatchParams({ processIds: batchIds() }, "processIds")
4083
3837
  });
4084
3838
  /** One stream's bytes, by range.
4085
3839
  *
@@ -4131,30 +3885,33 @@ const ConfigWorkspaceSetAvatarRequest = z.object({
4131
3885
  })
4132
3886
  });
4133
3887
  /** The workspace's uploaded picture, or `null` when it has none. */
4134
- const ConfigWorkspaceAvatarRequest = z.object({
4135
- method: z.literal("config.workspace.avatar"),
4136
- params: z.object({ workspaceId: z.string() })
4137
- });
4138
- /** Adds one work directory to a workspace: a tree its sessions may search and
4139
- * read without asking. It grants no writing — that is answered per path when
4140
- * a tool asks — so the params carry a path and nothing else.
4141
- *
4142
- * Adding a path already added is not an error and adds no second row; the
4143
- * answer is the whole workspace summary either way, so a caller cannot tell
4144
- * — and does not need to tell — "added" from "already there". */
4145
- const ConfigWorkspaceAddDirectoryRequest = z.object({
4146
- method: z.literal("config.workspace.addDirectory"),
3888
+ const ConfigWorkspaceAvatarsRequest = z.object({
3889
+ method: z.literal("config.workspace.avatars"),
3890
+ params: boundedBatchParams({
3891
+ workspaceIds: z.array(z.string()).min(1).max(4),
3892
+ maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
3893
+ }, "workspaceIds")
3894
+ });
3895
+ /** Adds or updates a bounded directory collection atomically; omitted access is read. */
3896
+ const ConfigWorkspaceAddDirectoriesRequest = z.object({
3897
+ method: z.literal("config.workspace.addDirectories"),
4147
3898
  params: z.object({
3899
+ operationId: z.uuid(),
4148
3900
  workspaceId: z.string(),
4149
- path: z.string().min(1)
4150
- })
4151
- });
4152
- const ConfigWorkspaceRemoveDirectoryRequest = z.object({
4153
- method: z.literal("config.workspace.removeDirectory"),
3901
+ directories: z.array(z.object({
3902
+ path: z.string().min(1),
3903
+ access: z.enum(["read", "read-write"]).default("read")
3904
+ }).strict()).min(1).max(64)
3905
+ }).strict().refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8388608, "batch input exceeds 8 MiB")
3906
+ });
3907
+ /** Removes directory authorizations atomically; already absent paths are successful no-ops. */
3908
+ const ConfigWorkspaceRemoveDirectoriesRequest = z.object({
3909
+ method: z.literal("config.workspace.removeDirectories"),
4154
3910
  params: z.object({
3911
+ operationId: z.uuid(),
4155
3912
  workspaceId: z.string(),
4156
- path: z.string().min(1)
4157
- })
3913
+ paths: z.array(z.string().min(1)).min(1).max(64)
3914
+ }).strict().refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8388608, "batch input exceeds 8 MiB")
4158
3915
  });
4159
3916
  /** Lists access records with ownership; omitted filters include all scopes. */
4160
3917
  const ConfigAccessListRequest = z.object({
@@ -4164,7 +3921,10 @@ const ConfigAccessListRequest = z.object({
4164
3921
  /** Adds a batch of globally reusable resources. */
4165
3922
  const ConfigAccessAddRequest = z.object({
4166
3923
  method: z.literal("config.access.add"),
4167
- params: z.object({ authorization: AuthorizationInput }).strict()
3924
+ params: boundedBatchParams({
3925
+ operationId: z.uuid(),
3926
+ authorizations: z.array(AuthorizationInput).min(1).max(64)
3927
+ }, "authorizations")
4168
3928
  });
4169
3929
  /** Reads whether new shell commands use operating-system confinement. */
4170
3930
  /** Persists the installation-wide switch; repeated writes are no-ops. */
@@ -4175,7 +3935,10 @@ const ConfigAccessAddRequest = z.object({
4175
3935
  * revoke says what the first one said. */
4176
3936
  const ConfigAccessRevokeRequest = z.object({
4177
3937
  method: z.literal("config.access.revoke"),
4178
- params: z.object({ id: z.string().min(1) }).strict()
3938
+ params: boundedBatchParams({
3939
+ operationId: z.uuid(),
3940
+ ids: batchIds()
3941
+ }, "ids")
4179
3942
  });
4180
3943
  z.object({
4181
3944
  name: z.string(),
@@ -4201,16 +3964,32 @@ const ConfigCredentialStatusRequest = z.object({
4201
3964
  * only. */
4202
3965
  const ConfigCredentialSetRequest = z.object({
4203
3966
  method: z.literal("config.credential.set"),
4204
- params: CredentialScopeParams.extend({
4205
- name: z.string().min(1),
4206
- value: z.string()
4207
- })
3967
+ params: boundedBatchParams({
3968
+ operationId: z.uuid(),
3969
+ plugin: z.string().min(1),
3970
+ scope: z.string().min(1),
3971
+ items: z.array(z.object({
3972
+ name: z.string().min(1),
3973
+ value: z.string()
3974
+ }).strict()).min(1).max(64)
3975
+ }, "items")
4208
3976
  });
4209
3977
  /** Clears one name, or the whole scope when `name` is omitted. Clearing
4210
3978
  * something absent succeeds and answers the current status. */
4211
3979
  const ConfigCredentialClearRequest = z.object({
4212
3980
  method: z.literal("config.credential.clear"),
4213
- params: CredentialScopeParams.extend({ name: z.string().min(1).optional() })
3981
+ params: boundedBatchParams({
3982
+ operationId: z.uuid(),
3983
+ plugin: z.string().min(1),
3984
+ items: z.array(z.discriminatedUnion("mode", [z.object({
3985
+ scope: z.string().min(1),
3986
+ mode: z.literal("names"),
3987
+ names: batchIds()
3988
+ }).strict(), z.object({
3989
+ scope: z.string().min(1),
3990
+ mode: z.literal("all")
3991
+ }).strict()])).min(1).max(64)
3992
+ }, "items")
4214
3993
  });
4215
3994
  /** Reads the hosts `web_fetch` may reach without asking. */
4216
3995
  /** Adds a bare host and broadcasts `config.webChanged`. With `includeSubdomains`, the
@@ -4230,17 +4009,13 @@ const ConfigCredentialClearRequest = z.object({
4230
4009
  * protocol pinned would be a second opinion about someone else's
4231
4010
  * configuration.
4232
4011
  */
4233
- const PluginInstallRequest = z.object({
4234
- method: z.literal("plugin.install"),
4235
- params: z.object({
4236
- spec: z.string().min(1),
4237
- config: z.record(z.string(), z.unknown()).optional()
4238
- })
4239
- });
4240
4012
  /** Installs the selected roots in one shared physical mutation and reports every root result. */
4241
4013
  const PluginInstallBatchRequest = z.object({
4242
4014
  method: z.literal("plugin.installBatch"),
4243
- params: z.object({ items: z.array(PluginInstallRequest.shape.params).min(1).max(64) })
4015
+ params: z.object({ items: z.array(z.object({
4016
+ spec: z.string().min(1),
4017
+ config: z.record(z.string(), z.unknown()).optional()
4018
+ })).min(1).max(64) })
4244
4019
  });
4245
4020
  /** Requested roots and their complete confirmed lifecycle closure. */
4246
4021
  const PluginRemovalBatchPlan = z.object({
@@ -4274,19 +4049,6 @@ z.object({
4274
4049
  names: z.array(z.string().min(1)),
4275
4050
  token: z.string().min(1)
4276
4051
  });
4277
- /** Previews every installed package removed with this extension without changing state. */
4278
- const PluginRemovePreviewRequest = z.object({
4279
- method: z.literal("plugin.removePreview"),
4280
- params: z.object({ name: z.string().min(1) })
4281
- });
4282
- /** Removes precisely the confirmed preview; a changed installation rejects before mutation. */
4283
- const PluginRemoveRequest = z.object({
4284
- method: z.literal("plugin.remove"),
4285
- params: z.object({
4286
- name: z.string().min(1),
4287
- token: z.string().min(1)
4288
- })
4289
- });
4290
4052
  z.object({
4291
4053
  /** Installed target extension. */
4292
4054
  name: z.string().min(1),
@@ -4298,377 +4060,1166 @@ z.object({
4298
4060
  token: z.string().min(1)
4299
4061
  });
4300
4062
  /** Previews activation changes without importing modules or modifying state. */
4301
- const PluginSetEnabledPreviewRequest = z.object({
4302
- method: z.literal("plugin.setEnabledPreview"),
4303
- params: z.object({
4304
- name: z.string().min(1),
4305
- enabled: z.boolean()
4306
- })
4307
- });
4308
4063
  /** Changes activation; a supplied stale preview token rejects before mutation. */
4309
- const PluginSetEnabledRequest = z.object({
4310
- method: z.literal("plugin.setEnabled"),
4064
+ /** Reads the declared configuration without including it in catalogue broadcasts. */
4065
+ const PluginGetConfigsRequest = z.object({
4066
+ method: z.literal("plugin.getConfigs"),
4067
+ params: boundedBatchParams({
4068
+ names: batchIds(),
4069
+ ...queryBudgets
4070
+ }, "names")
4071
+ });
4072
+ /** Replaces configuration and reloads enabled plugins and their active dependants. */
4073
+ const PluginSetConfigRequest = z.object({
4074
+ method: z.literal("plugin.setConfig"),
4311
4075
  params: z.object({
4312
4076
  name: z.string().min(1),
4313
- enabled: z.boolean(),
4314
- token: z.string().min(1).optional()
4077
+ config: z.record(z.string(), z.unknown())
4315
4078
  })
4316
4079
  });
4317
- /** Reads the declared configuration without including it in catalogue broadcasts. */
4318
- const PluginGetConfigRequest = z.object({
4319
- method: z.literal("plugin.getConfig"),
4320
- params: z.object({ name: z.string().min(1) })
4080
+ const PluginListRequest = z.object({
4081
+ method: z.literal("plugin.list"),
4082
+ params: z.object({}).optional()
4083
+ });
4084
+ /** Reads the whole plugin client surface in one call: every declared method,
4085
+ * every declared frame, and the address of every browser module. One call
4086
+ * rather than three, because an install can land between two of them and
4087
+ * leave a client holding a surface that contradicts itself. */
4088
+ const PluginSurfaceRequest = z.object({
4089
+ method: z.literal("plugin.surface"),
4090
+ params: z.object({}).optional()
4091
+ });
4092
+ /** Reads framework-managed instruction sources for the current Agent address. */
4093
+ const SessionInstructionsRequest = z.object({
4094
+ method: z.literal("session.instructions"),
4095
+ params: z.object({ sessionId: z.string() })
4096
+ });
4097
+ const RequestBody = z.discriminatedUnion("method", [
4098
+ TelemetryIngestRequest,
4099
+ TelemetryStatusRequest,
4100
+ TelemetryConfigureRequest,
4101
+ SessionInstructionsRequest,
4102
+ PingRequest,
4103
+ ConnectionInfoRequest,
4104
+ StatusRequest,
4105
+ GatewayShutdownRequest,
4106
+ SessionListRequest,
4107
+ SessionCreateRequest,
4108
+ SessionWatchRequest,
4109
+ SessionHistoryPageRequest,
4110
+ SessionMessagePartsRequest,
4111
+ SessionMessageContentsRequest,
4112
+ SessionLivePageRequest,
4113
+ SessionUnwatchRequest,
4114
+ SessionSendRequest,
4115
+ SessionForkRequest,
4116
+ SessionOperationsGetRequest,
4117
+ SessionAnswerRequest,
4118
+ SessionWithdrawRequest,
4119
+ SessionCancelRequest,
4120
+ SessionSetModelRequest,
4121
+ SessionSetModelParamsRequest,
4122
+ SessionArchiveRequest,
4123
+ SessionSetNameRequest,
4124
+ SessionJoinRequest,
4125
+ SessionLeaveRequest,
4126
+ ConfigLimitsGetRequest,
4127
+ ConfigLimitsSetRequest,
4128
+ ConfigAgentListRequest,
4129
+ ConfigAgentCreateRequest,
4130
+ ConfigPromptSlotsRequest,
4131
+ ConfigAgentUpdateRequest,
4132
+ ConfigAgentSetPromptSlotRequest,
4133
+ ConfigAgentPromptSlotsRequest,
4134
+ ConfigAgentSetAvatarRequest,
4135
+ ConfigAgentAvatarsRequest,
4136
+ ConfigAgentSaveRequest,
4137
+ ConfigAgentRevisionsRequest,
4138
+ ConfigAgentCompareRevisionsRequest,
4139
+ ConfigAgentPreviewRestoreRequest,
4140
+ ConfigAgentRestoreRevisionRequest,
4141
+ ConfigAgentRemoveRequest,
4142
+ ConfigToolListRequest,
4143
+ InboxListRequest,
4144
+ InboxReadRequest,
4145
+ InboxReadSessionRequest,
4146
+ InboxClearRequest,
4147
+ InboxClearReadRequest,
4148
+ TriggerListRequest,
4149
+ TriggerCreateRequest,
4150
+ TriggerUpdateRequest,
4151
+ TriggerSetEnabledRequest,
4152
+ TriggerRemoveRequest,
4153
+ TriggerRunsRequest,
4154
+ ProcessListRequest,
4155
+ ProcessStopRequest,
4156
+ ProcessOutputRequest,
4157
+ ConfigWorkspaceListRequest,
4158
+ ConfigWorkspaceCreateRequest,
4159
+ ConfigWorkspaceUpdateRequest,
4160
+ ConfigWorkspaceSetAvatarRequest,
4161
+ ConfigWorkspaceAvatarsRequest,
4162
+ ConfigWorkspaceAddDirectoriesRequest,
4163
+ ConfigWorkspaceRemoveDirectoriesRequest,
4164
+ ConfigAccessListRequest,
4165
+ ConfigAccessAddRequest,
4166
+ ConfigAccessRevokeRequest,
4167
+ ConfigCredentialStatusRequest,
4168
+ ConfigCredentialSetRequest,
4169
+ ConfigCredentialClearRequest,
4170
+ StdFsListRequest,
4171
+ PluginInstallBatchRequest,
4172
+ PluginSetEnabledBatchPreviewRequest,
4173
+ PluginSetEnabledBatchRequest,
4174
+ PluginRemoveBatchPreviewRequest,
4175
+ PluginRemoveBatchRequest,
4176
+ PluginListRequest,
4177
+ PluginGetConfigsRequest,
4178
+ PluginSetConfigRequest,
4179
+ PluginSurfaceRequest
4180
+ ]);
4181
+ /**
4182
+ * A request naming a method some plugin declared while this gateway was
4183
+ * running.
4184
+ *
4185
+ * The name is checked against the minting rule and **the parameters are not
4186
+ * read at all**: their shape is the plugin's zod, validated in the gateway,
4187
+ * and a second opinion here would be a second writer of someone else's
4188
+ * contract.
4189
+ *
4190
+ * `method` is a template literal type rather than a bare `string`, and that is
4191
+ * load-bearing: one `string` discriminant in this union and
4192
+ * `body.method === 'session.send'` stops narrowing, which takes every `switch`
4193
+ * that reads `body.params` afterwards down with it.
4194
+ *
4195
+ * `params` is optional because a call that takes none sends no key —
4196
+ * `JSON.stringify` drops an `undefined` — and a frame this schema refuses is
4197
+ * dropped in silence rather than answered. Bare `z.unknown()` would not
4198
+ * serve: zod 4 treats it as a required key, which would refuse exactly the
4199
+ * paramsless calls this field is meant to admit.
4200
+ */
4201
+ const PluginRequestBody = z.object({
4202
+ method: PluginWireName,
4203
+ params: z.unknown().optional()
4204
+ });
4205
+ /** One business request from a client. Authentication is a separate control
4206
+ * frame.
4207
+ *
4208
+ * The body is widened one layer out rather than `RequestBody` itself: the
4209
+ * core union stays a `discriminatedUnion` of names known at compile time,
4210
+ * and a plugin's runtime-minted name sits beside it. */
4211
+ const RequestFrame = z.object({
4212
+ kind: z.literal("request"),
4213
+ id: z.string(),
4214
+ trace: RequestTrace.optional(),
4215
+ body: z.union([RequestBody, PluginRequestBody])
4216
+ });
4217
+ /** Supplies the credential for one WebSocket connection. */
4218
+ const AuthenticationFrame = z.object({
4219
+ kind: z.literal("authentication"),
4220
+ id: z.string().min(1).max(128),
4221
+ token: z.string().max(256)
4321
4222
  });
4322
- /** Replaces configuration and reloads enabled plugins and their active dependants. */
4323
- const PluginSetConfigRequest = z.object({
4324
- method: z.literal("plugin.setConfig"),
4325
- params: z.object({
4326
- name: z.string().min(1),
4327
- config: z.record(z.string(), z.unknown())
4328
- })
4223
+ z.discriminatedUnion("kind", [RequestFrame, AuthenticationFrame]);
4224
+ z.object({ authenticated: z.literal(true) });
4225
+ z.enum(["auth-required", "auth-failed"]);
4226
+ z.enum([
4227
+ "history_conflict",
4228
+ "session_busy",
4229
+ "cut_unavailable",
4230
+ "source_unavailable",
4231
+ "file_unavailable",
4232
+ "operation_conflict",
4233
+ "history_preparing",
4234
+ "history_unavailable",
4235
+ "history_invalid",
4236
+ "history_stale",
4237
+ "history_cursor_invalid",
4238
+ "history_worker_unavailable",
4239
+ "reading_lease_invalid",
4240
+ "content_unavailable",
4241
+ "content_stale",
4242
+ "message_unavailable",
4243
+ "invalid_range"
4244
+ ]);
4245
+ z.enum(["configuration_write_rejected", "configuration_recovery_required"]);
4246
+ /** A bounded machine-readable refusal identifier; owner business codes are not enumerated by core. */
4247
+ const RequestErrorCode = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/);
4248
+ /** Gateway -> client: the answer to one request, addressed by its id. */
4249
+ const ResultFrame = z.object({
4250
+ kind: z.literal("result"),
4251
+ id: z.string(),
4252
+ ok: z.boolean(),
4253
+ data: z.unknown().optional(),
4254
+ error: z.string().optional(),
4255
+ errorCode: RequestErrorCode.optional(),
4256
+ /** Recoverable reading preparation lease and suggested polling interval. */
4257
+ readingDetails: z.object({
4258
+ readingLeaseId: z.string().optional(),
4259
+ retryAfterMs: z.number().int().positive().optional()
4260
+ }).optional()
4329
4261
  });
4330
- const PluginListRequest = z.object({
4331
- method: z.literal("plugin.list"),
4332
- params: z.object({}).optional()
4262
+ /** Gateway -> the connections that care: something happened. Carries no id,
4263
+ * because no one asked for it. */
4264
+ const EventFrame = z.object({
4265
+ kind: z.literal("event"),
4266
+ event: Frame
4333
4267
  });
4334
- /** Reads the whole plugin client surface in one call: every declared method,
4335
- * every declared frame, and the address of every browser module. One call
4336
- * rather than three, because an install can land between two of them and
4337
- * leave a client holding a surface that contradicts itself. */
4338
- const PluginSurfaceRequest = z.object({
4339
- method: z.literal("plugin.surface"),
4340
- params: z.object({}).optional()
4268
+ z.discriminatedUnion("kind", [ResultFrame, EventFrame]);
4269
+ z.object({
4270
+ instanceId: z.uuid(),
4271
+ gatewayVersion: z.string(),
4272
+ protocolVersion: z.string(),
4273
+ clientCount: z.number().int(),
4274
+ uptimeMs: z.number().int(),
4275
+ pid: z.number().int()
4341
4276
  });
4342
- /** Reads framework-managed instruction sources for the current Agent address. */
4343
- const SessionInstructionsRequest = z.object({
4344
- method: z.literal("session.instructions"),
4345
- params: z.object({ sessionId: z.string() })
4277
+ //#endregion
4278
+ //#region src/extension-catalog/projection.ts
4279
+ /** Minimal historical commit identity retained with a release admission. */
4280
+ const AcceptedSnapshotSchema = z.object({
4281
+ repository: z.literal(CATALOG_REPOSITORY),
4282
+ commit: GitShaSchema,
4283
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4284
+ }).strict();
4285
+ z.object({
4286
+ snapshot: AcceptedSnapshotSchema,
4287
+ release: ReleaseSchema,
4288
+ releaseDigest: z.string().regex(/^[0-9a-f]{64}$/)
4289
+ }).strict();
4290
+ /** Current directory source and actual host compatibility are independent of activation status. */
4291
+ const InstalledRowSchema = z.object({
4292
+ packageName: z.string(),
4293
+ distribution: z.enum([
4294
+ "builtin",
4295
+ "verified",
4296
+ "custom"
4297
+ ]),
4298
+ publisherKind: z.enum(["official", "third-party"]).optional(),
4299
+ compatibility: z.object({
4300
+ state: z.enum([
4301
+ "compatible",
4302
+ "incompatible",
4303
+ "unknown"
4304
+ ]),
4305
+ reasons: z.array(z.string()),
4306
+ assessedAt: z.string()
4307
+ }).strict(),
4308
+ updates: z.array(ReleaseSchema)
4309
+ }).strict();
4310
+ /** Uses current directory publisher markers while retaining actual saved host requirement facts. */
4311
+ function projectInstalled(observations, snapshot, host) {
4312
+ return observations.map((observation) => {
4313
+ const builtin = (observation.summary?.origin ?? observation.declared.origin) === "builtin";
4314
+ const listed = snapshot?.releases.filter((release) => release.packageName === observation.packageName).sort((a, b) => semver.rcompare(a.version, b.version))[0];
4315
+ const currentVersion = observation.summary?.version ?? observation.declared.version ?? observation.receipt?.version ?? "";
4316
+ const requirements = observation.hostRequirements;
4317
+ const compatibility = {
4318
+ state: requirements.state === "satisfied" ? "compatible" : requirements.state === "unsatisfied" ? "incompatible" : "unknown",
4319
+ reasons: [...requirements.reasons],
4320
+ assessedAt: requirements.checkedAt
4321
+ };
4322
+ const updates = !builtin && host && semver.valid(currentVersion) ? (snapshot?.releases ?? []).filter((release) => release.packageName === observation.packageName && semver.gt(release.version, currentVersion) && releaseCompatible(release, host)).sort((a, b) => semver.rcompare(a.version, b.version)) : [];
4323
+ return {
4324
+ packageName: observation.packageName,
4325
+ distribution: builtin ? "builtin" : listed ? "verified" : "custom",
4326
+ ...!builtin && listed ? { publisherKind: listed.publisher.kind } : {},
4327
+ compatibility,
4328
+ updates
4329
+ };
4330
+ });
4331
+ }
4332
+ //#endregion
4333
+ //#region src/extension-catalog/views.ts
4334
+ /** Explicit catalog synchronization result, independent of snapshot availability. */
4335
+ const SyncSchema = z.object({
4336
+ state: z.enum([
4337
+ "idle",
4338
+ "syncing",
4339
+ "succeeded",
4340
+ "failed"
4341
+ ]),
4342
+ taskId: z.uuid().optional(),
4343
+ error: z.string().max(4096).optional(),
4344
+ retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4345
+ }).strict();
4346
+ /** Pure cache-only list response; an empty catalog is a valid successful snapshot. */
4347
+ const ListSchema = z.object({
4348
+ revision: z.number().int().nonnegative(),
4349
+ snapshot: SnapshotSchema.omit({ releases: true }).nullable(),
4350
+ releases: z.array(ReleaseSchema).max(2e3),
4351
+ sync: SyncSchema
4352
+ }).strict();
4353
+ /** Short invalidation carrying no configuration, credentials, or archive bytes. */
4354
+ const CatalogChangedSchema = z.object({
4355
+ revision: z.number().int().nonnegative(),
4356
+ snapshot: z.object({
4357
+ commit: GitShaSchema,
4358
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4359
+ }).strict().optional(),
4360
+ sync: SyncSchema
4361
+ }).strict();
4362
+ /** Confirmation response for a fixed exact extension dependency closure. */
4363
+ const PreviewSchema = z.object({
4364
+ previewToken: z.string().min(1).max(8192),
4365
+ expiresAt: z.iso.datetime({ offset: true }),
4366
+ snapshot: z.object({
4367
+ commit: GitShaSchema,
4368
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4369
+ }).strict(),
4370
+ graphRevision: z.string().max(1024),
4371
+ resolvedSelections: z.array(ReleaseSchema).max(64),
4372
+ dependencies: z.array(z.object({
4373
+ packageName: z.string(),
4374
+ version: z.string()
4375
+ }).strict()).max(64),
4376
+ willEnable: z.array(z.string()).max(2e3),
4377
+ replacing: z.array(z.string()).max(64),
4378
+ affectedOwners: z.array(z.string()).max(2e3),
4379
+ warnings: z.array(ArtifactWarningSchema).max(64)
4380
+ }).strict();
4381
+ /** Durable installation operation facts returned by the generic owner-bound service. */
4382
+ const OperationSchema = z.object({
4383
+ operationId: z.uuid(),
4384
+ attemptId: z.uuid(),
4385
+ issuer: z.string(),
4386
+ submissionDigest: z.string(),
4387
+ requestDigest: z.string(),
4388
+ packageName: z.string(),
4389
+ warnings: z.array(ArtifactWarningSchema).max(3).optional(),
4390
+ warningCount: z.number().int().nonnegative().max(1e5).optional(),
4391
+ rootResults: z.array(z.object({
4392
+ packageName: z.string(),
4393
+ status: z.enum([
4394
+ "pending",
4395
+ "active",
4396
+ "disabled",
4397
+ "deferred",
4398
+ "failed"
4399
+ ]),
4400
+ reason: z.string().max(4096).optional()
4401
+ }).strict()).max(2e3).optional(),
4402
+ phase: z.enum([
4403
+ "preparing",
4404
+ "installing",
4405
+ "admitted",
4406
+ "activating",
4407
+ "settled"
4408
+ ]),
4409
+ currentStep: z.enum([
4410
+ "prepare",
4411
+ "download",
4412
+ "verify",
4413
+ "npm",
4414
+ "admission",
4415
+ "activation",
4416
+ "cleanup"
4417
+ ]),
4418
+ outcome: z.enum([
4419
+ "pending",
4420
+ "succeeded",
4421
+ "failed",
4422
+ "interrupted"
4423
+ ]),
4424
+ failureStage: z.enum([
4425
+ "prepare",
4426
+ "download",
4427
+ "verify",
4428
+ "npm",
4429
+ "admission",
4430
+ "activation",
4431
+ "cleanup",
4432
+ "recovery"
4433
+ ]).optional(),
4434
+ reason: z.string().max(4096).optional(),
4435
+ cleanup: z.enum([
4436
+ "not-needed",
4437
+ "pending",
4438
+ "complete",
4439
+ "failed"
4440
+ ]),
4441
+ startedAt: z.iso.datetime({ offset: true }),
4442
+ settledAt: z.iso.datetime({ offset: true }).optional(),
4443
+ packages: z.array(z.object({
4444
+ packageName: z.string(),
4445
+ beforeRevision: z.number().int().nonnegative(),
4446
+ receiptId: z.uuid().nullable(),
4447
+ diskChanged: z.boolean().optional(),
4448
+ ownerWithdrawn: z.boolean().optional()
4449
+ }).strict()).max(2e3)
4450
+ }).strict();
4451
+ /** Installation progress invalidation; clients query the durable attempt after reconnecting. */
4452
+ const InstallChangedSchema = z.object({
4453
+ operationId: z.uuid(),
4454
+ phase: OperationSchema.shape.phase,
4455
+ currentStep: OperationSchema.shape.currentStep,
4456
+ outcome: OperationSchema.shape.outcome,
4457
+ cleanup: OperationSchema.shape.cleanup,
4458
+ revision: z.number().int().nonnegative()
4459
+ }).strict();
4460
+ /** Current directory source markers and installed metadata for unique package names. */
4461
+ const InstalledSchema = z.object({
4462
+ observedAt: z.iso.datetime({ offset: true }),
4463
+ rows: z.array(InstalledRowSchema).max(2e3)
4464
+ }).strict();
4465
+ /** Existing owner RPC success/failure convention; sanitized errors remain actionable. */
4466
+ function resultSchema(data) {
4467
+ return z.union([z.object({
4468
+ ok: z.literal(true),
4469
+ data
4470
+ }).strict(), z.object({
4471
+ ok: z.literal(false),
4472
+ code: z.string(),
4473
+ message: z.string().max(4096),
4474
+ retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4475
+ }).strict()]);
4476
+ }
4477
+ //#endregion
4478
+ //#region src/extension-catalog/operations.ts
4479
+ /** Nonempty operation identities with per-member and complete encoded-response byte budgets. */
4480
+ const OperationQueriesParams = z.object({
4481
+ operationIds: z.array(z.uuid()).min(1).max(64),
4482
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
4483
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
4484
+ }).strict().superRefine((input, ctx) => {
4485
+ if (input.operationIds.length * input.maxItemBytes + 8192 > input.maxTotalBytes || input.operationIds.some((id) => Buffer.byteLength(JSON.stringify(id)) + 4096 > input.maxItemBytes)) ctx.addIssue({
4486
+ code: "custom",
4487
+ message: "declared operation response exceeds byte budget"
4488
+ });
4346
4489
  });
4347
- const RequestBody = z.discriminatedUnion("method", [
4348
- SessionInstructionsRequest,
4349
- PingRequest,
4350
- ConnectionInfoRequest,
4351
- StatusRequest,
4352
- GatewayShutdownRequest,
4353
- SessionListRequest,
4354
- SessionCreateRequest,
4355
- SessionWatchRequest,
4356
- SessionHistoryPageRequest,
4357
- SessionMessagePartsRequest,
4358
- SessionMessageContentRequest,
4359
- SessionLivePageRequest,
4360
- SessionUnwatchRequest,
4361
- SessionSendRequest,
4362
- SessionForkRequest,
4363
- SessionOperationGetRequest,
4364
- SessionAnswerRequest,
4365
- SessionWithdrawRequest,
4366
- SessionCancelRequest,
4367
- SessionSetModelRequest,
4368
- SessionSetModelParamsRequest,
4369
- SessionArchiveRequest,
4370
- SessionSetNameRequest,
4371
- SessionJoinRequest,
4372
- SessionLeaveRequest,
4373
- ConfigLimitsGetRequest,
4374
- ConfigLimitsSetRequest,
4375
- ConfigAgentListRequest,
4376
- ConfigAgentCreateRequest,
4377
- ConfigPromptSlotsRequest,
4378
- ConfigAgentUpdateRequest,
4379
- ConfigAgentSetPromptSlotRequest,
4380
- ConfigAgentPromptSlotsRequest,
4381
- ConfigAgentSetAvatarRequest,
4382
- ConfigAgentAvatarRequest,
4383
- ConfigAgentSaveRequest,
4384
- ConfigAgentRevisionsRequest,
4385
- ConfigAgentCompareRevisionsRequest,
4386
- ConfigAgentPreviewRestoreRequest,
4387
- ConfigAgentRestoreRevisionRequest,
4388
- ConfigAgentRemoveRequest,
4389
- ConfigToolListRequest,
4390
- InboxListRequest,
4391
- InboxReadRequest,
4392
- InboxReadSessionRequest,
4393
- InboxClearRequest,
4394
- InboxClearReadRequest,
4395
- TriggerListRequest,
4396
- TriggerCreateRequest,
4397
- TriggerUpdateRequest,
4398
- TriggerSetEnabledRequest,
4399
- TriggerRemoveRequest,
4400
- TriggerRunsRequest,
4401
- ProcessListRequest,
4402
- ProcessStopRequest,
4403
- ProcessOutputRequest,
4404
- ConfigWorkspaceListRequest,
4405
- ConfigWorkspaceCreateRequest,
4406
- ConfigWorkspaceUpdateRequest,
4407
- ConfigWorkspaceSetAvatarRequest,
4408
- ConfigWorkspaceAvatarRequest,
4409
- ConfigWorkspaceAddDirectoryRequest,
4410
- ConfigWorkspaceRemoveDirectoryRequest,
4411
- ConfigAccessListRequest,
4412
- ConfigAccessAddRequest,
4413
- ConfigAccessRevokeRequest,
4414
- ConfigCredentialStatusRequest,
4415
- ConfigCredentialSetRequest,
4416
- ConfigCredentialClearRequest,
4417
- StdFsListRequest,
4418
- PluginInstallRequest,
4419
- PluginInstallBatchRequest,
4420
- PluginSetEnabledBatchPreviewRequest,
4421
- PluginSetEnabledBatchRequest,
4422
- PluginRemoveBatchPreviewRequest,
4423
- PluginRemoveBatchRequest,
4424
- PluginRemovePreviewRequest,
4425
- PluginRemoveRequest,
4426
- PluginListRequest,
4427
- PluginSetEnabledPreviewRequest,
4428
- PluginSetEnabledRequest,
4429
- PluginGetConfigRequest,
4430
- PluginSetConfigRequest,
4431
- PluginSurfaceRequest
4432
- ]);
4490
+ /** Safe operation facts in the original request order. */
4491
+ const OperationQueriesData = z.object({ results: z.array(z.discriminatedUnion("ok", [z.object({
4492
+ index: z.number().int().nonnegative().max(63),
4493
+ target: z.uuid(),
4494
+ ok: z.literal(true),
4495
+ value: z.object({ operation: OperationSchema }).strict()
4496
+ }).strict(), z.object({
4497
+ index: z.number().int().nonnegative().max(63),
4498
+ target: z.uuid(),
4499
+ ok: z.literal(false),
4500
+ error: z.object({
4501
+ code: z.string().min(1).max(64),
4502
+ message: z.string().max(512),
4503
+ details: z.object({ retryAfterSeconds: z.number().nonnegative().max(86400) }).strict().optional()
4504
+ }).strict()
4505
+ }).strict()])).min(1).max(64) }).strict();
4506
+ //#endregion
4507
+ //#region src/defaults/service.ts
4508
+ /** Creates one shared initialization attempt scoped to this catalog owner. */
4509
+ function createDefaultsService(options) {
4510
+ const controller = new AbortController();
4511
+ const signal = AbortSignal.any([options.signal, controller.signal]);
4512
+ let active = null;
4513
+ function initial() {
4514
+ return {
4515
+ state: "pending-snapshot",
4516
+ enrolledAt: (/* @__PURE__ */ new Date()).toISOString(),
4517
+ candidates: []
4518
+ };
4519
+ }
4520
+ async function status() {
4521
+ const before = options.store.read() ?? initial();
4522
+ const observations = before.candidates.length ? await options.installer.observe(before.candidates.map((candidate) => candidate.packageName)) : [];
4523
+ const record = options.store.read() ?? initial();
4524
+ const candidates = record.candidates.map(({ artifactIntegrity: _integrity, receiptId, ...candidate }) => {
4525
+ const observed = observations.find((item) => item.packageName === candidate.packageName);
4526
+ const captured = before.candidates.find((item) => item.packageName === candidate.packageName);
4527
+ const matchesCapturedResult = captured?.state === "installed" && captured.receiptId === receiptId && captured.operationId === candidate.operationId && captured.releaseId === candidate.releaseId;
4528
+ if (candidate.state === "installed" && matchesCapturedResult && observed) {
4529
+ if (!observed.declared.installed || !observed.declared.enabled || receiptId && observed.receipt?.receiptId !== receiptId) {
4530
+ candidate.state = "user-managed";
4531
+ candidate.reasonCode = "USER_DECLARATION_PRESERVED";
4532
+ delete candidate.activation;
4533
+ } else {
4534
+ const activation = observed.activation ?? (observed.summary?.status === "active" ? "active" : observed.summary?.status === "failed" ? "failed" : void 0);
4535
+ if (activation) candidate.activation = activation;
4536
+ }
4537
+ }
4538
+ return candidate;
4539
+ });
4540
+ return DefaultsStatusSchema.parse({
4541
+ state: active ? "working" : record.state === "complete" ? "complete" : record.state === "pending-snapshot" ? "pending-snapshot" : "pending",
4542
+ taskId: active?.id ?? null,
4543
+ operationId: record.currentOperationId ?? null,
4544
+ counts: {
4545
+ installed: candidates.filter((c) => c.state === "installed").length,
4546
+ pending: candidates.filter((c) => c.state === "pending").length,
4547
+ skipped: candidates.filter((c) => c.state === "skipped" || c.state === "user-managed").length
4548
+ },
4549
+ activationDeferred: candidates.filter((c) => c.state === "installed" && c.activation === "deferred").length,
4550
+ candidates,
4551
+ ...record.lastReasonCode ? { reasonCode: record.lastReasonCode } : {},
4552
+ ...record.retryNotBefore ? { retryAfterSeconds: Math.min(86400, Math.max(0, Math.ceil((Date.parse(record.retryNotBefore) - Date.now()) / 1e3))) } : {}
4553
+ });
4554
+ }
4555
+ function persist(record) {
4556
+ if (record.snapshot) record.state = record.candidates.some((c) => c.state === "pending") ? "pending" : "complete";
4557
+ return options.store.save(record);
4558
+ }
4559
+ async function applyOperation(record, operation) {
4560
+ for (const candidate of record.candidates.filter((c) => c.operationId === operation.operationId && c.state === "pending")) {
4561
+ const packageResult = operation.packages.find((p) => p.packageName === candidate.packageName);
4562
+ const rootResult = operation.rootResults?.find((r) => r.packageName === candidate.packageName);
4563
+ if (packageResult?.receiptId) {
4564
+ candidate.state = "installed";
4565
+ candidate.receiptId = packageResult.receiptId;
4566
+ candidate.activation = rootResult?.status === "active" ? "active" : rootResult?.status === "deferred" ? "deferred" : "failed";
4567
+ delete candidate.reasonCode;
4568
+ } else if (operation.phase === "settled" && operation.outcome !== "pending") {
4569
+ candidate.reasonCode = "INSTALL_FAILED";
4570
+ record.lastReasonCode = "INSTALL_FAILED";
4571
+ }
4572
+ }
4573
+ if (record.lastReasonCode === "INSTALL_FAILED" && !record.candidates.some((candidate) => candidate.state === "pending")) delete record.lastReasonCode;
4574
+ persist(record);
4575
+ }
4576
+ async function joinOperation(operationId) {
4577
+ let operation = await options.installer.join(operationId);
4578
+ while (operation.cleanup === "failed" || operation.cleanup === "pending") {
4579
+ try {
4580
+ operation = await options.installer.retryCleanup(operationId);
4581
+ } catch {
4582
+ await setTimeout$1(250);
4583
+ continue;
4584
+ }
4585
+ if (operation.cleanup === "failed" || operation.cleanup === "pending") await setTimeout$1(250);
4586
+ }
4587
+ return operation;
4588
+ }
4589
+ async function recover(record) {
4590
+ const operationIds = [...new Set(record.candidates.filter((c) => c.state === "pending").map((c) => c.operationId).filter((id) => !!id))];
4591
+ for (const id of operationIds) {
4592
+ let operation;
4593
+ try {
4594
+ operation = await options.installer.operation(id);
4595
+ } catch (error) {
4596
+ if (managementError(error).code !== "OPERATION_NOT_FOUND") throw error;
4597
+ continue;
4598
+ }
4599
+ operation = await joinOperation(id);
4600
+ await applyOperation(record, operation);
4601
+ if (operation.phase !== "settled" || operation.outcome === "pending") throw new CatalogError("RECOVERY_PENDING", "The original default installation attempt is not settled");
4602
+ }
4603
+ }
4604
+ async function run(attempt) {
4605
+ let record = options.store.read() ?? options.store.save(initial());
4606
+ delete record.lastReasonCode;
4607
+ delete record.retryNotBefore;
4608
+ await recover(record);
4609
+ if (record.state === "complete") return;
4610
+ const snapshot = await options.acquireSnapshot(attempt);
4611
+ attempt.signal.throwIfAborted();
4612
+ if (!record.snapshot) {
4613
+ const chosen = /* @__PURE__ */ new Map();
4614
+ for (const release of snapshot.releases) {
4615
+ if (release.defaultInstall !== true || !releaseCompatible(release, options.identity)) continue;
4616
+ const before = chosen.get(release.packageName);
4617
+ if (!before || semver.gt(release.version, before.version)) chosen.set(release.packageName, release);
4618
+ }
4619
+ if (chosen.size > 64) throw new CatalogError("LIMIT_EXCEEDED", "Default extension cohort exceeds 64 roots");
4620
+ record = await options.installer.coordinate(() => options.store.save({
4621
+ ...record,
4622
+ state: chosen.size ? "frozen" : "complete",
4623
+ snapshot: {
4624
+ commit: snapshot.commit,
4625
+ contentDigest: snapshot.contentDigest
4626
+ },
4627
+ host: {
4628
+ version: options.identity.version,
4629
+ ...options.identity.target
4630
+ },
4631
+ candidates: [...chosen.values()].sort((a, b) => a.packageName < b.packageName ? -1 : a.packageName > b.packageName ? 1 : 0).map((r) => ({
4632
+ packageName: r.packageName,
4633
+ releaseId: r.releaseId,
4634
+ artifactIntegrity: r.artifact.integrity,
4635
+ state: "pending"
4636
+ }))
4637
+ }));
4638
+ }
4639
+ if (record.state === "complete") return;
4640
+ const observations = await options.installer.observe();
4641
+ for (const candidate of record.candidates.filter((c) => c.state === "pending")) if (observations.some((o) => o.packageName === candidate.packageName && o.declared.origin !== void 0)) {
4642
+ candidate.state = "user-managed";
4643
+ candidate.reasonCode = "USER_DECLARATION_PRESERVED";
4644
+ } else {
4645
+ const release = snapshot.releases.find((r) => r.releaseId === candidate.releaseId && r.artifact.integrity === candidate.artifactIntegrity);
4646
+ if (!release || release.defaultInstall !== true || !releaseCompatible(release, options.identity)) {
4647
+ candidate.state = "skipped";
4648
+ candidate.reasonCode = "RELEASE_REVOKED";
4649
+ }
4650
+ }
4651
+ persist(record);
4652
+ const roots = record.candidates.filter((c) => c.state === "pending");
4653
+ if (!roots.length) return;
4654
+ const plan = await options.preview(roots.map((c) => ({
4655
+ snapshotCommit: snapshot.commit,
4656
+ releaseId: c.releaseId,
4657
+ artifactIntegrity: c.artifactIntegrity
4658
+ })), attempt);
4659
+ attempt.signal.throwIfAborted();
4660
+ const operationId = randomUUID();
4661
+ record.currentOperationId = operationId;
4662
+ record.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
4663
+ for (const candidate of roots) candidate.operationId = operationId;
4664
+ persist(record);
4665
+ try {
4666
+ await options.installer.install({
4667
+ operationId,
4668
+ token: plan.previewToken
4669
+ }, attempt);
4670
+ } catch (error) {
4671
+ try {
4672
+ await options.installer.operation(operationId);
4673
+ } catch {
4674
+ throw error;
4675
+ }
4676
+ }
4677
+ const operation = await joinOperation(operationId);
4678
+ await applyOperation(record, operation);
4679
+ }
4680
+ return {
4681
+ /** Starts one shared bounded attempt immediately; completed initialization performs no network work. */
4682
+ async ensure(input) {
4683
+ signal.throwIfAborted();
4684
+ const params = DefaultsEnsureParamsSchema.parse(input);
4685
+ if (params.expectedProductVersion !== options.identity.version) throw new CatalogError("PRODUCT_VERSION_MISMATCH", "Default installation requires the current product version");
4686
+ const record = options.store.read() ?? initial();
4687
+ if (active) return {
4688
+ taskId: active.id,
4689
+ status: await status()
4690
+ };
4691
+ if (record.state === "complete" || record.retryNotBefore && Date.parse(record.retryNotBefore) > Date.now()) return {
4692
+ taskId: null,
4693
+ status: await status()
4694
+ };
4695
+ const id = randomUUID(), deadline = performance.now() + Math.min(18e4, params.remainingWorkMs);
4696
+ const timerController = new AbortController();
4697
+ const timer = setTimeout(() => timerController.abort(/* @__PURE__ */ new Error("Default installation work budget exhausted")), Math.max(1, deadline - performance.now()));
4698
+ const attempt = {
4699
+ signal: AbortSignal.any([signal, timerController.signal]),
4700
+ remainingWorkMs: () => Math.max(0, deadline - performance.now())
4701
+ };
4702
+ const work = Promise.resolve().then(() => run(attempt)).catch((error) => {
4703
+ const record = options.store.read() ?? initial(), failure = managementError(error);
4704
+ record.lastReasonCode = attempt.signal.aborted ? "ATTEMPT_CANCELLED" : failure.code;
4705
+ for (const candidate of record.candidates.filter((c) => c.state === "pending")) candidate.reasonCode = record.lastReasonCode;
4706
+ if (failure.retryAfterSeconds !== void 0) record.retryNotBefore = new Date(Date.now() + failure.retryAfterSeconds * 1e3).toISOString();
4707
+ persist(record);
4708
+ }).finally(() => {
4709
+ clearTimeout(timer);
4710
+ active = null;
4711
+ });
4712
+ work.catch(() => {});
4713
+ active = {
4714
+ id,
4715
+ work
4716
+ };
4717
+ return {
4718
+ taskId: id,
4719
+ status: await status()
4720
+ };
4721
+ },
4722
+ /** Projects current readonly installation facts over retained history; never enrolls or installs. */
4723
+ status,
4724
+ /** Cancels this automatic attempt and joins all work before releasing the owner's resources. */
4725
+ async dispose() {
4726
+ controller.abort(/* @__PURE__ */ new Error("Default installation owner is draining"));
4727
+ await active?.work;
4728
+ }
4729
+ };
4730
+ }
4731
+ //#endregion
4732
+ //#region src/extension-catalog/sync.ts
4733
+ /** Git smart HTTP ref advertisement for the catalog repository. */
4734
+ const CATALOG_REFS_URL = "https://github.com/yanxuan-lc/yaoguang-presets.git/info/refs?service=git-upload-pack";
4735
+ /** Raw content URL of the extension index pinned to one commit. */
4736
+ const catalogIndexUrl = (commit) => `https://raw.githubusercontent.com/yanxuan-lc/yaoguang-presets/${commit}/extensions/index.json`;
4737
+ const REFS_MAX_BYTES = 1048576;
4738
+ const headers = { "User-Agent": "YaoGuang-extensions" };
4433
4739
  /**
4434
- * A request naming a method some plugin declared while this gateway was
4435
- * running.
4436
- *
4437
- * The name is checked against the minting rule and **the parameters are not
4438
- * read at all**: their shape is the plugin's zod, validated in the gateway,
4439
- * and a second opinion here would be a second writer of someone else's
4440
- * contract.
4441
- *
4442
- * `method` is a template literal type rather than a bare `string`, and that is
4443
- * load-bearing: one `string` discriminant in this union and
4444
- * `body.method === 'session.send'` stops narrowing, which takes every `switch`
4445
- * that reads `body.params` afterwards down with it.
4446
- *
4447
- * `params` is optional because a call that takes none sends no key —
4448
- * `JSON.stringify` drops an `undefined` — and a frame this schema refuses is
4449
- * dropped in silence rather than answered. Bare `z.unknown()` would not
4450
- * serve: zod 4 treats it as a required key, which would refuse exactly the
4451
- * paramsless calls this field is meant to admit.
4740
+ * Returns the commit of `refs/heads/main` from a Git smart HTTP upload-pack advertisement.
4741
+ * Requires the leading service announcement and well-formed pkt-lines; any other shape,
4742
+ * including a missing main branch, is rejected as an invalid catalog.
4452
4743
  */
4453
- const PluginRequestBody = z.object({
4454
- method: PluginWireName,
4455
- params: z.unknown().optional()
4456
- });
4457
- /** One business request from a client. Authentication is a separate control
4458
- * frame.
4459
- *
4460
- * The body is widened one layer out rather than `RequestBody` itself: the
4461
- * core union stays a `discriminatedUnion` of names known at compile time,
4462
- * and a plugin's runtime-minted name sits beside it. */
4463
- const RequestFrame = z.object({
4464
- kind: z.literal("request"),
4465
- id: z.string(),
4466
- body: z.union([RequestBody, PluginRequestBody])
4467
- });
4468
- /** Supplies the credential for one WebSocket connection. */
4469
- const AuthenticationFrame = z.object({
4470
- kind: z.literal("authentication"),
4471
- id: z.string().min(1).max(128),
4472
- token: z.string().max(256)
4473
- });
4474
- z.discriminatedUnion("kind", [RequestFrame, AuthenticationFrame]);
4475
- z.object({ authenticated: z.literal(true) });
4476
- z.enum(["auth-required", "auth-failed"]);
4477
- z.enum([
4478
- "history_conflict",
4479
- "session_busy",
4480
- "cut_unavailable",
4481
- "source_unavailable",
4482
- "file_unavailable",
4483
- "operation_conflict",
4484
- "history_preparing",
4485
- "history_unavailable",
4486
- "history_invalid",
4487
- "history_stale",
4488
- "history_cursor_invalid",
4489
- "history_worker_unavailable",
4490
- "reading_lease_invalid",
4491
- "content_unavailable",
4492
- "content_stale",
4493
- "message_unavailable",
4494
- "invalid_range"
4495
- ]);
4496
- z.enum(["configuration_write_rejected", "configuration_recovery_required"]);
4497
- /** A bounded machine-readable refusal identifier; owner business codes are not enumerated by core. */
4498
- const RequestErrorCode = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/);
4499
- /** Gateway -> client: the answer to one request, addressed by its id. */
4500
- const ResultFrame = z.object({
4501
- kind: z.literal("result"),
4502
- id: z.string(),
4503
- ok: z.boolean(),
4504
- data: z.unknown().optional(),
4505
- error: z.string().optional(),
4506
- errorCode: RequestErrorCode.optional(),
4507
- /** Recoverable reading preparation lease and suggested polling interval. */
4508
- readingDetails: z.object({
4509
- readingLeaseId: z.string().optional(),
4510
- retryAfterMs: z.number().int().positive().optional()
4511
- }).optional()
4512
- });
4513
- /** Gateway -> the connections that care: something happened. Carries no id,
4514
- * because no one asked for it. */
4515
- const EventFrame = z.object({
4516
- kind: z.literal("event"),
4517
- event: Frame
4518
- });
4519
- z.discriminatedUnion("kind", [ResultFrame, EventFrame]);
4520
- z.object({
4521
- instanceId: z.uuid(),
4522
- gatewayVersion: z.string(),
4523
- protocolVersion: z.string(),
4524
- clientCount: z.number().int(),
4525
- uptimeMs: z.number().int(),
4526
- pid: z.number().int()
4527
- });
4744
+ function parseMainCommit(bytes) {
4745
+ const text = Buffer.from(bytes).toString("latin1");
4746
+ const lines = [];
4747
+ for (let at = 0; at < text.length;) {
4748
+ const prefix = text.slice(at, at + 4);
4749
+ if (!/^[0-9a-f]{4}$/.test(prefix)) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4750
+ const length = Number.parseInt(prefix, 16);
4751
+ if (length === 0) {
4752
+ lines.push(null);
4753
+ at += 4;
4754
+ continue;
4755
+ }
4756
+ if (length < 4 || at + length > text.length) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4757
+ lines.push(text.slice(at + 4, at + length).replace(/\n$/, ""));
4758
+ at += length;
4759
+ }
4760
+ if (lines[0] !== "# service=git-upload-pack" || lines[1] !== null) throw new CatalogError("CATALOG_INVALID", "Missing upload-pack service announcement");
4761
+ for (const line of lines.slice(2)) {
4762
+ if (line === null) continue;
4763
+ const match = /^([0-9a-f]{40}) ([^\0]+)(?:\0.*)?$/s.exec(line);
4764
+ if (!match) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4765
+ if (match[2] === "refs/heads/main") return match[1];
4766
+ }
4767
+ throw new CatalogError("CATALOG_INVALID", "Catalog repository has no main branch");
4768
+ }
4769
+ /**
4770
+ * Reads a bounded response without credentials, redirects, or remote-body diagnostics.
4771
+ * A failed status becomes `SYNC_FAILED`, with a retry delay (at most one day) taken from
4772
+ * `retry-after`, or from `x-ratelimit-reset` for 429 and exhausted-quota 403 responses.
4773
+ * A 404 throws the error built by `notFound` when it is supplied.
4774
+ */
4775
+ async function readBoundedResponse(network, url, signal, maxBytes, headers = {}, notFound) {
4776
+ signal.throwIfAborted();
4777
+ const response = await network.fetch(url, {
4778
+ signal,
4779
+ redirect: "error",
4780
+ headers
4781
+ });
4782
+ if (!response.ok) {
4783
+ await response.body?.cancel().catch(() => {});
4784
+ if (response.status === 404 && notFound) throw notFound();
4785
+ let retry = Number(response.headers.get("retry-after"));
4786
+ if (!(Number.isFinite(retry) && retry > 0) && (response.status === 429 || response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0")) retry = Number(response.headers.get("x-ratelimit-reset")) - Math.floor(Date.now() / 1e3);
4787
+ throw new CatalogError("SYNC_FAILED", `Request failed (HTTP ${response.status})`, Number.isFinite(retry) && retry > 0 ? Math.min(86400, retry) : void 0);
4788
+ }
4789
+ if (Number(response.headers.get("content-length")) > maxBytes) {
4790
+ await response.body?.cancel().catch(() => {});
4791
+ throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
4792
+ }
4793
+ const reader = response.body?.getReader();
4794
+ if (!reader) return /* @__PURE__ */ new Uint8Array();
4795
+ const chunks = [];
4796
+ let size = 0;
4797
+ try {
4798
+ for (;;) {
4799
+ signal.throwIfAborted();
4800
+ const chunk = await reader.read();
4801
+ if (chunk.done) break;
4802
+ size += chunk.value.length;
4803
+ if (size > maxBytes) throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
4804
+ chunks.push(chunk.value);
4805
+ }
4806
+ signal.throwIfAborted();
4807
+ return Buffer.concat(chunks, size);
4808
+ } finally {
4809
+ await reader.cancel().catch(() => {});
4810
+ reader.releaseLock();
4811
+ }
4812
+ }
4813
+ /**
4814
+ * Resolves the catalog's main commit with one ref advertisement request, then reads the complete
4815
+ * extension index pinned to that commit. An unchanged commit reuses `previous` with a new fetch
4816
+ * time. Requests carry no credentials, refuse redirects and share an 8 MiB budget and 30 s limit.
4817
+ */
4818
+ async function synchronize(network, ownerSignal, previous) {
4819
+ const controller = new AbortController();
4820
+ const signal = AbortSignal.any([ownerSignal, controller.signal]);
4821
+ const timer = setTimeout(() => controller.abort(new CatalogError("SYNC_FAILED", "Catalog synchronization exceeded 30 seconds")), 3e4);
4822
+ try {
4823
+ const commit = parseMainCommit(await readBoundedResponse(network, CATALOG_REFS_URL, signal, REFS_MAX_BYTES, headers));
4824
+ if (previous?.commit === commit) return {
4825
+ ...previous,
4826
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
4827
+ };
4828
+ const releases = decodeReleases(parseJson(decodeUtf8(await readBoundedResponse(network, catalogIndexUrl(commit), signal, CATALOG_MAX_BYTES, headers, () => new CatalogError("CATALOG_UNAVAILABLE", "No extension index is available")))));
4829
+ return {
4830
+ repository: CATALOG_REPOSITORY,
4831
+ commit,
4832
+ contentDigest: recordDigest({ releases }),
4833
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
4834
+ revision: previous?.revision ?? 0,
4835
+ releases
4836
+ };
4837
+ } catch (error) {
4838
+ controller.abort(error);
4839
+ if (error instanceof CatalogError) throw error;
4840
+ if (ownerSignal.aborted) throw ownerSignal.reason;
4841
+ throw new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful snapshot is retained");
4842
+ } finally {
4843
+ clearTimeout(timer);
4844
+ }
4845
+ }
4846
+ //#endregion
4847
+ //#region src/extension-catalog/service.ts
4848
+ /** Creates local catalog reads and explicit synchronization, preview, and operation management. */
4849
+ function createCatalogService(options) {
4850
+ let snapshot = null;
4851
+ let sync = { state: "idle" };
4852
+ try {
4853
+ snapshot = options.store.read();
4854
+ } catch {
4855
+ sync = {
4856
+ state: "failed",
4857
+ error: "Catalog cache is damaged; refresh to repair it"
4858
+ };
4859
+ }
4860
+ const controller = new AbortController();
4861
+ const signal = AbortSignal.any([options.signal, controller.signal]);
4862
+ const ownedTasks = /* @__PURE__ */ new Set();
4863
+ let synchronization = null;
4864
+ function notifySynchronization() {
4865
+ if (!signal.aborted) options.notify?.({
4866
+ revision: snapshot?.revision ?? 0,
4867
+ ...snapshot ? { snapshot: {
4868
+ commit: snapshot.commit,
4869
+ contentDigest: snapshot.contentDigest
4870
+ } } : {},
4871
+ sync: { ...sync }
4872
+ });
4873
+ }
4874
+ function sharedSynchronization(manual = false) {
4875
+ signal.throwIfAborted();
4876
+ if (synchronization) {
4877
+ if (manual) synchronization.manual = true;
4878
+ return synchronization;
4879
+ }
4880
+ const taskId = randomUUID(), taskController = new AbortController(), taskSignal = AbortSignal.any([signal, taskController.signal]);
4881
+ sync = {
4882
+ state: "syncing",
4883
+ taskId
4884
+ };
4885
+ const work = Promise.resolve().then(async () => {
4886
+ try {
4887
+ const acquired = await synchronize(options.network, taskSignal, snapshot);
4888
+ const saved = await options.installer.coordinate(() => {
4889
+ taskSignal.throwIfAborted();
4890
+ snapshot = options.store.save(acquired);
4891
+ return snapshot;
4892
+ });
4893
+ sync = {
4894
+ state: "succeeded",
4895
+ taskId
4896
+ };
4897
+ return saved;
4898
+ } catch (error) {
4899
+ const failure = error instanceof CatalogError ? error : new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful data is retained");
4900
+ sync = {
4901
+ state: "failed",
4902
+ taskId,
4903
+ error: failure.message,
4904
+ ...failure.retryAfterSeconds === void 0 ? {} : { retryAfterSeconds: failure.retryAfterSeconds }
4905
+ };
4906
+ throw failure;
4907
+ } finally {
4908
+ synchronization = null;
4909
+ notifySynchronization();
4910
+ }
4911
+ });
4912
+ synchronization = {
4913
+ taskId,
4914
+ controller: taskController,
4915
+ manual,
4916
+ consumers: /* @__PURE__ */ new Set(),
4917
+ work
4918
+ };
4919
+ ownedTasks.add(work);
4920
+ work.then(() => ownedTasks.delete(work), () => ownedTasks.delete(work));
4921
+ notifySynchronization();
4922
+ return synchronization;
4923
+ }
4924
+ async function acquireFreshSnapshot(attempt) {
4925
+ const consumerSignal = AbortSignal.any([signal, attempt.signal]);
4926
+ consumerSignal.throwIfAborted();
4927
+ const task = sharedSynchronization(), consumer = Symbol();
4928
+ task.consumers.add(consumer);
4929
+ let onAbort;
4930
+ const cancelled = new Promise((_resolve, reject) => {
4931
+ onAbort = () => {
4932
+ task.consumers.delete(consumer);
4933
+ if (!task.manual && !task.consumers.size) task.controller.abort(consumerSignal.reason);
4934
+ reject(consumerSignal.reason);
4935
+ };
4936
+ consumerSignal.addEventListener("abort", onAbort, { once: true });
4937
+ if (consumerSignal.aborted) onAbort();
4938
+ });
4939
+ try {
4940
+ const acquired = await Promise.race([task.work, cancelled]);
4941
+ consumerSignal.throwIfAborted();
4942
+ return acquired;
4943
+ } catch (error) {
4944
+ if (consumerSignal.aborted && !task.manual && !task.consumers.size) {
4945
+ task.controller.abort(consumerSignal.reason);
4946
+ await Promise.allSettled([task.work]);
4947
+ }
4948
+ throw error;
4949
+ } finally {
4950
+ task.consumers.delete(consumer);
4951
+ consumerSignal.removeEventListener("abort", onAbort);
4952
+ }
4953
+ }
4954
+ /** Prepares exact roots and one shared extension closure without imports or activation. */
4955
+ async function preview(inputs, enableNames = [], batch = false, attempt, automatic = false) {
4956
+ const preparationSignal = attempt ? AbortSignal.any([signal, attempt.signal]) : signal;
4957
+ preparationSignal.throwIfAborted();
4958
+ const selections = inputs.map((input) => SelectionSchema.parse(input)), selectedSnapshot = snapshot;
4959
+ if (!selections.length || selections.length > 64 || enableNames.length > 2e3) throw new CatalogError("LIMIT_EXCEEDED", "Select between one and 64 exact extension roots");
4960
+ if (!selectedSnapshot) throw new CatalogError("CATALOG_UNAVAILABLE", "Refresh the extension catalog before selecting a release");
4961
+ const accepted = structuredClone(selectedSnapshot);
4962
+ const selectedHost = options.hostIdentity;
4963
+ if (!selectedHost) throw new CatalogError("RELEASE_INCOMPATIBLE", "Current product and host target are unavailable");
4964
+ const host = selectedHost;
4965
+ const observations = await options.installer.observe();
4966
+ const roots = [];
4967
+ for (const selection of selections) {
4968
+ if (selection.snapshotCommit !== accepted.commit) throw new CatalogError("STALE_PREVIEW", "Selected catalog commit is no longer current");
4969
+ const release = accepted.releases.find((r) => r.releaseId === selection.releaseId);
4970
+ if (!release || release.artifact.integrity !== selection.artifactIntegrity) throw new CatalogError("RELEASE_UNLISTED", "Selected exact release is not listed");
4971
+ if (!releaseCompatible(release, host)) throw new CatalogError("RELEASE_INCOMPATIBLE", "Selected release does not accept the current product and host target");
4972
+ const existing = observations.find((o) => o.packageName === release.packageName);
4973
+ if (automatic && existing?.declared.origin !== void 0) throw new CatalogError("STALE_PREVIEW", "A user declaration now owns this default extension");
4974
+ if (selection.expectedInstalledReceiptId !== void 0 && existing?.receipt?.receiptId !== selection.expectedInstalledReceiptId) throw new CatalogError("STALE_PREVIEW", "Current installed receipt differs from the displayed selection");
4975
+ const prior = roots.find((r) => r.packageName === release.packageName);
4976
+ if (prior && recordDigest(prior) !== recordDigest(release)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension roots select conflicting exact releases");
4977
+ if (!prior) roots.push(release);
4978
+ }
4979
+ const resolved = [], chosen = new Map(roots.map((root) => [root.packageName, root])), expanded = /* @__PURE__ */ new Set();
4980
+ async function expand(candidate) {
4981
+ const prior = chosen.get(candidate.packageName);
4982
+ if (prior) {
4983
+ if (prior.releaseId !== candidate.releaseId) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension requirements select conflicting exact releases");
4984
+ if (expanded.has(candidate.packageName)) return;
4985
+ }
4986
+ if (!prior && chosen.size >= 64) throw new CatalogError("LIMIT_EXCEEDED", "Extension closure exceeds 64 packages");
4987
+ chosen.set(candidate.packageName, candidate);
4988
+ expanded.add(candidate.packageName);
4989
+ resolved.push(candidate);
4990
+ const raw = (await options.installer.inspect({
4991
+ expectedName: candidate.packageName,
4992
+ expectedVersion: candidate.version,
4993
+ ...candidate.artifact
4994
+ }, preparationSignal, attempt)).yaoguang?.dependencies ?? {};
4995
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).length > 64) throw new CatalogError("ARTIFACT_INVALID", "Invalid extension dependency declaration");
4996
+ for (const [name, range] of Object.entries(raw)) {
4997
+ if (typeof range !== "string" || semver.validRange(range) === null) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension dependency has an invalid version range");
4998
+ const selected = chosen.get(name);
4999
+ if (selected) {
5000
+ if (!semver.satisfies(selected.version, range)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Exact closure cannot satisfy all extension requirements");
5001
+ continue;
5002
+ }
5003
+ const installed = observations.find((o) => o.packageName === name && o.declared.origin !== void 0);
5004
+ if (automatic && installed && (!installed.declared.installed || !installed.declared.enabled)) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency declaration does not permit default installation");
5005
+ const installedVersion = installed?.receipt?.version ?? installed?.declared.version ?? installed?.summary?.version;
5006
+ if (installedVersion && semver.valid(installedVersion) && semver.satisfies(installedVersion, range)) continue;
5007
+ if (automatic && installed) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency version cannot be replaced by default installation");
5008
+ const choices = accepted.releases.filter((r) => r.packageName === name && semver.satisfies(r.version, range) && releaseCompatible(r, host));
5009
+ if (choices.length !== 1) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Missing extension dependency has no unique compatible exact release");
5010
+ await expand(choices[0]);
5011
+ }
5012
+ }
5013
+ for (const root of roots) await expand(root);
5014
+ function evidence(candidate) {
5015
+ return {
5016
+ expectedName: candidate.packageName,
5017
+ expectedVersion: candidate.version,
5018
+ ...candidate.artifact,
5019
+ sourceRecord: {
5020
+ snapshot: {
5021
+ repository: accepted.repository,
5022
+ commit: accepted.commit,
5023
+ contentDigest: accepted.contentDigest
5024
+ },
5025
+ release: candidate,
5026
+ releaseDigest: recordDigest(candidate)
5027
+ },
5028
+ activationConstraints: {
5029
+ hostVersionRange: candidate.compatibility.productRange,
5030
+ platformTargets: candidate.compatibility.platforms
5031
+ },
5032
+ display: {
5033
+ label: typeof candidate.displayName === "string" ? candidate.displayName : candidate.displayName["en-US"],
5034
+ detail: "Historical catalog admission"
5035
+ }
5036
+ };
5037
+ }
5038
+ const validate = () => {
5039
+ if (snapshot?.commit !== accepted.commit || snapshot.contentDigest !== accepted.contentDigest || snapshot.revision !== accepted.revision || resolved.some((r) => !snapshot.releases.some((current) => current.releaseId === r.releaseId && recordDigest(current) === recordDigest(r)))) throw new CatalogError("STALE_PREVIEW", "Catalog changed after preview; select the new exact release explicitly");
5040
+ };
5041
+ preparationSignal.throwIfAborted();
5042
+ validate();
5043
+ const rootNames = new Set(roots.map((root) => root.packageName));
5044
+ const dependencies = resolved.filter((record) => !rootNames.has(record.packageName)).map(evidence);
5045
+ const preview = batch ? await options.installer.previewBatch({
5046
+ roots: roots.map(evidence),
5047
+ dependencies,
5048
+ enabled: true,
5049
+ enableNames
5050
+ }, validate, attempt) : await options.installer.preview({
5051
+ ...evidence(roots[0]),
5052
+ enabled: true,
5053
+ dependencies
5054
+ }, validate, attempt);
5055
+ preparationSignal.throwIfAborted();
5056
+ if (automatic && preview.replacing.length) throw new CatalogError("STALE_PREVIEW", "Default installation cannot replace existing extensions");
5057
+ return {
5058
+ previewToken: preview.token,
5059
+ expiresAt: preview.expiresAt,
5060
+ snapshot: {
5061
+ commit: accepted.commit,
5062
+ contentDigest: accepted.contentDigest
5063
+ },
5064
+ graphRevision: preview.graphRevision,
5065
+ resolvedSelections: resolved,
5066
+ dependencies: preview.selections.filter((selection) => !rootNames.has(selection.expectedName)).map((s) => ({
5067
+ packageName: s.expectedName,
5068
+ version: s.expectedVersion
5069
+ })),
5070
+ willEnable: [...preview.willEnable],
5071
+ replacing: [...preview.replacing],
5072
+ affectedOwners: [...preview.affectedOwners],
5073
+ warnings: []
5074
+ };
5075
+ }
5076
+ const defaults = options.defaultsStore && options.hostIdentity ? createDefaultsService({
5077
+ store: options.defaultsStore,
5078
+ identity: options.hostIdentity,
5079
+ installer: options.installer,
5080
+ signal,
5081
+ preview: (selections, attempt) => preview(selections, [], true, attempt, true),
5082
+ acquireSnapshot: acquireFreshSnapshot
5083
+ }) : null;
5084
+ function requireDefaults() {
5085
+ if (!defaults) throw new CatalogError("DEFAULTS_UNAVAILABLE", "Default extension initialization is unavailable for this host");
5086
+ return defaults;
5087
+ }
5088
+ return {
5089
+ /** Starts or shares this owner's one-shot bounded automatic installation task. */
5090
+ defaultsEnsure(input) {
5091
+ return requireDefaults().ensure(input);
5092
+ },
5093
+ /** Returns passive initialization facts without refreshing or enrolling. */
5094
+ defaultsStatus() {
5095
+ return requireDefaults().status();
5096
+ },
5097
+ /** Returns cached data only; first use and failure never trigger network work. */
5098
+ list() {
5099
+ signal.throwIfAborted();
5100
+ if (!snapshot) return {
5101
+ revision: 0,
5102
+ snapshot: null,
5103
+ releases: [],
5104
+ sync: { ...sync }
5105
+ };
5106
+ const { releases, ...metadata } = snapshot;
5107
+ return {
5108
+ revision: snapshot.revision,
5109
+ snapshot: metadata,
5110
+ releases,
5111
+ sync: { ...sync }
5112
+ };
5113
+ },
5114
+ /** Joins the active fresh synchronization; manual work survives automatic attempt cancellation. */
5115
+ refresh() {
5116
+ return {
5117
+ taskId: sharedSynchronization(true).taskId,
5118
+ sync: { ...sync }
5119
+ };
5120
+ },
5121
+ /** Previews installation with target enablement and joins owned preparation before disposal. */
5122
+ preview(input) {
5123
+ const task = preview([input]);
5124
+ ownedTasks.add(task);
5125
+ task.then(() => {
5126
+ ownedTasks.delete(task);
5127
+ }, () => {
5128
+ ownedTasks.delete(task);
5129
+ });
5130
+ return task;
5131
+ },
5132
+ /** Prepares one approved union of exact roots and existing owners to enable. */
5133
+ previewBatch(inputs, enableNames = []) {
5134
+ const task = preview(inputs, enableNames, true);
5135
+ ownedTasks.add(task);
5136
+ task.then(() => ownedTasks.delete(task), () => ownedTasks.delete(task));
5137
+ return task;
5138
+ },
5139
+ /** Delegates deduplication before any token or current-snapshot validation. */
5140
+ install(operationId, previewToken) {
5141
+ signal.throwIfAborted();
5142
+ return options.installer.install({
5143
+ operationId,
5144
+ token: previewToken
5145
+ });
5146
+ },
5147
+ /** Reads an existing durable attempt without restarting work. */
5148
+ operation(operationId) {
5149
+ return options.installer.operation(operationId);
5150
+ },
5151
+ /** Retries only cleanup still owned by the queried attempt. */
5152
+ retryCleanup(operationId) {
5153
+ return options.installer.retryCleanup(operationId);
5154
+ },
5155
+ /** Projects installed metadata against the current cached directory without reading files. */
5156
+ async installed() {
5157
+ signal.throwIfAborted();
5158
+ const observations = await options.installer.observe();
5159
+ return {
5160
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
5161
+ rows: projectInstalled(observations, snapshot, options.hostIdentity)
5162
+ };
5163
+ },
5164
+ /** Joins all discovery work before owner disposal completes. */
5165
+ async dispose() {
5166
+ controller.abort(/* @__PURE__ */ new Error("Catalog owner withdrawn"));
5167
+ await Promise.all([defaults?.dispose(), Promise.allSettled([...ownedTasks])]);
5168
+ }
5169
+ };
5170
+ }
4528
5171
  //#endregion
4529
- //#region src/extension-catalog/views.ts
4530
- /** Explicit catalog synchronization result, independent of snapshot availability. */
4531
- const SyncSchema = z.object({
4532
- state: z.enum([
4533
- "idle",
4534
- "syncing",
4535
- "succeeded",
4536
- "failed"
4537
- ]),
4538
- taskId: z.uuid().optional(),
4539
- error: z.string().max(4096).optional(),
4540
- retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4541
- }).strict();
4542
- /** Pure cache-only list response; an empty catalog is a valid successful snapshot. */
4543
- const ListSchema = z.object({
4544
- revision: z.number().int().nonnegative(),
4545
- snapshot: SnapshotSchema.omit({ releases: true }).nullable(),
4546
- releases: z.array(ReleaseSchema).max(2e3),
4547
- sync: SyncSchema
4548
- }).strict();
4549
- /** Short invalidation carrying no configuration, credentials, or archive bytes. */
4550
- const CatalogChangedSchema = z.object({
4551
- revision: z.number().int().nonnegative(),
4552
- snapshot: z.object({
4553
- commit: GitShaSchema,
4554
- contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4555
- }).strict().optional(),
4556
- sync: SyncSchema
4557
- }).strict();
4558
- /** Confirmation response for a fixed exact extension dependency closure. */
4559
- const PreviewSchema = z.object({
4560
- previewToken: z.string().min(1).max(8192),
4561
- expiresAt: z.iso.datetime({ offset: true }),
4562
- snapshot: z.object({
4563
- commit: GitShaSchema,
4564
- contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4565
- }).strict(),
4566
- graphRevision: z.string().max(1024),
4567
- resolvedSelections: z.array(ReleaseSchema).max(64),
4568
- dependencies: z.array(z.object({
4569
- packageName: z.string(),
4570
- version: z.string()
4571
- }).strict()).max(64),
4572
- willEnable: z.array(z.string()).max(2e3),
4573
- replacing: z.array(z.string()).max(64),
4574
- affectedOwners: z.array(z.string()).max(2e3),
4575
- warnings: z.array(ArtifactWarningSchema).max(64)
4576
- }).strict();
4577
- /** Durable installation operation facts returned by the generic owner-bound service. */
4578
- const OperationSchema = z.object({
4579
- operationId: z.uuid(),
4580
- attemptId: z.uuid(),
4581
- issuer: z.string(),
4582
- submissionDigest: z.string(),
4583
- requestDigest: z.string(),
4584
- packageName: z.string(),
4585
- warnings: z.array(ArtifactWarningSchema).max(3).optional(),
4586
- warningCount: z.number().int().nonnegative().max(1e5).optional(),
4587
- rootResults: z.array(z.object({
4588
- packageName: z.string(),
4589
- status: z.enum([
4590
- "pending",
4591
- "active",
4592
- "disabled",
4593
- "deferred",
4594
- "failed"
4595
- ]),
4596
- reason: z.string().max(4096).optional()
4597
- }).strict()).max(2e3).optional(),
4598
- phase: z.enum([
4599
- "preparing",
4600
- "installing",
4601
- "admitted",
4602
- "activating",
4603
- "settled"
4604
- ]),
4605
- currentStep: z.enum([
4606
- "prepare",
4607
- "download",
4608
- "verify",
4609
- "npm",
4610
- "admission",
4611
- "activation",
4612
- "cleanup"
4613
- ]),
4614
- outcome: z.enum([
4615
- "pending",
4616
- "succeeded",
4617
- "failed",
4618
- "interrupted"
4619
- ]),
4620
- failureStage: z.enum([
4621
- "prepare",
4622
- "download",
4623
- "verify",
4624
- "npm",
4625
- "admission",
4626
- "activation",
4627
- "cleanup",
4628
- "recovery"
4629
- ]).optional(),
4630
- reason: z.string().max(4096).optional(),
4631
- cleanup: z.enum([
4632
- "not-needed",
4633
- "pending",
4634
- "complete",
4635
- "failed"
4636
- ]),
4637
- startedAt: z.iso.datetime({ offset: true }),
4638
- settledAt: z.iso.datetime({ offset: true }).optional(),
4639
- packages: z.array(z.object({
4640
- packageName: z.string(),
4641
- beforeRevision: z.number().int().nonnegative(),
4642
- receiptId: z.uuid().nullable(),
4643
- diskChanged: z.boolean().optional(),
4644
- ownerWithdrawn: z.boolean().optional()
4645
- }).strict()).max(2e3)
4646
- }).strict();
4647
- /** Installation progress invalidation; clients query the durable attempt after reconnecting. */
4648
- const InstallChangedSchema = z.object({
4649
- operationId: z.uuid(),
4650
- phase: OperationSchema.shape.phase,
4651
- currentStep: OperationSchema.shape.currentStep,
4652
- outcome: OperationSchema.shape.outcome,
4653
- cleanup: OperationSchema.shape.cleanup,
4654
- revision: z.number().int().nonnegative()
4655
- }).strict();
4656
- /** Current directory source markers and installed metadata for unique package names. */
4657
- const InstalledSchema = z.object({
4658
- observedAt: z.iso.datetime({ offset: true }),
4659
- rows: z.array(InstalledRowSchema).max(2e3)
4660
- }).strict();
4661
- /** Existing owner RPC success/failure convention; sanitized errors remain actionable. */
4662
- function resultSchema(data) {
4663
- return z.union([z.object({
4664
- ok: z.literal(true),
4665
- data
4666
- }).strict(), z.object({
4667
- ok: z.literal(false),
4668
- code: z.string(),
4669
- message: z.string().max(4096),
4670
- retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4671
- }).strict()]);
5172
+ //#region src/extension-catalog/store.ts
5173
+ /** Persists the last complete validated catalog snapshot in this owner's storage lease. */
5174
+ function createCatalogStore(storage) {
5175
+ const name = storage.tableName("catalog_snapshot");
5176
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid storage table identity");
5177
+ const table = `"${name}"`;
5178
+ storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK(id=1), snapshot_json TEXT NOT NULL)`);
5179
+ function validate(input) {
5180
+ const value = SnapshotSchema.parse(input);
5181
+ if (recordDigest({ releases: value.releases }) !== value.contentDigest) throw new CatalogError("CATALOG_INVALID", "Cached snapshot digest differs from its complete records");
5182
+ if (new Set(value.releases.map((r) => r.releaseId)).size !== value.releases.length) throw new CatalogError("CATALOG_INVALID", "Duplicate cached release");
5183
+ return value;
5184
+ }
5185
+ return {
5186
+ /** Reads validated last-success data without network activity; corruption refuses availability. */
5187
+ read() {
5188
+ const row = storage.db.prepare(`SELECT snapshot_json FROM ${table} WHERE id=1`).get();
5189
+ if (!row) return null;
5190
+ try {
5191
+ return validate(JSON.parse(row.snapshot_json));
5192
+ } catch {
5193
+ throw new CatalogError("CATALOG_INVALID", "Catalog cache is unavailable; refresh to repair it");
5194
+ }
5195
+ },
5196
+ /** Atomically replaces the complete snapshot and advances its successful revision. */
5197
+ save(input) {
5198
+ const snapshot = validate(input);
5199
+ storage.db.exec("SAVEPOINT catalog_snapshot_commit");
5200
+ try {
5201
+ let before = null;
5202
+ try {
5203
+ before = this.read();
5204
+ } catch {}
5205
+ const revision = (before?.revision ?? 0) + 1;
5206
+ if (!Number.isSafeInteger(revision)) throw new CatalogError("LIMIT_EXCEEDED", "Catalog revision is exhausted");
5207
+ const saved = {
5208
+ ...snapshot,
5209
+ revision
5210
+ };
5211
+ const json = canonicalJson(saved);
5212
+ if (Buffer.byteLength(json) > 8388608) throw new CatalogError("LIMIT_EXCEEDED", "Encoded catalog exceeds 8 MiB");
5213
+ storage.db.prepare(`INSERT INTO ${table}(id,snapshot_json) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET snapshot_json=excluded.snapshot_json`).run(json);
5214
+ storage.db.exec("RELEASE catalog_snapshot_commit");
5215
+ return saved;
5216
+ } catch (error) {
5217
+ storage.db.exec("ROLLBACK TO catalog_snapshot_commit");
5218
+ storage.db.exec("RELEASE catalog_snapshot_commit");
5219
+ throw error;
5220
+ }
5221
+ }
5222
+ };
4672
5223
  }
4673
5224
  //#endregion
4674
5225
  //#region src/extension-catalog/register.ts
@@ -4761,12 +5312,6 @@ function registerExtensionCatalog(ctx) {
4761
5312
  result: resultSchema(InstalledSchema),
4762
5313
  handle: () => result(() => service.installed())
4763
5314
  });
4764
- ctx.client.registerMethod({
4765
- name: "extensionCatalogPreview",
4766
- params: z.object({ selection: SelectionSchema }).strict(),
4767
- result: resultSchema(PreviewSchema),
4768
- handle: (p) => result(() => service.preview(p.selection))
4769
- });
4770
5315
  ctx.client.registerMethod({
4771
5316
  name: "extensionCatalogPreviewBatch",
4772
5317
  params: z.object({
@@ -4799,10 +5344,41 @@ function registerExtensionCatalog(ctx) {
4799
5344
  });
4800
5345
  const operationParams = z.object({ operationId: z.uuid() }).strict();
4801
5346
  ctx.client.registerMethod({
4802
- name: "extensionCatalogOperation",
4803
- params: operationParams,
4804
- result: resultSchema(z.object({ operation: OperationSchema }).strict()),
4805
- handle: (p) => result(async () => ({ operation: OperationSchema.parse(await service.operation(p.operationId)) }))
5347
+ name: "extensionCatalogOperations",
5348
+ params: OperationQueriesParams,
5349
+ result: resultSchema(OperationQueriesData),
5350
+ handle: (p) => result(async () => {
5351
+ const results = [];
5352
+ for (const [index, target] of p.operationIds.entries()) {
5353
+ ctx.signal.throwIfAborted();
5354
+ try {
5355
+ const operation = OperationSchema.parse(await service.operation(target));
5356
+ ctx.signal.throwIfAborted();
5357
+ const member = {
5358
+ index,
5359
+ target,
5360
+ ok: true,
5361
+ value: { operation }
5362
+ };
5363
+ if (Buffer.byteLength(JSON.stringify(member)) > p.maxItemBytes) throw new CatalogError("read-limit", "Operation result exceeds the declared member byte budget");
5364
+ results.push(member);
5365
+ } catch (error) {
5366
+ ctx.signal.throwIfAborted();
5367
+ const refusal = managementError(error);
5368
+ results.push({
5369
+ index,
5370
+ target,
5371
+ ok: false,
5372
+ error: {
5373
+ code: refusal.code.slice(0, 64).replace(/[\uD800-\uDBFF]$/, "") || "INSTALL_FAILED",
5374
+ message: refusal.message.slice(0, 512).replace(/[\uD800-\uDBFF]$/, ""),
5375
+ ...refusal.retryAfterSeconds === void 0 ? {} : { details: { retryAfterSeconds: refusal.retryAfterSeconds } }
5376
+ }
5377
+ });
5378
+ }
5379
+ }
5380
+ return { results };
5381
+ })
4806
5382
  });
4807
5383
  ctx.client.registerMethod({
4808
5384
  name: "extensionCatalogRetryCleanup",