@eum-agent/extension-catalog 1.0.2 → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +2163 -1476
  2. package/package.json +6 -6
  3. package/ui/ui.js +10 -6
package/dist/index.js CHANGED
@@ -313,1116 +313,458 @@ function createDefaultsStore(storage) {
313
313
  };
314
314
  }
315
315
  //#endregion
316
- //#region src/defaults/service.ts
317
- /** Creates one shared initialization attempt scoped to this catalog owner. */
318
- function createDefaultsService(options) {
319
- const controller = new AbortController();
320
- const signal = AbortSignal.any([options.signal, controller.signal]);
321
- let active = null;
322
- function initial() {
323
- return {
324
- state: "pending-snapshot",
325
- enrolledAt: (/* @__PURE__ */ new Date()).toISOString(),
326
- candidates: []
327
- };
328
- }
329
- async function status() {
330
- const before = options.store.read() ?? initial();
331
- const observations = before.candidates.length ? await options.installer.observe(before.candidates.map((candidate) => candidate.packageName)) : [];
332
- const record = options.store.read() ?? initial();
333
- const candidates = record.candidates.map(({ artifactIntegrity: _integrity, receiptId, ...candidate }) => {
334
- const observed = observations.find((item) => item.packageName === candidate.packageName);
335
- const captured = before.candidates.find((item) => item.packageName === candidate.packageName);
336
- const matchesCapturedResult = captured?.state === "installed" && captured.receiptId === receiptId && captured.operationId === candidate.operationId && captured.releaseId === candidate.releaseId;
337
- if (candidate.state === "installed" && matchesCapturedResult && observed) {
338
- if (!observed.declared.installed || !observed.declared.enabled || receiptId && observed.receipt?.receiptId !== receiptId) {
339
- candidate.state = "user-managed";
340
- candidate.reasonCode = "USER_DECLARATION_PRESERVED";
341
- delete candidate.activation;
342
- } else {
343
- const activation = observed.activation ?? (observed.summary?.status === "active" ? "active" : observed.summary?.status === "failed" ? "failed" : void 0);
344
- if (activation) candidate.activation = activation;
345
- }
346
- }
347
- return candidate;
348
- });
349
- return DefaultsStatusSchema.parse({
350
- state: active ? "working" : record.state === "complete" ? "complete" : record.state === "pending-snapshot" ? "pending-snapshot" : "pending",
351
- taskId: active?.id ?? null,
352
- operationId: record.currentOperationId ?? null,
353
- counts: {
354
- installed: candidates.filter((c) => c.state === "installed").length,
355
- pending: candidates.filter((c) => c.state === "pending").length,
356
- skipped: candidates.filter((c) => c.state === "skipped" || c.state === "user-managed").length
357
- },
358
- activationDeferred: candidates.filter((c) => c.state === "installed" && c.activation === "deferred").length,
359
- candidates,
360
- ...record.lastReasonCode ? { reasonCode: record.lastReasonCode } : {},
361
- ...record.retryNotBefore ? { retryAfterSeconds: Math.min(86400, Math.max(0, Math.ceil((Date.parse(record.retryNotBefore) - Date.now()) / 1e3))) } : {}
362
- });
363
- }
364
- function persist(record) {
365
- if (record.snapshot) record.state = record.candidates.some((c) => c.state === "pending") ? "pending" : "complete";
366
- return options.store.save(record);
367
- }
368
- async function applyOperation(record, operation) {
369
- for (const candidate of record.candidates.filter((c) => c.operationId === operation.operationId && c.state === "pending")) {
370
- const packageResult = operation.packages.find((p) => p.packageName === candidate.packageName);
371
- const rootResult = operation.rootResults?.find((r) => r.packageName === candidate.packageName);
372
- if (packageResult?.receiptId) {
373
- candidate.state = "installed";
374
- candidate.receiptId = packageResult.receiptId;
375
- candidate.activation = rootResult?.status === "active" ? "active" : rootResult?.status === "deferred" ? "deferred" : "failed";
376
- delete candidate.reasonCode;
377
- } else if (operation.phase === "settled" && operation.outcome !== "pending") {
378
- candidate.reasonCode = "INSTALL_FAILED";
379
- 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;
380
348
  }
381
349
  }
382
- if (record.lastReasonCode === "INSTALL_FAILED" && !record.candidates.some((candidate) => candidate.state === "pending")) delete record.lastReasonCode;
383
- persist(record);
350
+ active.delete(one);
351
+ return true;
384
352
  }
385
- async function joinOperation(operationId) {
386
- let operation = await options.installer.join(operationId);
387
- while (operation.cleanup === "failed" || operation.cleanup === "pending") {
388
- try {
389
- operation = await options.installer.retryCleanup(operationId);
390
- } catch {
391
- await setTimeout$1(250);
392
- continue;
393
- }
394
- if (operation.cleanup === "failed" || operation.cleanup === "pending") await setTimeout$1(250);
395
- }
396
- return operation;
353
+ try {
354
+ return visit(value, 1);
355
+ } catch {
356
+ return false;
397
357
  }
398
- async function recover(record) {
399
- const operationIds = [...new Set(record.candidates.filter((c) => c.state === "pending").map((c) => c.operationId).filter((id) => !!id))];
400
- for (const id of operationIds) {
401
- let operation;
402
- try {
403
- operation = await options.installer.operation(id);
404
- } catch (error) {
405
- if (managementError(error).code !== "OPERATION_NOT_FOUND") throw error;
406
- continue;
407
- }
408
- operation = await joinOperation(id);
409
- await applyOperation(record, operation);
410
- if (operation.phase !== "settled" || operation.outcome === "pending") throw new CatalogError("RECOVERY_PENDING", "The original default installation attempt is not settled");
411
- }
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);
412
415
  }
413
- async function run(attempt) {
414
- let record = options.store.read() ?? options.store.save(initial());
415
- delete record.lastReasonCode;
416
- delete record.retryNotBefore;
417
- await recover(record);
418
- if (record.state === "complete") return;
419
- const snapshot = await options.acquireSnapshot(attempt);
420
- attempt.signal.throwIfAborted();
421
- if (!record.snapshot) {
422
- const chosen = /* @__PURE__ */ new Map();
423
- for (const release of snapshot.releases) {
424
- if (release.defaultInstall !== true || !releaseCompatible(release, options.identity)) continue;
425
- const before = chosen.get(release.packageName);
426
- if (!before || semver.gt(release.version, before.version)) chosen.set(release.packageName, release);
427
- }
428
- if (chosen.size > 64) throw new CatalogError("LIMIT_EXCEEDED", "Default extension cohort exceeds 64 roots");
429
- record = await options.installer.coordinate(() => options.store.save({
430
- ...record,
431
- state: chosen.size ? "frozen" : "complete",
432
- snapshot: {
433
- commit: snapshot.commit,
434
- contentDigest: snapshot.contentDigest
435
- },
436
- host: {
437
- version: options.identity.version,
438
- ...options.identity.target
439
- },
440
- candidates: [...chosen.values()].sort((a, b) => a.packageName < b.packageName ? -1 : a.packageName > b.packageName ? 1 : 0).map((r) => ({
441
- packageName: r.packageName,
442
- releaseId: r.releaseId,
443
- artifactIntegrity: r.artifact.integrity,
444
- state: "pending"
445
- }))
446
- }));
447
- }
448
- if (record.state === "complete") return;
449
- const observations = await options.installer.observe();
450
- for (const candidate of record.candidates.filter((c) => c.state === "pending")) if (observations.some((o) => o.packageName === candidate.packageName && o.declared.origin !== void 0)) {
451
- candidate.state = "user-managed";
452
- candidate.reasonCode = "USER_DECLARATION_PRESERVED";
453
- } else {
454
- const release = snapshot.releases.find((r) => r.releaseId === candidate.releaseId && r.artifact.integrity === candidate.artifactIntegrity);
455
- if (!release || release.defaultInstall !== true || !releaseCompatible(release, options.identity)) {
456
- candidate.state = "skipped";
457
- candidate.reasonCode = "RELEASE_REVOKED";
458
- }
459
- }
460
- persist(record);
461
- const roots = record.candidates.filter((c) => c.state === "pending");
462
- if (!roots.length) return;
463
- const plan = await options.preview(roots.map((c) => ({
464
- snapshotCommit: snapshot.commit,
465
- releaseId: c.releaseId,
466
- artifactIntegrity: c.artifactIntegrity
467
- })), attempt);
468
- attempt.signal.throwIfAborted();
469
- const operationId = randomUUID();
470
- record.currentOperationId = operationId;
471
- record.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
472
- for (const candidate of roots) candidate.operationId = operationId;
473
- persist(record);
474
- try {
475
- await options.installer.install({
476
- operationId,
477
- token: plan.previewToken
478
- }, attempt);
479
- } catch (error) {
480
- try {
481
- await options.installer.operation(operationId);
482
- } catch {
483
- throw error;
484
- }
485
- }
486
- const operation = await joinOperation(operationId);
487
- await applyOperation(record, operation);
488
- }
489
- return {
490
- /** Starts one shared bounded attempt immediately; completed initialization performs no network work. */
491
- async ensure(input) {
492
- signal.throwIfAborted();
493
- const params = DefaultsEnsureParamsSchema.parse(input);
494
- if (params.expectedProductVersion !== options.identity.version) throw new CatalogError("PRODUCT_VERSION_MISMATCH", "Default installation requires the current product version");
495
- const record = options.store.read() ?? initial();
496
- if (active) return {
497
- taskId: active.id,
498
- status: await status()
499
- };
500
- if (record.state === "complete" || record.retryNotBefore && Date.parse(record.retryNotBefore) > Date.now()) return {
501
- taskId: null,
502
- status: await status()
503
- };
504
- const id = randomUUID(), deadline = performance.now() + Math.min(18e4, params.remainingWorkMs);
505
- const timerController = new AbortController();
506
- const timer = setTimeout(() => timerController.abort(/* @__PURE__ */ new Error("Default installation work budget exhausted")), Math.max(1, deadline - performance.now()));
507
- const attempt = {
508
- signal: AbortSignal.any([signal, timerController.signal]),
509
- remainingWorkMs: () => Math.max(0, deadline - performance.now())
510
- };
511
- const work = Promise.resolve().then(() => run(attempt)).catch((error) => {
512
- const record = options.store.read() ?? initial(), failure = managementError(error);
513
- record.lastReasonCode = attempt.signal.aborted ? "ATTEMPT_CANCELLED" : failure.code;
514
- for (const candidate of record.candidates.filter((c) => c.state === "pending")) candidate.reasonCode = record.lastReasonCode;
515
- if (failure.retryAfterSeconds !== void 0) record.retryNotBefore = new Date(Date.now() + failure.retryAfterSeconds * 1e3).toISOString();
516
- persist(record);
517
- }).finally(() => {
518
- clearTimeout(timer);
519
- active = null;
520
- });
521
- work.catch(() => {});
522
- active = {
523
- id,
524
- work
525
- };
526
- return {
527
- taskId: id,
528
- status: await status()
529
- };
530
- },
531
- /** Projects current readonly installation facts over retained history; never enrolls or installs. */
532
- status,
533
- /** Cancels this automatic attempt and joins all work before releasing the owner's resources. */
534
- async dispose() {
535
- controller.abort(/* @__PURE__ */ new Error("Default installation owner is draining"));
536
- await active?.work;
537
- }
538
- };
416
+ return value;
539
417
  }
540
418
  //#endregion
541
- //#region src/extension-catalog/projection.ts
542
- /** Minimal historical commit identity retained with a release admission. */
543
- const AcceptedSnapshotSchema = z.object({
544
- repository: z.literal(CATALOG_REPOSITORY),
545
- commit: GitShaSchema,
546
- contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
547
- }).strict();
548
- z.object({
549
- snapshot: AcceptedSnapshotSchema,
550
- release: ReleaseSchema,
551
- releaseDigest: z.string().regex(/^[0-9a-f]{64}$/)
552
- }).strict();
553
- /** Current directory source and actual host compatibility are independent of activation status. */
554
- const InstalledRowSchema = z.object({
555
- packageName: z.string(),
556
- distribution: z.enum([
557
- "builtin",
558
- "verified",
559
- "custom"
560
- ]),
561
- publisherKind: z.enum(["official", "third-party"]).optional(),
562
- compatibility: z.object({
563
- state: z.enum([
564
- "compatible",
565
- "incompatible",
566
- "unknown"
567
- ]),
568
- reasons: z.array(z.string()),
569
- assessedAt: z.string()
570
- }).strict(),
571
- updates: z.array(ReleaseSchema)
572
- }).strict();
573
- /** Uses current directory publisher markers while retaining actual saved host requirement facts. */
574
- function projectInstalled(observations, snapshot, host) {
575
- return observations.map((observation) => {
576
- const builtin = (observation.summary?.origin ?? observation.declared.origin) === "builtin";
577
- const listed = snapshot?.releases.filter((release) => release.packageName === observation.packageName).sort((a, b) => semver.rcompare(a.version, b.version))[0];
578
- const currentVersion = observation.summary?.version ?? observation.declared.version ?? observation.receipt?.version ?? "";
579
- const requirements = observation.hostRequirements;
580
- const compatibility = {
581
- state: requirements.state === "satisfied" ? "compatible" : requirements.state === "unsatisfied" ? "incompatible" : "unknown",
582
- reasons: [...requirements.reasons],
583
- assessedAt: requirements.checkedAt
584
- };
585
- 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)) : [];
586
- return {
587
- packageName: observation.packageName,
588
- distribution: builtin ? "builtin" : listed ? "verified" : "custom",
589
- ...!builtin && listed ? { publisherKind: listed.publisher.kind } : {},
590
- compatibility,
591
- updates
592
- };
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"
593
445
  });
594
- }
446
+ }).transform((entries) => freezeWidget(JSON.parse(JSON.stringify(entries))));
595
447
  //#endregion
596
- //#region src/extension-catalog/sync.ts
597
- /** Git smart HTTP ref advertisement for the catalog repository. */
598
- const CATALOG_REFS_URL = "https://github.com/yanxuan-lc/yaoguang-presets.git/info/refs?service=git-upload-pack";
599
- /** Raw content URL of the extension index pinned to one commit. */
600
- const catalogIndexUrl = (commit) => `https://raw.githubusercontent.com/yanxuan-lc/yaoguang-presets/${commit}/extensions/index.json`;
601
- const REFS_MAX_BYTES = 1048576;
602
- const headers = { "User-Agent": "YaoGuang-extensions" };
448
+ //#region ../../core/kernel/src/vocab/model-replay.ts
449
+ /** Opaque protocol state with a fixed UTF-8 storage budget. */
450
+ const ModelReplayDataSchema = z.custom((value) => isLosslessJson(value) && new TextEncoder().encode(JSON.stringify(value)).byteLength <= 2097152);
451
+ /** Host-bound producer identity; only that binding may consume the opaque data. */
452
+ const ModelReplaySchema = z.strictObject({
453
+ owner: z.string().min(1).max(256),
454
+ protocolId: z.string().min(1).max(256),
455
+ providerId: z.string().min(1).max(256),
456
+ model: z.string().min(1).max(256),
457
+ data: ModelReplayDataSchema
458
+ });
459
+ //#endregion
460
+ //#region ../../core/kernel/src/vocab/message.ts
603
461
  /**
604
- * Returns the commit of `refs/heads/main` from a Git smart HTTP upload-pack advertisement.
605
- * Requires the leading service announcement and well-formed pkt-lines; any other shape,
606
- * including a missing main branch, is rejected as an invalid catalog.
462
+ * The transcript's message shapes: the authoritative history that assembly
463
+ * reads. A message is either a plain user/assistant turn of text, an
464
+ * assistant reply that also requests tool calls, or a tool-results message
465
+ * that answers a batch of those calls. Zod schemas are the source of
466
+ * truth; the types are `z.infer`red from them so this vocabulary survives
467
+ * the event log round trip once `packages/core/store-sqlite` serializes it.
468
+ *
469
+ * Tool results are carried in a `role: 'user'` message with `tool-result`
470
+ * content parts. Protocol implementations translate this neutral transcript
471
+ * into their own request representation.
607
472
  */
608
- function parseMainCommit(bytes) {
609
- const text = Buffer.from(bytes).toString("latin1");
610
- const lines = [];
611
- for (let at = 0; at < text.length;) {
612
- const prefix = text.slice(at, at + 4);
613
- if (!/^[0-9a-f]{4}$/.test(prefix)) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
614
- const length = Number.parseInt(prefix, 16);
615
- if (length === 0) {
616
- lines.push(null);
617
- at += 4;
618
- continue;
619
- }
620
- if (length < 4 || at + length > text.length) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
621
- lines.push(text.slice(at + 4, at + length).replace(/\n$/, ""));
622
- at += length;
623
- }
624
- if (lines[0] !== "# service=git-upload-pack" || lines[1] !== null) throw new CatalogError("CATALOG_INVALID", "Missing upload-pack service announcement");
625
- for (const line of lines.slice(2)) {
626
- if (line === null) continue;
627
- const match = /^([0-9a-f]{40}) ([^\0]+)(?:\0.*)?$/s.exec(line);
628
- if (!match) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
629
- if (match[2] === "refs/heads/main") return match[1];
630
- }
631
- throw new CatalogError("CATALOG_INVALID", "Catalog repository has no main branch");
632
- }
473
+ const MessageRoleSchema = z.enum(["user", "assistant"]);
474
+ const TextPartSchema = z.object({
475
+ type: z.literal("text"),
476
+ text: z.string()
477
+ });
478
+ /** The model's thinking, attached to the same assistant message its reply
479
+ * text is. Symmetric with `TextPart` on purpose — it is the recorded
480
+ * counterpart of the publish-only `thinking-delta` chunk, carried the
481
+ * same way `TextPart` carries the recorded counterpart of `text-delta`.
482
+ * Accumulating deltas into this shape, and deciding whether to send it
483
+ * back on the next call, is the adapter's job — this package only
484
+ * carries it. */
485
+ const ThinkingPartSchema = z.object({
486
+ type: z.literal("thinking"),
487
+ text: z.string(),
488
+ /** An opaque token the provider issued with this block and requires back
489
+ * **unmodified** on any later turn that continues the same conversation.
490
+ * A fabricated or edited value can invalidate replay. Absent for protocols
491
+ * that issue no signature. The kernel never reads it; it only
492
+ * carries it, so that the adapter that produced it can hand it back. */
493
+ signature: z.string().optional(),
494
+ /**
495
+ * Which endpoint issued that signature.
496
+ *
497
+ * A signature is only worth anything to whoever signed it, and the product
498
+ * cannot tell whether two endpoints are the same signer — two keys against
499
+ * one vendor, or a proxy in front of it, look identical from here. So this
500
+ * is compared as an endpoint id and the comparison is a deliberate
501
+ * over-approximation: an adapter drops a block another endpoint signed,
502
+ * which between two endpoints of one vendor costs a block that would have
503
+ * replayed. The other way round costs a rejected request.
504
+ *
505
+ * Absent wherever `signature` is: nothing to attribute. The kernel never
506
+ * reads either; it carries them so the adapter that made the block can
507
+ * decide.
508
+ */
509
+ issuer: z.string().optional(),
510
+ /** Model identifier that produced this signed thinking block. */
511
+ originModel: z.string().optional(),
512
+ /**
513
+ * Stable compatibility fingerprint for the non-thinking prefix covered by
514
+ * the provider signature. Adapters omit a signed block when it does not match
515
+ * the request prefix they are about to send.
516
+ */
517
+ prefix: z.string().optional(),
518
+ /**
519
+ * Original output-token count used as a conservative upper bound when the
520
+ * provider retains more thinking state than the visible text represents.
521
+ */
522
+ outputTokens: z.number().int().nonnegative().optional(),
523
+ /**
524
+ * Set on a block the provider returned with no readable text — a protocol's
525
+ * `redacted_thinking`. `text` is then empty and `signature` holds the
526
+ * provider's opaque `data`, which goes back unmodified in the same place.
527
+ */
528
+ redacted: z.literal(true).optional()
529
+ });
530
+ /** A tool call the model requested. `input` is whatever JSON-serializable
531
+ * arguments the model produced for it — the kernel does not validate a
532
+ * tool's own argument shape, only that the call itself round-trips. */
533
+ const ToolUsePartSchema = z.object({
534
+ type: z.literal("tool-use"),
535
+ id: z.string(),
536
+ name: z.string(),
537
+ input: z.unknown(),
538
+ /** Host-projected execution identity; never changes the model's original call. */
539
+ execution: z.object({
540
+ name: z.string(),
541
+ input: z.unknown(),
542
+ definitionFingerprint: z.string()
543
+ }).optional()
544
+ });
545
+ const Sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
546
+ /** The copy of a file a model is sent, when it differs from the original:
547
+ * a content-addressed variant within every built-in provider type's limits. */
548
+ const FileVariantSchema = z.object({
549
+ id: Sha256Schema,
550
+ mediaType: z.string().min(1),
551
+ size: z.number().int().positive(),
552
+ width: z.number().int().positive().optional(),
553
+ height: z.number().int().positive().optional()
554
+ }).strict();
633
555
  /**
634
- * Reads a bounded response without credentials, redirects, or remote-body diagnostics.
635
- * A failed status becomes `SYNC_FAILED`, with a retry delay (at most one day) taken from
636
- * `retry-after`, or from `x-ratelimit-reset` for 429 and exhausted-quota 403 responses.
637
- * A 404 throws the error built by `notFound` when it is supplied.
556
+ * A reference to a content-addressed file of the session's workspace. Only
557
+ * metadata: the bytes live on disk under the workspace's `files/` directory
558
+ * and reach a request through `ModelRequest.files` alone, so an event, a
559
+ * frame or a snapshot never carries them. `name` belongs to the reference,
560
+ * not to the file: the same bytes may be named differently in two messages.
638
561
  */
639
- async function readBoundedResponse(network, url, signal, maxBytes, headers = {}, notFound) {
640
- signal.throwIfAborted();
641
- const response = await network.fetch(url, {
642
- signal,
643
- redirect: "error",
644
- headers
645
- });
646
- if (!response.ok) {
647
- await response.body?.cancel().catch(() => {});
648
- if (response.status === 404 && notFound) throw notFound();
649
- let retry = Number(response.headers.get("retry-after"));
650
- 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);
651
- throw new CatalogError("SYNC_FAILED", `Request failed (HTTP ${response.status})`, Number.isFinite(retry) && retry > 0 ? Math.min(86400, retry) : void 0);
652
- }
653
- if (Number(response.headers.get("content-length")) > maxBytes) {
654
- await response.body?.cancel().catch(() => {});
655
- throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
656
- }
657
- const reader = response.body?.getReader();
658
- if (!reader) return /* @__PURE__ */ new Uint8Array();
659
- const chunks = [];
660
- let size = 0;
661
- try {
662
- for (;;) {
663
- signal.throwIfAborted();
664
- const chunk = await reader.read();
665
- if (chunk.done) break;
666
- size += chunk.value.length;
667
- if (size > maxBytes) throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
668
- chunks.push(chunk.value);
669
- }
670
- signal.throwIfAborted();
671
- return Buffer.concat(chunks, size);
672
- } finally {
673
- await reader.cancel().catch(() => {});
674
- reader.releaseLock();
675
- }
676
- }
562
+ const FileRefSchema = z.object({
563
+ /** The original's sha256, lower-case hex. */
564
+ id: Sha256Schema,
565
+ mediaType: z.string().min(1),
566
+ name: z.string().min(1).max(200),
567
+ size: z.number().int().positive(),
568
+ /** Present for an image. */
569
+ width: z.number().int().positive().optional(),
570
+ height: z.number().int().positive().optional(),
571
+ /** The variant a model receives; absent when the original is within limits. */
572
+ forModel: FileVariantSchema.optional()
573
+ }).strict();
574
+ /** A file inside a message, at the place it was written: text and file parts
575
+ * interleave in the order a person composed them. */
576
+ const FilePartSchema = z.object({
577
+ type: z.literal("file"),
578
+ file: FileRefSchema,
579
+ /** Presentation preference; file bytes and model input remain unchanged. */
580
+ display: z.enum(["inline", "link"]).optional(),
581
+ /** Host-stamped actual producer; never accepted as execution authority. */
582
+ source: z.object({
583
+ providerId: z.string().min(1),
584
+ model: z.string().min(1),
585
+ route: z.enum(["native", "tool"]),
586
+ /** Connection display name captured by the host at generation time. */
587
+ providerName: z.string().min(1).optional(),
588
+ /** Configured model display name captured by the host when available. */
589
+ modelName: z.string().min(1).optional()
590
+ }).optional()
591
+ });
592
+ /** The host stamps the producing activation before persisting a block. */
593
+ const SavedRequiredContextBlockSchema = z.object({
594
+ id: z.string().min(1),
595
+ scope: z.string().min(1),
596
+ version: z.string().min(1),
597
+ text: z.string()
598
+ }).extend({ stampedSource: z.string().min(1) });
599
+ /** Pure delivery facts; live reservation objects never enter the event log. */
600
+ const ToolResultDeliverySchema = z.strictObject({
601
+ kind: z.enum([
602
+ "receipt",
603
+ "preview",
604
+ "exact-page"
605
+ ]),
606
+ outputTokens: z.number().int().nonnegative(),
607
+ sourceComplete: z.boolean().optional(),
608
+ /** Host-bound accepted reply identity; receipt text is not its original source. */
609
+ answerRequestId: z.string().min(1).optional(),
610
+ execution: z.enum([
611
+ "not-started",
612
+ "committed",
613
+ "partial",
614
+ "unknown"
615
+ ]).optional()
616
+ });
617
+ /** The answer to one tool call, matched back to it by `toolUseId`. */
618
+ const ToolResultPartSchema = z.object({
619
+ /** Immutable host provenance for the decision that admitted this result. */
620
+ ownerContext: OwnerContextSchema.optional(),
621
+ type: z.literal("tool-result"),
622
+ toolUseId: z.string(),
623
+ requiredContext: z.array(SavedRequiredContextBlockSchema).optional(),
624
+ /** Immutable host-accepted snapshots. */
625
+ widgets: z.array(WidgetInstanceSchema).max(8).optional(),
626
+ /** Fixed admission diagnostics. */
627
+ widgetIssues: z.array(WidgetIssueSchema).max(8).optional(),
628
+ content: z.string(),
629
+ isError: z.boolean().optional(),
630
+ /** Requested preview body tokens; invalid hints are ignored by the host. */
631
+ previewTokens: z.number().optional(),
632
+ /** Host-admitted delivery metadata; exact pages cannot be silently shortened. */
633
+ delivery: ToolResultDeliverySchema.optional(),
634
+ /** Files the call handed back, after its text. */
635
+ files: z.array(FileRefSchema).optional()
636
+ });
637
+ const ContentPartSchema = z.discriminatedUnion("type", [
638
+ TextPartSchema,
639
+ ThinkingPartSchema,
640
+ ToolUsePartSchema,
641
+ ToolResultPartSchema,
642
+ FilePartSchema
643
+ ]);
677
644
  /**
678
- * Resolves the catalog's main commit with one ref advertisement request, then reads the complete
679
- * extension index pinned to that commit. An unchanged commit reuses `previous` with a new fetch
680
- * time. Requests carry no credentials, refuse redirects and share an 8 MiB budget and 30 s limit.
645
+ * One volatile contributor's text as a request carried it: the contributor's
646
+ * `id` and the strings it gave, joined by a blank line. A request appends a
647
+ * note only when it differs from that contributor's last note in the history,
648
+ * or at a turn's first step under the default policy. An on-change contributor
649
+ * compares values across turn boundaries. The note stays in every later request at the
650
+ * place it was first sent.
681
651
  */
682
- async function synchronize(network, ownerSignal, previous) {
683
- const controller = new AbortController();
684
- const signal = AbortSignal.any([ownerSignal, controller.signal]);
685
- const timer = setTimeout(() => controller.abort(new CatalogError("SYNC_FAILED", "Catalog synchronization exceeded 30 seconds")), 3e4);
686
- try {
687
- const commit = parseMainCommit(await readBoundedResponse(network, CATALOG_REFS_URL, signal, REFS_MAX_BYTES, headers));
688
- if (previous?.commit === commit) return {
689
- ...previous,
690
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
691
- };
692
- const releases = decodeReleases(parseJson(decodeUtf8(await readBoundedResponse(network, catalogIndexUrl(commit), signal, CATALOG_MAX_BYTES, headers, () => new CatalogError("CATALOG_UNAVAILABLE", "No extension index is available")))));
693
- return {
694
- repository: CATALOG_REPOSITORY,
695
- commit,
696
- contentDigest: recordDigest({ releases }),
697
- fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
698
- revision: previous?.revision ?? 0,
699
- releases
700
- };
701
- } catch (error) {
702
- controller.abort(error);
703
- if (error instanceof CatalogError) throw error;
704
- if (ownerSignal.aborted) throw ownerSignal.reason;
705
- throw new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful snapshot is retained");
706
- } finally {
707
- clearTimeout(timer);
708
- }
709
- }
710
- //#endregion
711
- //#region src/extension-catalog/service.ts
712
- /** Creates local catalog reads and explicit synchronization, preview, and operation management. */
713
- function createCatalogService(options) {
714
- let snapshot = null;
715
- let sync = { state: "idle" };
716
- try {
717
- snapshot = options.store.read();
718
- } catch {
719
- sync = {
720
- state: "failed",
721
- error: "Catalog cache is damaged; refresh to repair it"
722
- };
723
- }
724
- const controller = new AbortController();
725
- const signal = AbortSignal.any([options.signal, controller.signal]);
726
- const ownedTasks = /* @__PURE__ */ new Set();
727
- let synchronization = null;
728
- function notifySynchronization() {
729
- if (!signal.aborted) options.notify?.({
730
- revision: snapshot?.revision ?? 0,
731
- ...snapshot ? { snapshot: {
732
- commit: snapshot.commit,
733
- contentDigest: snapshot.contentDigest
734
- } } : {},
735
- sync: { ...sync }
736
- });
737
- }
738
- function sharedSynchronization(manual = false) {
739
- signal.throwIfAborted();
740
- if (synchronization) {
741
- if (manual) synchronization.manual = true;
742
- return synchronization;
743
- }
744
- const taskId = randomUUID(), taskController = new AbortController(), taskSignal = AbortSignal.any([signal, taskController.signal]);
745
- sync = {
746
- state: "syncing",
747
- taskId
748
- };
749
- const work = Promise.resolve().then(async () => {
750
- try {
751
- const acquired = await synchronize(options.network, taskSignal, snapshot);
752
- const saved = await options.installer.coordinate(() => {
753
- taskSignal.throwIfAborted();
754
- snapshot = options.store.save(acquired);
755
- return snapshot;
756
- });
757
- sync = {
758
- state: "succeeded",
759
- taskId
760
- };
761
- return saved;
762
- } catch (error) {
763
- const failure = error instanceof CatalogError ? error : new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful data is retained");
764
- sync = {
765
- state: "failed",
766
- taskId,
767
- error: failure.message,
768
- ...failure.retryAfterSeconds === void 0 ? {} : { retryAfterSeconds: failure.retryAfterSeconds }
769
- };
770
- throw failure;
771
- } finally {
772
- synchronization = null;
773
- notifySynchronization();
774
- }
775
- });
776
- synchronization = {
777
- taskId,
778
- controller: taskController,
779
- manual,
780
- consumers: /* @__PURE__ */ new Set(),
781
- work
782
- };
783
- ownedTasks.add(work);
784
- work.then(() => ownedTasks.delete(work), () => ownedTasks.delete(work));
785
- notifySynchronization();
786
- return synchronization;
787
- }
788
- async function acquireFreshSnapshot(attempt) {
789
- const consumerSignal = AbortSignal.any([signal, attempt.signal]);
790
- consumerSignal.throwIfAborted();
791
- const task = sharedSynchronization(), consumer = Symbol();
792
- task.consumers.add(consumer);
793
- let onAbort;
794
- const cancelled = new Promise((_resolve, reject) => {
795
- onAbort = () => {
796
- task.consumers.delete(consumer);
797
- if (!task.manual && !task.consumers.size) task.controller.abort(consumerSignal.reason);
798
- reject(consumerSignal.reason);
799
- };
800
- consumerSignal.addEventListener("abort", onAbort, { once: true });
801
- if (consumerSignal.aborted) onAbort();
802
- });
803
- try {
804
- const acquired = await Promise.race([task.work, cancelled]);
805
- consumerSignal.throwIfAborted();
806
- return acquired;
807
- } catch (error) {
808
- if (consumerSignal.aborted && !task.manual && !task.consumers.size) {
809
- task.controller.abort(consumerSignal.reason);
810
- await Promise.allSettled([task.work]);
811
- }
812
- throw error;
813
- } finally {
814
- task.consumers.delete(consumer);
815
- consumerSignal.removeEventListener("abort", onAbort);
816
- }
817
- }
818
- /** Prepares exact roots and one shared extension closure without imports or activation. */
819
- async function preview(inputs, enableNames = [], batch = false, attempt, automatic = false) {
820
- const preparationSignal = attempt ? AbortSignal.any([signal, attempt.signal]) : signal;
821
- preparationSignal.throwIfAborted();
822
- const selections = inputs.map((input) => SelectionSchema.parse(input)), selectedSnapshot = snapshot;
823
- if (!selections.length || selections.length > 64 || enableNames.length > 2e3) throw new CatalogError("LIMIT_EXCEEDED", "Select between one and 64 exact extension roots");
824
- if (!selectedSnapshot) throw new CatalogError("CATALOG_UNAVAILABLE", "Refresh the extension catalog before selecting a release");
825
- const accepted = structuredClone(selectedSnapshot);
826
- const selectedHost = options.hostIdentity;
827
- if (!selectedHost) throw new CatalogError("RELEASE_INCOMPATIBLE", "Current product and host target are unavailable");
828
- const host = selectedHost;
829
- const observations = await options.installer.observe();
830
- const roots = [];
831
- for (const selection of selections) {
832
- if (selection.snapshotCommit !== accepted.commit) throw new CatalogError("STALE_PREVIEW", "Selected catalog commit is no longer current");
833
- const release = accepted.releases.find((r) => r.releaseId === selection.releaseId);
834
- if (!release || release.artifact.integrity !== selection.artifactIntegrity) throw new CatalogError("RELEASE_UNLISTED", "Selected exact release is not listed");
835
- if (!releaseCompatible(release, host)) throw new CatalogError("RELEASE_INCOMPATIBLE", "Selected release does not accept the current product and host target");
836
- const existing = observations.find((o) => o.packageName === release.packageName);
837
- if (automatic && existing?.declared.origin !== void 0) throw new CatalogError("STALE_PREVIEW", "A user declaration now owns this default extension");
838
- if (selection.expectedInstalledReceiptId !== void 0 && existing?.receipt?.receiptId !== selection.expectedInstalledReceiptId) throw new CatalogError("STALE_PREVIEW", "Current installed receipt differs from the displayed selection");
839
- const prior = roots.find((r) => r.packageName === release.packageName);
840
- if (prior && recordDigest(prior) !== recordDigest(release)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension roots select conflicting exact releases");
841
- if (!prior) roots.push(release);
842
- }
843
- const resolved = [], chosen = new Map(roots.map((root) => [root.packageName, root])), expanded = /* @__PURE__ */ new Set();
844
- async function expand(candidate) {
845
- const prior = chosen.get(candidate.packageName);
846
- if (prior) {
847
- if (prior.releaseId !== candidate.releaseId) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension requirements select conflicting exact releases");
848
- if (expanded.has(candidate.packageName)) return;
849
- }
850
- if (!prior && chosen.size >= 64) throw new CatalogError("LIMIT_EXCEEDED", "Extension closure exceeds 64 packages");
851
- chosen.set(candidate.packageName, candidate);
852
- expanded.add(candidate.packageName);
853
- resolved.push(candidate);
854
- const raw = (await options.installer.inspect({
855
- expectedName: candidate.packageName,
856
- expectedVersion: candidate.version,
857
- ...candidate.artifact
858
- }, preparationSignal, attempt)).yaoguang?.dependencies ?? {};
859
- if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).length > 64) throw new CatalogError("ARTIFACT_INVALID", "Invalid extension dependency declaration");
860
- for (const [name, range] of Object.entries(raw)) {
861
- if (typeof range !== "string" || semver.validRange(range) === null) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension dependency has an invalid version range");
862
- const selected = chosen.get(name);
863
- if (selected) {
864
- if (!semver.satisfies(selected.version, range)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Exact closure cannot satisfy all extension requirements");
865
- continue;
866
- }
867
- const installed = observations.find((o) => o.packageName === name && o.declared.origin !== void 0);
868
- if (automatic && installed && (!installed.declared.installed || !installed.declared.enabled)) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency declaration does not permit default installation");
869
- const installedVersion = installed?.receipt?.version ?? installed?.declared.version ?? installed?.summary?.version;
870
- if (installedVersion && semver.valid(installedVersion) && semver.satisfies(installedVersion, range)) continue;
871
- if (automatic && installed) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency version cannot be replaced by default installation");
872
- const choices = accepted.releases.filter((r) => r.packageName === name && semver.satisfies(r.version, range) && releaseCompatible(r, host));
873
- if (choices.length !== 1) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Missing extension dependency has no unique compatible exact release");
874
- await expand(choices[0]);
875
- }
876
- }
877
- for (const root of roots) await expand(root);
878
- function evidence(candidate) {
879
- return {
880
- expectedName: candidate.packageName,
881
- expectedVersion: candidate.version,
882
- ...candidate.artifact,
883
- sourceRecord: {
884
- snapshot: {
885
- repository: accepted.repository,
886
- commit: accepted.commit,
887
- contentDigest: accepted.contentDigest
888
- },
889
- release: candidate,
890
- releaseDigest: recordDigest(candidate)
891
- },
892
- activationConstraints: {
893
- hostVersionRange: candidate.compatibility.productRange,
894
- platformTargets: candidate.compatibility.platforms
895
- },
896
- display: {
897
- label: typeof candidate.displayName === "string" ? candidate.displayName : candidate.displayName["en-US"],
898
- detail: "Historical catalog admission"
899
- }
900
- };
901
- }
902
- const validate = () => {
903
- 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");
904
- };
905
- preparationSignal.throwIfAborted();
906
- validate();
907
- const rootNames = new Set(roots.map((root) => root.packageName));
908
- const dependencies = resolved.filter((record) => !rootNames.has(record.packageName)).map(evidence);
909
- const preview = batch ? await options.installer.previewBatch({
910
- roots: roots.map(evidence),
911
- dependencies,
912
- enabled: true,
913
- enableNames
914
- }, validate, attempt) : await options.installer.preview({
915
- ...evidence(roots[0]),
916
- enabled: true,
917
- dependencies
918
- }, validate, attempt);
919
- preparationSignal.throwIfAborted();
920
- if (automatic && preview.replacing.length) throw new CatalogError("STALE_PREVIEW", "Default installation cannot replace existing extensions");
921
- return {
922
- previewToken: preview.token,
923
- expiresAt: preview.expiresAt,
924
- snapshot: {
925
- commit: accepted.commit,
926
- contentDigest: accepted.contentDigest
927
- },
928
- graphRevision: preview.graphRevision,
929
- resolvedSelections: resolved,
930
- dependencies: preview.selections.filter((selection) => !rootNames.has(selection.expectedName)).map((s) => ({
931
- packageName: s.expectedName,
932
- version: s.expectedVersion
933
- })),
934
- willEnable: [...preview.willEnable],
935
- replacing: [...preview.replacing],
936
- affectedOwners: [...preview.affectedOwners],
937
- warnings: []
938
- };
939
- }
940
- const defaults = options.defaultsStore && options.hostIdentity ? createDefaultsService({
941
- store: options.defaultsStore,
942
- identity: options.hostIdentity,
943
- installer: options.installer,
944
- signal,
945
- preview: (selections, attempt) => preview(selections, [], true, attempt, true),
946
- acquireSnapshot: acquireFreshSnapshot
947
- }) : null;
948
- function requireDefaults() {
949
- if (!defaults) throw new CatalogError("DEFAULTS_UNAVAILABLE", "Default extension initialization is unavailable for this host");
950
- return defaults;
951
- }
952
- return {
953
- /** Starts or shares this owner's one-shot bounded automatic installation task. */
954
- defaultsEnsure(input) {
955
- return requireDefaults().ensure(input);
956
- },
957
- /** Returns passive initialization facts without refreshing or enrolling. */
958
- defaultsStatus() {
959
- return requireDefaults().status();
960
- },
961
- /** Returns cached data only; first use and failure never trigger network work. */
962
- list() {
963
- signal.throwIfAborted();
964
- if (!snapshot) return {
965
- revision: 0,
966
- snapshot: null,
967
- releases: [],
968
- sync: { ...sync }
969
- };
970
- const { releases, ...metadata } = snapshot;
971
- return {
972
- revision: snapshot.revision,
973
- snapshot: metadata,
974
- releases,
975
- sync: { ...sync }
976
- };
977
- },
978
- /** Joins the active fresh synchronization; manual work survives automatic attempt cancellation. */
979
- refresh() {
980
- return {
981
- taskId: sharedSynchronization(true).taskId,
982
- sync: { ...sync }
983
- };
984
- },
985
- /** Previews installation with target enablement and joins owned preparation before disposal. */
986
- preview(input) {
987
- const task = preview([input]);
988
- ownedTasks.add(task);
989
- task.then(() => {
990
- ownedTasks.delete(task);
991
- }, () => {
992
- ownedTasks.delete(task);
993
- });
994
- return task;
995
- },
996
- /** Prepares one approved union of exact roots and existing owners to enable. */
997
- previewBatch(inputs, enableNames = []) {
998
- const task = preview(inputs, enableNames, true);
999
- ownedTasks.add(task);
1000
- task.then(() => ownedTasks.delete(task), () => ownedTasks.delete(task));
1001
- return task;
1002
- },
1003
- /** Delegates deduplication before any token or current-snapshot validation. */
1004
- install(operationId, previewToken) {
1005
- signal.throwIfAborted();
1006
- return options.installer.install({
1007
- operationId,
1008
- token: previewToken
1009
- });
1010
- },
1011
- /** Reads an existing durable attempt without restarting work. */
1012
- operation(operationId) {
1013
- return options.installer.operation(operationId);
1014
- },
1015
- /** Retries only cleanup still owned by the queried attempt. */
1016
- retryCleanup(operationId) {
1017
- return options.installer.retryCleanup(operationId);
1018
- },
1019
- /** Projects installed metadata against the current cached directory without reading files. */
1020
- async installed() {
1021
- signal.throwIfAborted();
1022
- const observations = await options.installer.observe();
1023
- return {
1024
- observedAt: (/* @__PURE__ */ new Date()).toISOString(),
1025
- rows: projectInstalled(observations, snapshot, options.hostIdentity)
1026
- };
1027
- },
1028
- /** Joins all discovery work before owner disposal completes. */
1029
- async dispose() {
1030
- controller.abort(/* @__PURE__ */ new Error("Catalog owner withdrawn"));
1031
- await Promise.all([defaults?.dispose(), Promise.allSettled([...ownedTasks])]);
1032
- }
1033
- };
1034
- }
1035
- //#endregion
1036
- //#region src/extension-catalog/store.ts
1037
- /** Persists the last complete validated catalog snapshot in this owner's storage lease. */
1038
- function createCatalogStore(storage) {
1039
- const name = storage.tableName("catalog_snapshot");
1040
- if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid storage table identity");
1041
- const table = `"${name}"`;
1042
- storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK(id=1), snapshot_json TEXT NOT NULL)`);
1043
- function validate(input) {
1044
- const value = SnapshotSchema.parse(input);
1045
- if (recordDigest({ releases: value.releases }) !== value.contentDigest) throw new CatalogError("CATALOG_INVALID", "Cached snapshot digest differs from its complete records");
1046
- if (new Set(value.releases.map((r) => r.releaseId)).size !== value.releases.length) throw new CatalogError("CATALOG_INVALID", "Duplicate cached release");
1047
- return value;
1048
- }
1049
- return {
1050
- /** Reads validated last-success data without network activity; corruption refuses availability. */
1051
- read() {
1052
- const row = storage.db.prepare(`SELECT snapshot_json FROM ${table} WHERE id=1`).get();
1053
- if (!row) return null;
1054
- try {
1055
- return validate(JSON.parse(row.snapshot_json));
1056
- } catch {
1057
- throw new CatalogError("CATALOG_INVALID", "Catalog cache is unavailable; refresh to repair it");
1058
- }
1059
- },
1060
- /** Atomically replaces the complete snapshot and advances its successful revision. */
1061
- save(input) {
1062
- const snapshot = validate(input);
1063
- storage.db.exec("SAVEPOINT catalog_snapshot_commit");
1064
- try {
1065
- let before = null;
1066
- try {
1067
- before = this.read();
1068
- } catch {}
1069
- const revision = (before?.revision ?? 0) + 1;
1070
- if (!Number.isSafeInteger(revision)) throw new CatalogError("LIMIT_EXCEEDED", "Catalog revision is exhausted");
1071
- const saved = {
1072
- ...snapshot,
1073
- revision
1074
- };
1075
- const json = canonicalJson(saved);
1076
- if (Buffer.byteLength(json) > 8388608) throw new CatalogError("LIMIT_EXCEEDED", "Encoded catalog exceeds 8 MiB");
1077
- storage.db.prepare(`INSERT INTO ${table}(id,snapshot_json) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET snapshot_json=excluded.snapshot_json`).run(json);
1078
- storage.db.exec("RELEASE catalog_snapshot_commit");
1079
- return saved;
1080
- } catch (error) {
1081
- storage.db.exec("ROLLBACK TO catalog_snapshot_commit");
1082
- storage.db.exec("RELEASE catalog_snapshot_commit");
1083
- throw error;
1084
- }
1085
- }
1086
- };
1087
- }
1088
- //#endregion
1089
- //#region ../../core/kernel/src/vocab/widgets.ts
1090
- /** Returns whether a value is lossless JSON with at most 64 nested containers. */
1091
- function isLosslessJson(value) {
1092
- const active = /* @__PURE__ */ new Set();
1093
- function visit(one, depth) {
1094
- if (one === null || typeof one === "boolean") return true;
1095
- if (typeof one === "string") return !/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/u.test(one);
1096
- if (typeof one === "number") return Number.isFinite(one) && !Object.is(one, -0);
1097
- if (typeof one !== "object" || depth > 64 || active.has(one)) return false;
1098
- const array = Array.isArray(one);
1099
- if (!array && Object.getPrototypeOf(one) !== Object.prototype && Object.getPrototypeOf(one) !== null) return false;
1100
- if (Object.getOwnPropertySymbols(one).length !== 0) return false;
1101
- const descriptors = Object.getOwnPropertyDescriptors(one);
1102
- if (array && (Object.keys(descriptors).length !== one.length + 1 || !Array.from({ length: one.length }, (_, index) => Object.hasOwn(descriptors, String(index))).every(Boolean))) return false;
1103
- active.add(one);
1104
- for (const [key, descriptor] of Object.entries(descriptors)) {
1105
- if (array && key === "length") continue;
1106
- if (!("value" in descriptor) || !descriptor.enumerable || !visit(key, 0) || !visit(descriptor.value, depth + 1)) {
1107
- active.delete(one);
1108
- return false;
1109
- }
1110
- }
1111
- active.delete(one);
1112
- return true;
1113
- }
1114
- try {
1115
- return visit(value, 1);
1116
- } catch {
1117
- return false;
1118
- }
1119
- }
1120
- /** Pure stored JSON shape; validation requires no owner code. */
1121
- const JsonObjectSchema = z.custom((value) => isLosslessJson(value) && value !== null && !Array.isArray(value) && typeof value === "object");
1122
- /** Exact, portable widget reference identity. */
1123
- 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}$/);
1124
- /** Local type names never encode a business catalogue in the host. */
1125
- const WidgetTypeSchema = z.string().regex(/^[a-z][a-z0-9-]{0,63}$/);
1126
- /** Host-stamped original execution provenance, retained unchanged by forks. */
1127
- const WidgetSourceSchema = z.object({
1128
- sessionId: z.string().min(1),
1129
- messageId: z.string().uuid(),
1130
- toolCallId: z.string().min(1),
1131
- toolName: z.string().min(1)
1132
- }).strict();
1133
- /** Complete snapshot stored atomically with its tool result. */
1134
- const WidgetInstanceSchema = z.object({
1135
- id: WidgetIdSchema,
1136
- owner: z.string().min(1),
1137
- type: WidgetTypeSchema,
1138
- title: z.string().refine((text) => text.trim().length > 0 && [...text].length <= 200),
1139
- summary: z.string().refine((text) => text.trim().length > 0 && [...text].length <= 4e3),
1140
- data: JsonObjectSchema,
1141
- source: WidgetSourceSchema
1142
- }).strict().refine((widget) => widgetJsonBytes({
1143
- type: widget.type,
1144
- title: widget.title,
1145
- summary: widget.summary,
1146
- data: widget.data
1147
- }) <= 262144).transform((widget) => freezeWidget(widget));
1148
- /** Fixed diagnostics contain no rejected business data. */
1149
- const WidgetIssueCodeSchema = z.enum([
1150
- "count-limit",
1151
- "invalid-input",
1152
- "invalid-json",
1153
- "invalid-data",
1154
- "item-too-large",
1155
- "batch-too-large",
1156
- "unknown-type",
1157
- "source-unavailable",
1158
- "owner-unavailable",
1159
- "untrusted-instance",
1160
- "error-result"
1161
- ]);
1162
- /** One item index or one entire-group issue. */
1163
- const WidgetIssueSchema = z.object({
1164
- code: WidgetIssueCodeSchema,
1165
- index: z.number().int().min(0).max(7).optional()
1166
- }).strict();
1167
- /** Measures complete compact JSON in UTF-8 bytes. */
1168
- function widgetJsonBytes(value) {
1169
- return new TextEncoder().encode(JSON.stringify(value)).length;
1170
- }
1171
- /** Copies JSON into a deeply immutable snapshot. */
1172
- function freezeWidget(value) {
1173
- if (value !== null && typeof value === "object") {
1174
- for (const child of Object.values(value)) freezeWidget(child);
1175
- Object.freeze(value);
1176
- }
1177
- return value;
1178
- }
1179
- //#endregion
1180
- //#region ../../core/kernel/src/vocab/address.ts
1181
- /**
1182
- * A session's address: the `(Agent, Workspace)` pair it belongs to.
1183
- * Immutable for the session's whole life — it is set once at session
1184
- * creation and carried on every persisted event of that session and on
1185
- * the control state folded from them.
1186
- */
1187
- const SessionAddressSchema = z.object({
1188
- agentId: z.string(),
1189
- workspaceId: z.string()
1190
- });
1191
- //#endregion
1192
- //#region ../../core/kernel/src/vocab/message.ts
1193
- /**
1194
- * The transcript's message shapes: the authoritative history that assembly
1195
- * reads. A message is either a plain user/assistant turn of text, an
1196
- * assistant reply that also requests tool calls, or a tool-results message
1197
- * that answers a batch of those calls. Zod schemas are the source of
1198
- * truth; the types are `z.infer`red from them so this vocabulary survives
1199
- * the event log round trip once `packages/core/store-sqlite` serializes it.
1200
- *
1201
- * Tool results are carried in a `role: 'user'` message with `tool-result`
1202
- * content parts. Protocol implementations translate this neutral transcript
1203
- * into their own request representation.
1204
- */
1205
- const MessageRoleSchema = z.enum(["user", "assistant"]);
1206
- const TextPartSchema = z.object({
1207
- type: z.literal("text"),
1208
- text: z.string()
1209
- });
1210
- /** The model's thinking, attached to the same assistant message its reply
1211
- * text is. Symmetric with `TextPart` on purpose — it is the recorded
1212
- * counterpart of the publish-only `thinking-delta` chunk, carried the
1213
- * same way `TextPart` carries the recorded counterpart of `text-delta`.
1214
- * Accumulating deltas into this shape, and deciding whether to send it
1215
- * back on the next call, is the adapter's job — this package only
1216
- * carries it. */
1217
- const ThinkingPartSchema = z.object({
1218
- type: z.literal("thinking"),
1219
- text: z.string(),
1220
- /** An opaque token the provider issued with this block and requires back
1221
- * **unmodified** on any later turn that continues the same conversation.
1222
- * A fabricated or edited value can invalidate replay. Absent for protocols
1223
- * that issue no signature. The kernel never reads it; it only
1224
- * carries it, so that the adapter that produced it can hand it back. */
1225
- signature: z.string().optional(),
1226
- /**
1227
- * Which endpoint issued that signature.
1228
- *
1229
- * A signature is only worth anything to whoever signed it, and the product
1230
- * cannot tell whether two endpoints are the same signer — two keys against
1231
- * one vendor, or a proxy in front of it, look identical from here. So this
1232
- * is compared as an endpoint id and the comparison is a deliberate
1233
- * over-approximation: an adapter drops a block another endpoint signed,
1234
- * which between two endpoints of one vendor costs a block that would have
1235
- * replayed. The other way round costs a rejected request.
1236
- *
1237
- * Absent wherever `signature` is: nothing to attribute. The kernel never
1238
- * reads either; it carries them so the adapter that made the block can
1239
- * decide.
1240
- */
1241
- issuer: z.string().optional(),
1242
- /** Model identifier that produced this signed thinking block. */
1243
- originModel: z.string().optional(),
1244
- /**
1245
- * Stable compatibility fingerprint for the non-thinking prefix covered by
1246
- * the provider signature. Adapters omit a signed block when it does not match
1247
- * the request prefix they are about to send.
1248
- */
1249
- prefix: z.string().optional(),
1250
- /**
1251
- * Original output-token count used as a conservative upper bound when the
1252
- * provider retains more thinking state than the visible text represents.
1253
- */
1254
- outputTokens: z.number().int().nonnegative().optional(),
1255
- /**
1256
- * Set on a block the provider returned with no readable text — a protocol's
1257
- * `redacted_thinking`. `text` is then empty and `signature` holds the
1258
- * provider's opaque `data`, which goes back unmodified in the same place.
1259
- */
1260
- redacted: z.literal(true).optional()
1261
- });
1262
- /** A tool call the model requested. `input` is whatever JSON-serializable
1263
- * arguments the model produced for it — the kernel does not validate a
1264
- * tool's own argument shape, only that the call itself round-trips. */
1265
- const ToolUsePartSchema = z.object({
1266
- type: z.literal("tool-use"),
1267
- id: z.string(),
1268
- name: z.string(),
1269
- input: z.unknown()
1270
- });
1271
- const Sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
1272
- /** The copy of a file a model is sent, when it differs from the original:
1273
- * a content-addressed variant within every built-in provider type's limits. */
1274
- const FileVariantSchema = z.object({
1275
- id: Sha256Schema,
1276
- mediaType: z.string().min(1),
1277
- size: z.number().int().positive(),
1278
- width: z.number().int().positive().optional(),
1279
- height: z.number().int().positive().optional()
1280
- }).strict();
1281
- /**
1282
- * A reference to a content-addressed file of the session's workspace. Only
1283
- * metadata: the bytes live on disk under the workspace's `files/` directory
1284
- * and reach a request through `ModelRequest.files` alone, so an event, a
1285
- * frame or a snapshot never carries them. `name` belongs to the reference,
1286
- * not to the file: the same bytes may be named differently in two messages.
1287
- */
1288
- const FileRefSchema = z.object({
1289
- /** The original's sha256, lower-case hex. */
1290
- id: Sha256Schema,
1291
- mediaType: z.string().min(1),
1292
- name: z.string().min(1).max(200),
1293
- size: z.number().int().positive(),
1294
- /** Present for an image. */
1295
- width: z.number().int().positive().optional(),
1296
- height: z.number().int().positive().optional(),
1297
- /** The variant a model receives; absent when the original is within limits. */
1298
- forModel: FileVariantSchema.optional()
1299
- }).strict();
1300
- /** A file inside a message, at the place it was written: text and file parts
1301
- * interleave in the order a person composed them. */
1302
- const FilePartSchema = z.object({
1303
- type: z.literal("file"),
1304
- file: FileRefSchema
1305
- });
1306
- /** The answer to one tool call, matched back to it by `toolUseId`. */
1307
- const ToolResultPartSchema = z.object({
1308
- type: z.literal("tool-result"),
1309
- toolUseId: z.string(),
1310
- /** Immutable host-accepted snapshots. */
1311
- widgets: z.array(WidgetInstanceSchema).max(8).optional(),
1312
- /** Fixed admission diagnostics. */
1313
- widgetIssues: z.array(WidgetIssueSchema).max(8).optional(),
1314
- content: z.string(),
1315
- isError: z.boolean().optional(),
1316
- /** Requested preview body tokens; invalid hints are ignored by the host. */
1317
- previewTokens: z.number().optional(),
1318
- /** First-delivery instructions kept whole; ordinary history reduction remains allowed. */
1319
- previewProtected: z.boolean().optional(),
1320
- /** Files the call handed back, after its text. */
1321
- files: z.array(FileRefSchema).optional()
1322
- });
1323
- const ContentPartSchema = z.discriminatedUnion("type", [
1324
- TextPartSchema,
1325
- ThinkingPartSchema,
1326
- ToolUsePartSchema,
1327
- ToolResultPartSchema,
1328
- FilePartSchema
1329
- ]);
1330
- /**
1331
- * One volatile contributor's text as a request carried it: the contributor's
1332
- * `id` and the strings it gave, joined by a blank line. A request appends a
1333
- * note only when it differs from that contributor's last note in the history,
1334
- * or at a turn's first step, and the note stays in every later request at the
1335
- * place it was first sent.
1336
- */
1337
- const VolatileNoteSchema = z.object({
1338
- id: z.string(),
1339
- text: z.string()
1340
- }).strict();
1341
- /**
1342
- * Where a person's message came in, when it came in through a channel that
1343
- * names itself: the channel's id and display label, and the speaker the
1344
- * channel reported. Written by the gateway's access layer alone; a message
1345
- * typed in the product's own client carries none.
1346
- */
1347
- const MessageViaSchema = z.object({
1348
- channel: z.string().min(1),
1349
- label: z.string().min(1),
1350
- /** Who spoke, as the channel identifies them. `role` is whether they were
1351
- * the owner when they sent it; a later change of owner leaves it. */
1352
- sender: z.object({
1353
- id: z.string().min(1),
1354
- name: z.string().min(1).max(64),
1355
- role: z.enum(["owner", "member"])
1356
- }).strict().optional()
1357
- }).strict();
1358
- const MessageSchema = z.object({
1359
- /** UUID assigned when the message first forms and retained by every fork. */
1360
- id: z.string().uuid(),
1361
- role: MessageRoleSchema,
1362
- content: z.array(ContentPartSchema),
1363
- /** Present only on a message the model refused to complete — the
1364
- * provider's own category for why.
1365
- *
1366
- * It lives **on the message** rather than only on the `message-appended`
1367
- * event that records it, and that distinction is the whole point: `fold`
1368
- * rebuilds the transcript out of `event.message`, so a marker carried only
1369
- * by the event survives the log and is lost the moment anybody folds it
1370
- * back. The transcript needs to remember that a reply was a refusal,
1371
- * which means the message has to. Contrast `backfilled`, which stays on
1372
- * the event because it describes how that event came to be rather than
1373
- * anything about the message. */
1374
- refusalCategory: z.string().optional(),
1375
- /** Present on a message a composer command produced: what the person
1376
- * wrote, and the source that expanded it. `content` holds the expansion,
1377
- * which is what the model is sent; the transcript shows `text`. */
1378
- invocation: z.object({
1379
- text: z.string(),
1380
- namespace: z.string()
1381
- }).strict().optional(),
1382
- /** What a person attached, one entry per leading text block of `content`,
1383
- * which holds each attachment's original text. The model-facing envelope is
1384
- * added where a request is assembled and is never stored. */
1385
- attachments: z.array(z.object({
1386
- namespace: z.string(),
1387
- group: z.string().optional(),
1388
- label: z.string()
1389
- }).strict()).optional(),
1390
- /** Present only on a model reply: the pair that produced it, stamped by the
1391
- * host on the final chunk. On the message rather than the event for the
1392
- * reason `refusalCategory` is: `fold` rebuilds the transcript from
1393
- * `event.message`, and the latest reply's pair is what names the model a
1394
- * compaction after a switch summarizes on. */
1395
- model: z.object({
1396
- providerId: z.string(),
1397
- model: z.string()
1398
- }).strict().optional(),
1399
- /** Present only on a model reply: the volatile notes the request that
1400
- * produced it appended. Adapters render them just before this message, so
1401
- * every later request repeats the earlier one byte for byte. Clients do not
1402
- * draw them. */
1403
- volatile: z.array(VolatileNoteSchema).optional(),
1404
- /** Present only on a person's message that arrived through a labelled
1405
- * channel. Adapters never see it: the request a model receives carries a
1406
- * speaker line instead, added where the request is assembled. */
1407
- via: MessageViaSchema.optional(),
1408
- /** Durable host attribution, preserved in the transcript when the log is replayed. */
1409
- source: z.object({
1410
- kind: z.enum([
1411
- "delegation-result",
1412
- "delegation-task",
1413
- "notice",
1414
- "trigger",
1415
- "trigger-data"
1416
- ]),
1417
- owner: z.string(),
1418
- taskId: z.string(),
1419
- deliveryId: z.string().optional(),
1420
- /** The trigger definition a `trigger` or `trigger-data` delivery ran for. */
1421
- triggerId: z.string().optional(),
1422
- /** What a person calls the source: a scheduled task's name. */
1423
- label: z.string().optional()
1424
- }).strict().optional()
1425
- });
652
+ const VolatileNoteSchema = z.object({
653
+ id: z.string(),
654
+ text: z.string()
655
+ }).strict();
656
+ /**
657
+ * Where a person's message came in, when it came in through a channel that
658
+ * names itself: the channel's id and display label, and the speaker the
659
+ * channel reported. Written by the gateway's access layer alone; a message
660
+ * typed in the product's own client carries none.
661
+ */
662
+ const MessageViaSchema = z.object({
663
+ channel: z.string().min(1),
664
+ label: z.string().min(1),
665
+ /** Who spoke, as the channel identifies them. `role` is whether they were
666
+ * the owner when they sent it; a later change of owner leaves it. */
667
+ sender: z.object({
668
+ id: z.string().min(1),
669
+ name: z.string().min(1).max(64),
670
+ role: z.enum(["owner", "member"])
671
+ }).strict().optional()
672
+ }).strict();
673
+ /** Protocol-declared termination, independent of token usage. */
674
+ const FinishReasonSchema = z.enum([
675
+ "stop",
676
+ "tool-calls",
677
+ "max-tokens",
678
+ "refusal"
679
+ ]);
680
+ /** Discarded partial calls contain identities only, never executable arguments. */
681
+ const OutputTruncationSchema = z.object({
682
+ incompleteToolCalls: z.array(z.object({
683
+ id: z.string(),
684
+ name: z.string().optional()
685
+ })),
686
+ incompleteThinking: z.literal(true).optional()
687
+ });
688
+ const MessageSchema = z.object({
689
+ /** Host request identity for committed model usage and observation matching. */
690
+ modelCallId: z.string().min(1).max(256).optional(),
691
+ /** Protocol replay receipt stamped by the host after successful model completion. */
692
+ modelReplay: ModelReplaySchema.optional(),
693
+ finishReason: FinishReasonSchema.optional(),
694
+ outputTruncation: OutputTruncationSchema.optional(),
695
+ outputContinuation: z.object({
696
+ replyId: z.string().uuid(),
697
+ attempt: z.number().int().min(1).max(3)
698
+ }).optional(),
699
+ /** Immutable owner provenance, excluded from all model communication. */
700
+ ownerContext: OwnerContextSchema.optional(),
701
+ /** UUID assigned when the message first forms and retained by every fork. */
702
+ id: z.string().uuid(),
703
+ role: MessageRoleSchema,
704
+ content: z.array(ContentPartSchema),
705
+ /** Present only on a message the model refused to complete — the
706
+ * provider's own category for why.
707
+ *
708
+ * It lives **on the message** rather than only on the `message-appended`
709
+ * event that records it, and that distinction is the whole point: `fold`
710
+ * rebuilds the transcript out of `event.message`, so a marker carried only
711
+ * by the event survives the log and is lost the moment anybody folds it
712
+ * back. The transcript needs to remember that a reply was a refusal,
713
+ * which means the message has to. Contrast `backfilled`, which stays on
714
+ * the event because it describes how that event came to be rather than
715
+ * anything about the message. */
716
+ refusalCategory: z.string().optional(),
717
+ /** Present on a message a composer command produced: what the person
718
+ * wrote, and the source that expanded it. `content` holds the expansion,
719
+ * which is what the model is sent; the transcript shows `text`. */
720
+ invocation: z.object({
721
+ text: z.string(),
722
+ namespace: z.string()
723
+ }).strict().optional(),
724
+ /** What a person attached, one entry per leading text block of `content`,
725
+ * which holds each attachment's original text. The model-facing envelope is
726
+ * added where a request is assembled and is never stored. */
727
+ attachments: z.array(z.object({
728
+ namespace: z.string(),
729
+ group: z.string().optional(),
730
+ label: z.string()
731
+ }).strict()).optional(),
732
+ /** Present only on a model reply: the pair that produced it, stamped by the
733
+ * host on the final chunk. On the message rather than the event for the
734
+ * reason `refusalCategory` is: `fold` rebuilds the transcript from
735
+ * `event.message`, and the latest reply's pair is what names the model a
736
+ * compaction after a switch summarizes on. */
737
+ model: z.object({
738
+ providerId: z.string(),
739
+ model: z.string()
740
+ }).strict().optional(),
741
+ /** Present only on a model reply: the volatile notes the request that
742
+ * produced it appended. Adapters render them just before this message, so
743
+ * every later request repeats the earlier one byte for byte. Clients do not
744
+ * draw them. */
745
+ volatile: z.array(VolatileNoteSchema).optional(),
746
+ /** Present only on a person's message that arrived through a labelled
747
+ * channel. Adapters never see it: the request a model receives carries a
748
+ * speaker line instead, added where the request is assembled. */
749
+ via: MessageViaSchema.optional(),
750
+ /** Durable host attribution, preserved in the transcript when the log is replayed. */
751
+ source: z.object({
752
+ kind: z.enum([
753
+ "delegation-result",
754
+ "delegation-task",
755
+ "notice",
756
+ "trigger",
757
+ "trigger-data"
758
+ ]),
759
+ owner: z.string(),
760
+ taskId: z.string(),
761
+ deliveryId: z.string().optional(),
762
+ /** The trigger definition a `trigger` or `trigger-data` delivery ran for. */
763
+ triggerId: z.string().optional(),
764
+ /** What a person calls the source: a scheduled task's name. */
765
+ label: z.string().optional()
766
+ }).strict().optional()
767
+ });
1426
768
  //#endregion
1427
769
  //#region ../../core/kernel/src/vocab/human.ts
1428
770
  /**
@@ -1455,6 +797,8 @@ const HumanOptionSchema = z.object({
1455
797
  * text is the only answer there is. */
1456
798
  const HumanQuestionSchema = z.object({
1457
799
  id: z.string().min(1),
800
+ /** Optional short title for question navigation, separate from the complete text. */
801
+ header: z.string().optional(),
1458
802
  text: z.string().min(1),
1459
803
  options: z.array(HumanOptionSchema),
1460
804
  freeText: z.boolean(),
@@ -1512,16 +856,80 @@ z.object({
1512
856
  suspendedCalls: z.array(ToolUsePartSchema)
1513
857
  });
1514
858
  //#endregion
859
+ //#region ../../core/kernel/src/vocab/model-failure.ts
860
+ /** Bounded, verified facts about a logical model call failure. */
861
+ /** Stable failure facts; arbitrary provider text and unknown fields are refused. */
862
+ const ModelFailureSchema = z.strictObject({
863
+ code: z.enum([
864
+ "finish-reason-missing",
865
+ "finish-reason-unsupported",
866
+ "response-empty",
867
+ "final-chunk-missing",
868
+ "stream-interrupted",
869
+ "stream-idle-timeout",
870
+ "http-error",
871
+ "request-too-large",
872
+ "request-measurement-unsupported",
873
+ "authentication-required",
874
+ "authentication-expired",
875
+ "quota-exceeded",
876
+ "model-unavailable",
877
+ "context-limit-exceeded",
878
+ "provider-error",
879
+ "response-invalid",
880
+ "unknown"
881
+ ]),
882
+ stage: z.enum([
883
+ "request",
884
+ "transport",
885
+ "stream",
886
+ "response-validation",
887
+ "unknown"
888
+ ]),
889
+ category: z.enum([
890
+ "network",
891
+ "provider",
892
+ "request-too-large",
893
+ "protocol",
894
+ "unknown"
895
+ ]),
896
+ source: z.enum([
897
+ "protocol",
898
+ "transport",
899
+ "provider",
900
+ "host",
901
+ "unknown"
902
+ ]),
903
+ status: z.number().int().min(100).max(599).optional(),
904
+ retryable: z.boolean().optional(),
905
+ finishReason: z.enum([
906
+ "stop",
907
+ "tool-calls",
908
+ "max-tokens",
909
+ "refusal"
910
+ ]).optional(),
911
+ providerCode: z.enum([
912
+ "usage_not_included",
913
+ "usage_limit_reached",
914
+ "insufficient_quota",
915
+ "context_length_exceeded",
916
+ "rate_limit_exceeded",
917
+ "overloaded_error",
918
+ "api_error",
919
+ "rate_limit_error",
920
+ "cyber_policy",
921
+ "invalid_prompt",
922
+ "bio_policy",
923
+ "misalignment_policy_violation"
924
+ ]).optional(),
925
+ attemptCount: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
926
+ modelCallId: z.uuid().optional(),
927
+ turn: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
928
+ step: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()
929
+ }).refine((value) => JSON.stringify(value).length <= 2048, "model failure exceeds its size limit");
930
+ //#endregion
1515
931
  //#region ../../core/kernel/src/vocab/outcome.ts
1516
- /**
1517
- * How a turn ended: an exhaustive union at the top level (`completed` /
1518
- * `interrupted` / `failed`), open underneath it in `completed`'s reason
1519
- * (more reasons to stop are a pure addition, the three top-level kinds
1520
- * are closed). `completed` means the turn ended cleanly, not that it
1521
- * achieved a goal: hitting a limit, being
1522
- * refused and being policy-blocked all land here because each of them
1523
- * leaves a legal transcript with nothing broken.
1524
- */
932
+ /** Turn endings distinguish ordinary completion, cancellation, failures and host execution stops. */
1525
933
  const CompletedReasonSchema = z.enum([
1526
934
  "natural",
1527
935
  "step-limit",
@@ -1543,12 +951,50 @@ const InterruptedOutcomeSchema = z.object({ kind: z.literal("interrupted") });
1543
951
  * has more of these than this change implements transitions for. */
1544
952
  const FailedOutcomeSchema = z.object({
1545
953
  kind: z.literal("failed"),
1546
- reason: z.string()
954
+ reason: z.string(),
955
+ failure: ModelFailureSchema.optional()
956
+ });
957
+ /** A verified shared-resource admission failure; no model retry can create capacity. */
958
+ const ResourceExhaustionSchema = z.object({
959
+ reason: z.literal("resource-exhausted"),
960
+ pool: z.literal("query"),
961
+ dimension: z.enum([
962
+ "session-slots",
963
+ "session-bytes",
964
+ "resident-bytes",
965
+ "session-scratch",
966
+ "resident-scratch"
967
+ ]),
968
+ limit: z.number().int().positive().safe(),
969
+ held: z.number().int().nonnegative().safe(),
970
+ requested: z.number().int().nonnegative().safe(),
971
+ cleanup: z.enum([
972
+ "none",
973
+ "pending",
974
+ "failed"
975
+ ]),
976
+ recovery: z.enum([
977
+ "wait-cleanup",
978
+ "owner-recovery",
979
+ "expire-resources"
980
+ ])
981
+ });
982
+ /** Successful model output exhausted the fixed continuation budget. */
983
+ const ExecutionStopSchema = z.discriminatedUnion("reason", [ResourceExhaustionSchema, z.object({
984
+ reason: z.literal("output-limit"),
985
+ continuationsUsed: z.literal(3),
986
+ continuationLimit: z.literal(3)
987
+ })]);
988
+ /** A host execution boundary stopped a legal transcript without natural completion. */
989
+ const StoppedOutcomeSchema = z.object({
990
+ kind: z.literal("stopped"),
991
+ stop: ExecutionStopSchema
1547
992
  });
1548
993
  const OutcomeSchema = z.discriminatedUnion("kind", [
1549
994
  CompletedOutcomeSchema,
1550
995
  InterruptedOutcomeSchema,
1551
- FailedOutcomeSchema
996
+ FailedOutcomeSchema,
997
+ StoppedOutcomeSchema
1552
998
  ]);
1553
999
  //#endregion
1554
1000
  //#region ../../core/kernel/src/vocab/session-id.ts
@@ -1610,6 +1056,8 @@ z.object({
1610
1056
  phase: PhaseSchema,
1611
1057
  turn: z.number().int().nonnegative(),
1612
1058
  step: z.number().int().nonnegative(),
1059
+ outputContinuationsUsed: z.number().int().min(0).max(3),
1060
+ pendingOutputContinuation: z.object({ replyId: z.string().uuid() }).optional(),
1613
1061
  turnTokensUsed: z.number().int().nonnegative(),
1614
1062
  pendingToolCalls: z.array(PendingToolCallSchema),
1615
1063
  pendingHumanRequests: z.array(PendingHumanRequestSchema),
@@ -1659,6 +1107,24 @@ z.object({
1659
1107
  * throwing — a log a later build appended new variants to must still read
1660
1108
  * on an older one.
1661
1109
  */
1110
+ /** Durable owner JSON state and its idempotent operation receipt, ordered by physical sequence. */
1111
+ const OwnerStateEventSchema = OwnerContextEntrySchema.extend({
1112
+ kind: z.literal("owner-state"),
1113
+ sessionId: SessionIdSchema,
1114
+ address: SessionAddressSchema,
1115
+ operationId: z.string().min(1).max(256),
1116
+ requestHash: z.string().min(1).max(256)
1117
+ }).superRefine(({ owner, key, revision, data }, ctx) => {
1118
+ if (!OwnerContextSchema.safeParse([{
1119
+ owner,
1120
+ key,
1121
+ revision,
1122
+ data
1123
+ }]).success) ctx.addIssue({
1124
+ code: "custom",
1125
+ message: "Invalid or oversized owner state"
1126
+ });
1127
+ });
1662
1128
  const TriggerSourceSchema = z.enum(["human", "plugin"]);
1663
1129
  /** What a model call reported using, in the terms its final chunk gives
1664
1130
  * us. Carried on `model-replied` and folded into `ControlState.turnTokensUsed`
@@ -1704,6 +1170,8 @@ const TriggerEventSchema = z.object({
1704
1170
  * without needing the full `FinishReason` union carried over the wire. */
1705
1171
  const ModelRepliedEventSchema = z.object({
1706
1172
  kind: z.literal("model-replied"),
1173
+ finishReason: FinishReasonSchema,
1174
+ outputTruncation: OutputTruncationSchema.optional(),
1707
1175
  message: MessageSchema,
1708
1176
  usage: ModelUsageSchema,
1709
1177
  refusalCategory: z.string().optional()
@@ -1713,7 +1181,10 @@ const ModelRepliedEventSchema = z.object({
1713
1181
  * same reason as `model-replied`. */
1714
1182
  const ToolResultsAddedEventSchema = z.object({
1715
1183
  kind: z.literal("tool-results-added"),
1716
- message: MessageSchema
1184
+ ownerStates: z.array(OwnerStateEventSchema).max(16).optional(),
1185
+ message: MessageSchema,
1186
+ /** Host-verified stop, settled after all admitted calls finish. */
1187
+ stop: ExecutionStopSchema.optional()
1717
1188
  });
1718
1189
  /** A message became part of the transcript. */
1719
1190
  const MessageAppendedEventSchema = z.object({
@@ -1769,7 +1240,13 @@ const ContextMeasurementSchema = z.object({
1769
1240
  fingerprint: z.string(),
1770
1241
  inputBudget: z.number().int().nonnegative().optional(),
1771
1242
  /** Whether the reserve is enforceable upstream or the catalogue capacity. */
1772
- outputReserveSource: z.enum(["capacity", "enforced"]).optional()
1243
+ outputReserveSource: z.enum([
1244
+ "capacity",
1245
+ "enforced",
1246
+ "estimated"
1247
+ ]).optional(),
1248
+ /** Whether the capacity comes from a declaration or the owner's assumed baseline. */
1249
+ capacitySource: z.enum(["declared", "assumed"]).optional()
1773
1250
  });
1774
1251
  /** Why the context operation started. */
1775
1252
  const ContextTriggerSchema = z.enum([
@@ -1829,6 +1306,8 @@ const ContextOperationStatusSchema = z.enum([
1829
1306
  ]);
1830
1307
  /** Durable accounting and outcome for one automatic or explicit context operation. */
1831
1308
  const ContextOperationEventSchema = z.object({
1309
+ /** Independent auxiliary request identity, shared by its checkpoint and final accounting. */
1310
+ modelCallId: z.string().min(1).max(256).optional(),
1832
1311
  kind: z.literal("context-operation"),
1833
1312
  sessionId: SessionIdSchema,
1834
1313
  address: SessionAddressSchema,
@@ -1870,6 +1349,8 @@ const TurnEndedEventSchema = z.object({
1870
1349
  });
1871
1350
  /** Marks the end of copied history in a new independent session. */
1872
1351
  const HistorySeededEventSchema = z.object({
1352
+ /** Context identity of the retained prefix, independent of the destination session. */
1353
+ historyEpoch: z.string().optional(),
1873
1354
  kind: z.literal("history-seeded"),
1874
1355
  sessionId: SessionIdSchema,
1875
1356
  address: SessionAddressSchema,
@@ -1933,7 +1414,8 @@ const CancelledEventSchema = z.object({
1933
1414
  * same reason as `Cancelled`. */
1934
1415
  const EffectFailedEventSchema = z.object({
1935
1416
  kind: z.literal("effect-failed"),
1936
- reason: z.string()
1417
+ reason: z.string(),
1418
+ failure: ModelFailureSchema.optional()
1937
1419
  });
1938
1420
  /** A non-final chunk from the model port's stream, forwarded by the
1939
1421
  * call-model handler so that `decide` — never the handler itself — is
@@ -1946,6 +1428,7 @@ const EffectFailedEventSchema = z.object({
1946
1428
  * published, which only coincides with the port's transport shape today. */
1947
1429
  const ModelChunkEventSchema = z.object({
1948
1430
  kind: z.literal("model-chunk"),
1431
+ ownerContext: OwnerContextSchema.optional(),
1949
1432
  chunk: z.discriminatedUnion("kind", [
1950
1433
  z.object({
1951
1434
  kind: z.literal("text-delta"),
@@ -1969,6 +1452,7 @@ const ModelChunkEventSchema = z.object({
1969
1452
  * handler, which derives the recorded `human-asked` from it. */
1970
1453
  const StepSuspendedEventSchema = z.object({
1971
1454
  kind: z.literal("step-suspended"),
1455
+ ownerStates: z.array(OwnerStateEventSchema).max(16).optional(),
1972
1456
  settled: z.array(ToolResultPartSchema),
1973
1457
  requests: z.array(HumanRequestSchema)
1974
1458
  });
@@ -2008,7 +1492,43 @@ const ParticipantChangedEventSchema = z.object({
2008
1492
  reason: z.string().max(500).optional(),
2009
1493
  at: z.number().int().nonnegative()
2010
1494
  });
1495
+ /** Complete pure admission facts committed before any call in the batch starts. */
1496
+ const ToolCallsAdmittedEventSchema = z.object({
1497
+ kind: z.literal("tool-calls-admitted"),
1498
+ /** Assistant message whose original calls this fact annotates. */
1499
+ messageId: z.string().optional(),
1500
+ sessionId: SessionIdSchema,
1501
+ address: SessionAddressSchema,
1502
+ calls: z.array(z.object({
1503
+ callId: z.string(),
1504
+ partIndex: z.number().int().nonnegative().optional(),
1505
+ entry: z.object({
1506
+ name: z.string(),
1507
+ input: z.unknown()
1508
+ }),
1509
+ target: z.object({
1510
+ name: z.string(),
1511
+ input: z.unknown()
1512
+ }).optional(),
1513
+ definitionFingerprint: z.string(),
1514
+ status: z.enum(["admitted", "rejected"]),
1515
+ errorCode: z.string().optional()
1516
+ }))
1517
+ });
1518
+ /** Durable admission of one bounded continuation in the current turn. */
1519
+ const OutputContinuationStartedEventSchema = z.object({
1520
+ kind: z.literal("output-continuation-started"),
1521
+ sessionId: SessionIdSchema,
1522
+ address: SessionAddressSchema,
1523
+ turn: z.number().int().positive(),
1524
+ step: z.number().int().positive(),
1525
+ replyId: z.string().uuid(),
1526
+ attempt: z.number().int().min(1).max(3)
1527
+ });
2011
1528
  const RecordableEventSchema = z.discriminatedUnion("kind", [
1529
+ OutputContinuationStartedEventSchema,
1530
+ ToolCallsAdmittedEventSchema,
1531
+ OwnerStateEventSchema,
2012
1532
  TriggerEventSchema,
2013
1533
  HistorySeededEventSchema,
2014
1534
  HistoryRewoundEventSchema,
@@ -2022,6 +1542,9 @@ const RecordableEventSchema = z.discriminatedUnion("kind", [
2022
1542
  ParticipantChangedEventSchema
2023
1543
  ]);
2024
1544
  const EventSchema = z.discriminatedUnion("kind", [
1545
+ OutputContinuationStartedEventSchema,
1546
+ ToolCallsAdmittedEventSchema,
1547
+ OwnerStateEventSchema,
2025
1548
  TriggerEventSchema,
2026
1549
  HistorySeededEventSchema,
2027
1550
  HistoryRewoundEventSchema,
@@ -2099,6 +1622,214 @@ z.discriminatedUnion("kind", [
2099
1622
  CheckpointEffectSchema
2100
1623
  ]);
2101
1624
  //#endregion
1625
+ //#region ../../core/protocol/src/telemetry.ts
1626
+ /** Finite performance stages exclude arbitrary paths, SQL and business text. */
1627
+ const TelemetryStage = z.enum([
1628
+ "ui.interaction",
1629
+ "ui.feedback",
1630
+ "ui.commit",
1631
+ "ui.frame",
1632
+ "ui.stream-display",
1633
+ "reading.watch",
1634
+ "reading.content",
1635
+ "reading.page",
1636
+ "reading.queue",
1637
+ "reading.worker",
1638
+ "reading.projection",
1639
+ "reading.ack-wait",
1640
+ "reading.loss",
1641
+ "reading.source",
1642
+ "markdown.parse",
1643
+ "markdown.mount",
1644
+ "rpc.encode",
1645
+ "rpc.send",
1646
+ "rpc.receive",
1647
+ "rpc.decode",
1648
+ "rpc.resolve",
1649
+ "rpc.roundtrip",
1650
+ "rpc.dispatch",
1651
+ "browser.long-task",
1652
+ "browser.frame-gap",
1653
+ "browser.loss",
1654
+ "browser.input-delay",
1655
+ "native.bridge",
1656
+ "native.command",
1657
+ "native.socket.connect",
1658
+ "native.socket.queue",
1659
+ "native.socket.send",
1660
+ "native.socket.receive",
1661
+ "native.http.headers",
1662
+ "native.http.body",
1663
+ "native.file.open",
1664
+ "native.file.write",
1665
+ "native.file.commit",
1666
+ "native.file.cleanup",
1667
+ "native.picker.wait",
1668
+ "native.loss",
1669
+ "gateway.decode",
1670
+ "gateway.handler",
1671
+ "gateway.encode",
1672
+ "gateway.send",
1673
+ "runtime.admission",
1674
+ "runtime.event-batch",
1675
+ "runtime.owner-context",
1676
+ "runtime.prepare",
1677
+ "runtime.status",
1678
+ "runtime.snapshot",
1679
+ "runtime.publish",
1680
+ "runtime.reading",
1681
+ "runtime.turn",
1682
+ "model.inspect",
1683
+ "model.tokenizer",
1684
+ "model.cache",
1685
+ "model.call",
1686
+ "model.display",
1687
+ "context.inspect",
1688
+ "context.contributor",
1689
+ "tool.call",
1690
+ "database.read",
1691
+ "database.open",
1692
+ "database.close",
1693
+ "database.decode",
1694
+ "database.statement",
1695
+ "database.serialize",
1696
+ "database.transaction",
1697
+ "database.event-insert",
1698
+ "database.reading-projection",
1699
+ "database.commit",
1700
+ "database.rollback",
1701
+ "database.busy",
1702
+ "database.checkpoint",
1703
+ "file.open",
1704
+ "file.write",
1705
+ "file.rename",
1706
+ "file.close",
1707
+ "file.fsync",
1708
+ "file.directory-sync",
1709
+ "file.publication",
1710
+ "file.cleanup",
1711
+ "event-loop.delay",
1712
+ "event-loop.max",
1713
+ "event-loop.p95",
1714
+ "event-loop.p99",
1715
+ "event-loop.utilization",
1716
+ "process.cpu",
1717
+ "process.rss",
1718
+ "process.heap",
1719
+ "process.gc",
1720
+ "logging.write"
1721
+ ]);
1722
+ /** User intent labels contain no user-supplied text. */
1723
+ const TelemetryOperation = z.enum([
1724
+ "session-switch",
1725
+ "send",
1726
+ "human-answer",
1727
+ "approval",
1728
+ "cancel",
1729
+ "history-page",
1730
+ "heartbeat",
1731
+ "generic"
1732
+ ]);
1733
+ const nonnegative = z.number().finite().nonnegative();
1734
+ const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
1735
+ const identity = z.string().min(1).max(128).regex(/^[A-Za-z0-9@][A-Za-z0-9@/_.:-]*$/);
1736
+ /** Correlation is foreign input; server span and connection identities are host-supplied. */
1737
+ const RequestTrace = z.object({
1738
+ traceId: z.uuid(),
1739
+ parentSpanId: z.uuid().optional(),
1740
+ interactionId: z.uuid().optional()
1741
+ }).strict();
1742
+ /** One same-clock duration, with strictly bounded scalar metadata. */
1743
+ const TelemetryObservation = z.object({
1744
+ stage: TelemetryStage,
1745
+ clockDomain: z.uuid(),
1746
+ monotonicStartMs: nonnegative,
1747
+ durationMs: nonnegative,
1748
+ outcome: z.enum([
1749
+ "ok",
1750
+ "error",
1751
+ "cancelled",
1752
+ "timeout",
1753
+ "unknown"
1754
+ ]).optional(),
1755
+ operation: TelemetryOperation.optional(),
1756
+ spanId: z.uuid().optional(),
1757
+ traceId: z.uuid().optional(),
1758
+ parentSpanId: z.uuid().optional(),
1759
+ interactionId: z.uuid().optional(),
1760
+ sessionId: identity.optional(),
1761
+ requestId: identity.optional(),
1762
+ visibility: z.enum(["foreground", "background"]).optional(),
1763
+ cacheState: z.enum([
1764
+ "hit",
1765
+ "miss",
1766
+ "cold",
1767
+ "warm"
1768
+ ]).optional(),
1769
+ measurementPurpose: z.enum([
1770
+ "request",
1771
+ "text",
1772
+ "catalogue",
1773
+ "tool-result",
1774
+ "display"
1775
+ ]).optional(),
1776
+ bytes: counter.optional(),
1777
+ count: counter.optional(),
1778
+ hits: counter.optional(),
1779
+ misses: counter.optional(),
1780
+ evictions: counter.optional(),
1781
+ inputBytes: counter.optional(),
1782
+ retainedBytes: counter.optional()
1783
+ }).strict();
1784
+ /** Runtime-only capture controls; diagnostic TTL defaults to fifteen minutes. */
1785
+ const TelemetryConfigure = z.object({
1786
+ mode: z.enum([
1787
+ "off",
1788
+ "normal",
1789
+ "diagnostic"
1790
+ ]),
1791
+ durationSeconds: z.number().int().min(1).max(3600).optional()
1792
+ }).strict();
1793
+ /** Bounded client batch; transport additionally checks its serialized byte count. */
1794
+ const TelemetryIngest = z.object({
1795
+ batchId: z.uuid(),
1796
+ pageId: z.uuid(),
1797
+ observations: z.array(TelemetryObservation).max(128)
1798
+ }).strict();
1799
+ z.object({
1800
+ mode: z.enum([
1801
+ "off",
1802
+ "normal",
1803
+ "diagnostic"
1804
+ ]),
1805
+ expiresAt: z.iso.datetime().optional(),
1806
+ pendingRecords: counter,
1807
+ pendingBytes: counter,
1808
+ droppedRecords: counter,
1809
+ capabilities: z.object({ eventLoop: z.boolean() }).strict(),
1810
+ budgets: z.object({
1811
+ targetMs: z.literal(15),
1812
+ batchRecords: z.literal(128),
1813
+ batchBytes: z.literal(65536),
1814
+ recordBytes: z.literal(8192)
1815
+ }).strict()
1816
+ }).strict();
1817
+ /** Authenticated browser and native observation admission. */
1818
+ const TelemetryIngestRequest = z.object({
1819
+ method: z.literal("gateway.telemetryIngest"),
1820
+ params: TelemetryIngest
1821
+ });
1822
+ /** Authenticated collection status query. */
1823
+ const TelemetryStatusRequest = z.object({
1824
+ method: z.literal("gateway.telemetryStatus"),
1825
+ params: z.object({}).strict().optional()
1826
+ });
1827
+ /** Authenticated runtime-only collection configuration. */
1828
+ const TelemetryConfigureRequest = z.object({
1829
+ method: z.literal("gateway.telemetryConfigure"),
1830
+ params: TelemetryConfigure
1831
+ });
1832
+ //#endregion
2102
1833
  //#region ../../core/protocol/src/agent-revisions.ts
2103
1834
  /** Configuration history wire contracts. Shared resource contents are excluded. */
2104
1835
  const AgentId = z.string().min(1);
@@ -2310,8 +2041,13 @@ const ReadingTurnHeader = z.object({
2310
2041
  "running",
2311
2042
  "completed",
2312
2043
  "cancelled",
2313
- "failed"
2314
- ])
2044
+ "failed",
2045
+ "stopped"
2046
+ ]),
2047
+ /** Structured framework stop, independent of failed model response diagnostics. */
2048
+ stop: ExecutionStopSchema.optional(),
2049
+ reason: z.string().max(512).optional(),
2050
+ failure: ModelFailureSchema.optional()
2315
2051
  });
2316
2052
  /** A contiguous page, ordered by message ordinal. Cursors are exclusive boundaries. */
2317
2053
  const HistoryWindow = z.object({
@@ -2331,6 +2067,10 @@ const ReadingPartHeader = z.object({
2331
2067
  contentRef: ContentRef,
2332
2068
  metadataRef: ContentRef.optional(),
2333
2069
  callId: z.string().optional(),
2070
+ /** Effective admitted tool name, available without loading its input. */
2071
+ toolName: z.string().optional(),
2072
+ /** Committed tool-result failure flag, available without loading its output. */
2073
+ isError: z.boolean().optional(),
2334
2074
  relatedMessageId: z.string().optional(),
2335
2075
  association: z.enum([
2336
2076
  "loaded",
@@ -2378,6 +2118,7 @@ const SessionHistoryPageRequest = z.object({
2378
2118
  historyGeneration: z.number().int().nonnegative(),
2379
2119
  cursor: z.string().max(2048).optional(),
2380
2120
  aroundMessageId: z.string().optional(),
2121
+ turnId: z.string().optional(),
2381
2122
  limit: page
2382
2123
  }).strict().refine((p) => !(p.cursor && p.aroundMessageId))
2383
2124
  });
@@ -2392,16 +2133,39 @@ const SessionMessagePartsRequest = z.object({
2392
2133
  limit: page
2393
2134
  }).strict()
2394
2135
  });
2395
- /** Reads at most 256KiB from one authorized source object. */
2396
- const SessionMessageContentRequest = z.object({
2397
- method: z.literal("session.messageContent"),
2136
+ /** One authorized range consumed by the internal range reader; never a scalar wire entry. */
2137
+ const MessageContentInput = z.object({
2138
+ scope: ContentScope,
2139
+ readingLeaseId: z.string().optional(),
2140
+ contentRefId: z.string().max(256),
2141
+ offset: z.number().int().nonnegative(),
2142
+ maxBytes: z.number().int().min(4).max(262144)
2143
+ }).strict();
2144
+ /** Reads independent ranges after checking the complete raw and encoded budgets. */
2145
+ const SessionMessageContentsRequest = z.object({
2146
+ method: z.literal("session.messageContents"),
2398
2147
  params: z.object({
2399
2148
  scope: ContentScope,
2400
2149
  readingLeaseId: z.string().optional(),
2401
- contentRefId: z.string().max(256),
2402
- offset: z.number().int().nonnegative(),
2403
- maxBytes: z.number().int().min(4).max(262144)
2404
- }).strict()
2150
+ items: z.array(MessageContentInput.omit({
2151
+ scope: true,
2152
+ readingLeaseId: true
2153
+ })).min(1).max(64),
2154
+ maxTotalBytes: z.number().int().min(4).max(1048576).default(1048576)
2155
+ }).strict().superRefine((value, ctx) => {
2156
+ if (value.items.reduce((sum, item) => sum + item.maxBytes, 0) > value.maxTotalBytes) ctx.addIssue({
2157
+ code: "custom",
2158
+ message: "declared raw content exceeds maxTotalBytes"
2159
+ });
2160
+ if (value.items.reduce((sum, item) => sum + 4 * Math.ceil(item.maxBytes / 3) + 65536, 8192) > 2097152) ctx.addIssue({
2161
+ code: "custom",
2162
+ message: "declared encoded result exceeds 2 MiB"
2163
+ });
2164
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 8388608) ctx.addIssue({
2165
+ code: "custom",
2166
+ message: "batch input exceeds 8 MiB"
2167
+ });
2168
+ })
2405
2169
  });
2406
2170
  /** Reads durable annotations or process-local request descriptors. */
2407
2171
  const SessionLivePageRequest = z.object({
@@ -2467,6 +2231,54 @@ z.object({
2467
2231
  hasMore: z.boolean(),
2468
2232
  nextCursor: z.string().optional()
2469
2233
  });
2234
+ /** Selects complete Turn identities independently of their transcript length. */
2235
+ const SessionTurnPageRequest = z.object({
2236
+ method: z.literal("session.turnPage"),
2237
+ params: z.object({
2238
+ sessionId: z.string(),
2239
+ historyGeneration: z.number().int().nonnegative(),
2240
+ cursor: z.string().max(2048).optional(),
2241
+ aroundTurnId: z.string().optional(),
2242
+ aroundMessageId: z.string().optional(),
2243
+ limit: z.number().int().min(1).max(10).default(10)
2244
+ }).strict().refine((p) => [
2245
+ p.cursor,
2246
+ p.aroundTurnId,
2247
+ p.aroundMessageId
2248
+ ].filter(Boolean).length <= 1)
2249
+ });
2250
+ z.object({
2251
+ view: HistoryView,
2252
+ turns: z.array(ReadingTurnHeader).max(10),
2253
+ hasOlder: z.boolean(),
2254
+ hasNewer: z.boolean(),
2255
+ olderCursor: z.string().max(2048).optional(),
2256
+ newerCursor: z.string().max(2048).optional(),
2257
+ targetTurnId: z.string().optional()
2258
+ });
2259
+ /** One original part, or a partless message; repeated message headers have the same identity. */
2260
+ const TurnTranscriptEntry = z.object({
2261
+ message: ReadingMessageHeader,
2262
+ part: ReadingPartHeader.optional()
2263
+ });
2264
+ /** Reads bounded ordered descriptors within one Turn; bodies remain immutable range references. */
2265
+ const SessionTurnTranscriptPageRequest = z.object({
2266
+ method: z.literal("session.turnTranscriptPage"),
2267
+ params: z.object({
2268
+ sessionId: z.string(),
2269
+ historyGeneration: z.number().int().nonnegative(),
2270
+ turnId: z.string(),
2271
+ cursor: z.string().max(2048).optional(),
2272
+ limit: page
2273
+ }).strict()
2274
+ });
2275
+ z.object({
2276
+ view: HistoryView,
2277
+ turnId: z.string(),
2278
+ entries: z.array(TurnTranscriptEntry).max(64),
2279
+ hasMore: z.boolean(),
2280
+ nextCursor: z.string().max(2048).optional()
2281
+ });
2470
2282
  //#endregion
2471
2283
  //#region ../../core/protocol/src/index.ts
2472
2284
  /**
@@ -2541,11 +2353,11 @@ z.enum([
2541
2353
  "session",
2542
2354
  "permanent"
2543
2355
  ]);
2544
- /** One work directory, as `workspace list` shows it and as a search reads it:
2545
- * an absolute real path, resolved when it was added. It carries no mode —
2546
- * every work directory is readable, and what may be *changed* is a grant,
2547
- * answered by a person when a tool asked. */
2548
- const AuthorizedDirectory = z.object({ path: z.string() });
2356
+ /** An authorized workspace tree with its canonical real path and stored access level. */
2357
+ const AuthorizedDirectory = z.object({
2358
+ path: z.string(),
2359
+ access: z.enum(["read", "read-write"])
2360
+ });
2549
2361
  /** A workspace: an abstract scope, **bound to no path**. Its authorized
2550
2362
  * directories hang beneath it, zero of them being the normal state for a
2551
2363
  * freshly created one. */
@@ -2555,11 +2367,11 @@ const WorkspaceSummary = z.object({
2555
2367
  createdAt: z.number().int(),
2556
2368
  /** The revision of the uploaded picture, or `null` for none — then a
2557
2369
  * client draws the letters face derived from the name. The bytes travel
2558
- * only through `config.workspace.avatar`. */
2370
+ * only through `config.workspace.avatars`. */
2559
2371
  avatar: z.string().nullable(),
2560
2372
  /** Already-resolved absolute real paths, the whole tree under each. A
2561
- * summary says which trees this workspace may see and read; what may be
2562
- * changed under one of them is a grant, listed by `config.access.list`. */
2373
+ * summary preserves each authorized tree and its read or read-write level.
2374
+ * Additional resource grants are listed by `config.access.list`. */
2563
2375
  directories: z.array(AuthorizedDirectory)
2564
2376
  });
2565
2377
  /** A session as it appears in a list, without loading it. Everything here
@@ -2688,6 +2500,8 @@ const HumanOption = z.object({
2688
2500
  });
2689
2501
  const HumanQuestion = z.object({
2690
2502
  id: z.string().min(1),
2503
+ /** Optional short title for question navigation, separate from the complete text. */
2504
+ header: z.string().optional(),
2691
2505
  text: z.string().min(1),
2692
2506
  options: z.array(HumanOption),
2693
2507
  /** Whether an answer may skip the options and give text alone. */
@@ -3094,7 +2908,7 @@ const AgentChangedFrame = z.object({
3094
2908
  * names the agent rather than carrying a summary: there is none left. */
3095
2909
  const AgentRemovedFrame = z.object({
3096
2910
  kind: z.literal("config.agentRemoved"),
3097
- agentId: z.string()
2911
+ agentIds: z.array(z.string()).min(1).max(64)
3098
2912
  });
3099
2913
  const WorkspaceChangedFrame = z.object({
3100
2914
  kind: z.literal("config.workspaceChanged"),
@@ -3163,6 +2977,13 @@ const SessionMessageFrame = z.object({
3163
2977
  sourceSeq: z.number().int().min(-1),
3164
2978
  streamEpoch: z.string().optional()
3165
2979
  });
2980
+ /** Committed execution identities annotate existing calls without changing their protocol names. */
2981
+ const SessionToolCallsAdmittedFrame = z.object({
2982
+ kind: z.literal("session.toolCallsAdmitted"),
2983
+ ...sessionFrameBase,
2984
+ messageId: z.string(),
2985
+ sourceSeq: z.number().int().min(-1)
2986
+ });
3166
2987
  /** Replaces the entire effective snapshot after a rewind commits. */
3167
2988
  const SessionHistoryReplacedFrame = z.object({
3168
2989
  kind: z.literal("session.historyReplaced"),
@@ -3535,12 +3356,13 @@ const InboxChangedFrame = z.object({
3535
3356
  const CredentialChangedFrame = z.object({
3536
3357
  kind: z.literal("config.credentialChanged"),
3537
3358
  plugin: z.string(),
3538
- scope: z.string()
3359
+ scopes: z.array(z.string()).min(1).max(64)
3539
3360
  });
3540
3361
  const CoreSessionFrame = z.discriminatedUnion("kind", [
3541
3362
  TurnStartedFrame,
3542
3363
  DeltaFrame,
3543
3364
  DeltaResetFrame,
3365
+ SessionToolCallsAdmittedFrame,
3544
3366
  SessionMessageFrame,
3545
3367
  SessionHistoryReplacedFrame,
3546
3368
  TurnEndedFrame,
@@ -3579,6 +3401,7 @@ const CoreFrame = z.discriminatedUnion("kind", [
3579
3401
  TurnStartedFrame,
3580
3402
  DeltaFrame,
3581
3403
  DeltaResetFrame,
3404
+ SessionToolCallsAdmittedFrame,
3582
3405
  SessionMessageFrame,
3583
3406
  SessionHistoryReplacedFrame,
3584
3407
  TurnEndedFrame,
@@ -3694,20 +3517,39 @@ const SessionSendRequest = z.object({
3694
3517
  }).optional()
3695
3518
  })
3696
3519
  }).refine((request) => !request.params.rewind || request.params.operationId !== void 0);
3697
- /** Creates a new independent session before a current user message. */
3520
+ /** Forks before a committed user input in the displayed history generation; the source may run. */
3698
3521
  const SessionForkRequest = z.object({
3699
3522
  method: z.literal("session.fork"),
3700
3523
  params: z.object({
3701
3524
  sessionId: z.string(),
3702
3525
  beforeMessageId: z.string().uuid(),
3703
- expectedRevision: z.number().int().nonnegative(),
3526
+ expectedHistoryGeneration: z.number().int().nonnegative(),
3704
3527
  operationId: z.string().uuid()
3705
3528
  })
3706
3529
  });
3530
+ const batchIds = () => z.array(z.string().min(1)).min(1).max(64);
3531
+ const queryBudgets = {
3532
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
3533
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
3534
+ };
3535
+ const boundedBatchParams = (shape, collection) => z.object(shape).strict().superRefine((value, ctx) => {
3536
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 8388608) ctx.addIssue({
3537
+ code: "custom",
3538
+ message: "batch input exceeds 8 MiB"
3539
+ });
3540
+ const params = value;
3541
+ if (typeof params.maxItemBytes === "number" && typeof params.maxTotalBytes === "number" && Array.isArray(params[collection]) && params.maxItemBytes * params[collection].length + 8192 > params.maxTotalBytes) ctx.addIssue({
3542
+ code: "custom",
3543
+ message: "declared response budget exceeds maxTotalBytes"
3544
+ });
3545
+ });
3707
3546
  /** Reads one durable history-operation result after an uncertain response. */
3708
- const SessionOperationGetRequest = z.object({
3709
- method: z.literal("session.operation.get"),
3710
- params: z.object({ operationId: z.string().uuid() })
3547
+ const SessionOperationsGetRequest = z.object({
3548
+ method: z.literal("session.operations.get"),
3549
+ params: boundedBatchParams({
3550
+ operationIds: z.array(z.uuid()).min(1).max(64),
3551
+ ...queryBudgets
3552
+ }, "operationIds")
3711
3553
  });
3712
3554
  /** Takes back a message sent while a turn was running, before its step
3713
3555
  * claims it. Answers with the message, so the page that asked can put its
@@ -3797,10 +3639,11 @@ const SessionLeaveRequest = z.object({
3797
3639
  * contract `session.setModel` has. It produces no turn and writes no event. */
3798
3640
  const SessionArchiveRequest = z.object({
3799
3641
  method: z.literal("session.archive"),
3800
- params: z.object({
3801
- sessionId: z.string(),
3642
+ params: boundedBatchParams({
3643
+ operationId: z.uuid(),
3644
+ sessionIds: batchIds(),
3802
3645
  archived: z.boolean()
3803
- })
3646
+ }, "sessionIds")
3804
3647
  });
3805
3648
  /** Sets the name a person gives a session, or clears it: trimmed, at most 60
3806
3649
  * characters, and a name holding nothing but whitespace clears it. Leaves
@@ -3866,7 +3709,10 @@ const ConfigAgentSetPromptSlotRequest = z.object({
3866
3709
  });
3867
3710
  const ConfigAgentPromptSlotsRequest = z.object({
3868
3711
  method: z.literal("config.agent.promptSlots"),
3869
- params: z.object({ agentId: z.string() })
3712
+ params: boundedBatchParams({
3713
+ agentIds: batchIds(),
3714
+ ...queryBudgets
3715
+ }, "agentIds")
3870
3716
  });
3871
3717
  /** Sets an agent's picture, or with `null` returns it to the derived one.
3872
3718
  * The browser crops and encodes; the gateway checks it is a whole 256×256
@@ -3881,9 +3727,12 @@ const ConfigAgentSetAvatarRequest = z.object({
3881
3727
  })
3882
3728
  });
3883
3729
  /** The uploaded picture, or `null` when the agent has none. */
3884
- const ConfigAgentAvatarRequest = z.object({
3885
- method: z.literal("config.agent.avatar"),
3886
- params: z.object({ agentId: z.string() })
3730
+ const ConfigAgentAvatarsRequest = z.object({
3731
+ method: z.literal("config.agent.avatars"),
3732
+ params: boundedBatchParams({
3733
+ agentIds: z.array(z.string()).min(1).max(4),
3734
+ maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
3735
+ }, "agentIds")
3887
3736
  });
3888
3737
  /** Removes a user-created agent: its row, picture, model overrides, access
3889
3738
  * grants and its directory under the work root. Its sessions stay readable
@@ -3892,7 +3741,10 @@ const ConfigAgentAvatarRequest = z.object({
3892
3741
  * `config.agentRemoved` follows. */
3893
3742
  const ConfigAgentRemoveRequest = z.object({
3894
3743
  method: z.literal("config.agent.remove"),
3895
- params: z.object({ agentId: z.string().min(1) })
3744
+ params: boundedBatchParams({
3745
+ operationId: z.uuid(),
3746
+ agentIds: batchIds()
3747
+ }, "agentIds")
3896
3748
  });
3897
3749
  /** One save from the agent editor: every field the person changed, applied
3898
3750
  * together. Everything is validated before anything is written, and the
@@ -3943,7 +3795,8 @@ z.object({
3943
3795
  name: z.string(),
3944
3796
  description: z.string(),
3945
3797
  plugin: z.string(),
3946
- permitted: z.boolean()
3798
+ permitted: z.boolean(),
3799
+ preloadDefault: z.boolean()
3947
3800
  }))
3948
3801
  });
3949
3802
  /** Writes nothing, produces no turn, needs no session: safe to retry. An
@@ -3951,7 +3804,10 @@ z.object({
3951
3804
  * real and different answer — "this agent is offered no tools at all". */
3952
3805
  const ConfigToolListRequest = z.object({
3953
3806
  method: z.literal("config.tool.list"),
3954
- params: z.object({ agentId: z.string().min(1) })
3807
+ params: boundedBatchParams({
3808
+ agentIds: batchIds(),
3809
+ ...queryBudgets
3810
+ }, "agentIds")
3955
3811
  });
3956
3812
  /** What is under a directory, for a client that has to name one.
3957
3813
  *
@@ -4010,21 +3866,28 @@ const TriggerUpdateRequest = z.object({
4010
3866
  });
4011
3867
  const TriggerSetEnabledRequest = z.object({
4012
3868
  method: z.literal("trigger.setEnabled"),
4013
- params: z.object({
4014
- id: z.string().min(1),
3869
+ params: boundedBatchParams({
3870
+ operationId: z.uuid(),
3871
+ ids: batchIds(),
4015
3872
  enabled: z.boolean()
4016
- })
3873
+ }, "ids")
4017
3874
  });
4018
3875
  /** Removes a definition, its runs and its pre-authorized scope; sessions it
4019
3876
  * opened stay. */
4020
3877
  const TriggerRemoveRequest = z.object({
4021
3878
  method: z.literal("trigger.remove"),
4022
- params: z.object({ id: z.string().min(1) })
3879
+ params: boundedBatchParams({
3880
+ operationId: z.uuid(),
3881
+ ids: batchIds()
3882
+ }, "ids")
4023
3883
  });
4024
3884
  /** A definition's runs, newest first, at most 200. */
4025
3885
  const TriggerRunsRequest = z.object({
4026
3886
  method: z.literal("trigger.runs"),
4027
- params: z.object({ id: z.string().min(1) })
3887
+ params: boundedBatchParams({
3888
+ ids: batchIds(),
3889
+ ...queryBudgets
3890
+ }, "ids")
4028
3891
  });
4029
3892
  /** Every inbox item that still exists, newest first. No cap: unread notices
4030
3893
  * and waiting requests are never removed on anyone's behalf, so the list
@@ -4059,7 +3922,7 @@ const InboxClearReadRequest = z.object({
4059
3922
  * answers success with no side effect. */
4060
3923
  const ProcessStopRequest = z.object({
4061
3924
  method: z.literal("process.stop"),
4062
- params: z.object({ processId: z.string().min(1) })
3925
+ params: boundedBatchParams({ processIds: batchIds() }, "processIds")
4063
3926
  });
4064
3927
  /** One stream's bytes, by range.
4065
3928
  *
@@ -4111,30 +3974,33 @@ const ConfigWorkspaceSetAvatarRequest = z.object({
4111
3974
  })
4112
3975
  });
4113
3976
  /** The workspace's uploaded picture, or `null` when it has none. */
4114
- const ConfigWorkspaceAvatarRequest = z.object({
4115
- method: z.literal("config.workspace.avatar"),
4116
- params: z.object({ workspaceId: z.string() })
4117
- });
4118
- /** Adds one work directory to a workspace: a tree its sessions may search and
4119
- * read without asking. It grants no writing — that is answered per path when
4120
- * a tool asks — so the params carry a path and nothing else.
4121
- *
4122
- * Adding a path already added is not an error and adds no second row; the
4123
- * answer is the whole workspace summary either way, so a caller cannot tell
4124
- * — and does not need to tell — "added" from "already there". */
4125
- const ConfigWorkspaceAddDirectoryRequest = z.object({
4126
- method: z.literal("config.workspace.addDirectory"),
3977
+ const ConfigWorkspaceAvatarsRequest = z.object({
3978
+ method: z.literal("config.workspace.avatars"),
3979
+ params: boundedBatchParams({
3980
+ workspaceIds: z.array(z.string()).min(1).max(4),
3981
+ maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
3982
+ }, "workspaceIds")
3983
+ });
3984
+ /** Adds or updates a bounded directory collection atomically; omitted access is read. */
3985
+ const ConfigWorkspaceAddDirectoriesRequest = z.object({
3986
+ method: z.literal("config.workspace.addDirectories"),
4127
3987
  params: z.object({
3988
+ operationId: z.uuid(),
4128
3989
  workspaceId: z.string(),
4129
- path: z.string().min(1)
4130
- })
4131
- });
4132
- const ConfigWorkspaceRemoveDirectoryRequest = z.object({
4133
- method: z.literal("config.workspace.removeDirectory"),
3990
+ directories: z.array(z.object({
3991
+ path: z.string().min(1),
3992
+ access: z.enum(["read", "read-write"]).default("read")
3993
+ }).strict()).min(1).max(64)
3994
+ }).strict().refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8388608, "batch input exceeds 8 MiB")
3995
+ });
3996
+ /** Removes directory authorizations atomically; already absent paths are successful no-ops. */
3997
+ const ConfigWorkspaceRemoveDirectoriesRequest = z.object({
3998
+ method: z.literal("config.workspace.removeDirectories"),
4134
3999
  params: z.object({
4000
+ operationId: z.uuid(),
4135
4001
  workspaceId: z.string(),
4136
- path: z.string().min(1)
4137
- })
4002
+ paths: z.array(z.string().min(1)).min(1).max(64)
4003
+ }).strict().refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8388608, "batch input exceeds 8 MiB")
4138
4004
  });
4139
4005
  /** Lists access records with ownership; omitted filters include all scopes. */
4140
4006
  const ConfigAccessListRequest = z.object({
@@ -4144,7 +4010,10 @@ const ConfigAccessListRequest = z.object({
4144
4010
  /** Adds a batch of globally reusable resources. */
4145
4011
  const ConfigAccessAddRequest = z.object({
4146
4012
  method: z.literal("config.access.add"),
4147
- params: z.object({ authorization: AuthorizationInput }).strict()
4013
+ params: boundedBatchParams({
4014
+ operationId: z.uuid(),
4015
+ authorizations: z.array(AuthorizationInput).min(1).max(64)
4016
+ }, "authorizations")
4148
4017
  });
4149
4018
  /** Reads whether new shell commands use operating-system confinement. */
4150
4019
  /** Persists the installation-wide switch; repeated writes are no-ops. */
@@ -4155,7 +4024,10 @@ const ConfigAccessAddRequest = z.object({
4155
4024
  * revoke says what the first one said. */
4156
4025
  const ConfigAccessRevokeRequest = z.object({
4157
4026
  method: z.literal("config.access.revoke"),
4158
- params: z.object({ id: z.string().min(1) }).strict()
4027
+ params: boundedBatchParams({
4028
+ operationId: z.uuid(),
4029
+ ids: batchIds()
4030
+ }, "ids")
4159
4031
  });
4160
4032
  z.object({
4161
4033
  name: z.string(),
@@ -4181,16 +4053,32 @@ const ConfigCredentialStatusRequest = z.object({
4181
4053
  * only. */
4182
4054
  const ConfigCredentialSetRequest = z.object({
4183
4055
  method: z.literal("config.credential.set"),
4184
- params: CredentialScopeParams.extend({
4185
- name: z.string().min(1),
4186
- value: z.string()
4187
- })
4056
+ params: boundedBatchParams({
4057
+ operationId: z.uuid(),
4058
+ plugin: z.string().min(1),
4059
+ scope: z.string().min(1),
4060
+ items: z.array(z.object({
4061
+ name: z.string().min(1),
4062
+ value: z.string()
4063
+ }).strict()).min(1).max(64)
4064
+ }, "items")
4188
4065
  });
4189
4066
  /** Clears one name, or the whole scope when `name` is omitted. Clearing
4190
4067
  * something absent succeeds and answers the current status. */
4191
4068
  const ConfigCredentialClearRequest = z.object({
4192
4069
  method: z.literal("config.credential.clear"),
4193
- params: CredentialScopeParams.extend({ name: z.string().min(1).optional() })
4070
+ params: boundedBatchParams({
4071
+ operationId: z.uuid(),
4072
+ plugin: z.string().min(1),
4073
+ items: z.array(z.discriminatedUnion("mode", [z.object({
4074
+ scope: z.string().min(1),
4075
+ mode: z.literal("names"),
4076
+ names: batchIds()
4077
+ }).strict(), z.object({
4078
+ scope: z.string().min(1),
4079
+ mode: z.literal("all")
4080
+ }).strict()])).min(1).max(64)
4081
+ }, "items")
4194
4082
  });
4195
4083
  /** Reads the hosts `web_fetch` may reach without asking. */
4196
4084
  /** Adds a bare host and broadcasts `config.webChanged`. With `includeSubdomains`, the
@@ -4207,20 +4095,16 @@ const ConfigCredentialClearRequest = z.object({
4207
4095
  *
4208
4096
  * `config` is the plugin's own section, unread here: the plugin declares a
4209
4097
  * zod schema and the container validates against it, so a shape this
4210
- * protocol pinned would be a second opinion about someone else's
4211
- * configuration.
4212
- */
4213
- const PluginInstallRequest = z.object({
4214
- method: z.literal("plugin.install"),
4215
- params: z.object({
4216
- spec: z.string().min(1),
4217
- config: z.record(z.string(), z.unknown()).optional()
4218
- })
4219
- });
4098
+ * protocol pinned would be a second opinion about someone else's
4099
+ * configuration.
4100
+ */
4220
4101
  /** Installs the selected roots in one shared physical mutation and reports every root result. */
4221
4102
  const PluginInstallBatchRequest = z.object({
4222
4103
  method: z.literal("plugin.installBatch"),
4223
- params: z.object({ items: z.array(PluginInstallRequest.shape.params).min(1).max(64) })
4104
+ params: z.object({ items: z.array(z.object({
4105
+ spec: z.string().min(1),
4106
+ config: z.record(z.string(), z.unknown()).optional()
4107
+ })).min(1).max(64) })
4224
4108
  });
4225
4109
  /** Requested roots and their complete confirmed lifecycle closure. */
4226
4110
  const PluginRemovalBatchPlan = z.object({
@@ -4254,19 +4138,6 @@ z.object({
4254
4138
  names: z.array(z.string().min(1)),
4255
4139
  token: z.string().min(1)
4256
4140
  });
4257
- /** Previews every installed package removed with this extension without changing state. */
4258
- const PluginRemovePreviewRequest = z.object({
4259
- method: z.literal("plugin.removePreview"),
4260
- params: z.object({ name: z.string().min(1) })
4261
- });
4262
- /** Removes precisely the confirmed preview; a changed installation rejects before mutation. */
4263
- const PluginRemoveRequest = z.object({
4264
- method: z.literal("plugin.remove"),
4265
- params: z.object({
4266
- name: z.string().min(1),
4267
- token: z.string().min(1)
4268
- })
4269
- });
4270
4141
  z.object({
4271
4142
  /** Installed target extension. */
4272
4143
  name: z.string().min(1),
@@ -4278,26 +4149,14 @@ z.object({
4278
4149
  token: z.string().min(1)
4279
4150
  });
4280
4151
  /** Previews activation changes without importing modules or modifying state. */
4281
- const PluginSetEnabledPreviewRequest = z.object({
4282
- method: z.literal("plugin.setEnabledPreview"),
4283
- params: z.object({
4284
- name: z.string().min(1),
4285
- enabled: z.boolean()
4286
- })
4287
- });
4288
4152
  /** Changes activation; a supplied stale preview token rejects before mutation. */
4289
- const PluginSetEnabledRequest = z.object({
4290
- method: z.literal("plugin.setEnabled"),
4291
- params: z.object({
4292
- name: z.string().min(1),
4293
- enabled: z.boolean(),
4294
- token: z.string().min(1).optional()
4295
- })
4296
- });
4297
4153
  /** Reads the declared configuration without including it in catalogue broadcasts. */
4298
- const PluginGetConfigRequest = z.object({
4299
- method: z.literal("plugin.getConfig"),
4300
- params: z.object({ name: z.string().min(1) })
4154
+ const PluginGetConfigsRequest = z.object({
4155
+ method: z.literal("plugin.getConfigs"),
4156
+ params: boundedBatchParams({
4157
+ names: batchIds(),
4158
+ ...queryBudgets
4159
+ }, "names")
4301
4160
  });
4302
4161
  /** Replaces configuration and reloads enabled plugins and their active dependants. */
4303
4162
  const PluginSetConfigRequest = z.object({
@@ -4325,6 +4184,9 @@ const SessionInstructionsRequest = z.object({
4325
4184
  params: z.object({ sessionId: z.string() })
4326
4185
  });
4327
4186
  const RequestBody = z.discriminatedUnion("method", [
4187
+ TelemetryIngestRequest,
4188
+ TelemetryStatusRequest,
4189
+ TelemetryConfigureRequest,
4328
4190
  SessionInstructionsRequest,
4329
4191
  PingRequest,
4330
4192
  ConnectionInfoRequest,
@@ -4334,13 +4196,15 @@ const RequestBody = z.discriminatedUnion("method", [
4334
4196
  SessionCreateRequest,
4335
4197
  SessionWatchRequest,
4336
4198
  SessionHistoryPageRequest,
4199
+ SessionTurnPageRequest,
4200
+ SessionTurnTranscriptPageRequest,
4337
4201
  SessionMessagePartsRequest,
4338
- SessionMessageContentRequest,
4202
+ SessionMessageContentsRequest,
4339
4203
  SessionLivePageRequest,
4340
4204
  SessionUnwatchRequest,
4341
4205
  SessionSendRequest,
4342
4206
  SessionForkRequest,
4343
- SessionOperationGetRequest,
4207
+ SessionOperationsGetRequest,
4344
4208
  SessionAnswerRequest,
4345
4209
  SessionWithdrawRequest,
4346
4210
  SessionCancelRequest,
@@ -4359,7 +4223,7 @@ const RequestBody = z.discriminatedUnion("method", [
4359
4223
  ConfigAgentSetPromptSlotRequest,
4360
4224
  ConfigAgentPromptSlotsRequest,
4361
4225
  ConfigAgentSetAvatarRequest,
4362
- ConfigAgentAvatarRequest,
4226
+ ConfigAgentAvatarsRequest,
4363
4227
  ConfigAgentSaveRequest,
4364
4228
  ConfigAgentRevisionsRequest,
4365
4229
  ConfigAgentCompareRevisionsRequest,
@@ -4385,9 +4249,9 @@ const RequestBody = z.discriminatedUnion("method", [
4385
4249
  ConfigWorkspaceCreateRequest,
4386
4250
  ConfigWorkspaceUpdateRequest,
4387
4251
  ConfigWorkspaceSetAvatarRequest,
4388
- ConfigWorkspaceAvatarRequest,
4389
- ConfigWorkspaceAddDirectoryRequest,
4390
- ConfigWorkspaceRemoveDirectoryRequest,
4252
+ ConfigWorkspaceAvatarsRequest,
4253
+ ConfigWorkspaceAddDirectoriesRequest,
4254
+ ConfigWorkspaceRemoveDirectoriesRequest,
4391
4255
  ConfigAccessListRequest,
4392
4256
  ConfigAccessAddRequest,
4393
4257
  ConfigAccessRevokeRequest,
@@ -4395,260 +4259,1058 @@ const RequestBody = z.discriminatedUnion("method", [
4395
4259
  ConfigCredentialSetRequest,
4396
4260
  ConfigCredentialClearRequest,
4397
4261
  StdFsListRequest,
4398
- PluginInstallRequest,
4399
4262
  PluginInstallBatchRequest,
4400
4263
  PluginSetEnabledBatchPreviewRequest,
4401
4264
  PluginSetEnabledBatchRequest,
4402
4265
  PluginRemoveBatchPreviewRequest,
4403
4266
  PluginRemoveBatchRequest,
4404
- PluginRemovePreviewRequest,
4405
- PluginRemoveRequest,
4406
4267
  PluginListRequest,
4407
- PluginSetEnabledPreviewRequest,
4408
- PluginSetEnabledRequest,
4409
- PluginGetConfigRequest,
4268
+ PluginGetConfigsRequest,
4410
4269
  PluginSetConfigRequest,
4411
4270
  PluginSurfaceRequest
4412
4271
  ]);
4413
4272
  /**
4414
- * A request naming a method some plugin declared while this gateway was
4415
- * running.
4416
- *
4417
- * The name is checked against the minting rule and **the parameters are not
4418
- * read at all**: their shape is the plugin's zod, validated in the gateway,
4419
- * and a second opinion here would be a second writer of someone else's
4420
- * contract.
4421
- *
4422
- * `method` is a template literal type rather than a bare `string`, and that is
4423
- * load-bearing: one `string` discriminant in this union and
4424
- * `body.method === 'session.send'` stops narrowing, which takes every `switch`
4425
- * that reads `body.params` afterwards down with it.
4426
- *
4427
- * `params` is optional because a call that takes none sends no key —
4428
- * `JSON.stringify` drops an `undefined` — and a frame this schema refuses is
4429
- * dropped in silence rather than answered. Bare `z.unknown()` would not
4430
- * serve: zod 4 treats it as a required key, which would refuse exactly the
4431
- * paramsless calls this field is meant to admit.
4273
+ * A request naming a method some plugin declared while this gateway was
4274
+ * running.
4275
+ *
4276
+ * The name is checked against the minting rule and **the parameters are not
4277
+ * read at all**: their shape is the plugin's zod, validated in the gateway,
4278
+ * and a second opinion here would be a second writer of someone else's
4279
+ * contract.
4280
+ *
4281
+ * `method` is a template literal type rather than a bare `string`, and that is
4282
+ * load-bearing: one `string` discriminant in this union and
4283
+ * `body.method === 'session.send'` stops narrowing, which takes every `switch`
4284
+ * that reads `body.params` afterwards down with it.
4285
+ *
4286
+ * `params` is optional because a call that takes none sends no key —
4287
+ * `JSON.stringify` drops an `undefined` — and a frame this schema refuses is
4288
+ * dropped in silence rather than answered. Bare `z.unknown()` would not
4289
+ * serve: zod 4 treats it as a required key, which would refuse exactly the
4290
+ * paramsless calls this field is meant to admit.
4291
+ */
4292
+ const PluginRequestBody = z.object({
4293
+ method: PluginWireName,
4294
+ params: z.unknown().optional()
4295
+ });
4296
+ /** One business request from a client. Authentication is a separate control
4297
+ * frame.
4298
+ *
4299
+ * The body is widened one layer out rather than `RequestBody` itself: the
4300
+ * core union stays a `discriminatedUnion` of names known at compile time,
4301
+ * and a plugin's runtime-minted name sits beside it. */
4302
+ const RequestFrame = z.object({
4303
+ kind: z.literal("request"),
4304
+ id: z.string(),
4305
+ trace: RequestTrace.optional(),
4306
+ body: z.union([RequestBody, PluginRequestBody])
4307
+ });
4308
+ /** Supplies the credential for one WebSocket connection. */
4309
+ const AuthenticationFrame = z.object({
4310
+ kind: z.literal("authentication"),
4311
+ id: z.string().min(1).max(128),
4312
+ token: z.string().max(256)
4313
+ });
4314
+ z.discriminatedUnion("kind", [RequestFrame, AuthenticationFrame]);
4315
+ z.object({ authenticated: z.literal(true) });
4316
+ z.enum(["auth-required", "auth-failed"]);
4317
+ z.enum([
4318
+ "history_conflict",
4319
+ "session_busy",
4320
+ "cut_unavailable",
4321
+ "source_unavailable",
4322
+ "file_unavailable",
4323
+ "operation_conflict",
4324
+ "history_preparing",
4325
+ "history_unavailable",
4326
+ "history_invalid",
4327
+ "history_stale",
4328
+ "history_cursor_invalid",
4329
+ "history_worker_unavailable",
4330
+ "reading_lease_invalid",
4331
+ "content_unavailable",
4332
+ "content_stale",
4333
+ "message_unavailable",
4334
+ "invalid_range"
4335
+ ]);
4336
+ z.enum(["configuration_write_rejected", "configuration_recovery_required"]);
4337
+ /** A bounded machine-readable refusal identifier; owner business codes are not enumerated by core. */
4338
+ const RequestErrorCode = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/);
4339
+ /** Gateway -> client: the answer to one request, addressed by its id. */
4340
+ const ResultFrame = z.object({
4341
+ kind: z.literal("result"),
4342
+ id: z.string(),
4343
+ ok: z.boolean(),
4344
+ data: z.unknown().optional(),
4345
+ error: z.string().optional(),
4346
+ errorCode: RequestErrorCode.optional(),
4347
+ /** Recoverable reading preparation lease and suggested polling interval. */
4348
+ readingDetails: z.object({
4349
+ readingLeaseId: z.string().optional(),
4350
+ retryAfterMs: z.number().int().positive().optional()
4351
+ }).optional()
4352
+ });
4353
+ /** Gateway -> the connections that care: something happened. Carries no id,
4354
+ * because no one asked for it. */
4355
+ const EventFrame = z.object({
4356
+ kind: z.literal("event"),
4357
+ event: Frame
4358
+ });
4359
+ z.discriminatedUnion("kind", [ResultFrame, EventFrame]);
4360
+ z.object({
4361
+ instanceId: z.uuid(),
4362
+ gatewayVersion: z.string(),
4363
+ protocolVersion: z.string(),
4364
+ clientCount: z.number().int(),
4365
+ uptimeMs: z.number().int(),
4366
+ pid: z.number().int()
4367
+ });
4368
+ //#endregion
4369
+ //#region src/extension-catalog/projection.ts
4370
+ /** Minimal historical commit identity retained with a release admission. */
4371
+ const AcceptedSnapshotSchema = z.object({
4372
+ repository: z.literal(CATALOG_REPOSITORY),
4373
+ commit: GitShaSchema,
4374
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4375
+ }).strict();
4376
+ z.object({
4377
+ snapshot: AcceptedSnapshotSchema,
4378
+ release: ReleaseSchema,
4379
+ releaseDigest: z.string().regex(/^[0-9a-f]{64}$/)
4380
+ }).strict();
4381
+ /** Current directory source and actual host compatibility are independent of activation status. */
4382
+ const InstalledRowSchema = z.object({
4383
+ packageName: z.string(),
4384
+ distribution: z.enum([
4385
+ "builtin",
4386
+ "verified",
4387
+ "custom"
4388
+ ]),
4389
+ publisherKind: z.enum(["official", "third-party"]).optional(),
4390
+ compatibility: z.object({
4391
+ state: z.enum([
4392
+ "compatible",
4393
+ "incompatible",
4394
+ "unknown"
4395
+ ]),
4396
+ reasons: z.array(z.string()),
4397
+ assessedAt: z.string()
4398
+ }).strict(),
4399
+ updates: z.array(ReleaseSchema)
4400
+ }).strict();
4401
+ /** Uses current directory publisher markers while retaining actual saved host requirement facts. */
4402
+ function projectInstalled(observations, snapshot, host) {
4403
+ return observations.map((observation) => {
4404
+ const builtin = (observation.summary?.origin ?? observation.declared.origin) === "builtin";
4405
+ const listed = snapshot?.releases.filter((release) => release.packageName === observation.packageName).sort((a, b) => semver.rcompare(a.version, b.version))[0];
4406
+ const currentVersion = observation.summary?.version ?? observation.declared.version ?? observation.receipt?.version ?? "";
4407
+ const requirements = observation.hostRequirements;
4408
+ const compatibility = {
4409
+ state: requirements.state === "satisfied" ? "compatible" : requirements.state === "unsatisfied" ? "incompatible" : "unknown",
4410
+ reasons: [...requirements.reasons],
4411
+ assessedAt: requirements.checkedAt
4412
+ };
4413
+ 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)) : [];
4414
+ return {
4415
+ packageName: observation.packageName,
4416
+ distribution: builtin ? "builtin" : listed ? "verified" : "custom",
4417
+ ...!builtin && listed ? { publisherKind: listed.publisher.kind } : {},
4418
+ compatibility,
4419
+ updates
4420
+ };
4421
+ });
4422
+ }
4423
+ //#endregion
4424
+ //#region src/extension-catalog/views.ts
4425
+ /** Explicit catalog synchronization result, independent of snapshot availability. */
4426
+ const SyncSchema = z.object({
4427
+ state: z.enum([
4428
+ "idle",
4429
+ "syncing",
4430
+ "succeeded",
4431
+ "failed"
4432
+ ]),
4433
+ taskId: z.uuid().optional(),
4434
+ error: z.string().max(4096).optional(),
4435
+ retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4436
+ }).strict();
4437
+ /** Pure cache-only list response; an empty catalog is a valid successful snapshot. */
4438
+ const ListSchema = z.object({
4439
+ revision: z.number().int().nonnegative(),
4440
+ snapshot: SnapshotSchema.omit({ releases: true }).nullable(),
4441
+ releases: z.array(ReleaseSchema).max(2e3),
4442
+ sync: SyncSchema
4443
+ }).strict();
4444
+ /** Short invalidation carrying no configuration, credentials, or archive bytes. */
4445
+ const CatalogChangedSchema = z.object({
4446
+ revision: z.number().int().nonnegative(),
4447
+ snapshot: z.object({
4448
+ commit: GitShaSchema,
4449
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4450
+ }).strict().optional(),
4451
+ sync: SyncSchema
4452
+ }).strict();
4453
+ /** Confirmation response for a fixed exact extension dependency closure. */
4454
+ const PreviewSchema = z.object({
4455
+ previewToken: z.string().min(1).max(8192),
4456
+ expiresAt: z.iso.datetime({ offset: true }),
4457
+ snapshot: z.object({
4458
+ commit: GitShaSchema,
4459
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4460
+ }).strict(),
4461
+ graphRevision: z.string().max(1024),
4462
+ resolvedSelections: z.array(ReleaseSchema).max(64),
4463
+ dependencies: z.array(z.object({
4464
+ packageName: z.string(),
4465
+ version: z.string()
4466
+ }).strict()).max(64),
4467
+ willEnable: z.array(z.string()).max(2e3),
4468
+ replacing: z.array(z.string()).max(64),
4469
+ affectedOwners: z.array(z.string()).max(2e3),
4470
+ warnings: z.array(ArtifactWarningSchema).max(64)
4471
+ }).strict();
4472
+ /** Durable installation operation facts returned by the generic owner-bound service. */
4473
+ const OperationSchema = z.object({
4474
+ operationId: z.uuid(),
4475
+ attemptId: z.uuid(),
4476
+ issuer: z.string(),
4477
+ submissionDigest: z.string(),
4478
+ requestDigest: z.string(),
4479
+ packageName: z.string(),
4480
+ warnings: z.array(ArtifactWarningSchema).max(3).optional(),
4481
+ warningCount: z.number().int().nonnegative().max(1e5).optional(),
4482
+ rootResults: z.array(z.object({
4483
+ packageName: z.string(),
4484
+ status: z.enum([
4485
+ "pending",
4486
+ "active",
4487
+ "disabled",
4488
+ "deferred",
4489
+ "failed"
4490
+ ]),
4491
+ reason: z.string().max(4096).optional()
4492
+ }).strict()).max(2e3).optional(),
4493
+ phase: z.enum([
4494
+ "preparing",
4495
+ "installing",
4496
+ "admitted",
4497
+ "activating",
4498
+ "settled"
4499
+ ]),
4500
+ currentStep: z.enum([
4501
+ "prepare",
4502
+ "download",
4503
+ "verify",
4504
+ "npm",
4505
+ "admission",
4506
+ "activation",
4507
+ "cleanup"
4508
+ ]),
4509
+ outcome: z.enum([
4510
+ "pending",
4511
+ "succeeded",
4512
+ "failed",
4513
+ "interrupted"
4514
+ ]),
4515
+ failureStage: z.enum([
4516
+ "prepare",
4517
+ "download",
4518
+ "verify",
4519
+ "npm",
4520
+ "admission",
4521
+ "activation",
4522
+ "cleanup",
4523
+ "recovery"
4524
+ ]).optional(),
4525
+ reason: z.string().max(4096).optional(),
4526
+ cleanup: z.enum([
4527
+ "not-needed",
4528
+ "pending",
4529
+ "complete",
4530
+ "failed"
4531
+ ]),
4532
+ startedAt: z.iso.datetime({ offset: true }),
4533
+ settledAt: z.iso.datetime({ offset: true }).optional(),
4534
+ packages: z.array(z.object({
4535
+ packageName: z.string(),
4536
+ beforeRevision: z.number().int().nonnegative(),
4537
+ receiptId: z.uuid().nullable(),
4538
+ diskChanged: z.boolean().optional(),
4539
+ ownerWithdrawn: z.boolean().optional()
4540
+ }).strict()).max(2e3)
4541
+ }).strict();
4542
+ /** Installation progress invalidation; clients query the durable attempt after reconnecting. */
4543
+ const InstallChangedSchema = z.object({
4544
+ operationId: z.uuid(),
4545
+ phase: OperationSchema.shape.phase,
4546
+ currentStep: OperationSchema.shape.currentStep,
4547
+ outcome: OperationSchema.shape.outcome,
4548
+ cleanup: OperationSchema.shape.cleanup,
4549
+ revision: z.number().int().nonnegative()
4550
+ }).strict();
4551
+ /** Current directory source markers and installed metadata for unique package names. */
4552
+ const InstalledSchema = z.object({
4553
+ observedAt: z.iso.datetime({ offset: true }),
4554
+ rows: z.array(InstalledRowSchema).max(2e3)
4555
+ }).strict();
4556
+ /** Existing owner RPC success/failure convention; sanitized errors remain actionable. */
4557
+ function resultSchema(data) {
4558
+ return z.union([z.object({
4559
+ ok: z.literal(true),
4560
+ data
4561
+ }).strict(), z.object({
4562
+ ok: z.literal(false),
4563
+ code: z.string(),
4564
+ message: z.string().max(4096),
4565
+ retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4566
+ }).strict()]);
4567
+ }
4568
+ //#endregion
4569
+ //#region src/extension-catalog/operations.ts
4570
+ /** Nonempty operation identities with per-member and complete encoded-response byte budgets. */
4571
+ const OperationQueriesParams = z.object({
4572
+ operationIds: z.array(z.uuid()).min(1).max(64),
4573
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
4574
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
4575
+ }).strict().superRefine((input, ctx) => {
4576
+ if (input.operationIds.length * input.maxItemBytes + 8192 > input.maxTotalBytes || input.operationIds.some((id) => Buffer.byteLength(JSON.stringify(id)) + 4096 > input.maxItemBytes)) ctx.addIssue({
4577
+ code: "custom",
4578
+ message: "declared operation response exceeds byte budget"
4579
+ });
4580
+ });
4581
+ /** Safe operation facts in the original request order. */
4582
+ const OperationQueriesData = z.object({ results: z.array(z.discriminatedUnion("ok", [z.object({
4583
+ index: z.number().int().nonnegative().max(63),
4584
+ target: z.uuid(),
4585
+ ok: z.literal(true),
4586
+ value: z.object({ operation: OperationSchema }).strict()
4587
+ }).strict(), z.object({
4588
+ index: z.number().int().nonnegative().max(63),
4589
+ target: z.uuid(),
4590
+ ok: z.literal(false),
4591
+ error: z.object({
4592
+ code: z.string().min(1).max(64),
4593
+ message: z.string().max(512),
4594
+ details: z.object({ retryAfterSeconds: z.number().nonnegative().max(86400) }).strict().optional()
4595
+ }).strict()
4596
+ }).strict()])).min(1).max(64) }).strict();
4597
+ //#endregion
4598
+ //#region src/defaults/service.ts
4599
+ /** Creates one shared initialization attempt scoped to this catalog owner. */
4600
+ function createDefaultsService(options) {
4601
+ const controller = new AbortController();
4602
+ const signal = AbortSignal.any([options.signal, controller.signal]);
4603
+ let active = null;
4604
+ function initial() {
4605
+ return {
4606
+ state: "pending-snapshot",
4607
+ enrolledAt: (/* @__PURE__ */ new Date()).toISOString(),
4608
+ candidates: []
4609
+ };
4610
+ }
4611
+ async function status() {
4612
+ const before = options.store.read() ?? initial();
4613
+ const observations = before.candidates.length ? await options.installer.observe(before.candidates.map((candidate) => candidate.packageName)) : [];
4614
+ const record = options.store.read() ?? initial();
4615
+ const candidates = record.candidates.map(({ artifactIntegrity: _integrity, receiptId, ...candidate }) => {
4616
+ const observed = observations.find((item) => item.packageName === candidate.packageName);
4617
+ const captured = before.candidates.find((item) => item.packageName === candidate.packageName);
4618
+ const matchesCapturedResult = captured?.state === "installed" && captured.receiptId === receiptId && captured.operationId === candidate.operationId && captured.releaseId === candidate.releaseId;
4619
+ if (candidate.state === "installed" && matchesCapturedResult && observed) {
4620
+ if (!observed.declared.installed || !observed.declared.enabled || receiptId && observed.receipt?.receiptId !== receiptId) {
4621
+ candidate.state = "user-managed";
4622
+ candidate.reasonCode = "USER_DECLARATION_PRESERVED";
4623
+ delete candidate.activation;
4624
+ } else {
4625
+ const activation = observed.activation ?? (observed.summary?.status === "active" ? "active" : observed.summary?.status === "failed" ? "failed" : void 0);
4626
+ if (activation) candidate.activation = activation;
4627
+ }
4628
+ }
4629
+ return candidate;
4630
+ });
4631
+ return DefaultsStatusSchema.parse({
4632
+ state: active ? "working" : record.state === "complete" ? "complete" : record.state === "pending-snapshot" ? "pending-snapshot" : "pending",
4633
+ taskId: active?.id ?? null,
4634
+ operationId: record.currentOperationId ?? null,
4635
+ counts: {
4636
+ installed: candidates.filter((c) => c.state === "installed").length,
4637
+ pending: candidates.filter((c) => c.state === "pending").length,
4638
+ skipped: candidates.filter((c) => c.state === "skipped" || c.state === "user-managed").length
4639
+ },
4640
+ activationDeferred: candidates.filter((c) => c.state === "installed" && c.activation === "deferred").length,
4641
+ candidates,
4642
+ ...record.lastReasonCode ? { reasonCode: record.lastReasonCode } : {},
4643
+ ...record.retryNotBefore ? { retryAfterSeconds: Math.min(86400, Math.max(0, Math.ceil((Date.parse(record.retryNotBefore) - Date.now()) / 1e3))) } : {}
4644
+ });
4645
+ }
4646
+ function persist(record) {
4647
+ if (record.snapshot) record.state = record.candidates.some((c) => c.state === "pending") ? "pending" : "complete";
4648
+ return options.store.save(record);
4649
+ }
4650
+ async function applyOperation(record, operation) {
4651
+ for (const candidate of record.candidates.filter((c) => c.operationId === operation.operationId && c.state === "pending")) {
4652
+ const packageResult = operation.packages.find((p) => p.packageName === candidate.packageName);
4653
+ const rootResult = operation.rootResults?.find((r) => r.packageName === candidate.packageName);
4654
+ if (packageResult?.receiptId) {
4655
+ candidate.state = "installed";
4656
+ candidate.receiptId = packageResult.receiptId;
4657
+ candidate.activation = rootResult?.status === "active" ? "active" : rootResult?.status === "deferred" ? "deferred" : "failed";
4658
+ delete candidate.reasonCode;
4659
+ } else if (operation.phase === "settled" && operation.outcome !== "pending") {
4660
+ candidate.reasonCode = "INSTALL_FAILED";
4661
+ record.lastReasonCode = "INSTALL_FAILED";
4662
+ }
4663
+ }
4664
+ if (record.lastReasonCode === "INSTALL_FAILED" && !record.candidates.some((candidate) => candidate.state === "pending")) delete record.lastReasonCode;
4665
+ persist(record);
4666
+ }
4667
+ async function joinOperation(operationId) {
4668
+ let operation = await options.installer.join(operationId);
4669
+ while (operation.cleanup === "failed" || operation.cleanup === "pending") {
4670
+ try {
4671
+ operation = await options.installer.retryCleanup(operationId);
4672
+ } catch {
4673
+ await setTimeout$1(250);
4674
+ continue;
4675
+ }
4676
+ if (operation.cleanup === "failed" || operation.cleanup === "pending") await setTimeout$1(250);
4677
+ }
4678
+ return operation;
4679
+ }
4680
+ async function recover(record) {
4681
+ const operationIds = [...new Set(record.candidates.filter((c) => c.state === "pending").map((c) => c.operationId).filter((id) => !!id))];
4682
+ for (const id of operationIds) {
4683
+ let operation;
4684
+ try {
4685
+ operation = await options.installer.operation(id);
4686
+ } catch (error) {
4687
+ if (managementError(error).code !== "OPERATION_NOT_FOUND") throw error;
4688
+ continue;
4689
+ }
4690
+ operation = await joinOperation(id);
4691
+ await applyOperation(record, operation);
4692
+ if (operation.phase !== "settled" || operation.outcome === "pending") throw new CatalogError("RECOVERY_PENDING", "The original default installation attempt is not settled");
4693
+ }
4694
+ }
4695
+ async function run(attempt) {
4696
+ let record = options.store.read() ?? options.store.save(initial());
4697
+ delete record.lastReasonCode;
4698
+ delete record.retryNotBefore;
4699
+ await recover(record);
4700
+ if (record.state === "complete") return;
4701
+ const snapshot = await options.acquireSnapshot(attempt);
4702
+ attempt.signal.throwIfAborted();
4703
+ if (!record.snapshot) {
4704
+ const chosen = /* @__PURE__ */ new Map();
4705
+ for (const release of snapshot.releases) {
4706
+ if (release.defaultInstall !== true || !releaseCompatible(release, options.identity)) continue;
4707
+ const before = chosen.get(release.packageName);
4708
+ if (!before || semver.gt(release.version, before.version)) chosen.set(release.packageName, release);
4709
+ }
4710
+ if (chosen.size > 64) throw new CatalogError("LIMIT_EXCEEDED", "Default extension cohort exceeds 64 roots");
4711
+ record = await options.installer.coordinate(() => options.store.save({
4712
+ ...record,
4713
+ state: chosen.size ? "frozen" : "complete",
4714
+ snapshot: {
4715
+ commit: snapshot.commit,
4716
+ contentDigest: snapshot.contentDigest
4717
+ },
4718
+ host: {
4719
+ version: options.identity.version,
4720
+ ...options.identity.target
4721
+ },
4722
+ candidates: [...chosen.values()].sort((a, b) => a.packageName < b.packageName ? -1 : a.packageName > b.packageName ? 1 : 0).map((r) => ({
4723
+ packageName: r.packageName,
4724
+ releaseId: r.releaseId,
4725
+ artifactIntegrity: r.artifact.integrity,
4726
+ state: "pending"
4727
+ }))
4728
+ }));
4729
+ }
4730
+ if (record.state === "complete") return;
4731
+ const observations = await options.installer.observe();
4732
+ for (const candidate of record.candidates.filter((c) => c.state === "pending")) if (observations.some((o) => o.packageName === candidate.packageName && o.declared.origin !== void 0)) {
4733
+ candidate.state = "user-managed";
4734
+ candidate.reasonCode = "USER_DECLARATION_PRESERVED";
4735
+ } else {
4736
+ const release = snapshot.releases.find((r) => r.releaseId === candidate.releaseId && r.artifact.integrity === candidate.artifactIntegrity);
4737
+ if (!release || release.defaultInstall !== true || !releaseCompatible(release, options.identity)) {
4738
+ candidate.state = "skipped";
4739
+ candidate.reasonCode = "RELEASE_REVOKED";
4740
+ }
4741
+ }
4742
+ persist(record);
4743
+ const roots = record.candidates.filter((c) => c.state === "pending");
4744
+ if (!roots.length) return;
4745
+ const plan = await options.preview(roots.map((c) => ({
4746
+ snapshotCommit: snapshot.commit,
4747
+ releaseId: c.releaseId,
4748
+ artifactIntegrity: c.artifactIntegrity
4749
+ })), attempt);
4750
+ attempt.signal.throwIfAborted();
4751
+ const operationId = randomUUID();
4752
+ record.currentOperationId = operationId;
4753
+ record.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
4754
+ for (const candidate of roots) candidate.operationId = operationId;
4755
+ persist(record);
4756
+ try {
4757
+ await options.installer.install({
4758
+ operationId,
4759
+ token: plan.previewToken
4760
+ }, attempt);
4761
+ } catch (error) {
4762
+ try {
4763
+ await options.installer.operation(operationId);
4764
+ } catch {
4765
+ throw error;
4766
+ }
4767
+ }
4768
+ const operation = await joinOperation(operationId);
4769
+ await applyOperation(record, operation);
4770
+ }
4771
+ return {
4772
+ /** Starts one shared bounded attempt immediately; completed initialization performs no network work. */
4773
+ async ensure(input) {
4774
+ signal.throwIfAborted();
4775
+ const params = DefaultsEnsureParamsSchema.parse(input);
4776
+ if (params.expectedProductVersion !== options.identity.version) throw new CatalogError("PRODUCT_VERSION_MISMATCH", "Default installation requires the current product version");
4777
+ const record = options.store.read() ?? initial();
4778
+ if (active) return {
4779
+ taskId: active.id,
4780
+ status: await status()
4781
+ };
4782
+ if (record.state === "complete" || record.retryNotBefore && Date.parse(record.retryNotBefore) > Date.now()) return {
4783
+ taskId: null,
4784
+ status: await status()
4785
+ };
4786
+ const id = randomUUID(), deadline = performance.now() + Math.min(18e4, params.remainingWorkMs);
4787
+ const timerController = new AbortController();
4788
+ const timer = setTimeout(() => timerController.abort(/* @__PURE__ */ new Error("Default installation work budget exhausted")), Math.max(1, deadline - performance.now()));
4789
+ const attempt = {
4790
+ signal: AbortSignal.any([signal, timerController.signal]),
4791
+ remainingWorkMs: () => Math.max(0, deadline - performance.now())
4792
+ };
4793
+ const work = Promise.resolve().then(() => run(attempt)).catch((error) => {
4794
+ const record = options.store.read() ?? initial(), failure = managementError(error);
4795
+ record.lastReasonCode = attempt.signal.aborted ? "ATTEMPT_CANCELLED" : failure.code;
4796
+ for (const candidate of record.candidates.filter((c) => c.state === "pending")) candidate.reasonCode = record.lastReasonCode;
4797
+ if (failure.retryAfterSeconds !== void 0) record.retryNotBefore = new Date(Date.now() + failure.retryAfterSeconds * 1e3).toISOString();
4798
+ persist(record);
4799
+ }).finally(() => {
4800
+ clearTimeout(timer);
4801
+ active = null;
4802
+ });
4803
+ work.catch(() => {});
4804
+ active = {
4805
+ id,
4806
+ work
4807
+ };
4808
+ return {
4809
+ taskId: id,
4810
+ status: await status()
4811
+ };
4812
+ },
4813
+ /** Projects current readonly installation facts over retained history; never enrolls or installs. */
4814
+ status,
4815
+ /** Cancels this automatic attempt and joins all work before releasing the owner's resources. */
4816
+ async dispose() {
4817
+ controller.abort(/* @__PURE__ */ new Error("Default installation owner is draining"));
4818
+ await active?.work;
4819
+ }
4820
+ };
4821
+ }
4822
+ //#endregion
4823
+ //#region src/extension-catalog/sync.ts
4824
+ /** Git smart HTTP ref advertisement for the catalog repository. */
4825
+ const CATALOG_REFS_URL = "https://github.com/yanxuan-lc/yaoguang-presets.git/info/refs?service=git-upload-pack";
4826
+ /** Raw content URL of the extension index pinned to one commit. */
4827
+ const catalogIndexUrl = (commit) => `https://raw.githubusercontent.com/yanxuan-lc/yaoguang-presets/${commit}/extensions/index.json`;
4828
+ const REFS_MAX_BYTES = 1048576;
4829
+ const headers = { "User-Agent": "YaoGuang-extensions" };
4830
+ /**
4831
+ * Returns the commit of `refs/heads/main` from a Git smart HTTP upload-pack advertisement.
4832
+ * Requires the leading service announcement and well-formed pkt-lines; any other shape,
4833
+ * including a missing main branch, is rejected as an invalid catalog.
4432
4834
  */
4433
- const PluginRequestBody = z.object({
4434
- method: PluginWireName,
4435
- params: z.unknown().optional()
4436
- });
4437
- /** One business request from a client. Authentication is a separate control
4438
- * frame.
4439
- *
4440
- * The body is widened one layer out rather than `RequestBody` itself: the
4441
- * core union stays a `discriminatedUnion` of names known at compile time,
4442
- * and a plugin's runtime-minted name sits beside it. */
4443
- const RequestFrame = z.object({
4444
- kind: z.literal("request"),
4445
- id: z.string(),
4446
- body: z.union([RequestBody, PluginRequestBody])
4447
- });
4448
- /** Supplies the credential for one WebSocket connection. */
4449
- const AuthenticationFrame = z.object({
4450
- kind: z.literal("authentication"),
4451
- id: z.string().min(1).max(128),
4452
- token: z.string().max(256)
4453
- });
4454
- z.discriminatedUnion("kind", [RequestFrame, AuthenticationFrame]);
4455
- z.object({ authenticated: z.literal(true) });
4456
- z.enum(["auth-required", "auth-failed"]);
4457
- z.enum([
4458
- "history_conflict",
4459
- "session_busy",
4460
- "cut_unavailable",
4461
- "source_unavailable",
4462
- "file_unavailable",
4463
- "operation_conflict",
4464
- "history_preparing",
4465
- "history_unavailable",
4466
- "history_invalid",
4467
- "history_stale",
4468
- "history_cursor_invalid",
4469
- "history_worker_unavailable",
4470
- "reading_lease_invalid",
4471
- "content_unavailable",
4472
- "content_stale",
4473
- "message_unavailable",
4474
- "invalid_range"
4475
- ]);
4476
- z.enum(["configuration_write_rejected", "configuration_recovery_required"]);
4477
- /** A bounded machine-readable refusal identifier; owner business codes are not enumerated by core. */
4478
- const RequestErrorCode = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/);
4479
- /** Gateway -> client: the answer to one request, addressed by its id. */
4480
- const ResultFrame = z.object({
4481
- kind: z.literal("result"),
4482
- id: z.string(),
4483
- ok: z.boolean(),
4484
- data: z.unknown().optional(),
4485
- error: z.string().optional(),
4486
- errorCode: RequestErrorCode.optional(),
4487
- /** Recoverable reading preparation lease and suggested polling interval. */
4488
- readingDetails: z.object({
4489
- readingLeaseId: z.string().optional(),
4490
- retryAfterMs: z.number().int().positive().optional()
4491
- }).optional()
4492
- });
4493
- /** Gateway -> the connections that care: something happened. Carries no id,
4494
- * because no one asked for it. */
4495
- const EventFrame = z.object({
4496
- kind: z.literal("event"),
4497
- event: Frame
4498
- });
4499
- z.discriminatedUnion("kind", [ResultFrame, EventFrame]);
4500
- z.object({
4501
- instanceId: z.uuid(),
4502
- gatewayVersion: z.string(),
4503
- protocolVersion: z.string(),
4504
- clientCount: z.number().int(),
4505
- uptimeMs: z.number().int(),
4506
- pid: z.number().int()
4507
- });
4835
+ function parseMainCommit(bytes) {
4836
+ const text = Buffer.from(bytes).toString("latin1");
4837
+ const lines = [];
4838
+ for (let at = 0; at < text.length;) {
4839
+ const prefix = text.slice(at, at + 4);
4840
+ if (!/^[0-9a-f]{4}$/.test(prefix)) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4841
+ const length = Number.parseInt(prefix, 16);
4842
+ if (length === 0) {
4843
+ lines.push(null);
4844
+ at += 4;
4845
+ continue;
4846
+ }
4847
+ if (length < 4 || at + length > text.length) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4848
+ lines.push(text.slice(at + 4, at + length).replace(/\n$/, ""));
4849
+ at += length;
4850
+ }
4851
+ if (lines[0] !== "# service=git-upload-pack" || lines[1] !== null) throw new CatalogError("CATALOG_INVALID", "Missing upload-pack service announcement");
4852
+ for (const line of lines.slice(2)) {
4853
+ if (line === null) continue;
4854
+ const match = /^([0-9a-f]{40}) ([^\0]+)(?:\0.*)?$/s.exec(line);
4855
+ if (!match) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4856
+ if (match[2] === "refs/heads/main") return match[1];
4857
+ }
4858
+ throw new CatalogError("CATALOG_INVALID", "Catalog repository has no main branch");
4859
+ }
4860
+ /**
4861
+ * Reads a bounded response without credentials, redirects, or remote-body diagnostics.
4862
+ * A failed status becomes `SYNC_FAILED`, with a retry delay (at most one day) taken from
4863
+ * `retry-after`, or from `x-ratelimit-reset` for 429 and exhausted-quota 403 responses.
4864
+ * A 404 throws the error built by `notFound` when it is supplied.
4865
+ */
4866
+ async function readBoundedResponse(network, url, signal, maxBytes, headers = {}, notFound) {
4867
+ signal.throwIfAborted();
4868
+ const response = await network.fetch(url, {
4869
+ signal,
4870
+ redirect: "error",
4871
+ headers
4872
+ });
4873
+ if (!response.ok) {
4874
+ await response.body?.cancel().catch(() => {});
4875
+ if (response.status === 404 && notFound) throw notFound();
4876
+ let retry = Number(response.headers.get("retry-after"));
4877
+ 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);
4878
+ throw new CatalogError("SYNC_FAILED", `Request failed (HTTP ${response.status})`, Number.isFinite(retry) && retry > 0 ? Math.min(86400, retry) : void 0);
4879
+ }
4880
+ if (Number(response.headers.get("content-length")) > maxBytes) {
4881
+ await response.body?.cancel().catch(() => {});
4882
+ throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
4883
+ }
4884
+ const reader = response.body?.getReader();
4885
+ if (!reader) return /* @__PURE__ */ new Uint8Array();
4886
+ const chunks = [];
4887
+ let size = 0;
4888
+ try {
4889
+ for (;;) {
4890
+ signal.throwIfAborted();
4891
+ const chunk = await reader.read();
4892
+ if (chunk.done) break;
4893
+ size += chunk.value.length;
4894
+ if (size > maxBytes) throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
4895
+ chunks.push(chunk.value);
4896
+ }
4897
+ signal.throwIfAborted();
4898
+ return Buffer.concat(chunks, size);
4899
+ } finally {
4900
+ await reader.cancel().catch(() => {});
4901
+ reader.releaseLock();
4902
+ }
4903
+ }
4904
+ /**
4905
+ * Resolves the catalog's main commit with one ref advertisement request, then reads the complete
4906
+ * extension index pinned to that commit. An unchanged commit reuses `previous` with a new fetch
4907
+ * time. Requests carry no credentials, refuse redirects and share an 8 MiB budget and 30 s limit.
4908
+ */
4909
+ async function synchronize(network, ownerSignal, previous) {
4910
+ const controller = new AbortController();
4911
+ const signal = AbortSignal.any([ownerSignal, controller.signal]);
4912
+ const timer = setTimeout(() => controller.abort(new CatalogError("SYNC_FAILED", "Catalog synchronization exceeded 30 seconds")), 3e4);
4913
+ try {
4914
+ const commit = parseMainCommit(await readBoundedResponse(network, CATALOG_REFS_URL, signal, REFS_MAX_BYTES, headers));
4915
+ if (previous?.commit === commit) return {
4916
+ ...previous,
4917
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
4918
+ };
4919
+ const releases = decodeReleases(parseJson(decodeUtf8(await readBoundedResponse(network, catalogIndexUrl(commit), signal, CATALOG_MAX_BYTES, headers, () => new CatalogError("CATALOG_UNAVAILABLE", "No extension index is available")))));
4920
+ return {
4921
+ repository: CATALOG_REPOSITORY,
4922
+ commit,
4923
+ contentDigest: recordDigest({ releases }),
4924
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
4925
+ revision: previous?.revision ?? 0,
4926
+ releases
4927
+ };
4928
+ } catch (error) {
4929
+ controller.abort(error);
4930
+ if (error instanceof CatalogError) throw error;
4931
+ if (ownerSignal.aborted) throw ownerSignal.reason;
4932
+ throw new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful snapshot is retained");
4933
+ } finally {
4934
+ clearTimeout(timer);
4935
+ }
4936
+ }
4937
+ //#endregion
4938
+ //#region src/extension-catalog/service.ts
4939
+ /** Creates local catalog reads and explicit synchronization, preview, and operation management. */
4940
+ function createCatalogService(options) {
4941
+ let snapshot = null;
4942
+ let sync = { state: "idle" };
4943
+ try {
4944
+ snapshot = options.store.read();
4945
+ } catch {
4946
+ sync = {
4947
+ state: "failed",
4948
+ error: "Catalog cache is damaged; refresh to repair it"
4949
+ };
4950
+ }
4951
+ const controller = new AbortController();
4952
+ const signal = AbortSignal.any([options.signal, controller.signal]);
4953
+ const ownedTasks = /* @__PURE__ */ new Set();
4954
+ let synchronization = null;
4955
+ function notifySynchronization() {
4956
+ if (!signal.aborted) options.notify?.({
4957
+ revision: snapshot?.revision ?? 0,
4958
+ ...snapshot ? { snapshot: {
4959
+ commit: snapshot.commit,
4960
+ contentDigest: snapshot.contentDigest
4961
+ } } : {},
4962
+ sync: { ...sync }
4963
+ });
4964
+ }
4965
+ function sharedSynchronization(manual = false) {
4966
+ signal.throwIfAborted();
4967
+ if (synchronization) {
4968
+ if (manual) synchronization.manual = true;
4969
+ return synchronization;
4970
+ }
4971
+ const taskId = randomUUID(), taskController = new AbortController(), taskSignal = AbortSignal.any([signal, taskController.signal]);
4972
+ sync = {
4973
+ state: "syncing",
4974
+ taskId
4975
+ };
4976
+ const work = Promise.resolve().then(async () => {
4977
+ try {
4978
+ const acquired = await synchronize(options.network, taskSignal, snapshot);
4979
+ const saved = await options.installer.coordinate(() => {
4980
+ taskSignal.throwIfAborted();
4981
+ snapshot = options.store.save(acquired);
4982
+ return snapshot;
4983
+ });
4984
+ sync = {
4985
+ state: "succeeded",
4986
+ taskId
4987
+ };
4988
+ return saved;
4989
+ } catch (error) {
4990
+ const failure = error instanceof CatalogError ? error : new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful data is retained");
4991
+ sync = {
4992
+ state: "failed",
4993
+ taskId,
4994
+ error: failure.message,
4995
+ ...failure.retryAfterSeconds === void 0 ? {} : { retryAfterSeconds: failure.retryAfterSeconds }
4996
+ };
4997
+ throw failure;
4998
+ } finally {
4999
+ synchronization = null;
5000
+ notifySynchronization();
5001
+ }
5002
+ });
5003
+ synchronization = {
5004
+ taskId,
5005
+ controller: taskController,
5006
+ manual,
5007
+ consumers: /* @__PURE__ */ new Set(),
5008
+ work
5009
+ };
5010
+ ownedTasks.add(work);
5011
+ work.then(() => ownedTasks.delete(work), () => ownedTasks.delete(work));
5012
+ notifySynchronization();
5013
+ return synchronization;
5014
+ }
5015
+ async function acquireFreshSnapshot(attempt) {
5016
+ const consumerSignal = AbortSignal.any([signal, attempt.signal]);
5017
+ consumerSignal.throwIfAborted();
5018
+ const task = sharedSynchronization(), consumer = Symbol();
5019
+ task.consumers.add(consumer);
5020
+ let onAbort;
5021
+ const cancelled = new Promise((_resolve, reject) => {
5022
+ onAbort = () => {
5023
+ task.consumers.delete(consumer);
5024
+ if (!task.manual && !task.consumers.size) task.controller.abort(consumerSignal.reason);
5025
+ reject(consumerSignal.reason);
5026
+ };
5027
+ consumerSignal.addEventListener("abort", onAbort, { once: true });
5028
+ if (consumerSignal.aborted) onAbort();
5029
+ });
5030
+ try {
5031
+ const acquired = await Promise.race([task.work, cancelled]);
5032
+ consumerSignal.throwIfAborted();
5033
+ return acquired;
5034
+ } catch (error) {
5035
+ if (consumerSignal.aborted && !task.manual && !task.consumers.size) {
5036
+ task.controller.abort(consumerSignal.reason);
5037
+ await Promise.allSettled([task.work]);
5038
+ }
5039
+ throw error;
5040
+ } finally {
5041
+ task.consumers.delete(consumer);
5042
+ consumerSignal.removeEventListener("abort", onAbort);
5043
+ }
5044
+ }
5045
+ /** Prepares exact roots and one shared extension closure without imports or activation. */
5046
+ async function preview(inputs, enableNames = [], batch = false, attempt, automatic = false) {
5047
+ const preparationSignal = attempt ? AbortSignal.any([signal, attempt.signal]) : signal;
5048
+ preparationSignal.throwIfAborted();
5049
+ const selections = inputs.map((input) => SelectionSchema.parse(input)), selectedSnapshot = snapshot;
5050
+ if (!selections.length || selections.length > 64 || enableNames.length > 2e3) throw new CatalogError("LIMIT_EXCEEDED", "Select between one and 64 exact extension roots");
5051
+ if (!selectedSnapshot) throw new CatalogError("CATALOG_UNAVAILABLE", "Refresh the extension catalog before selecting a release");
5052
+ const accepted = structuredClone(selectedSnapshot);
5053
+ const selectedHost = options.hostIdentity;
5054
+ if (!selectedHost) throw new CatalogError("RELEASE_INCOMPATIBLE", "Current product and host target are unavailable");
5055
+ const host = selectedHost;
5056
+ const observations = await options.installer.observe();
5057
+ const roots = [];
5058
+ for (const selection of selections) {
5059
+ if (selection.snapshotCommit !== accepted.commit) throw new CatalogError("STALE_PREVIEW", "Selected catalog commit is no longer current");
5060
+ const release = accepted.releases.find((r) => r.releaseId === selection.releaseId);
5061
+ if (!release || release.artifact.integrity !== selection.artifactIntegrity) throw new CatalogError("RELEASE_UNLISTED", "Selected exact release is not listed");
5062
+ if (!releaseCompatible(release, host)) throw new CatalogError("RELEASE_INCOMPATIBLE", "Selected release does not accept the current product and host target");
5063
+ const existing = observations.find((o) => o.packageName === release.packageName);
5064
+ if (automatic && existing?.declared.origin !== void 0) throw new CatalogError("STALE_PREVIEW", "A user declaration now owns this default extension");
5065
+ if (selection.expectedInstalledReceiptId !== void 0 && existing?.receipt?.receiptId !== selection.expectedInstalledReceiptId) throw new CatalogError("STALE_PREVIEW", "Current installed receipt differs from the displayed selection");
5066
+ const prior = roots.find((r) => r.packageName === release.packageName);
5067
+ if (prior && recordDigest(prior) !== recordDigest(release)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension roots select conflicting exact releases");
5068
+ if (!prior) roots.push(release);
5069
+ }
5070
+ const resolved = [], chosen = new Map(roots.map((root) => [root.packageName, root])), expanded = /* @__PURE__ */ new Set();
5071
+ async function expand(candidate) {
5072
+ const prior = chosen.get(candidate.packageName);
5073
+ if (prior) {
5074
+ if (prior.releaseId !== candidate.releaseId) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension requirements select conflicting exact releases");
5075
+ if (expanded.has(candidate.packageName)) return;
5076
+ }
5077
+ if (!prior && chosen.size >= 64) throw new CatalogError("LIMIT_EXCEEDED", "Extension closure exceeds 64 packages");
5078
+ chosen.set(candidate.packageName, candidate);
5079
+ expanded.add(candidate.packageName);
5080
+ resolved.push(candidate);
5081
+ const raw = (await options.installer.inspect({
5082
+ expectedName: candidate.packageName,
5083
+ expectedVersion: candidate.version,
5084
+ ...candidate.artifact
5085
+ }, preparationSignal, attempt)).yaoguang?.dependencies ?? {};
5086
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).length > 64) throw new CatalogError("ARTIFACT_INVALID", "Invalid extension dependency declaration");
5087
+ for (const [name, range] of Object.entries(raw)) {
5088
+ if (typeof range !== "string" || semver.validRange(range) === null) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension dependency has an invalid version range");
5089
+ const selected = chosen.get(name);
5090
+ if (selected) {
5091
+ if (!semver.satisfies(selected.version, range)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Exact closure cannot satisfy all extension requirements");
5092
+ continue;
5093
+ }
5094
+ const installed = observations.find((o) => o.packageName === name && o.declared.origin !== void 0);
5095
+ if (automatic && installed && (!installed.declared.installed || !installed.declared.enabled)) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency declaration does not permit default installation");
5096
+ const installedVersion = installed?.receipt?.version ?? installed?.declared.version ?? installed?.summary?.version;
5097
+ if (installedVersion && semver.valid(installedVersion) && semver.satisfies(installedVersion, range)) continue;
5098
+ if (automatic && installed) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency version cannot be replaced by default installation");
5099
+ const choices = accepted.releases.filter((r) => r.packageName === name && semver.satisfies(r.version, range) && releaseCompatible(r, host));
5100
+ if (choices.length !== 1) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Missing extension dependency has no unique compatible exact release");
5101
+ await expand(choices[0]);
5102
+ }
5103
+ }
5104
+ for (const root of roots) await expand(root);
5105
+ function evidence(candidate) {
5106
+ return {
5107
+ expectedName: candidate.packageName,
5108
+ expectedVersion: candidate.version,
5109
+ ...candidate.artifact,
5110
+ sourceRecord: {
5111
+ snapshot: {
5112
+ repository: accepted.repository,
5113
+ commit: accepted.commit,
5114
+ contentDigest: accepted.contentDigest
5115
+ },
5116
+ release: candidate,
5117
+ releaseDigest: recordDigest(candidate)
5118
+ },
5119
+ activationConstraints: {
5120
+ hostVersionRange: candidate.compatibility.productRange,
5121
+ platformTargets: candidate.compatibility.platforms
5122
+ },
5123
+ display: {
5124
+ label: typeof candidate.displayName === "string" ? candidate.displayName : candidate.displayName["en-US"],
5125
+ detail: "Historical catalog admission"
5126
+ }
5127
+ };
5128
+ }
5129
+ const validate = () => {
5130
+ 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");
5131
+ };
5132
+ preparationSignal.throwIfAborted();
5133
+ validate();
5134
+ const rootNames = new Set(roots.map((root) => root.packageName));
5135
+ const dependencies = resolved.filter((record) => !rootNames.has(record.packageName)).map(evidence);
5136
+ const preview = batch ? await options.installer.previewBatch({
5137
+ roots: roots.map(evidence),
5138
+ dependencies,
5139
+ enabled: true,
5140
+ enableNames
5141
+ }, validate, attempt) : await options.installer.preview({
5142
+ ...evidence(roots[0]),
5143
+ enabled: true,
5144
+ dependencies
5145
+ }, validate, attempt);
5146
+ preparationSignal.throwIfAborted();
5147
+ if (automatic && preview.replacing.length) throw new CatalogError("STALE_PREVIEW", "Default installation cannot replace existing extensions");
5148
+ return {
5149
+ previewToken: preview.token,
5150
+ expiresAt: preview.expiresAt,
5151
+ snapshot: {
5152
+ commit: accepted.commit,
5153
+ contentDigest: accepted.contentDigest
5154
+ },
5155
+ graphRevision: preview.graphRevision,
5156
+ resolvedSelections: resolved,
5157
+ dependencies: preview.selections.filter((selection) => !rootNames.has(selection.expectedName)).map((s) => ({
5158
+ packageName: s.expectedName,
5159
+ version: s.expectedVersion
5160
+ })),
5161
+ willEnable: [...preview.willEnable],
5162
+ replacing: [...preview.replacing],
5163
+ affectedOwners: [...preview.affectedOwners],
5164
+ warnings: []
5165
+ };
5166
+ }
5167
+ const defaults = options.defaultsStore && options.hostIdentity ? createDefaultsService({
5168
+ store: options.defaultsStore,
5169
+ identity: options.hostIdentity,
5170
+ installer: options.installer,
5171
+ signal,
5172
+ preview: (selections, attempt) => preview(selections, [], true, attempt, true),
5173
+ acquireSnapshot: acquireFreshSnapshot
5174
+ }) : null;
5175
+ function requireDefaults() {
5176
+ if (!defaults) throw new CatalogError("DEFAULTS_UNAVAILABLE", "Default extension initialization is unavailable for this host");
5177
+ return defaults;
5178
+ }
5179
+ return {
5180
+ /** Starts or shares this owner's one-shot bounded automatic installation task. */
5181
+ defaultsEnsure(input) {
5182
+ return requireDefaults().ensure(input);
5183
+ },
5184
+ /** Returns passive initialization facts without refreshing or enrolling. */
5185
+ defaultsStatus() {
5186
+ return requireDefaults().status();
5187
+ },
5188
+ /** Returns cached data only; first use and failure never trigger network work. */
5189
+ list() {
5190
+ signal.throwIfAborted();
5191
+ if (!snapshot) return {
5192
+ revision: 0,
5193
+ snapshot: null,
5194
+ releases: [],
5195
+ sync: { ...sync }
5196
+ };
5197
+ const { releases, ...metadata } = snapshot;
5198
+ return {
5199
+ revision: snapshot.revision,
5200
+ snapshot: metadata,
5201
+ releases,
5202
+ sync: { ...sync }
5203
+ };
5204
+ },
5205
+ /** Joins the active fresh synchronization; manual work survives automatic attempt cancellation. */
5206
+ refresh() {
5207
+ return {
5208
+ taskId: sharedSynchronization(true).taskId,
5209
+ sync: { ...sync }
5210
+ };
5211
+ },
5212
+ /** Previews installation with target enablement and joins owned preparation before disposal. */
5213
+ preview(input) {
5214
+ const task = preview([input]);
5215
+ ownedTasks.add(task);
5216
+ task.then(() => {
5217
+ ownedTasks.delete(task);
5218
+ }, () => {
5219
+ ownedTasks.delete(task);
5220
+ });
5221
+ return task;
5222
+ },
5223
+ /** Prepares one approved union of exact roots and existing owners to enable. */
5224
+ previewBatch(inputs, enableNames = []) {
5225
+ const task = preview(inputs, enableNames, true);
5226
+ ownedTasks.add(task);
5227
+ task.then(() => ownedTasks.delete(task), () => ownedTasks.delete(task));
5228
+ return task;
5229
+ },
5230
+ /** Delegates deduplication before any token or current-snapshot validation. */
5231
+ install(operationId, previewToken) {
5232
+ signal.throwIfAborted();
5233
+ return options.installer.install({
5234
+ operationId,
5235
+ token: previewToken
5236
+ });
5237
+ },
5238
+ /** Reads an existing durable attempt without restarting work. */
5239
+ operation(operationId) {
5240
+ return options.installer.operation(operationId);
5241
+ },
5242
+ /** Retries only cleanup still owned by the queried attempt. */
5243
+ retryCleanup(operationId) {
5244
+ return options.installer.retryCleanup(operationId);
5245
+ },
5246
+ /** Projects installed metadata against the current cached directory without reading files. */
5247
+ async installed() {
5248
+ signal.throwIfAborted();
5249
+ const observations = await options.installer.observe();
5250
+ return {
5251
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
5252
+ rows: projectInstalled(observations, snapshot, options.hostIdentity)
5253
+ };
5254
+ },
5255
+ /** Joins all discovery work before owner disposal completes. */
5256
+ async dispose() {
5257
+ controller.abort(/* @__PURE__ */ new Error("Catalog owner withdrawn"));
5258
+ await Promise.all([defaults?.dispose(), Promise.allSettled([...ownedTasks])]);
5259
+ }
5260
+ };
5261
+ }
4508
5262
  //#endregion
4509
- //#region src/extension-catalog/views.ts
4510
- /** Explicit catalog synchronization result, independent of snapshot availability. */
4511
- const SyncSchema = z.object({
4512
- state: z.enum([
4513
- "idle",
4514
- "syncing",
4515
- "succeeded",
4516
- "failed"
4517
- ]),
4518
- taskId: z.uuid().optional(),
4519
- error: z.string().max(4096).optional(),
4520
- retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4521
- }).strict();
4522
- /** Pure cache-only list response; an empty catalog is a valid successful snapshot. */
4523
- const ListSchema = z.object({
4524
- revision: z.number().int().nonnegative(),
4525
- snapshot: SnapshotSchema.omit({ releases: true }).nullable(),
4526
- releases: z.array(ReleaseSchema).max(2e3),
4527
- sync: SyncSchema
4528
- }).strict();
4529
- /** Short invalidation carrying no configuration, credentials, or archive bytes. */
4530
- const CatalogChangedSchema = z.object({
4531
- revision: z.number().int().nonnegative(),
4532
- snapshot: z.object({
4533
- commit: GitShaSchema,
4534
- contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4535
- }).strict().optional(),
4536
- sync: SyncSchema
4537
- }).strict();
4538
- /** Confirmation response for a fixed exact extension dependency closure. */
4539
- const PreviewSchema = z.object({
4540
- previewToken: z.string().min(1).max(8192),
4541
- expiresAt: z.iso.datetime({ offset: true }),
4542
- snapshot: z.object({
4543
- commit: GitShaSchema,
4544
- contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4545
- }).strict(),
4546
- graphRevision: z.string().max(1024),
4547
- resolvedSelections: z.array(ReleaseSchema).max(64),
4548
- dependencies: z.array(z.object({
4549
- packageName: z.string(),
4550
- version: z.string()
4551
- }).strict()).max(64),
4552
- willEnable: z.array(z.string()).max(2e3),
4553
- replacing: z.array(z.string()).max(64),
4554
- affectedOwners: z.array(z.string()).max(2e3),
4555
- warnings: z.array(ArtifactWarningSchema).max(64)
4556
- }).strict();
4557
- /** Durable installation operation facts returned by the generic owner-bound service. */
4558
- const OperationSchema = z.object({
4559
- operationId: z.uuid(),
4560
- attemptId: z.uuid(),
4561
- issuer: z.string(),
4562
- submissionDigest: z.string(),
4563
- requestDigest: z.string(),
4564
- packageName: z.string(),
4565
- warnings: z.array(ArtifactWarningSchema).max(3).optional(),
4566
- warningCount: z.number().int().nonnegative().max(1e5).optional(),
4567
- rootResults: z.array(z.object({
4568
- packageName: z.string(),
4569
- status: z.enum([
4570
- "pending",
4571
- "active",
4572
- "disabled",
4573
- "deferred",
4574
- "failed"
4575
- ]),
4576
- reason: z.string().max(4096).optional()
4577
- }).strict()).max(2e3).optional(),
4578
- phase: z.enum([
4579
- "preparing",
4580
- "installing",
4581
- "admitted",
4582
- "activating",
4583
- "settled"
4584
- ]),
4585
- currentStep: z.enum([
4586
- "prepare",
4587
- "download",
4588
- "verify",
4589
- "npm",
4590
- "admission",
4591
- "activation",
4592
- "cleanup"
4593
- ]),
4594
- outcome: z.enum([
4595
- "pending",
4596
- "succeeded",
4597
- "failed",
4598
- "interrupted"
4599
- ]),
4600
- failureStage: z.enum([
4601
- "prepare",
4602
- "download",
4603
- "verify",
4604
- "npm",
4605
- "admission",
4606
- "activation",
4607
- "cleanup",
4608
- "recovery"
4609
- ]).optional(),
4610
- reason: z.string().max(4096).optional(),
4611
- cleanup: z.enum([
4612
- "not-needed",
4613
- "pending",
4614
- "complete",
4615
- "failed"
4616
- ]),
4617
- startedAt: z.iso.datetime({ offset: true }),
4618
- settledAt: z.iso.datetime({ offset: true }).optional(),
4619
- packages: z.array(z.object({
4620
- packageName: z.string(),
4621
- beforeRevision: z.number().int().nonnegative(),
4622
- receiptId: z.uuid().nullable(),
4623
- diskChanged: z.boolean().optional(),
4624
- ownerWithdrawn: z.boolean().optional()
4625
- }).strict()).max(2e3)
4626
- }).strict();
4627
- /** Installation progress invalidation; clients query the durable attempt after reconnecting. */
4628
- const InstallChangedSchema = z.object({
4629
- operationId: z.uuid(),
4630
- phase: OperationSchema.shape.phase,
4631
- currentStep: OperationSchema.shape.currentStep,
4632
- outcome: OperationSchema.shape.outcome,
4633
- cleanup: OperationSchema.shape.cleanup,
4634
- revision: z.number().int().nonnegative()
4635
- }).strict();
4636
- /** Current directory source markers and installed metadata for unique package names. */
4637
- const InstalledSchema = z.object({
4638
- observedAt: z.iso.datetime({ offset: true }),
4639
- rows: z.array(InstalledRowSchema).max(2e3)
4640
- }).strict();
4641
- /** Existing owner RPC success/failure convention; sanitized errors remain actionable. */
4642
- function resultSchema(data) {
4643
- return z.union([z.object({
4644
- ok: z.literal(true),
4645
- data
4646
- }).strict(), z.object({
4647
- ok: z.literal(false),
4648
- code: z.string(),
4649
- message: z.string().max(4096),
4650
- retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4651
- }).strict()]);
5263
+ //#region src/extension-catalog/store.ts
5264
+ /** Persists the last complete validated catalog snapshot in this owner's storage lease. */
5265
+ function createCatalogStore(storage) {
5266
+ const name = storage.tableName("catalog_snapshot");
5267
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid storage table identity");
5268
+ const table = `"${name}"`;
5269
+ storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK(id=1), snapshot_json TEXT NOT NULL)`);
5270
+ function validate(input) {
5271
+ const value = SnapshotSchema.parse(input);
5272
+ if (recordDigest({ releases: value.releases }) !== value.contentDigest) throw new CatalogError("CATALOG_INVALID", "Cached snapshot digest differs from its complete records");
5273
+ if (new Set(value.releases.map((r) => r.releaseId)).size !== value.releases.length) throw new CatalogError("CATALOG_INVALID", "Duplicate cached release");
5274
+ return value;
5275
+ }
5276
+ return {
5277
+ /** Reads validated last-success data without network activity; corruption refuses availability. */
5278
+ read() {
5279
+ const row = storage.db.prepare(`SELECT snapshot_json FROM ${table} WHERE id=1`).get();
5280
+ if (!row) return null;
5281
+ try {
5282
+ return validate(JSON.parse(row.snapshot_json));
5283
+ } catch {
5284
+ throw new CatalogError("CATALOG_INVALID", "Catalog cache is unavailable; refresh to repair it");
5285
+ }
5286
+ },
5287
+ /** Atomically replaces the complete snapshot and advances its successful revision. */
5288
+ save(input) {
5289
+ const snapshot = validate(input);
5290
+ storage.db.exec("SAVEPOINT catalog_snapshot_commit");
5291
+ try {
5292
+ let before = null;
5293
+ try {
5294
+ before = this.read();
5295
+ } catch {}
5296
+ const revision = (before?.revision ?? 0) + 1;
5297
+ if (!Number.isSafeInteger(revision)) throw new CatalogError("LIMIT_EXCEEDED", "Catalog revision is exhausted");
5298
+ const saved = {
5299
+ ...snapshot,
5300
+ revision
5301
+ };
5302
+ const json = canonicalJson(saved);
5303
+ if (Buffer.byteLength(json) > 8388608) throw new CatalogError("LIMIT_EXCEEDED", "Encoded catalog exceeds 8 MiB");
5304
+ storage.db.prepare(`INSERT INTO ${table}(id,snapshot_json) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET snapshot_json=excluded.snapshot_json`).run(json);
5305
+ storage.db.exec("RELEASE catalog_snapshot_commit");
5306
+ return saved;
5307
+ } catch (error) {
5308
+ storage.db.exec("ROLLBACK TO catalog_snapshot_commit");
5309
+ storage.db.exec("RELEASE catalog_snapshot_commit");
5310
+ throw error;
5311
+ }
5312
+ }
5313
+ };
4652
5314
  }
4653
5315
  //#endregion
4654
5316
  //#region src/extension-catalog/register.ts
@@ -4741,12 +5403,6 @@ function registerExtensionCatalog(ctx) {
4741
5403
  result: resultSchema(InstalledSchema),
4742
5404
  handle: () => result(() => service.installed())
4743
5405
  });
4744
- ctx.client.registerMethod({
4745
- name: "extensionCatalogPreview",
4746
- params: z.object({ selection: SelectionSchema }).strict(),
4747
- result: resultSchema(PreviewSchema),
4748
- handle: (p) => result(() => service.preview(p.selection))
4749
- });
4750
5406
  ctx.client.registerMethod({
4751
5407
  name: "extensionCatalogPreviewBatch",
4752
5408
  params: z.object({
@@ -4779,10 +5435,41 @@ function registerExtensionCatalog(ctx) {
4779
5435
  });
4780
5436
  const operationParams = z.object({ operationId: z.uuid() }).strict();
4781
5437
  ctx.client.registerMethod({
4782
- name: "extensionCatalogOperation",
4783
- params: operationParams,
4784
- result: resultSchema(z.object({ operation: OperationSchema }).strict()),
4785
- handle: (p) => result(async () => ({ operation: OperationSchema.parse(await service.operation(p.operationId)) }))
5438
+ name: "extensionCatalogOperations",
5439
+ params: OperationQueriesParams,
5440
+ result: resultSchema(OperationQueriesData),
5441
+ handle: (p) => result(async () => {
5442
+ const results = [];
5443
+ for (const [index, target] of p.operationIds.entries()) {
5444
+ ctx.signal.throwIfAborted();
5445
+ try {
5446
+ const operation = OperationSchema.parse(await service.operation(target));
5447
+ ctx.signal.throwIfAborted();
5448
+ const member = {
5449
+ index,
5450
+ target,
5451
+ ok: true,
5452
+ value: { operation }
5453
+ };
5454
+ if (Buffer.byteLength(JSON.stringify(member)) > p.maxItemBytes) throw new CatalogError("read-limit", "Operation result exceeds the declared member byte budget");
5455
+ results.push(member);
5456
+ } catch (error) {
5457
+ ctx.signal.throwIfAborted();
5458
+ const refusal = managementError(error);
5459
+ results.push({
5460
+ index,
5461
+ target,
5462
+ ok: false,
5463
+ error: {
5464
+ code: refusal.code.slice(0, 64).replace(/[\uD800-\uDBFF]$/, "") || "INSTALL_FAILED",
5465
+ message: refusal.message.slice(0, 512).replace(/[\uD800-\uDBFF]$/, ""),
5466
+ ...refusal.retryAfterSeconds === void 0 ? {} : { details: { retryAfterSeconds: refusal.retryAfterSeconds } }
5467
+ }
5468
+ });
5469
+ }
5470
+ }
5471
+ return { results };
5472
+ })
4786
5473
  });
4787
5474
  ctx.client.registerMethod({
4788
5475
  name: "extensionCatalogRetryCleanup",