@eum-agent/extension-catalog 1.0.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.js +2070 -1474
  2. package/package.json +6 -6
  3. package/ui/ui.js +9 -6
package/dist/index.js CHANGED
@@ -313,1116 +313,430 @@ 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/message.ts
603
449
  /**
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.
450
+ * The transcript's message shapes: the authoritative history that assembly
451
+ * reads. A message is either a plain user/assistant turn of text, an
452
+ * assistant reply that also requests tool calls, or a tool-results message
453
+ * that answers a batch of those calls. Zod schemas are the source of
454
+ * truth; the types are `z.infer`red from them so this vocabulary survives
455
+ * the event log round trip once `packages/core/store-sqlite` serializes it.
456
+ *
457
+ * Tool results are carried in a `role: 'user'` message with `tool-result`
458
+ * content parts. Protocol implementations translate this neutral transcript
459
+ * into their own request representation.
607
460
  */
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
- }
461
+ const MessageRoleSchema = z.enum(["user", "assistant"]);
462
+ const TextPartSchema = z.object({
463
+ type: z.literal("text"),
464
+ text: z.string()
465
+ });
466
+ /** The model's thinking, attached to the same assistant message its reply
467
+ * text is. Symmetric with `TextPart` on purpose — it is the recorded
468
+ * counterpart of the publish-only `thinking-delta` chunk, carried the
469
+ * same way `TextPart` carries the recorded counterpart of `text-delta`.
470
+ * Accumulating deltas into this shape, and deciding whether to send it
471
+ * back on the next call, is the adapter's job — this package only
472
+ * carries it. */
473
+ const ThinkingPartSchema = z.object({
474
+ type: z.literal("thinking"),
475
+ text: z.string(),
476
+ /** An opaque token the provider issued with this block and requires back
477
+ * **unmodified** on any later turn that continues the same conversation.
478
+ * A fabricated or edited value can invalidate replay. Absent for protocols
479
+ * that issue no signature. The kernel never reads it; it only
480
+ * carries it, so that the adapter that produced it can hand it back. */
481
+ signature: z.string().optional(),
482
+ /**
483
+ * Which endpoint issued that signature.
484
+ *
485
+ * A signature is only worth anything to whoever signed it, and the product
486
+ * cannot tell whether two endpoints are the same signer — two keys against
487
+ * one vendor, or a proxy in front of it, look identical from here. So this
488
+ * is compared as an endpoint id and the comparison is a deliberate
489
+ * over-approximation: an adapter drops a block another endpoint signed,
490
+ * which between two endpoints of one vendor costs a block that would have
491
+ * replayed. The other way round costs a rejected request.
492
+ *
493
+ * Absent wherever `signature` is: nothing to attribute. The kernel never
494
+ * reads either; it carries them so the adapter that made the block can
495
+ * decide.
496
+ */
497
+ issuer: z.string().optional(),
498
+ /** Model identifier that produced this signed thinking block. */
499
+ originModel: z.string().optional(),
500
+ /**
501
+ * Stable compatibility fingerprint for the non-thinking prefix covered by
502
+ * the provider signature. Adapters omit a signed block when it does not match
503
+ * the request prefix they are about to send.
504
+ */
505
+ prefix: z.string().optional(),
506
+ /**
507
+ * Original output-token count used as a conservative upper bound when the
508
+ * provider retains more thinking state than the visible text represents.
509
+ */
510
+ outputTokens: z.number().int().nonnegative().optional(),
511
+ /**
512
+ * Set on a block the provider returned with no readable text — a protocol's
513
+ * `redacted_thinking`. `text` is then empty and `signature` holds the
514
+ * provider's opaque `data`, which goes back unmodified in the same place.
515
+ */
516
+ redacted: z.literal(true).optional()
517
+ });
518
+ /** A tool call the model requested. `input` is whatever JSON-serializable
519
+ * arguments the model produced for it — the kernel does not validate a
520
+ * tool's own argument shape, only that the call itself round-trips. */
521
+ const ToolUsePartSchema = z.object({
522
+ type: z.literal("tool-use"),
523
+ id: z.string(),
524
+ name: z.string(),
525
+ input: z.unknown(),
526
+ /** Host-projected execution identity; never changes the model's original call. */
527
+ execution: z.object({
528
+ name: z.string(),
529
+ input: z.unknown(),
530
+ definitionFingerprint: z.string()
531
+ }).optional()
532
+ });
533
+ const Sha256Schema = z.string().regex(/^[0-9a-f]{64}$/);
534
+ /** The copy of a file a model is sent, when it differs from the original:
535
+ * a content-addressed variant within every built-in provider type's limits. */
536
+ const FileVariantSchema = z.object({
537
+ id: Sha256Schema,
538
+ mediaType: z.string().min(1),
539
+ size: z.number().int().positive(),
540
+ width: z.number().int().positive().optional(),
541
+ height: z.number().int().positive().optional()
542
+ }).strict();
633
543
  /**
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.
544
+ * A reference to a content-addressed file of the session's workspace. Only
545
+ * metadata: the bytes live on disk under the workspace's `files/` directory
546
+ * and reach a request through `ModelRequest.files` alone, so an event, a
547
+ * frame or a snapshot never carries them. `name` belongs to the reference,
548
+ * not to the file: the same bytes may be named differently in two messages.
638
549
  */
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
- }
550
+ const FileRefSchema = z.object({
551
+ /** The original's sha256, lower-case hex. */
552
+ id: Sha256Schema,
553
+ mediaType: z.string().min(1),
554
+ name: z.string().min(1).max(200),
555
+ size: z.number().int().positive(),
556
+ /** Present for an image. */
557
+ width: z.number().int().positive().optional(),
558
+ height: z.number().int().positive().optional(),
559
+ /** The variant a model receives; absent when the original is within limits. */
560
+ forModel: FileVariantSchema.optional()
561
+ }).strict();
562
+ /** A file inside a message, at the place it was written: text and file parts
563
+ * interleave in the order a person composed them. */
564
+ const FilePartSchema = z.object({
565
+ type: z.literal("file"),
566
+ file: FileRefSchema
567
+ });
568
+ /** The host stamps the producing activation before persisting a block. */
569
+ const SavedRequiredContextBlockSchema = z.object({
570
+ id: z.string().min(1),
571
+ scope: z.string().min(1),
572
+ version: z.string().min(1),
573
+ text: z.string()
574
+ }).extend({ stampedSource: z.string().min(1) });
575
+ /** Pure delivery facts; live reservation objects never enter the event log. */
576
+ const ToolResultDeliverySchema = z.strictObject({
577
+ kind: z.enum([
578
+ "receipt",
579
+ "preview",
580
+ "exact-page"
581
+ ]),
582
+ outputTokens: z.number().int().nonnegative(),
583
+ sourceComplete: z.boolean().optional(),
584
+ /** Host-bound accepted reply identity; receipt text is not its original source. */
585
+ answerRequestId: z.string().min(1).optional(),
586
+ execution: z.enum([
587
+ "not-started",
588
+ "committed",
589
+ "partial",
590
+ "unknown"
591
+ ]).optional()
592
+ });
593
+ /** The answer to one tool call, matched back to it by `toolUseId`. */
594
+ const ToolResultPartSchema = z.object({
595
+ /** Immutable host provenance for the decision that admitted this result. */
596
+ ownerContext: OwnerContextSchema.optional(),
597
+ type: z.literal("tool-result"),
598
+ toolUseId: z.string(),
599
+ requiredContext: z.array(SavedRequiredContextBlockSchema).optional(),
600
+ /** Immutable host-accepted snapshots. */
601
+ widgets: z.array(WidgetInstanceSchema).max(8).optional(),
602
+ /** Fixed admission diagnostics. */
603
+ widgetIssues: z.array(WidgetIssueSchema).max(8).optional(),
604
+ content: z.string(),
605
+ isError: z.boolean().optional(),
606
+ /** Requested preview body tokens; invalid hints are ignored by the host. */
607
+ previewTokens: z.number().optional(),
608
+ /** Host-admitted delivery metadata; exact pages cannot be silently shortened. */
609
+ delivery: ToolResultDeliverySchema.optional(),
610
+ /** Files the call handed back, after its text. */
611
+ files: z.array(FileRefSchema).optional()
612
+ });
613
+ const ContentPartSchema = z.discriminatedUnion("type", [
614
+ TextPartSchema,
615
+ ThinkingPartSchema,
616
+ ToolUsePartSchema,
617
+ ToolResultPartSchema,
618
+ FilePartSchema
619
+ ]);
677
620
  /**
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.
621
+ * One volatile contributor's text as a request carried it: the contributor's
622
+ * `id` and the strings it gave, joined by a blank line. A request appends a
623
+ * note only when it differs from that contributor's last note in the history,
624
+ * or at a turn's first step under the default policy. An on-change contributor
625
+ * compares values across turn boundaries. The note stays in every later request at the
626
+ * place it was first sent.
681
627
  */
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
- });
628
+ const VolatileNoteSchema = z.object({
629
+ id: z.string(),
630
+ text: z.string()
631
+ }).strict();
632
+ /**
633
+ * Where a person's message came in, when it came in through a channel that
634
+ * names itself: the channel's id and display label, and the speaker the
635
+ * channel reported. Written by the gateway's access layer alone; a message
636
+ * typed in the product's own client carries none.
637
+ */
638
+ const MessageViaSchema = z.object({
639
+ channel: z.string().min(1),
640
+ label: z.string().min(1),
641
+ /** Who spoke, as the channel identifies them. `role` is whether they were
642
+ * the owner when they sent it; a later change of owner leaves it. */
643
+ sender: z.object({
644
+ id: z.string().min(1),
645
+ name: z.string().min(1).max(64),
646
+ role: z.enum(["owner", "member"])
647
+ }).strict().optional()
648
+ }).strict();
649
+ /** Protocol-declared termination, independent of token usage. */
650
+ const FinishReasonSchema = z.enum([
651
+ "stop",
652
+ "tool-calls",
653
+ "max-tokens",
654
+ "refusal"
655
+ ]);
656
+ /** Discarded partial calls contain identities only, never executable arguments. */
657
+ const OutputTruncationSchema = z.object({
658
+ incompleteToolCalls: z.array(z.object({
659
+ id: z.string(),
660
+ name: z.string().optional()
661
+ })),
662
+ incompleteThinking: z.literal(true).optional()
663
+ });
664
+ const MessageSchema = z.object({
665
+ finishReason: FinishReasonSchema.optional(),
666
+ outputTruncation: OutputTruncationSchema.optional(),
667
+ outputContinuation: z.object({
668
+ replyId: z.string().uuid(),
669
+ attempt: z.number().int().min(1).max(3)
670
+ }).optional(),
671
+ /** Immutable owner provenance, excluded from all model communication. */
672
+ ownerContext: OwnerContextSchema.optional(),
673
+ /** UUID assigned when the message first forms and retained by every fork. */
674
+ id: z.string().uuid(),
675
+ role: MessageRoleSchema,
676
+ content: z.array(ContentPartSchema),
677
+ /** Present only on a message the model refused to complete — the
678
+ * provider's own category for why.
679
+ *
680
+ * It lives **on the message** rather than only on the `message-appended`
681
+ * event that records it, and that distinction is the whole point: `fold`
682
+ * rebuilds the transcript out of `event.message`, so a marker carried only
683
+ * by the event survives the log and is lost the moment anybody folds it
684
+ * back. The transcript needs to remember that a reply was a refusal,
685
+ * which means the message has to. Contrast `backfilled`, which stays on
686
+ * the event because it describes how that event came to be rather than
687
+ * anything about the message. */
688
+ refusalCategory: z.string().optional(),
689
+ /** Present on a message a composer command produced: what the person
690
+ * wrote, and the source that expanded it. `content` holds the expansion,
691
+ * which is what the model is sent; the transcript shows `text`. */
692
+ invocation: z.object({
693
+ text: z.string(),
694
+ namespace: z.string()
695
+ }).strict().optional(),
696
+ /** What a person attached, one entry per leading text block of `content`,
697
+ * which holds each attachment's original text. The model-facing envelope is
698
+ * added where a request is assembled and is never stored. */
699
+ attachments: z.array(z.object({
700
+ namespace: z.string(),
701
+ group: z.string().optional(),
702
+ label: z.string()
703
+ }).strict()).optional(),
704
+ /** Present only on a model reply: the pair that produced it, stamped by the
705
+ * host on the final chunk. On the message rather than the event for the
706
+ * reason `refusalCategory` is: `fold` rebuilds the transcript from
707
+ * `event.message`, and the latest reply's pair is what names the model a
708
+ * compaction after a switch summarizes on. */
709
+ model: z.object({
710
+ providerId: z.string(),
711
+ model: z.string()
712
+ }).strict().optional(),
713
+ /** Present only on a model reply: the volatile notes the request that
714
+ * produced it appended. Adapters render them just before this message, so
715
+ * every later request repeats the earlier one byte for byte. Clients do not
716
+ * draw them. */
717
+ volatile: z.array(VolatileNoteSchema).optional(),
718
+ /** Present only on a person's message that arrived through a labelled
719
+ * channel. Adapters never see it: the request a model receives carries a
720
+ * speaker line instead, added where the request is assembled. */
721
+ via: MessageViaSchema.optional(),
722
+ /** Durable host attribution, preserved in the transcript when the log is replayed. */
723
+ source: z.object({
724
+ kind: z.enum([
725
+ "delegation-result",
726
+ "delegation-task",
727
+ "notice",
728
+ "trigger",
729
+ "trigger-data"
730
+ ]),
731
+ owner: z.string(),
732
+ taskId: z.string(),
733
+ deliveryId: z.string().optional(),
734
+ /** The trigger definition a `trigger` or `trigger-data` delivery ran for. */
735
+ triggerId: z.string().optional(),
736
+ /** What a person calls the source: a scheduled task's name. */
737
+ label: z.string().optional()
738
+ }).strict().optional()
739
+ });
1426
740
  //#endregion
1427
741
  //#region ../../core/kernel/src/vocab/human.ts
1428
742
  /**
@@ -1512,16 +826,80 @@ z.object({
1512
826
  suspendedCalls: z.array(ToolUsePartSchema)
1513
827
  });
1514
828
  //#endregion
829
+ //#region ../../core/kernel/src/vocab/model-failure.ts
830
+ /** Bounded, verified facts about a logical model call failure. */
831
+ /** Stable failure facts; arbitrary provider text and unknown fields are refused. */
832
+ const ModelFailureSchema = z.strictObject({
833
+ code: z.enum([
834
+ "finish-reason-missing",
835
+ "finish-reason-unsupported",
836
+ "response-empty",
837
+ "final-chunk-missing",
838
+ "stream-interrupted",
839
+ "stream-idle-timeout",
840
+ "http-error",
841
+ "request-too-large",
842
+ "request-measurement-unsupported",
843
+ "authentication-required",
844
+ "authentication-expired",
845
+ "quota-exceeded",
846
+ "model-unavailable",
847
+ "context-limit-exceeded",
848
+ "provider-error",
849
+ "response-invalid",
850
+ "unknown"
851
+ ]),
852
+ stage: z.enum([
853
+ "request",
854
+ "transport",
855
+ "stream",
856
+ "response-validation",
857
+ "unknown"
858
+ ]),
859
+ category: z.enum([
860
+ "network",
861
+ "provider",
862
+ "request-too-large",
863
+ "protocol",
864
+ "unknown"
865
+ ]),
866
+ source: z.enum([
867
+ "protocol",
868
+ "transport",
869
+ "provider",
870
+ "host",
871
+ "unknown"
872
+ ]),
873
+ status: z.number().int().min(100).max(599).optional(),
874
+ retryable: z.boolean().optional(),
875
+ finishReason: z.enum([
876
+ "stop",
877
+ "tool-calls",
878
+ "max-tokens",
879
+ "refusal"
880
+ ]).optional(),
881
+ providerCode: z.enum([
882
+ "usage_not_included",
883
+ "usage_limit_reached",
884
+ "insufficient_quota",
885
+ "context_length_exceeded",
886
+ "rate_limit_exceeded",
887
+ "overloaded_error",
888
+ "api_error",
889
+ "rate_limit_error",
890
+ "cyber_policy",
891
+ "invalid_prompt",
892
+ "bio_policy",
893
+ "misalignment_policy_violation"
894
+ ]).optional(),
895
+ attemptCount: z.number().int().positive().max(Number.MAX_SAFE_INTEGER).optional(),
896
+ modelCallId: z.uuid().optional(),
897
+ turn: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional(),
898
+ step: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).optional()
899
+ }).refine((value) => JSON.stringify(value).length <= 2048, "model failure exceeds its size limit");
900
+ //#endregion
1515
901
  //#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
- */
902
+ /** Turn endings distinguish ordinary completion, cancellation, failures and host execution stops. */
1525
903
  const CompletedReasonSchema = z.enum([
1526
904
  "natural",
1527
905
  "step-limit",
@@ -1543,12 +921,50 @@ const InterruptedOutcomeSchema = z.object({ kind: z.literal("interrupted") });
1543
921
  * has more of these than this change implements transitions for. */
1544
922
  const FailedOutcomeSchema = z.object({
1545
923
  kind: z.literal("failed"),
1546
- reason: z.string()
924
+ reason: z.string(),
925
+ failure: ModelFailureSchema.optional()
926
+ });
927
+ /** A verified shared-resource admission failure; no model retry can create capacity. */
928
+ const ResourceExhaustionSchema = z.object({
929
+ reason: z.literal("resource-exhausted"),
930
+ pool: z.literal("query"),
931
+ dimension: z.enum([
932
+ "session-slots",
933
+ "session-bytes",
934
+ "resident-bytes",
935
+ "session-scratch",
936
+ "resident-scratch"
937
+ ]),
938
+ limit: z.number().int().positive().safe(),
939
+ held: z.number().int().nonnegative().safe(),
940
+ requested: z.number().int().nonnegative().safe(),
941
+ cleanup: z.enum([
942
+ "none",
943
+ "pending",
944
+ "failed"
945
+ ]),
946
+ recovery: z.enum([
947
+ "wait-cleanup",
948
+ "owner-recovery",
949
+ "expire-resources"
950
+ ])
951
+ });
952
+ /** Successful model output exhausted the fixed continuation budget. */
953
+ const ExecutionStopSchema = z.discriminatedUnion("reason", [ResourceExhaustionSchema, z.object({
954
+ reason: z.literal("output-limit"),
955
+ continuationsUsed: z.literal(3),
956
+ continuationLimit: z.literal(3)
957
+ })]);
958
+ /** A host execution boundary stopped a legal transcript without natural completion. */
959
+ const StoppedOutcomeSchema = z.object({
960
+ kind: z.literal("stopped"),
961
+ stop: ExecutionStopSchema
1547
962
  });
1548
963
  const OutcomeSchema = z.discriminatedUnion("kind", [
1549
964
  CompletedOutcomeSchema,
1550
965
  InterruptedOutcomeSchema,
1551
- FailedOutcomeSchema
966
+ FailedOutcomeSchema,
967
+ StoppedOutcomeSchema
1552
968
  ]);
1553
969
  //#endregion
1554
970
  //#region ../../core/kernel/src/vocab/session-id.ts
@@ -1610,6 +1026,8 @@ z.object({
1610
1026
  phase: PhaseSchema,
1611
1027
  turn: z.number().int().nonnegative(),
1612
1028
  step: z.number().int().nonnegative(),
1029
+ outputContinuationsUsed: z.number().int().min(0).max(3),
1030
+ pendingOutputContinuation: z.object({ replyId: z.string().uuid() }).optional(),
1613
1031
  turnTokensUsed: z.number().int().nonnegative(),
1614
1032
  pendingToolCalls: z.array(PendingToolCallSchema),
1615
1033
  pendingHumanRequests: z.array(PendingHumanRequestSchema),
@@ -1659,6 +1077,24 @@ z.object({
1659
1077
  * throwing — a log a later build appended new variants to must still read
1660
1078
  * on an older one.
1661
1079
  */
1080
+ /** Durable owner JSON state and its idempotent operation receipt, ordered by physical sequence. */
1081
+ const OwnerStateEventSchema = OwnerContextEntrySchema.extend({
1082
+ kind: z.literal("owner-state"),
1083
+ sessionId: SessionIdSchema,
1084
+ address: SessionAddressSchema,
1085
+ operationId: z.string().min(1).max(256),
1086
+ requestHash: z.string().min(1).max(256)
1087
+ }).superRefine(({ owner, key, revision, data }, ctx) => {
1088
+ if (!OwnerContextSchema.safeParse([{
1089
+ owner,
1090
+ key,
1091
+ revision,
1092
+ data
1093
+ }]).success) ctx.addIssue({
1094
+ code: "custom",
1095
+ message: "Invalid or oversized owner state"
1096
+ });
1097
+ });
1662
1098
  const TriggerSourceSchema = z.enum(["human", "plugin"]);
1663
1099
  /** What a model call reported using, in the terms its final chunk gives
1664
1100
  * us. Carried on `model-replied` and folded into `ControlState.turnTokensUsed`
@@ -1704,6 +1140,8 @@ const TriggerEventSchema = z.object({
1704
1140
  * without needing the full `FinishReason` union carried over the wire. */
1705
1141
  const ModelRepliedEventSchema = z.object({
1706
1142
  kind: z.literal("model-replied"),
1143
+ finishReason: FinishReasonSchema,
1144
+ outputTruncation: OutputTruncationSchema.optional(),
1707
1145
  message: MessageSchema,
1708
1146
  usage: ModelUsageSchema,
1709
1147
  refusalCategory: z.string().optional()
@@ -1713,7 +1151,10 @@ const ModelRepliedEventSchema = z.object({
1713
1151
  * same reason as `model-replied`. */
1714
1152
  const ToolResultsAddedEventSchema = z.object({
1715
1153
  kind: z.literal("tool-results-added"),
1716
- message: MessageSchema
1154
+ ownerStates: z.array(OwnerStateEventSchema).max(16).optional(),
1155
+ message: MessageSchema,
1156
+ /** Host-verified stop, settled after all admitted calls finish. */
1157
+ stop: ExecutionStopSchema.optional()
1717
1158
  });
1718
1159
  /** A message became part of the transcript. */
1719
1160
  const MessageAppendedEventSchema = z.object({
@@ -1769,7 +1210,13 @@ const ContextMeasurementSchema = z.object({
1769
1210
  fingerprint: z.string(),
1770
1211
  inputBudget: z.number().int().nonnegative().optional(),
1771
1212
  /** Whether the reserve is enforceable upstream or the catalogue capacity. */
1772
- outputReserveSource: z.enum(["capacity", "enforced"]).optional()
1213
+ outputReserveSource: z.enum([
1214
+ "capacity",
1215
+ "enforced",
1216
+ "estimated"
1217
+ ]).optional(),
1218
+ /** Whether the capacity comes from a declaration or the owner's assumed baseline. */
1219
+ capacitySource: z.enum(["declared", "assumed"]).optional()
1773
1220
  });
1774
1221
  /** Why the context operation started. */
1775
1222
  const ContextTriggerSchema = z.enum([
@@ -1933,7 +1380,8 @@ const CancelledEventSchema = z.object({
1933
1380
  * same reason as `Cancelled`. */
1934
1381
  const EffectFailedEventSchema = z.object({
1935
1382
  kind: z.literal("effect-failed"),
1936
- reason: z.string()
1383
+ reason: z.string(),
1384
+ failure: ModelFailureSchema.optional()
1937
1385
  });
1938
1386
  /** A non-final chunk from the model port's stream, forwarded by the
1939
1387
  * call-model handler so that `decide` — never the handler itself — is
@@ -1946,6 +1394,7 @@ const EffectFailedEventSchema = z.object({
1946
1394
  * published, which only coincides with the port's transport shape today. */
1947
1395
  const ModelChunkEventSchema = z.object({
1948
1396
  kind: z.literal("model-chunk"),
1397
+ ownerContext: OwnerContextSchema.optional(),
1949
1398
  chunk: z.discriminatedUnion("kind", [
1950
1399
  z.object({
1951
1400
  kind: z.literal("text-delta"),
@@ -1969,6 +1418,7 @@ const ModelChunkEventSchema = z.object({
1969
1418
  * handler, which derives the recorded `human-asked` from it. */
1970
1419
  const StepSuspendedEventSchema = z.object({
1971
1420
  kind: z.literal("step-suspended"),
1421
+ ownerStates: z.array(OwnerStateEventSchema).max(16).optional(),
1972
1422
  settled: z.array(ToolResultPartSchema),
1973
1423
  requests: z.array(HumanRequestSchema)
1974
1424
  });
@@ -2008,7 +1458,43 @@ const ParticipantChangedEventSchema = z.object({
2008
1458
  reason: z.string().max(500).optional(),
2009
1459
  at: z.number().int().nonnegative()
2010
1460
  });
1461
+ /** Complete pure admission facts committed before any call in the batch starts. */
1462
+ const ToolCallsAdmittedEventSchema = z.object({
1463
+ kind: z.literal("tool-calls-admitted"),
1464
+ /** Assistant message whose original calls this fact annotates. */
1465
+ messageId: z.string().optional(),
1466
+ sessionId: SessionIdSchema,
1467
+ address: SessionAddressSchema,
1468
+ calls: z.array(z.object({
1469
+ callId: z.string(),
1470
+ partIndex: z.number().int().nonnegative().optional(),
1471
+ entry: z.object({
1472
+ name: z.string(),
1473
+ input: z.unknown()
1474
+ }),
1475
+ target: z.object({
1476
+ name: z.string(),
1477
+ input: z.unknown()
1478
+ }).optional(),
1479
+ definitionFingerprint: z.string(),
1480
+ status: z.enum(["admitted", "rejected"]),
1481
+ errorCode: z.string().optional()
1482
+ }))
1483
+ });
1484
+ /** Durable admission of one bounded continuation in the current turn. */
1485
+ const OutputContinuationStartedEventSchema = z.object({
1486
+ kind: z.literal("output-continuation-started"),
1487
+ sessionId: SessionIdSchema,
1488
+ address: SessionAddressSchema,
1489
+ turn: z.number().int().positive(),
1490
+ step: z.number().int().positive(),
1491
+ replyId: z.string().uuid(),
1492
+ attempt: z.number().int().min(1).max(3)
1493
+ });
2011
1494
  const RecordableEventSchema = z.discriminatedUnion("kind", [
1495
+ OutputContinuationStartedEventSchema,
1496
+ ToolCallsAdmittedEventSchema,
1497
+ OwnerStateEventSchema,
2012
1498
  TriggerEventSchema,
2013
1499
  HistorySeededEventSchema,
2014
1500
  HistoryRewoundEventSchema,
@@ -2022,6 +1508,9 @@ const RecordableEventSchema = z.discriminatedUnion("kind", [
2022
1508
  ParticipantChangedEventSchema
2023
1509
  ]);
2024
1510
  const EventSchema = z.discriminatedUnion("kind", [
1511
+ OutputContinuationStartedEventSchema,
1512
+ ToolCallsAdmittedEventSchema,
1513
+ OwnerStateEventSchema,
2025
1514
  TriggerEventSchema,
2026
1515
  HistorySeededEventSchema,
2027
1516
  HistoryRewoundEventSchema,
@@ -2099,6 +1588,214 @@ z.discriminatedUnion("kind", [
2099
1588
  CheckpointEffectSchema
2100
1589
  ]);
2101
1590
  //#endregion
1591
+ //#region ../../core/protocol/src/telemetry.ts
1592
+ /** Finite performance stages exclude arbitrary paths, SQL and business text. */
1593
+ const TelemetryStage = z.enum([
1594
+ "ui.interaction",
1595
+ "ui.feedback",
1596
+ "ui.commit",
1597
+ "ui.frame",
1598
+ "ui.stream-display",
1599
+ "reading.watch",
1600
+ "reading.content",
1601
+ "reading.page",
1602
+ "reading.queue",
1603
+ "reading.worker",
1604
+ "reading.projection",
1605
+ "reading.ack-wait",
1606
+ "reading.loss",
1607
+ "reading.source",
1608
+ "markdown.parse",
1609
+ "markdown.mount",
1610
+ "rpc.encode",
1611
+ "rpc.send",
1612
+ "rpc.receive",
1613
+ "rpc.decode",
1614
+ "rpc.resolve",
1615
+ "rpc.roundtrip",
1616
+ "rpc.dispatch",
1617
+ "browser.long-task",
1618
+ "browser.frame-gap",
1619
+ "browser.loss",
1620
+ "browser.input-delay",
1621
+ "native.bridge",
1622
+ "native.command",
1623
+ "native.socket.connect",
1624
+ "native.socket.queue",
1625
+ "native.socket.send",
1626
+ "native.socket.receive",
1627
+ "native.http.headers",
1628
+ "native.http.body",
1629
+ "native.file.open",
1630
+ "native.file.write",
1631
+ "native.file.commit",
1632
+ "native.file.cleanup",
1633
+ "native.picker.wait",
1634
+ "native.loss",
1635
+ "gateway.decode",
1636
+ "gateway.handler",
1637
+ "gateway.encode",
1638
+ "gateway.send",
1639
+ "runtime.admission",
1640
+ "runtime.event-batch",
1641
+ "runtime.owner-context",
1642
+ "runtime.prepare",
1643
+ "runtime.status",
1644
+ "runtime.snapshot",
1645
+ "runtime.publish",
1646
+ "runtime.reading",
1647
+ "runtime.turn",
1648
+ "model.inspect",
1649
+ "model.tokenizer",
1650
+ "model.cache",
1651
+ "model.call",
1652
+ "model.display",
1653
+ "context.inspect",
1654
+ "context.contributor",
1655
+ "tool.call",
1656
+ "database.read",
1657
+ "database.open",
1658
+ "database.close",
1659
+ "database.decode",
1660
+ "database.statement",
1661
+ "database.serialize",
1662
+ "database.transaction",
1663
+ "database.event-insert",
1664
+ "database.reading-projection",
1665
+ "database.commit",
1666
+ "database.rollback",
1667
+ "database.busy",
1668
+ "database.checkpoint",
1669
+ "file.open",
1670
+ "file.write",
1671
+ "file.rename",
1672
+ "file.close",
1673
+ "file.fsync",
1674
+ "file.directory-sync",
1675
+ "file.publication",
1676
+ "file.cleanup",
1677
+ "event-loop.delay",
1678
+ "event-loop.max",
1679
+ "event-loop.p95",
1680
+ "event-loop.p99",
1681
+ "event-loop.utilization",
1682
+ "process.cpu",
1683
+ "process.rss",
1684
+ "process.heap",
1685
+ "process.gc",
1686
+ "logging.write"
1687
+ ]);
1688
+ /** User intent labels contain no user-supplied text. */
1689
+ const TelemetryOperation = z.enum([
1690
+ "session-switch",
1691
+ "send",
1692
+ "human-answer",
1693
+ "approval",
1694
+ "cancel",
1695
+ "history-page",
1696
+ "heartbeat",
1697
+ "generic"
1698
+ ]);
1699
+ const nonnegative = z.number().finite().nonnegative();
1700
+ const counter = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
1701
+ const identity = z.string().min(1).max(128).regex(/^[A-Za-z0-9@][A-Za-z0-9@/_.:-]*$/);
1702
+ /** Correlation is foreign input; server span and connection identities are host-supplied. */
1703
+ const RequestTrace = z.object({
1704
+ traceId: z.uuid(),
1705
+ parentSpanId: z.uuid().optional(),
1706
+ interactionId: z.uuid().optional()
1707
+ }).strict();
1708
+ /** One same-clock duration, with strictly bounded scalar metadata. */
1709
+ const TelemetryObservation = z.object({
1710
+ stage: TelemetryStage,
1711
+ clockDomain: z.uuid(),
1712
+ monotonicStartMs: nonnegative,
1713
+ durationMs: nonnegative,
1714
+ outcome: z.enum([
1715
+ "ok",
1716
+ "error",
1717
+ "cancelled",
1718
+ "timeout",
1719
+ "unknown"
1720
+ ]).optional(),
1721
+ operation: TelemetryOperation.optional(),
1722
+ spanId: z.uuid().optional(),
1723
+ traceId: z.uuid().optional(),
1724
+ parentSpanId: z.uuid().optional(),
1725
+ interactionId: z.uuid().optional(),
1726
+ sessionId: identity.optional(),
1727
+ requestId: identity.optional(),
1728
+ visibility: z.enum(["foreground", "background"]).optional(),
1729
+ cacheState: z.enum([
1730
+ "hit",
1731
+ "miss",
1732
+ "cold",
1733
+ "warm"
1734
+ ]).optional(),
1735
+ measurementPurpose: z.enum([
1736
+ "request",
1737
+ "text",
1738
+ "catalogue",
1739
+ "tool-result",
1740
+ "display"
1741
+ ]).optional(),
1742
+ bytes: counter.optional(),
1743
+ count: counter.optional(),
1744
+ hits: counter.optional(),
1745
+ misses: counter.optional(),
1746
+ evictions: counter.optional(),
1747
+ inputBytes: counter.optional(),
1748
+ retainedBytes: counter.optional()
1749
+ }).strict();
1750
+ /** Runtime-only capture controls; diagnostic TTL defaults to fifteen minutes. */
1751
+ const TelemetryConfigure = z.object({
1752
+ mode: z.enum([
1753
+ "off",
1754
+ "normal",
1755
+ "diagnostic"
1756
+ ]),
1757
+ durationSeconds: z.number().int().min(1).max(3600).optional()
1758
+ }).strict();
1759
+ /** Bounded client batch; transport additionally checks its serialized byte count. */
1760
+ const TelemetryIngest = z.object({
1761
+ batchId: z.uuid(),
1762
+ pageId: z.uuid(),
1763
+ observations: z.array(TelemetryObservation).max(128)
1764
+ }).strict();
1765
+ z.object({
1766
+ mode: z.enum([
1767
+ "off",
1768
+ "normal",
1769
+ "diagnostic"
1770
+ ]),
1771
+ expiresAt: z.iso.datetime().optional(),
1772
+ pendingRecords: counter,
1773
+ pendingBytes: counter,
1774
+ droppedRecords: counter,
1775
+ capabilities: z.object({ eventLoop: z.boolean() }).strict(),
1776
+ budgets: z.object({
1777
+ targetMs: z.literal(15),
1778
+ batchRecords: z.literal(128),
1779
+ batchBytes: z.literal(65536),
1780
+ recordBytes: z.literal(8192)
1781
+ }).strict()
1782
+ }).strict();
1783
+ /** Authenticated browser and native observation admission. */
1784
+ const TelemetryIngestRequest = z.object({
1785
+ method: z.literal("gateway.telemetryIngest"),
1786
+ params: TelemetryIngest
1787
+ });
1788
+ /** Authenticated collection status query. */
1789
+ const TelemetryStatusRequest = z.object({
1790
+ method: z.literal("gateway.telemetryStatus"),
1791
+ params: z.object({}).strict().optional()
1792
+ });
1793
+ /** Authenticated runtime-only collection configuration. */
1794
+ const TelemetryConfigureRequest = z.object({
1795
+ method: z.literal("gateway.telemetryConfigure"),
1796
+ params: TelemetryConfigure
1797
+ });
1798
+ //#endregion
2102
1799
  //#region ../../core/protocol/src/agent-revisions.ts
2103
1800
  /** Configuration history wire contracts. Shared resource contents are excluded. */
2104
1801
  const AgentId = z.string().min(1);
@@ -2310,8 +2007,13 @@ const ReadingTurnHeader = z.object({
2310
2007
  "running",
2311
2008
  "completed",
2312
2009
  "cancelled",
2313
- "failed"
2314
- ])
2010
+ "failed",
2011
+ "stopped"
2012
+ ]),
2013
+ /** Structured framework stop, independent of failed model response diagnostics. */
2014
+ stop: ExecutionStopSchema.optional(),
2015
+ reason: z.string().max(512).optional(),
2016
+ failure: ModelFailureSchema.optional()
2315
2017
  });
2316
2018
  /** A contiguous page, ordered by message ordinal. Cursors are exclusive boundaries. */
2317
2019
  const HistoryWindow = z.object({
@@ -2392,16 +2094,39 @@ const SessionMessagePartsRequest = z.object({
2392
2094
  limit: page
2393
2095
  }).strict()
2394
2096
  });
2395
- /** Reads at most 256KiB from one authorized source object. */
2396
- const SessionMessageContentRequest = z.object({
2397
- method: z.literal("session.messageContent"),
2097
+ /** One authorized range consumed by the internal range reader; never a scalar wire entry. */
2098
+ const MessageContentInput = z.object({
2099
+ scope: ContentScope,
2100
+ readingLeaseId: z.string().optional(),
2101
+ contentRefId: z.string().max(256),
2102
+ offset: z.number().int().nonnegative(),
2103
+ maxBytes: z.number().int().min(4).max(262144)
2104
+ }).strict();
2105
+ /** Reads independent ranges after checking the complete raw and encoded budgets. */
2106
+ const SessionMessageContentsRequest = z.object({
2107
+ method: z.literal("session.messageContents"),
2398
2108
  params: z.object({
2399
2109
  scope: ContentScope,
2400
2110
  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()
2111
+ items: z.array(MessageContentInput.omit({
2112
+ scope: true,
2113
+ readingLeaseId: true
2114
+ })).min(1).max(64),
2115
+ maxTotalBytes: z.number().int().min(4).max(1048576).default(1048576)
2116
+ }).strict().superRefine((value, ctx) => {
2117
+ if (value.items.reduce((sum, item) => sum + item.maxBytes, 0) > value.maxTotalBytes) ctx.addIssue({
2118
+ code: "custom",
2119
+ message: "declared raw content exceeds maxTotalBytes"
2120
+ });
2121
+ if (value.items.reduce((sum, item) => sum + 4 * Math.ceil(item.maxBytes / 3) + 65536, 8192) > 2097152) ctx.addIssue({
2122
+ code: "custom",
2123
+ message: "declared encoded result exceeds 2 MiB"
2124
+ });
2125
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 8388608) ctx.addIssue({
2126
+ code: "custom",
2127
+ message: "batch input exceeds 8 MiB"
2128
+ });
2129
+ })
2405
2130
  });
2406
2131
  /** Reads durable annotations or process-local request descriptors. */
2407
2132
  const SessionLivePageRequest = z.object({
@@ -2541,11 +2266,11 @@ z.enum([
2541
2266
  "session",
2542
2267
  "permanent"
2543
2268
  ]);
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() });
2269
+ /** An authorized workspace tree with its canonical real path and stored access level. */
2270
+ const AuthorizedDirectory = z.object({
2271
+ path: z.string(),
2272
+ access: z.enum(["read", "read-write"])
2273
+ });
2549
2274
  /** A workspace: an abstract scope, **bound to no path**. Its authorized
2550
2275
  * directories hang beneath it, zero of them being the normal state for a
2551
2276
  * freshly created one. */
@@ -2555,11 +2280,11 @@ const WorkspaceSummary = z.object({
2555
2280
  createdAt: z.number().int(),
2556
2281
  /** The revision of the uploaded picture, or `null` for none — then a
2557
2282
  * client draws the letters face derived from the name. The bytes travel
2558
- * only through `config.workspace.avatar`. */
2283
+ * only through `config.workspace.avatars`. */
2559
2284
  avatar: z.string().nullable(),
2560
2285
  /** 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`. */
2286
+ * summary preserves each authorized tree and its read or read-write level.
2287
+ * Additional resource grants are listed by `config.access.list`. */
2563
2288
  directories: z.array(AuthorizedDirectory)
2564
2289
  });
2565
2290
  /** A session as it appears in a list, without loading it. Everything here
@@ -3094,7 +2819,7 @@ const AgentChangedFrame = z.object({
3094
2819
  * names the agent rather than carrying a summary: there is none left. */
3095
2820
  const AgentRemovedFrame = z.object({
3096
2821
  kind: z.literal("config.agentRemoved"),
3097
- agentId: z.string()
2822
+ agentIds: z.array(z.string()).min(1).max(64)
3098
2823
  });
3099
2824
  const WorkspaceChangedFrame = z.object({
3100
2825
  kind: z.literal("config.workspaceChanged"),
@@ -3163,6 +2888,13 @@ const SessionMessageFrame = z.object({
3163
2888
  sourceSeq: z.number().int().min(-1),
3164
2889
  streamEpoch: z.string().optional()
3165
2890
  });
2891
+ /** Committed execution identities annotate existing calls without changing their protocol names. */
2892
+ const SessionToolCallsAdmittedFrame = z.object({
2893
+ kind: z.literal("session.toolCallsAdmitted"),
2894
+ ...sessionFrameBase,
2895
+ messageId: z.string(),
2896
+ sourceSeq: z.number().int().min(-1)
2897
+ });
3166
2898
  /** Replaces the entire effective snapshot after a rewind commits. */
3167
2899
  const SessionHistoryReplacedFrame = z.object({
3168
2900
  kind: z.literal("session.historyReplaced"),
@@ -3535,12 +3267,13 @@ const InboxChangedFrame = z.object({
3535
3267
  const CredentialChangedFrame = z.object({
3536
3268
  kind: z.literal("config.credentialChanged"),
3537
3269
  plugin: z.string(),
3538
- scope: z.string()
3270
+ scopes: z.array(z.string()).min(1).max(64)
3539
3271
  });
3540
3272
  const CoreSessionFrame = z.discriminatedUnion("kind", [
3541
3273
  TurnStartedFrame,
3542
3274
  DeltaFrame,
3543
3275
  DeltaResetFrame,
3276
+ SessionToolCallsAdmittedFrame,
3544
3277
  SessionMessageFrame,
3545
3278
  SessionHistoryReplacedFrame,
3546
3279
  TurnEndedFrame,
@@ -3579,6 +3312,7 @@ const CoreFrame = z.discriminatedUnion("kind", [
3579
3312
  TurnStartedFrame,
3580
3313
  DeltaFrame,
3581
3314
  DeltaResetFrame,
3315
+ SessionToolCallsAdmittedFrame,
3582
3316
  SessionMessageFrame,
3583
3317
  SessionHistoryReplacedFrame,
3584
3318
  TurnEndedFrame,
@@ -3704,10 +3438,29 @@ const SessionForkRequest = z.object({
3704
3438
  operationId: z.string().uuid()
3705
3439
  })
3706
3440
  });
3441
+ const batchIds = () => z.array(z.string().min(1)).min(1).max(64);
3442
+ const queryBudgets = {
3443
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
3444
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
3445
+ };
3446
+ const boundedBatchParams = (shape, collection) => z.object(shape).strict().superRefine((value, ctx) => {
3447
+ if (new TextEncoder().encode(JSON.stringify(value)).byteLength > 8388608) ctx.addIssue({
3448
+ code: "custom",
3449
+ message: "batch input exceeds 8 MiB"
3450
+ });
3451
+ const params = value;
3452
+ if (typeof params.maxItemBytes === "number" && typeof params.maxTotalBytes === "number" && Array.isArray(params[collection]) && params.maxItemBytes * params[collection].length + 8192 > params.maxTotalBytes) ctx.addIssue({
3453
+ code: "custom",
3454
+ message: "declared response budget exceeds maxTotalBytes"
3455
+ });
3456
+ });
3707
3457
  /** 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() })
3458
+ const SessionOperationsGetRequest = z.object({
3459
+ method: z.literal("session.operations.get"),
3460
+ params: boundedBatchParams({
3461
+ operationIds: z.array(z.uuid()).min(1).max(64),
3462
+ ...queryBudgets
3463
+ }, "operationIds")
3711
3464
  });
3712
3465
  /** Takes back a message sent while a turn was running, before its step
3713
3466
  * claims it. Answers with the message, so the page that asked can put its
@@ -3797,10 +3550,11 @@ const SessionLeaveRequest = z.object({
3797
3550
  * contract `session.setModel` has. It produces no turn and writes no event. */
3798
3551
  const SessionArchiveRequest = z.object({
3799
3552
  method: z.literal("session.archive"),
3800
- params: z.object({
3801
- sessionId: z.string(),
3553
+ params: boundedBatchParams({
3554
+ operationId: z.uuid(),
3555
+ sessionIds: batchIds(),
3802
3556
  archived: z.boolean()
3803
- })
3557
+ }, "sessionIds")
3804
3558
  });
3805
3559
  /** Sets the name a person gives a session, or clears it: trimmed, at most 60
3806
3560
  * characters, and a name holding nothing but whitespace clears it. Leaves
@@ -3866,7 +3620,10 @@ const ConfigAgentSetPromptSlotRequest = z.object({
3866
3620
  });
3867
3621
  const ConfigAgentPromptSlotsRequest = z.object({
3868
3622
  method: z.literal("config.agent.promptSlots"),
3869
- params: z.object({ agentId: z.string() })
3623
+ params: boundedBatchParams({
3624
+ agentIds: batchIds(),
3625
+ ...queryBudgets
3626
+ }, "agentIds")
3870
3627
  });
3871
3628
  /** Sets an agent's picture, or with `null` returns it to the derived one.
3872
3629
  * The browser crops and encodes; the gateway checks it is a whole 256×256
@@ -3881,9 +3638,12 @@ const ConfigAgentSetAvatarRequest = z.object({
3881
3638
  })
3882
3639
  });
3883
3640
  /** 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() })
3641
+ const ConfigAgentAvatarsRequest = z.object({
3642
+ method: z.literal("config.agent.avatars"),
3643
+ params: boundedBatchParams({
3644
+ agentIds: z.array(z.string()).min(1).max(4),
3645
+ maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
3646
+ }, "agentIds")
3887
3647
  });
3888
3648
  /** Removes a user-created agent: its row, picture, model overrides, access
3889
3649
  * grants and its directory under the work root. Its sessions stay readable
@@ -3892,7 +3652,10 @@ const ConfigAgentAvatarRequest = z.object({
3892
3652
  * `config.agentRemoved` follows. */
3893
3653
  const ConfigAgentRemoveRequest = z.object({
3894
3654
  method: z.literal("config.agent.remove"),
3895
- params: z.object({ agentId: z.string().min(1) })
3655
+ params: boundedBatchParams({
3656
+ operationId: z.uuid(),
3657
+ agentIds: batchIds()
3658
+ }, "agentIds")
3896
3659
  });
3897
3660
  /** One save from the agent editor: every field the person changed, applied
3898
3661
  * together. Everything is validated before anything is written, and the
@@ -3943,7 +3706,8 @@ z.object({
3943
3706
  name: z.string(),
3944
3707
  description: z.string(),
3945
3708
  plugin: z.string(),
3946
- permitted: z.boolean()
3709
+ permitted: z.boolean(),
3710
+ preloadDefault: z.boolean()
3947
3711
  }))
3948
3712
  });
3949
3713
  /** Writes nothing, produces no turn, needs no session: safe to retry. An
@@ -3951,7 +3715,10 @@ z.object({
3951
3715
  * real and different answer — "this agent is offered no tools at all". */
3952
3716
  const ConfigToolListRequest = z.object({
3953
3717
  method: z.literal("config.tool.list"),
3954
- params: z.object({ agentId: z.string().min(1) })
3718
+ params: boundedBatchParams({
3719
+ agentIds: batchIds(),
3720
+ ...queryBudgets
3721
+ }, "agentIds")
3955
3722
  });
3956
3723
  /** What is under a directory, for a client that has to name one.
3957
3724
  *
@@ -4010,21 +3777,28 @@ const TriggerUpdateRequest = z.object({
4010
3777
  });
4011
3778
  const TriggerSetEnabledRequest = z.object({
4012
3779
  method: z.literal("trigger.setEnabled"),
4013
- params: z.object({
4014
- id: z.string().min(1),
3780
+ params: boundedBatchParams({
3781
+ operationId: z.uuid(),
3782
+ ids: batchIds(),
4015
3783
  enabled: z.boolean()
4016
- })
3784
+ }, "ids")
4017
3785
  });
4018
3786
  /** Removes a definition, its runs and its pre-authorized scope; sessions it
4019
3787
  * opened stay. */
4020
3788
  const TriggerRemoveRequest = z.object({
4021
3789
  method: z.literal("trigger.remove"),
4022
- params: z.object({ id: z.string().min(1) })
3790
+ params: boundedBatchParams({
3791
+ operationId: z.uuid(),
3792
+ ids: batchIds()
3793
+ }, "ids")
4023
3794
  });
4024
3795
  /** A definition's runs, newest first, at most 200. */
4025
3796
  const TriggerRunsRequest = z.object({
4026
3797
  method: z.literal("trigger.runs"),
4027
- params: z.object({ id: z.string().min(1) })
3798
+ params: boundedBatchParams({
3799
+ ids: batchIds(),
3800
+ ...queryBudgets
3801
+ }, "ids")
4028
3802
  });
4029
3803
  /** Every inbox item that still exists, newest first. No cap: unread notices
4030
3804
  * and waiting requests are never removed on anyone's behalf, so the list
@@ -4059,7 +3833,7 @@ const InboxClearReadRequest = z.object({
4059
3833
  * answers success with no side effect. */
4060
3834
  const ProcessStopRequest = z.object({
4061
3835
  method: z.literal("process.stop"),
4062
- params: z.object({ processId: z.string().min(1) })
3836
+ params: boundedBatchParams({ processIds: batchIds() }, "processIds")
4063
3837
  });
4064
3838
  /** One stream's bytes, by range.
4065
3839
  *
@@ -4111,30 +3885,33 @@ const ConfigWorkspaceSetAvatarRequest = z.object({
4111
3885
  })
4112
3886
  });
4113
3887
  /** 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"),
3888
+ const ConfigWorkspaceAvatarsRequest = z.object({
3889
+ method: z.literal("config.workspace.avatars"),
3890
+ params: boundedBatchParams({
3891
+ workspaceIds: z.array(z.string()).min(1).max(4),
3892
+ maxTotalBytes: z.number().int().min(1).max(4194304).default(4194304)
3893
+ }, "workspaceIds")
3894
+ });
3895
+ /** Adds or updates a bounded directory collection atomically; omitted access is read. */
3896
+ const ConfigWorkspaceAddDirectoriesRequest = z.object({
3897
+ method: z.literal("config.workspace.addDirectories"),
4127
3898
  params: z.object({
3899
+ operationId: z.uuid(),
4128
3900
  workspaceId: z.string(),
4129
- path: z.string().min(1)
4130
- })
4131
- });
4132
- const ConfigWorkspaceRemoveDirectoryRequest = z.object({
4133
- method: z.literal("config.workspace.removeDirectory"),
3901
+ directories: z.array(z.object({
3902
+ path: z.string().min(1),
3903
+ access: z.enum(["read", "read-write"]).default("read")
3904
+ }).strict()).min(1).max(64)
3905
+ }).strict().refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8388608, "batch input exceeds 8 MiB")
3906
+ });
3907
+ /** Removes directory authorizations atomically; already absent paths are successful no-ops. */
3908
+ const ConfigWorkspaceRemoveDirectoriesRequest = z.object({
3909
+ method: z.literal("config.workspace.removeDirectories"),
4134
3910
  params: z.object({
3911
+ operationId: z.uuid(),
4135
3912
  workspaceId: z.string(),
4136
- path: z.string().min(1)
4137
- })
3913
+ paths: z.array(z.string().min(1)).min(1).max(64)
3914
+ }).strict().refine((value) => new TextEncoder().encode(JSON.stringify(value)).byteLength <= 8388608, "batch input exceeds 8 MiB")
4138
3915
  });
4139
3916
  /** Lists access records with ownership; omitted filters include all scopes. */
4140
3917
  const ConfigAccessListRequest = z.object({
@@ -4144,7 +3921,10 @@ const ConfigAccessListRequest = z.object({
4144
3921
  /** Adds a batch of globally reusable resources. */
4145
3922
  const ConfigAccessAddRequest = z.object({
4146
3923
  method: z.literal("config.access.add"),
4147
- params: z.object({ authorization: AuthorizationInput }).strict()
3924
+ params: boundedBatchParams({
3925
+ operationId: z.uuid(),
3926
+ authorizations: z.array(AuthorizationInput).min(1).max(64)
3927
+ }, "authorizations")
4148
3928
  });
4149
3929
  /** Reads whether new shell commands use operating-system confinement. */
4150
3930
  /** Persists the installation-wide switch; repeated writes are no-ops. */
@@ -4155,7 +3935,10 @@ const ConfigAccessAddRequest = z.object({
4155
3935
  * revoke says what the first one said. */
4156
3936
  const ConfigAccessRevokeRequest = z.object({
4157
3937
  method: z.literal("config.access.revoke"),
4158
- params: z.object({ id: z.string().min(1) }).strict()
3938
+ params: boundedBatchParams({
3939
+ operationId: z.uuid(),
3940
+ ids: batchIds()
3941
+ }, "ids")
4159
3942
  });
4160
3943
  z.object({
4161
3944
  name: z.string(),
@@ -4181,16 +3964,32 @@ const ConfigCredentialStatusRequest = z.object({
4181
3964
  * only. */
4182
3965
  const ConfigCredentialSetRequest = z.object({
4183
3966
  method: z.literal("config.credential.set"),
4184
- params: CredentialScopeParams.extend({
4185
- name: z.string().min(1),
4186
- value: z.string()
4187
- })
3967
+ params: boundedBatchParams({
3968
+ operationId: z.uuid(),
3969
+ plugin: z.string().min(1),
3970
+ scope: z.string().min(1),
3971
+ items: z.array(z.object({
3972
+ name: z.string().min(1),
3973
+ value: z.string()
3974
+ }).strict()).min(1).max(64)
3975
+ }, "items")
4188
3976
  });
4189
3977
  /** Clears one name, or the whole scope when `name` is omitted. Clearing
4190
3978
  * something absent succeeds and answers the current status. */
4191
3979
  const ConfigCredentialClearRequest = z.object({
4192
3980
  method: z.literal("config.credential.clear"),
4193
- params: CredentialScopeParams.extend({ name: z.string().min(1).optional() })
3981
+ params: boundedBatchParams({
3982
+ operationId: z.uuid(),
3983
+ plugin: z.string().min(1),
3984
+ items: z.array(z.discriminatedUnion("mode", [z.object({
3985
+ scope: z.string().min(1),
3986
+ mode: z.literal("names"),
3987
+ names: batchIds()
3988
+ }).strict(), z.object({
3989
+ scope: z.string().min(1),
3990
+ mode: z.literal("all")
3991
+ }).strict()])).min(1).max(64)
3992
+ }, "items")
4194
3993
  });
4195
3994
  /** Reads the hosts `web_fetch` may reach without asking. */
4196
3995
  /** Adds a bare host and broadcasts `config.webChanged`. With `includeSubdomains`, the
@@ -4207,20 +4006,16 @@ const ConfigCredentialClearRequest = z.object({
4207
4006
  *
4208
4007
  * `config` is the plugin's own section, unread here: the plugin declares a
4209
4008
  * 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
- });
4009
+ * protocol pinned would be a second opinion about someone else's
4010
+ * configuration.
4011
+ */
4220
4012
  /** Installs the selected roots in one shared physical mutation and reports every root result. */
4221
4013
  const PluginInstallBatchRequest = z.object({
4222
4014
  method: z.literal("plugin.installBatch"),
4223
- params: z.object({ items: z.array(PluginInstallRequest.shape.params).min(1).max(64) })
4015
+ params: z.object({ items: z.array(z.object({
4016
+ spec: z.string().min(1),
4017
+ config: z.record(z.string(), z.unknown()).optional()
4018
+ })).min(1).max(64) })
4224
4019
  });
4225
4020
  /** Requested roots and their complete confirmed lifecycle closure. */
4226
4021
  const PluginRemovalBatchPlan = z.object({
@@ -4254,19 +4049,6 @@ z.object({
4254
4049
  names: z.array(z.string().min(1)),
4255
4050
  token: z.string().min(1)
4256
4051
  });
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
4052
  z.object({
4271
4053
  /** Installed target extension. */
4272
4054
  name: z.string().min(1),
@@ -4278,26 +4060,14 @@ z.object({
4278
4060
  token: z.string().min(1)
4279
4061
  });
4280
4062
  /** 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
4063
  /** 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
4064
  /** 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) })
4065
+ const PluginGetConfigsRequest = z.object({
4066
+ method: z.literal("plugin.getConfigs"),
4067
+ params: boundedBatchParams({
4068
+ names: batchIds(),
4069
+ ...queryBudgets
4070
+ }, "names")
4301
4071
  });
4302
4072
  /** Replaces configuration and reloads enabled plugins and their active dependants. */
4303
4073
  const PluginSetConfigRequest = z.object({
@@ -4325,6 +4095,9 @@ const SessionInstructionsRequest = z.object({
4325
4095
  params: z.object({ sessionId: z.string() })
4326
4096
  });
4327
4097
  const RequestBody = z.discriminatedUnion("method", [
4098
+ TelemetryIngestRequest,
4099
+ TelemetryStatusRequest,
4100
+ TelemetryConfigureRequest,
4328
4101
  SessionInstructionsRequest,
4329
4102
  PingRequest,
4330
4103
  ConnectionInfoRequest,
@@ -4335,12 +4108,12 @@ const RequestBody = z.discriminatedUnion("method", [
4335
4108
  SessionWatchRequest,
4336
4109
  SessionHistoryPageRequest,
4337
4110
  SessionMessagePartsRequest,
4338
- SessionMessageContentRequest,
4111
+ SessionMessageContentsRequest,
4339
4112
  SessionLivePageRequest,
4340
4113
  SessionUnwatchRequest,
4341
4114
  SessionSendRequest,
4342
4115
  SessionForkRequest,
4343
- SessionOperationGetRequest,
4116
+ SessionOperationsGetRequest,
4344
4117
  SessionAnswerRequest,
4345
4118
  SessionWithdrawRequest,
4346
4119
  SessionCancelRequest,
@@ -4359,7 +4132,7 @@ const RequestBody = z.discriminatedUnion("method", [
4359
4132
  ConfigAgentSetPromptSlotRequest,
4360
4133
  ConfigAgentPromptSlotsRequest,
4361
4134
  ConfigAgentSetAvatarRequest,
4362
- ConfigAgentAvatarRequest,
4135
+ ConfigAgentAvatarsRequest,
4363
4136
  ConfigAgentSaveRequest,
4364
4137
  ConfigAgentRevisionsRequest,
4365
4138
  ConfigAgentCompareRevisionsRequest,
@@ -4385,9 +4158,9 @@ const RequestBody = z.discriminatedUnion("method", [
4385
4158
  ConfigWorkspaceCreateRequest,
4386
4159
  ConfigWorkspaceUpdateRequest,
4387
4160
  ConfigWorkspaceSetAvatarRequest,
4388
- ConfigWorkspaceAvatarRequest,
4389
- ConfigWorkspaceAddDirectoryRequest,
4390
- ConfigWorkspaceRemoveDirectoryRequest,
4161
+ ConfigWorkspaceAvatarsRequest,
4162
+ ConfigWorkspaceAddDirectoriesRequest,
4163
+ ConfigWorkspaceRemoveDirectoriesRequest,
4391
4164
  ConfigAccessListRequest,
4392
4165
  ConfigAccessAddRequest,
4393
4166
  ConfigAccessRevokeRequest,
@@ -4395,260 +4168,1058 @@ const RequestBody = z.discriminatedUnion("method", [
4395
4168
  ConfigCredentialSetRequest,
4396
4169
  ConfigCredentialClearRequest,
4397
4170
  StdFsListRequest,
4398
- PluginInstallRequest,
4399
4171
  PluginInstallBatchRequest,
4400
4172
  PluginSetEnabledBatchPreviewRequest,
4401
4173
  PluginSetEnabledBatchRequest,
4402
4174
  PluginRemoveBatchPreviewRequest,
4403
4175
  PluginRemoveBatchRequest,
4404
- PluginRemovePreviewRequest,
4405
- PluginRemoveRequest,
4406
4176
  PluginListRequest,
4407
- PluginSetEnabledPreviewRequest,
4408
- PluginSetEnabledRequest,
4409
- PluginGetConfigRequest,
4177
+ PluginGetConfigsRequest,
4410
4178
  PluginSetConfigRequest,
4411
4179
  PluginSurfaceRequest
4412
4180
  ]);
4413
4181
  /**
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.
4182
+ * A request naming a method some plugin declared while this gateway was
4183
+ * running.
4184
+ *
4185
+ * The name is checked against the minting rule and **the parameters are not
4186
+ * read at all**: their shape is the plugin's zod, validated in the gateway,
4187
+ * and a second opinion here would be a second writer of someone else's
4188
+ * contract.
4189
+ *
4190
+ * `method` is a template literal type rather than a bare `string`, and that is
4191
+ * load-bearing: one `string` discriminant in this union and
4192
+ * `body.method === 'session.send'` stops narrowing, which takes every `switch`
4193
+ * that reads `body.params` afterwards down with it.
4194
+ *
4195
+ * `params` is optional because a call that takes none sends no key —
4196
+ * `JSON.stringify` drops an `undefined` — and a frame this schema refuses is
4197
+ * dropped in silence rather than answered. Bare `z.unknown()` would not
4198
+ * serve: zod 4 treats it as a required key, which would refuse exactly the
4199
+ * paramsless calls this field is meant to admit.
4200
+ */
4201
+ const PluginRequestBody = z.object({
4202
+ method: PluginWireName,
4203
+ params: z.unknown().optional()
4204
+ });
4205
+ /** One business request from a client. Authentication is a separate control
4206
+ * frame.
4207
+ *
4208
+ * The body is widened one layer out rather than `RequestBody` itself: the
4209
+ * core union stays a `discriminatedUnion` of names known at compile time,
4210
+ * and a plugin's runtime-minted name sits beside it. */
4211
+ const RequestFrame = z.object({
4212
+ kind: z.literal("request"),
4213
+ id: z.string(),
4214
+ trace: RequestTrace.optional(),
4215
+ body: z.union([RequestBody, PluginRequestBody])
4216
+ });
4217
+ /** Supplies the credential for one WebSocket connection. */
4218
+ const AuthenticationFrame = z.object({
4219
+ kind: z.literal("authentication"),
4220
+ id: z.string().min(1).max(128),
4221
+ token: z.string().max(256)
4222
+ });
4223
+ z.discriminatedUnion("kind", [RequestFrame, AuthenticationFrame]);
4224
+ z.object({ authenticated: z.literal(true) });
4225
+ z.enum(["auth-required", "auth-failed"]);
4226
+ z.enum([
4227
+ "history_conflict",
4228
+ "session_busy",
4229
+ "cut_unavailable",
4230
+ "source_unavailable",
4231
+ "file_unavailable",
4232
+ "operation_conflict",
4233
+ "history_preparing",
4234
+ "history_unavailable",
4235
+ "history_invalid",
4236
+ "history_stale",
4237
+ "history_cursor_invalid",
4238
+ "history_worker_unavailable",
4239
+ "reading_lease_invalid",
4240
+ "content_unavailable",
4241
+ "content_stale",
4242
+ "message_unavailable",
4243
+ "invalid_range"
4244
+ ]);
4245
+ z.enum(["configuration_write_rejected", "configuration_recovery_required"]);
4246
+ /** A bounded machine-readable refusal identifier; owner business codes are not enumerated by core. */
4247
+ const RequestErrorCode = z.string().min(1).max(128).regex(/^[A-Za-z0-9_.-]+$/);
4248
+ /** Gateway -> client: the answer to one request, addressed by its id. */
4249
+ const ResultFrame = z.object({
4250
+ kind: z.literal("result"),
4251
+ id: z.string(),
4252
+ ok: z.boolean(),
4253
+ data: z.unknown().optional(),
4254
+ error: z.string().optional(),
4255
+ errorCode: RequestErrorCode.optional(),
4256
+ /** Recoverable reading preparation lease and suggested polling interval. */
4257
+ readingDetails: z.object({
4258
+ readingLeaseId: z.string().optional(),
4259
+ retryAfterMs: z.number().int().positive().optional()
4260
+ }).optional()
4261
+ });
4262
+ /** Gateway -> the connections that care: something happened. Carries no id,
4263
+ * because no one asked for it. */
4264
+ const EventFrame = z.object({
4265
+ kind: z.literal("event"),
4266
+ event: Frame
4267
+ });
4268
+ z.discriminatedUnion("kind", [ResultFrame, EventFrame]);
4269
+ z.object({
4270
+ instanceId: z.uuid(),
4271
+ gatewayVersion: z.string(),
4272
+ protocolVersion: z.string(),
4273
+ clientCount: z.number().int(),
4274
+ uptimeMs: z.number().int(),
4275
+ pid: z.number().int()
4276
+ });
4277
+ //#endregion
4278
+ //#region src/extension-catalog/projection.ts
4279
+ /** Minimal historical commit identity retained with a release admission. */
4280
+ const AcceptedSnapshotSchema = z.object({
4281
+ repository: z.literal(CATALOG_REPOSITORY),
4282
+ commit: GitShaSchema,
4283
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4284
+ }).strict();
4285
+ z.object({
4286
+ snapshot: AcceptedSnapshotSchema,
4287
+ release: ReleaseSchema,
4288
+ releaseDigest: z.string().regex(/^[0-9a-f]{64}$/)
4289
+ }).strict();
4290
+ /** Current directory source and actual host compatibility are independent of activation status. */
4291
+ const InstalledRowSchema = z.object({
4292
+ packageName: z.string(),
4293
+ distribution: z.enum([
4294
+ "builtin",
4295
+ "verified",
4296
+ "custom"
4297
+ ]),
4298
+ publisherKind: z.enum(["official", "third-party"]).optional(),
4299
+ compatibility: z.object({
4300
+ state: z.enum([
4301
+ "compatible",
4302
+ "incompatible",
4303
+ "unknown"
4304
+ ]),
4305
+ reasons: z.array(z.string()),
4306
+ assessedAt: z.string()
4307
+ }).strict(),
4308
+ updates: z.array(ReleaseSchema)
4309
+ }).strict();
4310
+ /** Uses current directory publisher markers while retaining actual saved host requirement facts. */
4311
+ function projectInstalled(observations, snapshot, host) {
4312
+ return observations.map((observation) => {
4313
+ const builtin = (observation.summary?.origin ?? observation.declared.origin) === "builtin";
4314
+ const listed = snapshot?.releases.filter((release) => release.packageName === observation.packageName).sort((a, b) => semver.rcompare(a.version, b.version))[0];
4315
+ const currentVersion = observation.summary?.version ?? observation.declared.version ?? observation.receipt?.version ?? "";
4316
+ const requirements = observation.hostRequirements;
4317
+ const compatibility = {
4318
+ state: requirements.state === "satisfied" ? "compatible" : requirements.state === "unsatisfied" ? "incompatible" : "unknown",
4319
+ reasons: [...requirements.reasons],
4320
+ assessedAt: requirements.checkedAt
4321
+ };
4322
+ const updates = !builtin && host && semver.valid(currentVersion) ? (snapshot?.releases ?? []).filter((release) => release.packageName === observation.packageName && semver.gt(release.version, currentVersion) && releaseCompatible(release, host)).sort((a, b) => semver.rcompare(a.version, b.version)) : [];
4323
+ return {
4324
+ packageName: observation.packageName,
4325
+ distribution: builtin ? "builtin" : listed ? "verified" : "custom",
4326
+ ...!builtin && listed ? { publisherKind: listed.publisher.kind } : {},
4327
+ compatibility,
4328
+ updates
4329
+ };
4330
+ });
4331
+ }
4332
+ //#endregion
4333
+ //#region src/extension-catalog/views.ts
4334
+ /** Explicit catalog synchronization result, independent of snapshot availability. */
4335
+ const SyncSchema = z.object({
4336
+ state: z.enum([
4337
+ "idle",
4338
+ "syncing",
4339
+ "succeeded",
4340
+ "failed"
4341
+ ]),
4342
+ taskId: z.uuid().optional(),
4343
+ error: z.string().max(4096).optional(),
4344
+ retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4345
+ }).strict();
4346
+ /** Pure cache-only list response; an empty catalog is a valid successful snapshot. */
4347
+ const ListSchema = z.object({
4348
+ revision: z.number().int().nonnegative(),
4349
+ snapshot: SnapshotSchema.omit({ releases: true }).nullable(),
4350
+ releases: z.array(ReleaseSchema).max(2e3),
4351
+ sync: SyncSchema
4352
+ }).strict();
4353
+ /** Short invalidation carrying no configuration, credentials, or archive bytes. */
4354
+ const CatalogChangedSchema = z.object({
4355
+ revision: z.number().int().nonnegative(),
4356
+ snapshot: z.object({
4357
+ commit: GitShaSchema,
4358
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4359
+ }).strict().optional(),
4360
+ sync: SyncSchema
4361
+ }).strict();
4362
+ /** Confirmation response for a fixed exact extension dependency closure. */
4363
+ const PreviewSchema = z.object({
4364
+ previewToken: z.string().min(1).max(8192),
4365
+ expiresAt: z.iso.datetime({ offset: true }),
4366
+ snapshot: z.object({
4367
+ commit: GitShaSchema,
4368
+ contentDigest: z.string().regex(/^[0-9a-f]{64}$/)
4369
+ }).strict(),
4370
+ graphRevision: z.string().max(1024),
4371
+ resolvedSelections: z.array(ReleaseSchema).max(64),
4372
+ dependencies: z.array(z.object({
4373
+ packageName: z.string(),
4374
+ version: z.string()
4375
+ }).strict()).max(64),
4376
+ willEnable: z.array(z.string()).max(2e3),
4377
+ replacing: z.array(z.string()).max(64),
4378
+ affectedOwners: z.array(z.string()).max(2e3),
4379
+ warnings: z.array(ArtifactWarningSchema).max(64)
4380
+ }).strict();
4381
+ /** Durable installation operation facts returned by the generic owner-bound service. */
4382
+ const OperationSchema = z.object({
4383
+ operationId: z.uuid(),
4384
+ attemptId: z.uuid(),
4385
+ issuer: z.string(),
4386
+ submissionDigest: z.string(),
4387
+ requestDigest: z.string(),
4388
+ packageName: z.string(),
4389
+ warnings: z.array(ArtifactWarningSchema).max(3).optional(),
4390
+ warningCount: z.number().int().nonnegative().max(1e5).optional(),
4391
+ rootResults: z.array(z.object({
4392
+ packageName: z.string(),
4393
+ status: z.enum([
4394
+ "pending",
4395
+ "active",
4396
+ "disabled",
4397
+ "deferred",
4398
+ "failed"
4399
+ ]),
4400
+ reason: z.string().max(4096).optional()
4401
+ }).strict()).max(2e3).optional(),
4402
+ phase: z.enum([
4403
+ "preparing",
4404
+ "installing",
4405
+ "admitted",
4406
+ "activating",
4407
+ "settled"
4408
+ ]),
4409
+ currentStep: z.enum([
4410
+ "prepare",
4411
+ "download",
4412
+ "verify",
4413
+ "npm",
4414
+ "admission",
4415
+ "activation",
4416
+ "cleanup"
4417
+ ]),
4418
+ outcome: z.enum([
4419
+ "pending",
4420
+ "succeeded",
4421
+ "failed",
4422
+ "interrupted"
4423
+ ]),
4424
+ failureStage: z.enum([
4425
+ "prepare",
4426
+ "download",
4427
+ "verify",
4428
+ "npm",
4429
+ "admission",
4430
+ "activation",
4431
+ "cleanup",
4432
+ "recovery"
4433
+ ]).optional(),
4434
+ reason: z.string().max(4096).optional(),
4435
+ cleanup: z.enum([
4436
+ "not-needed",
4437
+ "pending",
4438
+ "complete",
4439
+ "failed"
4440
+ ]),
4441
+ startedAt: z.iso.datetime({ offset: true }),
4442
+ settledAt: z.iso.datetime({ offset: true }).optional(),
4443
+ packages: z.array(z.object({
4444
+ packageName: z.string(),
4445
+ beforeRevision: z.number().int().nonnegative(),
4446
+ receiptId: z.uuid().nullable(),
4447
+ diskChanged: z.boolean().optional(),
4448
+ ownerWithdrawn: z.boolean().optional()
4449
+ }).strict()).max(2e3)
4450
+ }).strict();
4451
+ /** Installation progress invalidation; clients query the durable attempt after reconnecting. */
4452
+ const InstallChangedSchema = z.object({
4453
+ operationId: z.uuid(),
4454
+ phase: OperationSchema.shape.phase,
4455
+ currentStep: OperationSchema.shape.currentStep,
4456
+ outcome: OperationSchema.shape.outcome,
4457
+ cleanup: OperationSchema.shape.cleanup,
4458
+ revision: z.number().int().nonnegative()
4459
+ }).strict();
4460
+ /** Current directory source markers and installed metadata for unique package names. */
4461
+ const InstalledSchema = z.object({
4462
+ observedAt: z.iso.datetime({ offset: true }),
4463
+ rows: z.array(InstalledRowSchema).max(2e3)
4464
+ }).strict();
4465
+ /** Existing owner RPC success/failure convention; sanitized errors remain actionable. */
4466
+ function resultSchema(data) {
4467
+ return z.union([z.object({
4468
+ ok: z.literal(true),
4469
+ data
4470
+ }).strict(), z.object({
4471
+ ok: z.literal(false),
4472
+ code: z.string(),
4473
+ message: z.string().max(4096),
4474
+ retryAfterSeconds: z.number().nonnegative().max(86400).optional()
4475
+ }).strict()]);
4476
+ }
4477
+ //#endregion
4478
+ //#region src/extension-catalog/operations.ts
4479
+ /** Nonempty operation identities with per-member and complete encoded-response byte budgets. */
4480
+ const OperationQueriesParams = z.object({
4481
+ operationIds: z.array(z.uuid()).min(1).max(64),
4482
+ maxItemBytes: z.number().int().min(1).max(8388608).default(262144),
4483
+ maxTotalBytes: z.number().int().min(1).max(8388608).default(8388608)
4484
+ }).strict().superRefine((input, ctx) => {
4485
+ if (input.operationIds.length * input.maxItemBytes + 8192 > input.maxTotalBytes || input.operationIds.some((id) => Buffer.byteLength(JSON.stringify(id)) + 4096 > input.maxItemBytes)) ctx.addIssue({
4486
+ code: "custom",
4487
+ message: "declared operation response exceeds byte budget"
4488
+ });
4489
+ });
4490
+ /** Safe operation facts in the original request order. */
4491
+ const OperationQueriesData = z.object({ results: z.array(z.discriminatedUnion("ok", [z.object({
4492
+ index: z.number().int().nonnegative().max(63),
4493
+ target: z.uuid(),
4494
+ ok: z.literal(true),
4495
+ value: z.object({ operation: OperationSchema }).strict()
4496
+ }).strict(), z.object({
4497
+ index: z.number().int().nonnegative().max(63),
4498
+ target: z.uuid(),
4499
+ ok: z.literal(false),
4500
+ error: z.object({
4501
+ code: z.string().min(1).max(64),
4502
+ message: z.string().max(512),
4503
+ details: z.object({ retryAfterSeconds: z.number().nonnegative().max(86400) }).strict().optional()
4504
+ }).strict()
4505
+ }).strict()])).min(1).max(64) }).strict();
4506
+ //#endregion
4507
+ //#region src/defaults/service.ts
4508
+ /** Creates one shared initialization attempt scoped to this catalog owner. */
4509
+ function createDefaultsService(options) {
4510
+ const controller = new AbortController();
4511
+ const signal = AbortSignal.any([options.signal, controller.signal]);
4512
+ let active = null;
4513
+ function initial() {
4514
+ return {
4515
+ state: "pending-snapshot",
4516
+ enrolledAt: (/* @__PURE__ */ new Date()).toISOString(),
4517
+ candidates: []
4518
+ };
4519
+ }
4520
+ async function status() {
4521
+ const before = options.store.read() ?? initial();
4522
+ const observations = before.candidates.length ? await options.installer.observe(before.candidates.map((candidate) => candidate.packageName)) : [];
4523
+ const record = options.store.read() ?? initial();
4524
+ const candidates = record.candidates.map(({ artifactIntegrity: _integrity, receiptId, ...candidate }) => {
4525
+ const observed = observations.find((item) => item.packageName === candidate.packageName);
4526
+ const captured = before.candidates.find((item) => item.packageName === candidate.packageName);
4527
+ const matchesCapturedResult = captured?.state === "installed" && captured.receiptId === receiptId && captured.operationId === candidate.operationId && captured.releaseId === candidate.releaseId;
4528
+ if (candidate.state === "installed" && matchesCapturedResult && observed) {
4529
+ if (!observed.declared.installed || !observed.declared.enabled || receiptId && observed.receipt?.receiptId !== receiptId) {
4530
+ candidate.state = "user-managed";
4531
+ candidate.reasonCode = "USER_DECLARATION_PRESERVED";
4532
+ delete candidate.activation;
4533
+ } else {
4534
+ const activation = observed.activation ?? (observed.summary?.status === "active" ? "active" : observed.summary?.status === "failed" ? "failed" : void 0);
4535
+ if (activation) candidate.activation = activation;
4536
+ }
4537
+ }
4538
+ return candidate;
4539
+ });
4540
+ return DefaultsStatusSchema.parse({
4541
+ state: active ? "working" : record.state === "complete" ? "complete" : record.state === "pending-snapshot" ? "pending-snapshot" : "pending",
4542
+ taskId: active?.id ?? null,
4543
+ operationId: record.currentOperationId ?? null,
4544
+ counts: {
4545
+ installed: candidates.filter((c) => c.state === "installed").length,
4546
+ pending: candidates.filter((c) => c.state === "pending").length,
4547
+ skipped: candidates.filter((c) => c.state === "skipped" || c.state === "user-managed").length
4548
+ },
4549
+ activationDeferred: candidates.filter((c) => c.state === "installed" && c.activation === "deferred").length,
4550
+ candidates,
4551
+ ...record.lastReasonCode ? { reasonCode: record.lastReasonCode } : {},
4552
+ ...record.retryNotBefore ? { retryAfterSeconds: Math.min(86400, Math.max(0, Math.ceil((Date.parse(record.retryNotBefore) - Date.now()) / 1e3))) } : {}
4553
+ });
4554
+ }
4555
+ function persist(record) {
4556
+ if (record.snapshot) record.state = record.candidates.some((c) => c.state === "pending") ? "pending" : "complete";
4557
+ return options.store.save(record);
4558
+ }
4559
+ async function applyOperation(record, operation) {
4560
+ for (const candidate of record.candidates.filter((c) => c.operationId === operation.operationId && c.state === "pending")) {
4561
+ const packageResult = operation.packages.find((p) => p.packageName === candidate.packageName);
4562
+ const rootResult = operation.rootResults?.find((r) => r.packageName === candidate.packageName);
4563
+ if (packageResult?.receiptId) {
4564
+ candidate.state = "installed";
4565
+ candidate.receiptId = packageResult.receiptId;
4566
+ candidate.activation = rootResult?.status === "active" ? "active" : rootResult?.status === "deferred" ? "deferred" : "failed";
4567
+ delete candidate.reasonCode;
4568
+ } else if (operation.phase === "settled" && operation.outcome !== "pending") {
4569
+ candidate.reasonCode = "INSTALL_FAILED";
4570
+ record.lastReasonCode = "INSTALL_FAILED";
4571
+ }
4572
+ }
4573
+ if (record.lastReasonCode === "INSTALL_FAILED" && !record.candidates.some((candidate) => candidate.state === "pending")) delete record.lastReasonCode;
4574
+ persist(record);
4575
+ }
4576
+ async function joinOperation(operationId) {
4577
+ let operation = await options.installer.join(operationId);
4578
+ while (operation.cleanup === "failed" || operation.cleanup === "pending") {
4579
+ try {
4580
+ operation = await options.installer.retryCleanup(operationId);
4581
+ } catch {
4582
+ await setTimeout$1(250);
4583
+ continue;
4584
+ }
4585
+ if (operation.cleanup === "failed" || operation.cleanup === "pending") await setTimeout$1(250);
4586
+ }
4587
+ return operation;
4588
+ }
4589
+ async function recover(record) {
4590
+ const operationIds = [...new Set(record.candidates.filter((c) => c.state === "pending").map((c) => c.operationId).filter((id) => !!id))];
4591
+ for (const id of operationIds) {
4592
+ let operation;
4593
+ try {
4594
+ operation = await options.installer.operation(id);
4595
+ } catch (error) {
4596
+ if (managementError(error).code !== "OPERATION_NOT_FOUND") throw error;
4597
+ continue;
4598
+ }
4599
+ operation = await joinOperation(id);
4600
+ await applyOperation(record, operation);
4601
+ if (operation.phase !== "settled" || operation.outcome === "pending") throw new CatalogError("RECOVERY_PENDING", "The original default installation attempt is not settled");
4602
+ }
4603
+ }
4604
+ async function run(attempt) {
4605
+ let record = options.store.read() ?? options.store.save(initial());
4606
+ delete record.lastReasonCode;
4607
+ delete record.retryNotBefore;
4608
+ await recover(record);
4609
+ if (record.state === "complete") return;
4610
+ const snapshot = await options.acquireSnapshot(attempt);
4611
+ attempt.signal.throwIfAborted();
4612
+ if (!record.snapshot) {
4613
+ const chosen = /* @__PURE__ */ new Map();
4614
+ for (const release of snapshot.releases) {
4615
+ if (release.defaultInstall !== true || !releaseCompatible(release, options.identity)) continue;
4616
+ const before = chosen.get(release.packageName);
4617
+ if (!before || semver.gt(release.version, before.version)) chosen.set(release.packageName, release);
4618
+ }
4619
+ if (chosen.size > 64) throw new CatalogError("LIMIT_EXCEEDED", "Default extension cohort exceeds 64 roots");
4620
+ record = await options.installer.coordinate(() => options.store.save({
4621
+ ...record,
4622
+ state: chosen.size ? "frozen" : "complete",
4623
+ snapshot: {
4624
+ commit: snapshot.commit,
4625
+ contentDigest: snapshot.contentDigest
4626
+ },
4627
+ host: {
4628
+ version: options.identity.version,
4629
+ ...options.identity.target
4630
+ },
4631
+ candidates: [...chosen.values()].sort((a, b) => a.packageName < b.packageName ? -1 : a.packageName > b.packageName ? 1 : 0).map((r) => ({
4632
+ packageName: r.packageName,
4633
+ releaseId: r.releaseId,
4634
+ artifactIntegrity: r.artifact.integrity,
4635
+ state: "pending"
4636
+ }))
4637
+ }));
4638
+ }
4639
+ if (record.state === "complete") return;
4640
+ const observations = await options.installer.observe();
4641
+ for (const candidate of record.candidates.filter((c) => c.state === "pending")) if (observations.some((o) => o.packageName === candidate.packageName && o.declared.origin !== void 0)) {
4642
+ candidate.state = "user-managed";
4643
+ candidate.reasonCode = "USER_DECLARATION_PRESERVED";
4644
+ } else {
4645
+ const release = snapshot.releases.find((r) => r.releaseId === candidate.releaseId && r.artifact.integrity === candidate.artifactIntegrity);
4646
+ if (!release || release.defaultInstall !== true || !releaseCompatible(release, options.identity)) {
4647
+ candidate.state = "skipped";
4648
+ candidate.reasonCode = "RELEASE_REVOKED";
4649
+ }
4650
+ }
4651
+ persist(record);
4652
+ const roots = record.candidates.filter((c) => c.state === "pending");
4653
+ if (!roots.length) return;
4654
+ const plan = await options.preview(roots.map((c) => ({
4655
+ snapshotCommit: snapshot.commit,
4656
+ releaseId: c.releaseId,
4657
+ artifactIntegrity: c.artifactIntegrity
4658
+ })), attempt);
4659
+ attempt.signal.throwIfAborted();
4660
+ const operationId = randomUUID();
4661
+ record.currentOperationId = operationId;
4662
+ record.lastAttemptAt = (/* @__PURE__ */ new Date()).toISOString();
4663
+ for (const candidate of roots) candidate.operationId = operationId;
4664
+ persist(record);
4665
+ try {
4666
+ await options.installer.install({
4667
+ operationId,
4668
+ token: plan.previewToken
4669
+ }, attempt);
4670
+ } catch (error) {
4671
+ try {
4672
+ await options.installer.operation(operationId);
4673
+ } catch {
4674
+ throw error;
4675
+ }
4676
+ }
4677
+ const operation = await joinOperation(operationId);
4678
+ await applyOperation(record, operation);
4679
+ }
4680
+ return {
4681
+ /** Starts one shared bounded attempt immediately; completed initialization performs no network work. */
4682
+ async ensure(input) {
4683
+ signal.throwIfAborted();
4684
+ const params = DefaultsEnsureParamsSchema.parse(input);
4685
+ if (params.expectedProductVersion !== options.identity.version) throw new CatalogError("PRODUCT_VERSION_MISMATCH", "Default installation requires the current product version");
4686
+ const record = options.store.read() ?? initial();
4687
+ if (active) return {
4688
+ taskId: active.id,
4689
+ status: await status()
4690
+ };
4691
+ if (record.state === "complete" || record.retryNotBefore && Date.parse(record.retryNotBefore) > Date.now()) return {
4692
+ taskId: null,
4693
+ status: await status()
4694
+ };
4695
+ const id = randomUUID(), deadline = performance.now() + Math.min(18e4, params.remainingWorkMs);
4696
+ const timerController = new AbortController();
4697
+ const timer = setTimeout(() => timerController.abort(/* @__PURE__ */ new Error("Default installation work budget exhausted")), Math.max(1, deadline - performance.now()));
4698
+ const attempt = {
4699
+ signal: AbortSignal.any([signal, timerController.signal]),
4700
+ remainingWorkMs: () => Math.max(0, deadline - performance.now())
4701
+ };
4702
+ const work = Promise.resolve().then(() => run(attempt)).catch((error) => {
4703
+ const record = options.store.read() ?? initial(), failure = managementError(error);
4704
+ record.lastReasonCode = attempt.signal.aborted ? "ATTEMPT_CANCELLED" : failure.code;
4705
+ for (const candidate of record.candidates.filter((c) => c.state === "pending")) candidate.reasonCode = record.lastReasonCode;
4706
+ if (failure.retryAfterSeconds !== void 0) record.retryNotBefore = new Date(Date.now() + failure.retryAfterSeconds * 1e3).toISOString();
4707
+ persist(record);
4708
+ }).finally(() => {
4709
+ clearTimeout(timer);
4710
+ active = null;
4711
+ });
4712
+ work.catch(() => {});
4713
+ active = {
4714
+ id,
4715
+ work
4716
+ };
4717
+ return {
4718
+ taskId: id,
4719
+ status: await status()
4720
+ };
4721
+ },
4722
+ /** Projects current readonly installation facts over retained history; never enrolls or installs. */
4723
+ status,
4724
+ /** Cancels this automatic attempt and joins all work before releasing the owner's resources. */
4725
+ async dispose() {
4726
+ controller.abort(/* @__PURE__ */ new Error("Default installation owner is draining"));
4727
+ await active?.work;
4728
+ }
4729
+ };
4730
+ }
4731
+ //#endregion
4732
+ //#region src/extension-catalog/sync.ts
4733
+ /** Git smart HTTP ref advertisement for the catalog repository. */
4734
+ const CATALOG_REFS_URL = "https://github.com/yanxuan-lc/yaoguang-presets.git/info/refs?service=git-upload-pack";
4735
+ /** Raw content URL of the extension index pinned to one commit. */
4736
+ const catalogIndexUrl = (commit) => `https://raw.githubusercontent.com/yanxuan-lc/yaoguang-presets/${commit}/extensions/index.json`;
4737
+ const REFS_MAX_BYTES = 1048576;
4738
+ const headers = { "User-Agent": "YaoGuang-extensions" };
4739
+ /**
4740
+ * Returns the commit of `refs/heads/main` from a Git smart HTTP upload-pack advertisement.
4741
+ * Requires the leading service announcement and well-formed pkt-lines; any other shape,
4742
+ * including a missing main branch, is rejected as an invalid catalog.
4432
4743
  */
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
- });
4744
+ function parseMainCommit(bytes) {
4745
+ const text = Buffer.from(bytes).toString("latin1");
4746
+ const lines = [];
4747
+ for (let at = 0; at < text.length;) {
4748
+ const prefix = text.slice(at, at + 4);
4749
+ if (!/^[0-9a-f]{4}$/.test(prefix)) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4750
+ const length = Number.parseInt(prefix, 16);
4751
+ if (length === 0) {
4752
+ lines.push(null);
4753
+ at += 4;
4754
+ continue;
4755
+ }
4756
+ if (length < 4 || at + length > text.length) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4757
+ lines.push(text.slice(at + 4, at + length).replace(/\n$/, ""));
4758
+ at += length;
4759
+ }
4760
+ if (lines[0] !== "# service=git-upload-pack" || lines[1] !== null) throw new CatalogError("CATALOG_INVALID", "Missing upload-pack service announcement");
4761
+ for (const line of lines.slice(2)) {
4762
+ if (line === null) continue;
4763
+ const match = /^([0-9a-f]{40}) ([^\0]+)(?:\0.*)?$/s.exec(line);
4764
+ if (!match) throw new CatalogError("CATALOG_INVALID", "Malformed ref advertisement");
4765
+ if (match[2] === "refs/heads/main") return match[1];
4766
+ }
4767
+ throw new CatalogError("CATALOG_INVALID", "Catalog repository has no main branch");
4768
+ }
4769
+ /**
4770
+ * Reads a bounded response without credentials, redirects, or remote-body diagnostics.
4771
+ * A failed status becomes `SYNC_FAILED`, with a retry delay (at most one day) taken from
4772
+ * `retry-after`, or from `x-ratelimit-reset` for 429 and exhausted-quota 403 responses.
4773
+ * A 404 throws the error built by `notFound` when it is supplied.
4774
+ */
4775
+ async function readBoundedResponse(network, url, signal, maxBytes, headers = {}, notFound) {
4776
+ signal.throwIfAborted();
4777
+ const response = await network.fetch(url, {
4778
+ signal,
4779
+ redirect: "error",
4780
+ headers
4781
+ });
4782
+ if (!response.ok) {
4783
+ await response.body?.cancel().catch(() => {});
4784
+ if (response.status === 404 && notFound) throw notFound();
4785
+ let retry = Number(response.headers.get("retry-after"));
4786
+ if (!(Number.isFinite(retry) && retry > 0) && (response.status === 429 || response.status === 403 && response.headers.get("x-ratelimit-remaining") === "0")) retry = Number(response.headers.get("x-ratelimit-reset")) - Math.floor(Date.now() / 1e3);
4787
+ throw new CatalogError("SYNC_FAILED", `Request failed (HTTP ${response.status})`, Number.isFinite(retry) && retry > 0 ? Math.min(86400, retry) : void 0);
4788
+ }
4789
+ if (Number(response.headers.get("content-length")) > maxBytes) {
4790
+ await response.body?.cancel().catch(() => {});
4791
+ throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
4792
+ }
4793
+ const reader = response.body?.getReader();
4794
+ if (!reader) return /* @__PURE__ */ new Uint8Array();
4795
+ const chunks = [];
4796
+ let size = 0;
4797
+ try {
4798
+ for (;;) {
4799
+ signal.throwIfAborted();
4800
+ const chunk = await reader.read();
4801
+ if (chunk.done) break;
4802
+ size += chunk.value.length;
4803
+ if (size > maxBytes) throw new CatalogError("LIMIT_EXCEEDED", "Response exceeds byte budget");
4804
+ chunks.push(chunk.value);
4805
+ }
4806
+ signal.throwIfAborted();
4807
+ return Buffer.concat(chunks, size);
4808
+ } finally {
4809
+ await reader.cancel().catch(() => {});
4810
+ reader.releaseLock();
4811
+ }
4812
+ }
4813
+ /**
4814
+ * Resolves the catalog's main commit with one ref advertisement request, then reads the complete
4815
+ * extension index pinned to that commit. An unchanged commit reuses `previous` with a new fetch
4816
+ * time. Requests carry no credentials, refuse redirects and share an 8 MiB budget and 30 s limit.
4817
+ */
4818
+ async function synchronize(network, ownerSignal, previous) {
4819
+ const controller = new AbortController();
4820
+ const signal = AbortSignal.any([ownerSignal, controller.signal]);
4821
+ const timer = setTimeout(() => controller.abort(new CatalogError("SYNC_FAILED", "Catalog synchronization exceeded 30 seconds")), 3e4);
4822
+ try {
4823
+ const commit = parseMainCommit(await readBoundedResponse(network, CATALOG_REFS_URL, signal, REFS_MAX_BYTES, headers));
4824
+ if (previous?.commit === commit) return {
4825
+ ...previous,
4826
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString()
4827
+ };
4828
+ const releases = decodeReleases(parseJson(decodeUtf8(await readBoundedResponse(network, catalogIndexUrl(commit), signal, CATALOG_MAX_BYTES, headers, () => new CatalogError("CATALOG_UNAVAILABLE", "No extension index is available")))));
4829
+ return {
4830
+ repository: CATALOG_REPOSITORY,
4831
+ commit,
4832
+ contentDigest: recordDigest({ releases }),
4833
+ fetchedAt: (/* @__PURE__ */ new Date()).toISOString(),
4834
+ revision: previous?.revision ?? 0,
4835
+ releases
4836
+ };
4837
+ } catch (error) {
4838
+ controller.abort(error);
4839
+ if (error instanceof CatalogError) throw error;
4840
+ if (ownerSignal.aborted) throw ownerSignal.reason;
4841
+ throw new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful snapshot is retained");
4842
+ } finally {
4843
+ clearTimeout(timer);
4844
+ }
4845
+ }
4846
+ //#endregion
4847
+ //#region src/extension-catalog/service.ts
4848
+ /** Creates local catalog reads and explicit synchronization, preview, and operation management. */
4849
+ function createCatalogService(options) {
4850
+ let snapshot = null;
4851
+ let sync = { state: "idle" };
4852
+ try {
4853
+ snapshot = options.store.read();
4854
+ } catch {
4855
+ sync = {
4856
+ state: "failed",
4857
+ error: "Catalog cache is damaged; refresh to repair it"
4858
+ };
4859
+ }
4860
+ const controller = new AbortController();
4861
+ const signal = AbortSignal.any([options.signal, controller.signal]);
4862
+ const ownedTasks = /* @__PURE__ */ new Set();
4863
+ let synchronization = null;
4864
+ function notifySynchronization() {
4865
+ if (!signal.aborted) options.notify?.({
4866
+ revision: snapshot?.revision ?? 0,
4867
+ ...snapshot ? { snapshot: {
4868
+ commit: snapshot.commit,
4869
+ contentDigest: snapshot.contentDigest
4870
+ } } : {},
4871
+ sync: { ...sync }
4872
+ });
4873
+ }
4874
+ function sharedSynchronization(manual = false) {
4875
+ signal.throwIfAborted();
4876
+ if (synchronization) {
4877
+ if (manual) synchronization.manual = true;
4878
+ return synchronization;
4879
+ }
4880
+ const taskId = randomUUID(), taskController = new AbortController(), taskSignal = AbortSignal.any([signal, taskController.signal]);
4881
+ sync = {
4882
+ state: "syncing",
4883
+ taskId
4884
+ };
4885
+ const work = Promise.resolve().then(async () => {
4886
+ try {
4887
+ const acquired = await synchronize(options.network, taskSignal, snapshot);
4888
+ const saved = await options.installer.coordinate(() => {
4889
+ taskSignal.throwIfAborted();
4890
+ snapshot = options.store.save(acquired);
4891
+ return snapshot;
4892
+ });
4893
+ sync = {
4894
+ state: "succeeded",
4895
+ taskId
4896
+ };
4897
+ return saved;
4898
+ } catch (error) {
4899
+ const failure = error instanceof CatalogError ? error : new CatalogError("SYNC_FAILED", "Catalog synchronization failed; last successful data is retained");
4900
+ sync = {
4901
+ state: "failed",
4902
+ taskId,
4903
+ error: failure.message,
4904
+ ...failure.retryAfterSeconds === void 0 ? {} : { retryAfterSeconds: failure.retryAfterSeconds }
4905
+ };
4906
+ throw failure;
4907
+ } finally {
4908
+ synchronization = null;
4909
+ notifySynchronization();
4910
+ }
4911
+ });
4912
+ synchronization = {
4913
+ taskId,
4914
+ controller: taskController,
4915
+ manual,
4916
+ consumers: /* @__PURE__ */ new Set(),
4917
+ work
4918
+ };
4919
+ ownedTasks.add(work);
4920
+ work.then(() => ownedTasks.delete(work), () => ownedTasks.delete(work));
4921
+ notifySynchronization();
4922
+ return synchronization;
4923
+ }
4924
+ async function acquireFreshSnapshot(attempt) {
4925
+ const consumerSignal = AbortSignal.any([signal, attempt.signal]);
4926
+ consumerSignal.throwIfAborted();
4927
+ const task = sharedSynchronization(), consumer = Symbol();
4928
+ task.consumers.add(consumer);
4929
+ let onAbort;
4930
+ const cancelled = new Promise((_resolve, reject) => {
4931
+ onAbort = () => {
4932
+ task.consumers.delete(consumer);
4933
+ if (!task.manual && !task.consumers.size) task.controller.abort(consumerSignal.reason);
4934
+ reject(consumerSignal.reason);
4935
+ };
4936
+ consumerSignal.addEventListener("abort", onAbort, { once: true });
4937
+ if (consumerSignal.aborted) onAbort();
4938
+ });
4939
+ try {
4940
+ const acquired = await Promise.race([task.work, cancelled]);
4941
+ consumerSignal.throwIfAborted();
4942
+ return acquired;
4943
+ } catch (error) {
4944
+ if (consumerSignal.aborted && !task.manual && !task.consumers.size) {
4945
+ task.controller.abort(consumerSignal.reason);
4946
+ await Promise.allSettled([task.work]);
4947
+ }
4948
+ throw error;
4949
+ } finally {
4950
+ task.consumers.delete(consumer);
4951
+ consumerSignal.removeEventListener("abort", onAbort);
4952
+ }
4953
+ }
4954
+ /** Prepares exact roots and one shared extension closure without imports or activation. */
4955
+ async function preview(inputs, enableNames = [], batch = false, attempt, automatic = false) {
4956
+ const preparationSignal = attempt ? AbortSignal.any([signal, attempt.signal]) : signal;
4957
+ preparationSignal.throwIfAborted();
4958
+ const selections = inputs.map((input) => SelectionSchema.parse(input)), selectedSnapshot = snapshot;
4959
+ if (!selections.length || selections.length > 64 || enableNames.length > 2e3) throw new CatalogError("LIMIT_EXCEEDED", "Select between one and 64 exact extension roots");
4960
+ if (!selectedSnapshot) throw new CatalogError("CATALOG_UNAVAILABLE", "Refresh the extension catalog before selecting a release");
4961
+ const accepted = structuredClone(selectedSnapshot);
4962
+ const selectedHost = options.hostIdentity;
4963
+ if (!selectedHost) throw new CatalogError("RELEASE_INCOMPATIBLE", "Current product and host target are unavailable");
4964
+ const host = selectedHost;
4965
+ const observations = await options.installer.observe();
4966
+ const roots = [];
4967
+ for (const selection of selections) {
4968
+ if (selection.snapshotCommit !== accepted.commit) throw new CatalogError("STALE_PREVIEW", "Selected catalog commit is no longer current");
4969
+ const release = accepted.releases.find((r) => r.releaseId === selection.releaseId);
4970
+ if (!release || release.artifact.integrity !== selection.artifactIntegrity) throw new CatalogError("RELEASE_UNLISTED", "Selected exact release is not listed");
4971
+ if (!releaseCompatible(release, host)) throw new CatalogError("RELEASE_INCOMPATIBLE", "Selected release does not accept the current product and host target");
4972
+ const existing = observations.find((o) => o.packageName === release.packageName);
4973
+ if (automatic && existing?.declared.origin !== void 0) throw new CatalogError("STALE_PREVIEW", "A user declaration now owns this default extension");
4974
+ if (selection.expectedInstalledReceiptId !== void 0 && existing?.receipt?.receiptId !== selection.expectedInstalledReceiptId) throw new CatalogError("STALE_PREVIEW", "Current installed receipt differs from the displayed selection");
4975
+ const prior = roots.find((r) => r.packageName === release.packageName);
4976
+ if (prior && recordDigest(prior) !== recordDigest(release)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension roots select conflicting exact releases");
4977
+ if (!prior) roots.push(release);
4978
+ }
4979
+ const resolved = [], chosen = new Map(roots.map((root) => [root.packageName, root])), expanded = /* @__PURE__ */ new Set();
4980
+ async function expand(candidate) {
4981
+ const prior = chosen.get(candidate.packageName);
4982
+ if (prior) {
4983
+ if (prior.releaseId !== candidate.releaseId) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension requirements select conflicting exact releases");
4984
+ if (expanded.has(candidate.packageName)) return;
4985
+ }
4986
+ if (!prior && chosen.size >= 64) throw new CatalogError("LIMIT_EXCEEDED", "Extension closure exceeds 64 packages");
4987
+ chosen.set(candidate.packageName, candidate);
4988
+ expanded.add(candidate.packageName);
4989
+ resolved.push(candidate);
4990
+ const raw = (await options.installer.inspect({
4991
+ expectedName: candidate.packageName,
4992
+ expectedVersion: candidate.version,
4993
+ ...candidate.artifact
4994
+ }, preparationSignal, attempt)).yaoguang?.dependencies ?? {};
4995
+ if (!raw || typeof raw !== "object" || Array.isArray(raw) || Object.keys(raw).length > 64) throw new CatalogError("ARTIFACT_INVALID", "Invalid extension dependency declaration");
4996
+ for (const [name, range] of Object.entries(raw)) {
4997
+ if (typeof range !== "string" || semver.validRange(range) === null) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Extension dependency has an invalid version range");
4998
+ const selected = chosen.get(name);
4999
+ if (selected) {
5000
+ if (!semver.satisfies(selected.version, range)) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Exact closure cannot satisfy all extension requirements");
5001
+ continue;
5002
+ }
5003
+ const installed = observations.find((o) => o.packageName === name && o.declared.origin !== void 0);
5004
+ if (automatic && installed && (!installed.declared.installed || !installed.declared.enabled)) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency declaration does not permit default installation");
5005
+ const installedVersion = installed?.receipt?.version ?? installed?.declared.version ?? installed?.summary?.version;
5006
+ if (installedVersion && semver.valid(installedVersion) && semver.satisfies(installedVersion, range)) continue;
5007
+ if (automatic && installed) throw new CatalogError("DEPENDENCY_USER_MANAGED", "An existing dependency version cannot be replaced by default installation");
5008
+ const choices = accepted.releases.filter((r) => r.packageName === name && semver.satisfies(r.version, range) && releaseCompatible(r, host));
5009
+ if (choices.length !== 1) throw new CatalogError("DEPENDENCY_UNRESOLVED", "Missing extension dependency has no unique compatible exact release");
5010
+ await expand(choices[0]);
5011
+ }
5012
+ }
5013
+ for (const root of roots) await expand(root);
5014
+ function evidence(candidate) {
5015
+ return {
5016
+ expectedName: candidate.packageName,
5017
+ expectedVersion: candidate.version,
5018
+ ...candidate.artifact,
5019
+ sourceRecord: {
5020
+ snapshot: {
5021
+ repository: accepted.repository,
5022
+ commit: accepted.commit,
5023
+ contentDigest: accepted.contentDigest
5024
+ },
5025
+ release: candidate,
5026
+ releaseDigest: recordDigest(candidate)
5027
+ },
5028
+ activationConstraints: {
5029
+ hostVersionRange: candidate.compatibility.productRange,
5030
+ platformTargets: candidate.compatibility.platforms
5031
+ },
5032
+ display: {
5033
+ label: typeof candidate.displayName === "string" ? candidate.displayName : candidate.displayName["en-US"],
5034
+ detail: "Historical catalog admission"
5035
+ }
5036
+ };
5037
+ }
5038
+ const validate = () => {
5039
+ if (snapshot?.commit !== accepted.commit || snapshot.contentDigest !== accepted.contentDigest || snapshot.revision !== accepted.revision || resolved.some((r) => !snapshot.releases.some((current) => current.releaseId === r.releaseId && recordDigest(current) === recordDigest(r)))) throw new CatalogError("STALE_PREVIEW", "Catalog changed after preview; select the new exact release explicitly");
5040
+ };
5041
+ preparationSignal.throwIfAborted();
5042
+ validate();
5043
+ const rootNames = new Set(roots.map((root) => root.packageName));
5044
+ const dependencies = resolved.filter((record) => !rootNames.has(record.packageName)).map(evidence);
5045
+ const preview = batch ? await options.installer.previewBatch({
5046
+ roots: roots.map(evidence),
5047
+ dependencies,
5048
+ enabled: true,
5049
+ enableNames
5050
+ }, validate, attempt) : await options.installer.preview({
5051
+ ...evidence(roots[0]),
5052
+ enabled: true,
5053
+ dependencies
5054
+ }, validate, attempt);
5055
+ preparationSignal.throwIfAborted();
5056
+ if (automatic && preview.replacing.length) throw new CatalogError("STALE_PREVIEW", "Default installation cannot replace existing extensions");
5057
+ return {
5058
+ previewToken: preview.token,
5059
+ expiresAt: preview.expiresAt,
5060
+ snapshot: {
5061
+ commit: accepted.commit,
5062
+ contentDigest: accepted.contentDigest
5063
+ },
5064
+ graphRevision: preview.graphRevision,
5065
+ resolvedSelections: resolved,
5066
+ dependencies: preview.selections.filter((selection) => !rootNames.has(selection.expectedName)).map((s) => ({
5067
+ packageName: s.expectedName,
5068
+ version: s.expectedVersion
5069
+ })),
5070
+ willEnable: [...preview.willEnable],
5071
+ replacing: [...preview.replacing],
5072
+ affectedOwners: [...preview.affectedOwners],
5073
+ warnings: []
5074
+ };
5075
+ }
5076
+ const defaults = options.defaultsStore && options.hostIdentity ? createDefaultsService({
5077
+ store: options.defaultsStore,
5078
+ identity: options.hostIdentity,
5079
+ installer: options.installer,
5080
+ signal,
5081
+ preview: (selections, attempt) => preview(selections, [], true, attempt, true),
5082
+ acquireSnapshot: acquireFreshSnapshot
5083
+ }) : null;
5084
+ function requireDefaults() {
5085
+ if (!defaults) throw new CatalogError("DEFAULTS_UNAVAILABLE", "Default extension initialization is unavailable for this host");
5086
+ return defaults;
5087
+ }
5088
+ return {
5089
+ /** Starts or shares this owner's one-shot bounded automatic installation task. */
5090
+ defaultsEnsure(input) {
5091
+ return requireDefaults().ensure(input);
5092
+ },
5093
+ /** Returns passive initialization facts without refreshing or enrolling. */
5094
+ defaultsStatus() {
5095
+ return requireDefaults().status();
5096
+ },
5097
+ /** Returns cached data only; first use and failure never trigger network work. */
5098
+ list() {
5099
+ signal.throwIfAborted();
5100
+ if (!snapshot) return {
5101
+ revision: 0,
5102
+ snapshot: null,
5103
+ releases: [],
5104
+ sync: { ...sync }
5105
+ };
5106
+ const { releases, ...metadata } = snapshot;
5107
+ return {
5108
+ revision: snapshot.revision,
5109
+ snapshot: metadata,
5110
+ releases,
5111
+ sync: { ...sync }
5112
+ };
5113
+ },
5114
+ /** Joins the active fresh synchronization; manual work survives automatic attempt cancellation. */
5115
+ refresh() {
5116
+ return {
5117
+ taskId: sharedSynchronization(true).taskId,
5118
+ sync: { ...sync }
5119
+ };
5120
+ },
5121
+ /** Previews installation with target enablement and joins owned preparation before disposal. */
5122
+ preview(input) {
5123
+ const task = preview([input]);
5124
+ ownedTasks.add(task);
5125
+ task.then(() => {
5126
+ ownedTasks.delete(task);
5127
+ }, () => {
5128
+ ownedTasks.delete(task);
5129
+ });
5130
+ return task;
5131
+ },
5132
+ /** Prepares one approved union of exact roots and existing owners to enable. */
5133
+ previewBatch(inputs, enableNames = []) {
5134
+ const task = preview(inputs, enableNames, true);
5135
+ ownedTasks.add(task);
5136
+ task.then(() => ownedTasks.delete(task), () => ownedTasks.delete(task));
5137
+ return task;
5138
+ },
5139
+ /** Delegates deduplication before any token or current-snapshot validation. */
5140
+ install(operationId, previewToken) {
5141
+ signal.throwIfAborted();
5142
+ return options.installer.install({
5143
+ operationId,
5144
+ token: previewToken
5145
+ });
5146
+ },
5147
+ /** Reads an existing durable attempt without restarting work. */
5148
+ operation(operationId) {
5149
+ return options.installer.operation(operationId);
5150
+ },
5151
+ /** Retries only cleanup still owned by the queried attempt. */
5152
+ retryCleanup(operationId) {
5153
+ return options.installer.retryCleanup(operationId);
5154
+ },
5155
+ /** Projects installed metadata against the current cached directory without reading files. */
5156
+ async installed() {
5157
+ signal.throwIfAborted();
5158
+ const observations = await options.installer.observe();
5159
+ return {
5160
+ observedAt: (/* @__PURE__ */ new Date()).toISOString(),
5161
+ rows: projectInstalled(observations, snapshot, options.hostIdentity)
5162
+ };
5163
+ },
5164
+ /** Joins all discovery work before owner disposal completes. */
5165
+ async dispose() {
5166
+ controller.abort(/* @__PURE__ */ new Error("Catalog owner withdrawn"));
5167
+ await Promise.all([defaults?.dispose(), Promise.allSettled([...ownedTasks])]);
5168
+ }
5169
+ };
5170
+ }
4508
5171
  //#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()]);
5172
+ //#region src/extension-catalog/store.ts
5173
+ /** Persists the last complete validated catalog snapshot in this owner's storage lease. */
5174
+ function createCatalogStore(storage) {
5175
+ const name = storage.tableName("catalog_snapshot");
5176
+ if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) throw new Error("Invalid storage table identity");
5177
+ const table = `"${name}"`;
5178
+ storage.db.exec(`CREATE TABLE IF NOT EXISTS ${table} (id INTEGER PRIMARY KEY CHECK(id=1), snapshot_json TEXT NOT NULL)`);
5179
+ function validate(input) {
5180
+ const value = SnapshotSchema.parse(input);
5181
+ if (recordDigest({ releases: value.releases }) !== value.contentDigest) throw new CatalogError("CATALOG_INVALID", "Cached snapshot digest differs from its complete records");
5182
+ if (new Set(value.releases.map((r) => r.releaseId)).size !== value.releases.length) throw new CatalogError("CATALOG_INVALID", "Duplicate cached release");
5183
+ return value;
5184
+ }
5185
+ return {
5186
+ /** Reads validated last-success data without network activity; corruption refuses availability. */
5187
+ read() {
5188
+ const row = storage.db.prepare(`SELECT snapshot_json FROM ${table} WHERE id=1`).get();
5189
+ if (!row) return null;
5190
+ try {
5191
+ return validate(JSON.parse(row.snapshot_json));
5192
+ } catch {
5193
+ throw new CatalogError("CATALOG_INVALID", "Catalog cache is unavailable; refresh to repair it");
5194
+ }
5195
+ },
5196
+ /** Atomically replaces the complete snapshot and advances its successful revision. */
5197
+ save(input) {
5198
+ const snapshot = validate(input);
5199
+ storage.db.exec("SAVEPOINT catalog_snapshot_commit");
5200
+ try {
5201
+ let before = null;
5202
+ try {
5203
+ before = this.read();
5204
+ } catch {}
5205
+ const revision = (before?.revision ?? 0) + 1;
5206
+ if (!Number.isSafeInteger(revision)) throw new CatalogError("LIMIT_EXCEEDED", "Catalog revision is exhausted");
5207
+ const saved = {
5208
+ ...snapshot,
5209
+ revision
5210
+ };
5211
+ const json = canonicalJson(saved);
5212
+ if (Buffer.byteLength(json) > 8388608) throw new CatalogError("LIMIT_EXCEEDED", "Encoded catalog exceeds 8 MiB");
5213
+ storage.db.prepare(`INSERT INTO ${table}(id,snapshot_json) VALUES(1,?) ON CONFLICT(id) DO UPDATE SET snapshot_json=excluded.snapshot_json`).run(json);
5214
+ storage.db.exec("RELEASE catalog_snapshot_commit");
5215
+ return saved;
5216
+ } catch (error) {
5217
+ storage.db.exec("ROLLBACK TO catalog_snapshot_commit");
5218
+ storage.db.exec("RELEASE catalog_snapshot_commit");
5219
+ throw error;
5220
+ }
5221
+ }
5222
+ };
4652
5223
  }
4653
5224
  //#endregion
4654
5225
  //#region src/extension-catalog/register.ts
@@ -4741,12 +5312,6 @@ function registerExtensionCatalog(ctx) {
4741
5312
  result: resultSchema(InstalledSchema),
4742
5313
  handle: () => result(() => service.installed())
4743
5314
  });
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
5315
  ctx.client.registerMethod({
4751
5316
  name: "extensionCatalogPreviewBatch",
4752
5317
  params: z.object({
@@ -4779,10 +5344,41 @@ function registerExtensionCatalog(ctx) {
4779
5344
  });
4780
5345
  const operationParams = z.object({ operationId: z.uuid() }).strict();
4781
5346
  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)) }))
5347
+ name: "extensionCatalogOperations",
5348
+ params: OperationQueriesParams,
5349
+ result: resultSchema(OperationQueriesData),
5350
+ handle: (p) => result(async () => {
5351
+ const results = [];
5352
+ for (const [index, target] of p.operationIds.entries()) {
5353
+ ctx.signal.throwIfAborted();
5354
+ try {
5355
+ const operation = OperationSchema.parse(await service.operation(target));
5356
+ ctx.signal.throwIfAborted();
5357
+ const member = {
5358
+ index,
5359
+ target,
5360
+ ok: true,
5361
+ value: { operation }
5362
+ };
5363
+ if (Buffer.byteLength(JSON.stringify(member)) > p.maxItemBytes) throw new CatalogError("read-limit", "Operation result exceeds the declared member byte budget");
5364
+ results.push(member);
5365
+ } catch (error) {
5366
+ ctx.signal.throwIfAborted();
5367
+ const refusal = managementError(error);
5368
+ results.push({
5369
+ index,
5370
+ target,
5371
+ ok: false,
5372
+ error: {
5373
+ code: refusal.code.slice(0, 64).replace(/[\uD800-\uDBFF]$/, "") || "INSTALL_FAILED",
5374
+ message: refusal.message.slice(0, 512).replace(/[\uD800-\uDBFF]$/, ""),
5375
+ ...refusal.retryAfterSeconds === void 0 ? {} : { details: { retryAfterSeconds: refusal.retryAfterSeconds } }
5376
+ }
5377
+ });
5378
+ }
5379
+ }
5380
+ return { results };
5381
+ })
4786
5382
  });
4787
5383
  ctx.client.registerMethod({
4788
5384
  name: "extensionCatalogRetryCleanup",