@pstdio/pocketcoder-sdk 0.7.0 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { t as __exportAll } from "./rolldown-runtime-D7D4PA-g.js";
1
2
  import { z } from "zod";
2
3
  import { createHash } from "node:crypto";
3
4
  import { posix } from "node:path";
@@ -14,37 +15,6 @@ const AttachmentDescriptorSchema = z.object({
14
15
  size_bytes: z.number().int().min(0).max(ATTACHMENT_MAX_FILE_BYTES),
15
16
  sha256: z.string().regex(/^[0-9a-f]{64}$/)
16
17
  });
17
- z.looseObject({
18
- type: z.literal("user"),
19
- content: z.string(),
20
- attachment_ids: z.array(z.uuid()).min(1).max(10).refine((ids) => new Set(ids).size === ids.length, "attachment_ids must be unique").optional()
21
- });
22
- const MANIFEST_OPEN = "<pocketcoder-attachments>";
23
- const MANIFEST_CLOSE = "</pocketcoder-attachments>";
24
- function splitAttachmentManifest(content) {
25
- const open = content.lastIndexOf(MANIFEST_OPEN);
26
- if (open < 0 || !content.trimEnd().endsWith(MANIFEST_CLOSE)) return {
27
- text: content,
28
- attachments: null
29
- };
30
- const close = content.lastIndexOf(MANIFEST_CLOSE);
31
- const parsed = z.array(AttachmentDescriptorSchema).safeParse(safeJson(content.slice(open + 25, close)));
32
- if (!parsed.success) return {
33
- text: content,
34
- attachments: null
35
- };
36
- return {
37
- text: content.slice(0, open).trimEnd(),
38
- attachments: parsed.data
39
- };
40
- }
41
- function safeJson(value) {
42
- try {
43
- return JSON.parse(value);
44
- } catch {
45
- return;
46
- }
47
- }
48
18
  const AttachmentStartPayload = z.object({
49
19
  operation_id: z.uuid(),
50
20
  attachment_id: z.uuid(),
@@ -139,7 +109,8 @@ const WorkloadCapabilitySchema = z.enum([
139
109
  "workspace-services",
140
110
  "revocable-preview-grants",
141
111
  "workspace-cancel",
142
- "unknown-outcome"
112
+ "unknown-outcome",
113
+ "parallel-conversations"
143
114
  ]);
144
115
  const WorkloadProfileSchema = z.enum([
145
116
  "finite-process",
@@ -191,8 +162,7 @@ const InstalledWorkloadSchema = z.strictObject({
191
162
  kind: z.enum([
192
163
  "process",
193
164
  "service",
194
- "pi",
195
- "agentapi"
165
+ "pi"
196
166
  ]),
197
167
  digest: WorkloadDigestSchema,
198
168
  protocol: z.string().min(1).max(128),
@@ -203,6 +173,7 @@ const InstalledWorkloadSchema = z.strictObject({
203
173
  //#region ../contracts/src/attachments/input-reference.ts
204
174
  const InputObjectReferenceSchema = z.strictObject({
205
175
  workspaceId: z.uuid(),
176
+ storageOwnerId: z.uuid().optional(),
206
177
  fileId: z.uuid(),
207
178
  objectVersion: WorkloadDigestSchema,
208
179
  name: z.string().min(1).max(255),
@@ -268,6 +239,10 @@ const SCOPES = [
268
239
  "network:read",
269
240
  "terminal:attach",
270
241
  "terminal:read",
242
+ "sessions:read",
243
+ "sessions:write",
244
+ "budgets:read",
245
+ "budgets:admin",
271
246
  "admin"
272
247
  ];
273
248
  z.strictObject({
@@ -472,7 +447,8 @@ z.object({
472
447
  z.object({
473
448
  external_id: z.string().min(1).max(256),
474
449
  metadata: z.record(z.string().max(64), z.string().max(512)).optional(),
475
- launch_input: z.record(z.string(), z.unknown()).optional()
450
+ launch_input: z.record(z.string(), z.unknown()).optional(),
451
+ template_version: z.string().min(1).max(256).optional()
476
452
  });
477
453
  const CheckpointManifestEntrySchema = z.object({
478
454
  path: z.string(),
@@ -571,6 +547,7 @@ const ERROR_CODES = {
571
547
  "principal.name_conflict": 409,
572
548
  "key.not_found": 404,
573
549
  "request.body_too_large": 413,
550
+ "request.not_found": 404,
574
551
  "validation.invalid": 400,
575
552
  "idempotency.conflict": 409,
576
553
  "capacity.queue_full": 429,
@@ -634,6 +611,16 @@ const ERROR_CODES = {
634
611
  "account.purge_pending": 503,
635
612
  "recovery.required": 503,
636
613
  "recovery.failed": 409,
614
+ "session.not_found": 404,
615
+ "session.closed": 409,
616
+ "profile.not_found": 404,
617
+ "budget.not_found": 404,
618
+ "budget.exhausted": 429,
619
+ "budget.conflict": 409,
620
+ "revision.stale": 412,
621
+ "events.cursor_invalid": 400,
622
+ "events.cursor_expired": 410,
623
+ "runtime.unavailable": 503,
637
624
  "internal.error": 500
638
625
  };
639
626
  const errorCodes = Object.keys(ERROR_CODES);
@@ -733,6 +720,45 @@ const ConversationProtocolSupportSchema = z.object({
733
720
  producer_capabilities: z.null()
734
721
  });
735
722
  //#endregion
723
+ //#region ../contracts/src/conversations/parts.ts
724
+ const text = z.string().max(262144);
725
+ const payload = JsonValueSchema.refine((value) => new TextEncoder().encode(JSON.stringify(value)).length <= 262144, "Session part payload exceeds 256 KiB");
726
+ const ConversationPartSchema = z.discriminatedUnion("type", [
727
+ z.strictObject({
728
+ type: z.literal("text"),
729
+ text
730
+ }),
731
+ z.strictObject({
732
+ type: z.literal("tool"),
733
+ call_id: z.string().min(1).max(256),
734
+ name: z.string().min(1).max(128),
735
+ status: z.enum([
736
+ "pending",
737
+ "running",
738
+ "completed",
739
+ "failed",
740
+ "canceled"
741
+ ]),
742
+ input: payload,
743
+ output: payload.optional(),
744
+ output_text: text.optional(),
745
+ started_at: z.iso.datetime().nullable().optional(),
746
+ ended_at: z.iso.datetime().nullable().optional()
747
+ }),
748
+ z.strictObject({
749
+ type: z.literal("error"),
750
+ code: z.string().min(1).max(128),
751
+ message: text
752
+ }),
753
+ z.strictObject({
754
+ type: z.literal("file"),
755
+ file_id: z.uuid(),
756
+ name: z.string().min(1).max(512),
757
+ media_type: z.string().min(1).max(256),
758
+ size_bytes: z.number().int().nonnegative()
759
+ })
760
+ ]);
761
+ //#endregion
736
762
  //#region ../contracts/src/conversations/conversation.ts
737
763
  const CONVERSATION_ROLES = [
738
764
  "user",
@@ -745,6 +771,7 @@ const ConversationMessageInputSchema = z.object({
745
771
  message_id: z.string().min(1).max(256),
746
772
  role: z.enum(CONVERSATION_ROLES),
747
773
  content: z.string().max(262144),
774
+ parts: z.array(ConversationPartSchema).max(256).optional(),
748
775
  occurred_at: z.iso.datetime(),
749
776
  metadata: ConversationMetadataSchema.default({}),
750
777
  identity: ConversationMessageIdentitySchema.nullable().optional()
@@ -788,7 +815,7 @@ const ConversationActivitySchema = z.object({
788
815
  ended_at: z.iso.datetime().nullable(),
789
816
  outcome: z.string().nullable()
790
817
  });
791
- z.object({
818
+ const ConversationRecordDocumentSchema = z.object({
792
819
  schema: z.literal("pocketcoder.conversation-record/v1"),
793
820
  turn_id: z.uuid().nullable(),
794
821
  request: ConversationRequestIdentitySchema.nullable(),
@@ -849,7 +876,10 @@ const ViewSessionSchema = z.discriminatedUnion("mode", [
849
876
  parentOrigin: HttpsOriginSchema
850
877
  })
851
878
  ]);
852
- z.strictObject({ session: ViewSessionSchema.default({ mode: "local" }) });
879
+ z.strictObject({
880
+ session: ViewSessionSchema.default({ mode: "local" }),
881
+ grantId: z.uuid().optional()
882
+ }).refine((input) => input.session.mode === "local" || !!input.grantId, "Cloud previews require a grant");
853
883
  //#endregion
854
884
  //#region ../contracts/src/displays/display.ts
855
885
  const DisplaySchema = z.strictObject({ mode: z.enum(["desktop", "browser"]) });
@@ -1021,7 +1051,7 @@ const ExportObjectReferenceSchema = z.strictObject({
1021
1051
  mediaType: AttachmentMediaTypeSchema,
1022
1052
  digest: WorkloadDigestSchema
1023
1053
  });
1024
- z.strictObject({
1054
+ const WorkloadExportReferenceSchema = z.strictObject({
1025
1055
  exportId: z.uuid(),
1026
1056
  execution: WorkloadExecutionReferenceSchema,
1027
1057
  manifestDigest: WorkloadDigestSchema,
@@ -1030,6 +1060,11 @@ z.strictObject({
1030
1060
  "partial",
1031
1061
  "lost"
1032
1062
  ]),
1063
+ cleanupState: z.enum([
1064
+ "not_required",
1065
+ "pending",
1066
+ "complete"
1067
+ ]).optional(),
1033
1068
  publication: z.enum([
1034
1069
  "published",
1035
1070
  "unavailable",
@@ -1056,6 +1091,11 @@ z.strictObject({
1056
1091
  path: ["expiresAt"],
1057
1092
  message: "export retention must be positive"
1058
1093
  });
1094
+ if (value.completeness === "complete" !== (value.errors.length === 0)) ctx.addIssue({
1095
+ code: "custom",
1096
+ path: ["errors"],
1097
+ message: "Export errors must agree with completeness"
1098
+ });
1059
1099
  const ids = value.objects.map((object) => object.objectId);
1060
1100
  if (new Set(ids).size !== ids.length) ctx.addIssue({
1061
1101
  code: "custom",
@@ -1123,6 +1163,14 @@ const PreviewSocketPayload = z.discriminatedUnion("op", [
1123
1163
  request_id: z.uuid()
1124
1164
  })
1125
1165
  ]);
1166
+ z.strictObject({
1167
+ id: z.uuid(),
1168
+ subject: z.string().min(1).max(256),
1169
+ accessRevision: z.string().min(1).max(256),
1170
+ previews: z.array(PreviewNameSchema).min(1).max(16).refine((names) => new Set(names).size === names.length, "Preview names must be unique"),
1171
+ ceilingAt: z.iso.datetime()
1172
+ });
1173
+ z.strictObject({ accessRevision: z.string().min(1).max(256) });
1126
1174
  //#endregion
1127
1175
  //#region ../contracts/src/workspaces/workspace.ts
1128
1176
  const WORKSPACE_STATES = [
@@ -1169,6 +1217,7 @@ const REASON_CODES = [
1169
1217
  "idle_expired",
1170
1218
  "queue_timeout",
1171
1219
  "launch_failed",
1220
+ "launch_refused",
1172
1221
  "preserve_requested",
1173
1222
  "preserved_by_policy",
1174
1223
  "checkpoint_created",
@@ -1189,7 +1238,6 @@ const AGENT_STATES = [
1189
1238
  "running",
1190
1239
  "stable"
1191
1240
  ];
1192
- const AgentInterruptResponseSchema = z.object({ status: z.enum(["requested", "idle"]) });
1193
1241
  z.object({
1194
1242
  external_id: z.string().min(1).max(256),
1195
1243
  template: z.object({
@@ -1205,15 +1253,10 @@ const TemplateRefSchema = z.object({
1205
1253
  version: z.string(),
1206
1254
  digest: z.string()
1207
1255
  });
1208
- const AgentMetadataSchema = z.object({
1209
- type: z.string(),
1210
- model: z.string().min(1).max(255).nullable()
1211
- });
1212
1256
  const WorkspaceResourceSchema = z.object({
1213
1257
  id: z.uuid(),
1214
1258
  external_id: z.string(),
1215
1259
  template: TemplateRefSchema,
1216
- agent: AgentMetadataSchema.nullable(),
1217
1260
  state: z.enum(WORKSPACE_STATES),
1218
1261
  reason_code: z.enum(REASON_CODES).nullable(),
1219
1262
  agent_state: z.enum(AGENT_STATES),
@@ -1227,6 +1270,10 @@ const WorkspaceResourceSchema = z.object({
1227
1270
  connected_at: z.iso.datetime().nullable(),
1228
1271
  ready_at: z.iso.datetime().nullable(),
1229
1272
  deadline_at: z.iso.datetime(),
1273
+ lifetime: z.strictObject({
1274
+ revision: z.number().int().positive(),
1275
+ ceilingAt: z.iso.datetime()
1276
+ }).optional(),
1230
1277
  terminal_at: z.iso.datetime().nullable(),
1231
1278
  metadata: z.record(z.string(), z.string()),
1232
1279
  origin_workspace_id: z.uuid().nullable(),
@@ -1271,7 +1318,6 @@ const TemplateListItemSchema = z.object({
1271
1318
  name: z.string(),
1272
1319
  version: z.string(),
1273
1320
  digest: z.string(),
1274
- agent: AgentMetadataSchema.nullable(),
1275
1321
  description: z.string().optional(),
1276
1322
  status: z.enum([
1277
1323
  "active",
@@ -1451,14 +1497,6 @@ const HarnessSchema = z.object({
1451
1497
  env: EnvSchema.default({}),
1452
1498
  cwd: z.string().refine(isAbsolutePath, "expected an absolute path").optional()
1453
1499
  });
1454
- const AgentSchema = HarnessSchema.extend({
1455
- model: z.string().min(1).max(255).optional().describe("Display metadata only; does not configure the agent model."),
1456
- type: z.string().regex(/^[a-z0-9][a-z0-9-]{0,63}$/).default("custom"),
1457
- transport: z.enum(["pty", "acp"]).default("pty"),
1458
- termWidth: z.number().int().min(10).max(65535).optional(),
1459
- stateFile: z.string().refine(isAbsolutePath, "expected an absolute path").optional(),
1460
- interruptKeys: z.string().min(1).max(16).optional()
1461
- });
1462
1500
  const TerminalSchema = z.object({
1463
1501
  command: CommandSchema,
1464
1502
  env: EnvSchema.default({}),
@@ -1537,7 +1575,7 @@ const CheckpointHookSchema = z.object({
1537
1575
  env: EnvSchema.default({}),
1538
1576
  cwd: z.string().refine(isAbsolutePath, "expected an absolute path").optional()
1539
1577
  });
1540
- const TemplateSpecSchema = z.object({
1578
+ const RuntimeTemplatePolicySchema = z.object({
1541
1579
  version: z.string().regex(SEMVER_RE),
1542
1580
  image: z.string().regex(IMAGE_DIGEST_RE, { message: "image must be digest-pinned (repo@sha256:<64 hex>)" }),
1543
1581
  imagePullSecret: z.string().refine((value) => value.startsWith("secretRef:") && SecretNameSchema.safeParse(value.slice(10)).success, "imagePullSecret must name a stored secret").optional(),
@@ -1548,7 +1586,6 @@ const TemplateSpecSchema = z.object({
1548
1586
  "/run/pocketcoder/input"
1549
1587
  ]),
1550
1588
  setup: z.array(SetupStepSchema).max(32).default([]),
1551
- agent: AgentSchema.optional(),
1552
1589
  harness: HarnessSchema.optional(),
1553
1590
  terminal: TerminalSchema.optional(),
1554
1591
  previews: PreviewsSchema.optional(),
@@ -1560,59 +1597,14 @@ const TemplateSpecSchema = z.object({
1560
1597
  security: SecuritySchema.prefault({}),
1561
1598
  network: NetworkPolicySchema,
1562
1599
  maxLaunchInputBytes: z.number().int().positive().max(1048576).default(65536),
1563
- compat: z.object({
1564
- agent: z.string().optional(),
1565
- agentapi: z.string().optional()
1566
- }).default({}),
1567
1600
  persistence: PersistenceSpecSchema.prefault({}),
1568
1601
  source: SourceSpecSchema.nullable().default(null),
1569
1602
  checkpointHook: CheckpointHookSchema.optional(),
1570
1603
  outputs: z.record(z.string().regex(NAME_RE), OutputDeclarationSchema).default({})
1571
- }).superRefine((spec, ctx) => {
1572
- if (!spec.agent && !spec.harness) ctx.addIssue({
1573
- code: "custom",
1574
- path: ["harness"],
1575
- message: "either agent or harness is required"
1576
- });
1577
- if (!spec.agent) return;
1578
- if (spec.agent.transport === "acp") for (const field of [
1579
- "termWidth",
1580
- "stateFile",
1581
- "interruptKeys"
1582
- ]) {
1583
- if (spec.agent[field] === void 0) continue;
1584
- ctx.addIssue({
1585
- code: "custom",
1586
- path: ["agent", field],
1587
- message: `${field} is only valid for PTY transport`
1588
- });
1589
- }
1590
- for (const field of [
1591
- "harness",
1592
- "services",
1593
- "checkpointHook"
1594
- ]) {
1595
- if (spec[field] === void 0) continue;
1596
- ctx.addIssue({
1597
- code: "custom",
1598
- path: [field],
1599
- message: `agent cannot be combined with ${field}`
1600
- });
1601
- }
1602
- }).transform((spec) => {
1603
- if (spec.agent) {
1604
- const { harness: _harness, services: _services, checkpointHook: _hook, ...native } = spec;
1605
- return {
1606
- ...native,
1607
- agent: spec.agent
1608
- };
1609
- }
1610
- const { agent: _agent, ...legacy } = spec;
1611
- return {
1612
- ...legacy,
1613
- harness: spec.harness,
1614
- services: spec.services ?? {}
1615
- };
1604
+ });
1605
+ const TemplateSpecSchema = RuntimeTemplatePolicySchema.extend({
1606
+ harness: HarnessSchema,
1607
+ services: z.record(z.string().regex(NAME_RE), ServiceSchema).default({})
1616
1608
  });
1617
1609
  const TemplateManifestBaseSchema = z.object({
1618
1610
  apiVersion: z.literal("pocketcoder.dev/v1alpha1", { error: "unsupported template format for the alpha runtime; canonical workloads require an installed workload runtime" }),
@@ -1663,7 +1655,12 @@ const WaitingRuntimeSpecSchema = z.strictObject({
1663
1655
  incarnationId: z.string().min(1).max(256),
1664
1656
  profile: WorkloadProfileSchema,
1665
1657
  operations: z.record(z.string(), HarnessSchema),
1666
- infrastructure: z.record(z.string(), HarnessSchema)
1658
+ infrastructure: z.record(z.string(), HarnessSchema),
1659
+ serviceHealth: z.record(z.string(), z.strictObject({
1660
+ baseUrl: z.string().url(),
1661
+ healthPath: z.string()
1662
+ })).optional(),
1663
+ manualServices: z.array(z.string()).optional()
1667
1664
  });
1668
1665
  const ProcessStartPayload = z.strictObject({
1669
1666
  execution: ProcessReferenceSchema,
@@ -1687,6 +1684,11 @@ const ProcessCancelResultPayload = ProcessTargetPayload.extend({
1687
1684
  ])
1688
1685
  });
1689
1686
  //#endregion
1687
+ //#region ../contracts/src/templates/template-runtime.ts
1688
+ function templateServices(spec) {
1689
+ return spec.services ?? {};
1690
+ }
1691
+ //#endregion
1690
1692
  //#region ../contracts/src/secrets/credential-slot.ts
1691
1693
  const CredentialSlotSchema = z.strictObject({
1692
1694
  policyRef: z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._/-]{0,254}$/).refine((value) => !value.includes("..")),
@@ -1726,22 +1728,18 @@ const WorkloadInputSchema = z.strictObject({
1726
1728
  //#endregion
1727
1729
  //#region ../contracts/src/templates/template-validation.ts
1728
1730
  function envSources(spec) {
1729
- const sources = [[["spec", "env"], spec.env], [isAgentApiNative(spec) ? [
1730
- "spec",
1731
- "agent",
1732
- "env"
1733
- ] : [
1731
+ const sources = [[["spec", "env"], spec.env], [[
1734
1732
  "spec",
1735
1733
  "harness",
1736
1734
  "env"
1737
- ], agentApiHarness(spec).env]];
1735
+ ], spec.harness.env]];
1738
1736
  for (const [i, step] of spec.setup.entries()) sources.push([[
1739
1737
  "spec",
1740
1738
  "setup",
1741
1739
  i,
1742
1740
  "env"
1743
1741
  ], step.env]);
1744
- if (!isAgentApiNative(spec) && spec.checkpointHook) sources.push([[
1742
+ if (spec.checkpointHook) sources.push([[
1745
1743
  "spec",
1746
1744
  "checkpointHook",
1747
1745
  "env"
@@ -1792,10 +1790,10 @@ function validateServices$1(spec, ctx) {
1792
1790
  ],
1793
1791
  message: "healthPath must be a normalized absolute path"
1794
1792
  });
1795
- validateServiceRoutes(serviceName, service.routes, ctx);
1793
+ validateServiceRoutes$1(serviceName, service.routes, ctx);
1796
1794
  }
1797
1795
  }
1798
- function validateServiceRoutes(serviceName, routes, ctx) {
1796
+ function validateServiceRoutes$1(serviceName, routes, ctx) {
1799
1797
  const seen = /* @__PURE__ */ new Set();
1800
1798
  for (const [index, route] of routes.entries()) {
1801
1799
  if (!isNormalizedPath(route.path)) ctx.addIssue({
@@ -1918,7 +1916,6 @@ function validateTemplatePersistence(spec, ctx) {
1918
1916
  const mounts = spec.persistence.mounts;
1919
1917
  for (const [index, mount] of mounts.entries()) validatePersistenceMount(spec, mounts, mount, index, seenNames, ctx);
1920
1918
  validateSourceMount(spec, mounts, ctx);
1921
- validateAgentStateFile(spec, mounts, ctx);
1922
1919
  if (spec.persistence.conversationRestore === "supported" && (!spec.persistence.sessionCompatibility || mounts.length < 2)) ctx.addIssue({
1923
1920
  code: "custom",
1924
1921
  path: [
@@ -1929,43 +1926,6 @@ function validateTemplatePersistence(spec, ctx) {
1929
1926
  message: "supported conversation restore requires sessionCompatibility and a separate harness-state mount"
1930
1927
  });
1931
1928
  }
1932
- function validateAgentStateFile(spec, mounts, ctx) {
1933
- if (!spec.agent) return;
1934
- const stateFile = spec.agent.stateFile;
1935
- const normalized = stateFile !== void 0 && isNormalizedFilesystemPath(stateFile);
1936
- if (stateFile !== void 0 && !normalized) ctx.addIssue({
1937
- code: "custom",
1938
- path: [
1939
- "spec",
1940
- "agent",
1941
- "stateFile"
1942
- ],
1943
- message: "stateFile must be a normalized absolute filesystem path"
1944
- });
1945
- if (spec.agent.transport === "acp" && spec.persistence.conversationRestore === "supported") {
1946
- ctx.addIssue({
1947
- code: "custom",
1948
- path: [
1949
- "spec",
1950
- "persistence",
1951
- "conversationRestore"
1952
- ],
1953
- message: "supported conversation restore requires PTY transport"
1954
- });
1955
- return;
1956
- }
1957
- if (spec.persistence.conversationRestore !== "supported") return;
1958
- if (normalized && mounts.some((mount) => stateFile.startsWith(`${mount.target}/`))) return;
1959
- ctx.addIssue({
1960
- code: "custom",
1961
- path: [
1962
- "spec",
1963
- "agent",
1964
- "stateFile"
1965
- ],
1966
- message: "supported conversation restore requires agent.stateFile below a persistence mount"
1967
- });
1968
- }
1969
1929
  function validatePersistenceMount(spec, mounts, mount, index, seenNames, ctx) {
1970
1930
  const path = [
1971
1931
  "spec",
@@ -2107,7 +2067,7 @@ function validateAdapters(spec, issue) {
2107
2067
  const path = ["adapters", name];
2108
2068
  if (adapter.kind === "service") {
2109
2069
  if (!adapter.service || !Object.hasOwn(spec.services, adapter.service) || adapter.command) issue(path, "service adapters require a declared service and no process command");
2110
- } else if (!adapter.command || adapter.service) issue(path, "process, Pi and AgentAPI adapters require a command and no service reference");
2070
+ } else if (!adapter.command || adapter.service) issue(path, "process and Pi adapters require a command and no service reference");
2111
2071
  }
2112
2072
  }
2113
2073
  function validateProcessEnvironment(spec, issue) {
@@ -2163,16 +2123,24 @@ function validateOperations(spec, issue) {
2163
2123
  "adapter"
2164
2124
  ], "operation must name a pinned adapter");
2165
2125
  if (spec.profile === "cloud-interactive" && adapter?.kind === "process") issue(["operations", name], "cloud-interactive requires request-aware adapters");
2166
- for (const root of operation.outputRoots) if (!isWorkloadPath(root) || [
2126
+ validateOutputRoots(spec, name, operation.outputRoots, issue);
2127
+ }
2128
+ }
2129
+ function validateOutputRoots(spec, name, roots, issue) {
2130
+ const path = [
2131
+ "operations",
2132
+ name,
2133
+ "outputRoots"
2134
+ ];
2135
+ for (const root of roots) {
2136
+ if (!isWorkloadPath(root) || [
2167
2137
  "/run",
2168
2138
  "/proc",
2169
2139
  "/sys",
2170
2140
  "/dev"
2171
- ].some((path) => overlaps(path, root))) issue([
2172
- "operations",
2173
- name,
2174
- "outputRoots"
2175
- ], "output roots must be normalized and outside protected storage");
2141
+ ].some((base) => overlaps(base, root))) issue(path, "output roots must be normalized and outside protected storage");
2142
+ if (spec.lifecycle?.persistence.mounts.some((mount) => overlaps(mount.target, root))) issue(path, "output roots must not overlap checkpoint storage");
2143
+ if (roots.some((other) => other !== root && overlaps(root, other))) issue(path, "output roots must not overlap");
2176
2144
  }
2177
2145
  }
2178
2146
  function serviceUrl(value) {
@@ -2191,27 +2159,32 @@ function isLoopbackService(url) {
2191
2159
  }
2192
2160
  function validateServices(spec, issue) {
2193
2161
  for (const [name, service] of Object.entries(spec.services)) {
2162
+ if (service.autostart === false && service.required) issue(["services", name], "manual services cannot be required for initial readiness");
2194
2163
  const url = serviceUrl(service.baseUrl);
2195
2164
  if (!url || !isLoopbackService(url)) {
2196
2165
  issue(["services", name], "service must use loopback HTTP without credentials or a path");
2197
2166
  continue;
2198
2167
  }
2199
- const routes = /* @__PURE__ */ new Set();
2200
- if (!isNormalizedPath(service.healthPath)) issue([
2168
+ validateServiceRoutes(name, service, issue);
2169
+ const privateTransport = Object.values(spec.adapters).some((adapter) => adapter.service === name);
2170
+ for (const [previewName, preview] of Object.entries(spec.previews)) if (privateTransport && preview.port === Number(url.port || 80)) issue(["previews", previewName], "preview port is reserved by a service");
2171
+ }
2172
+ }
2173
+ function validateServiceRoutes(name, service, issue) {
2174
+ const routes = /* @__PURE__ */ new Set();
2175
+ if (!isNormalizedPath(service.healthPath)) issue([
2176
+ "services",
2177
+ name,
2178
+ "healthPath"
2179
+ ], "health path must be normalized");
2180
+ for (const route of service.routes) {
2181
+ const key = `${route.method} ${route.path}`;
2182
+ if (!isNormalizedPath(route.path) || routes.has(key)) issue([
2201
2183
  "services",
2202
2184
  name,
2203
- "healthPath"
2204
- ], "health path must be normalized");
2205
- for (const route of service.routes) {
2206
- const key = `${route.method} ${route.path}`;
2207
- if (!isNormalizedPath(route.path) || routes.has(key)) issue([
2208
- "services",
2209
- name,
2210
- "routes"
2211
- ], "routes must be normalized and unique");
2212
- routes.add(key);
2213
- }
2214
- for (const [previewName, preview] of Object.entries(spec.previews)) if (preview.port === Number(url.port || 80)) issue(["previews", previewName], "preview port is reserved by a service");
2185
+ "routes"
2186
+ ], "routes must be normalized and unique");
2187
+ routes.add(key);
2215
2188
  }
2216
2189
  }
2217
2190
  function validateWorkloadTemplate(manifest, ctx) {
@@ -2242,8 +2215,7 @@ const WorkloadAdapterSchema = z.strictObject({
2242
2215
  kind: z.enum([
2243
2216
  "process",
2244
2217
  "service",
2245
- "pi",
2246
- "agentapi"
2218
+ "pi"
2247
2219
  ]),
2248
2220
  digest: WorkloadDigestSchema,
2249
2221
  protocol: z.string().min(1).max(128),
@@ -2268,11 +2240,15 @@ const WorkloadTemplateSchema = z.strictObject({
2268
2240
  spec: z.strictObject({
2269
2241
  version: z.string().regex(/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/),
2270
2242
  image: WorkloadImageSchema,
2243
+ imagePullSecret: RuntimeTemplatePolicySchema.shape.imagePullSecret,
2271
2244
  runtime: WorkloadRuntimePinSchema,
2272
2245
  profile: WorkloadProfileSchema,
2273
2246
  adapters: z.record(WorkloadNameSchema, WorkloadAdapterSchema),
2274
2247
  operations: z.record(WorkloadNameSchema, WorkloadOperationSchema),
2275
- services: z.record(WorkloadNameSchema, ServiceSchema.extend({ process: HarnessSchema.strict().optional() }).strict()),
2248
+ services: z.record(WorkloadNameSchema, ServiceSchema.extend({
2249
+ process: HarnessSchema.strict().optional(),
2250
+ autostart: z.boolean().optional()
2251
+ }).strict()),
2276
2252
  previews: PreviewsSchema,
2277
2253
  credentialSlots: z.record(WorkloadNameSchema, CredentialSlotSchema),
2278
2254
  resources: ResourcesSchema.strict(),
@@ -2299,65 +2275,6 @@ const WorkloadTemplateSnapshotSchema = z.strictObject({
2299
2275
  message: "snapshot identity does not match its immutable manifest"
2300
2276
  });
2301
2277
  });
2302
- //#endregion
2303
- //#region ../contracts/src/templates/template-runtime.ts
2304
- const LEGACY_AGENTAPI_SERVICE = ServiceSchema.parse({
2305
- baseUrl: "http://127.0.0.1:3284",
2306
- routes: [
2307
- {
2308
- method: "GET",
2309
- path: "/status"
2310
- },
2311
- {
2312
- method: "GET",
2313
- path: "/messages",
2314
- query: ["after"]
2315
- },
2316
- {
2317
- method: "POST",
2318
- path: "/message"
2319
- }
2320
- ]
2321
- });
2322
- const AGENTAPI_SERVICE = ServiceSchema.parse({
2323
- ...LEGACY_AGENTAPI_SERVICE,
2324
- routes: [...LEGACY_AGENTAPI_SERVICE.routes, {
2325
- method: "GET",
2326
- path: "/events",
2327
- responseMode: "stream",
2328
- maxResponseBytes: 4194304,
2329
- deadlineSeconds: 300
2330
- }]
2331
- });
2332
- function isAgentApiNative(spec) {
2333
- return "agent" in spec && spec.agent !== void 0;
2334
- }
2335
- function agentApiHarness(spec) {
2336
- if (!isAgentApiNative(spec)) {
2337
- if (!spec.harness) throw new Error("A workload infrastructure process is not an alpha harness.");
2338
- return spec.harness;
2339
- }
2340
- return {
2341
- command: [
2342
- "/usr/local/bin/agentapi",
2343
- "server",
2344
- "--type",
2345
- spec.agent.type,
2346
- ...spec.agent.transport === "acp" ? ["--experimental-acp"] : [],
2347
- ...spec.agent.termWidth === void 0 ? [] : ["--term-width", String(spec.agent.termWidth)],
2348
- ...spec.agent.stateFile === void 0 ? [] : ["--state-file", spec.agent.stateFile],
2349
- "--port",
2350
- "3284",
2351
- "--",
2352
- ...spec.agent.command
2353
- ],
2354
- env: spec.agent.env,
2355
- ...spec.agent.cwd ? { cwd: spec.agent.cwd } : {}
2356
- };
2357
- }
2358
- function templateServices(spec) {
2359
- return isAgentApiNative(spec) ? { agent: AGENTAPI_SERVICE } : spec.services ?? {};
2360
- }
2361
2278
  z.object({
2362
2279
  name: z.string(),
2363
2280
  version: z.string(),
@@ -2427,7 +2344,6 @@ const CheckpointUploadStatusPayload = z.object({
2427
2344
  const SOURCE_CREDENTIAL_MAX_BYTES = 65536;
2428
2345
  const RestoreModeSchema = z.enum(["provider_installed", "controller_archive"]);
2429
2346
  const ExecSpecSchema = z.object({
2430
- agentapi_native: z.boolean().default(false),
2431
2347
  setup: z.array(SetupStepSchema),
2432
2348
  harness: HarnessSchema.nullable(),
2433
2349
  workload: WaitingRuntimeSpecSchema.optional(),
@@ -2704,7 +2620,8 @@ const EnvelopeBase = z.object({
2704
2620
  z.literal(10),
2705
2621
  z.literal(11),
2706
2622
  z.literal(12),
2707
- z.literal(13)
2623
+ z.literal(13),
2624
+ z.literal(14)
2708
2625
  ]),
2709
2626
  workspace_id: z.uuid(),
2710
2627
  connection_id: z.uuid(),
@@ -2718,25 +2635,17 @@ const RegisteredPayload = z.object({
2718
2635
  version: z.string(),
2719
2636
  digest: z.string()
2720
2637
  }),
2721
- agentapi_version: z.string().optional(),
2722
2638
  services: z.array(z.string()),
2723
2639
  pid: z.number().int().positive()
2724
2640
  });
2725
- const HeartbeatPayload = z.object({
2726
- child: z.enum([
2727
- "starting",
2728
- "setup",
2729
- "waiting",
2730
- "running",
2731
- "exited",
2732
- "terminating"
2733
- ]),
2734
- agentapi_state: z.enum([
2735
- "unknown",
2736
- "stable",
2737
- "running"
2738
- ]).optional()
2739
- });
2641
+ const HeartbeatPayload = z.object({ child: z.enum([
2642
+ "starting",
2643
+ "setup",
2644
+ "waiting",
2645
+ "running",
2646
+ "exited",
2647
+ "terminating"
2648
+ ]) });
2740
2649
  const ProcessStatePayload = z.object({
2741
2650
  phase: z.enum([
2742
2651
  "starting",
@@ -3139,194 +3048,758 @@ z.strictObject({
3139
3048
  root: fileIdentity,
3140
3049
  lock: fileIdentity
3141
3050
  });
3142
- z.strictObject({ manifest: z.union([TemplateManifestSchema, WorkloadTemplateSchema]) });
3143
- z.object({
3144
- name: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/),
3145
- version: z.string().min(1).max(256)
3051
+ //#endregion
3052
+ //#region ../contracts/src/budgets/policy.ts
3053
+ const BudgetPolicyWriteSchema = z.strictObject({
3054
+ scopeId: z.uuid(),
3055
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3056
+ period: z.enum(["utc_day", "utc_month"]),
3057
+ limits: z.strictObject({
3058
+ workspaceStarts: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).nullable(),
3059
+ maxActiveWorkspaces: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).nullable(),
3060
+ maxRunningRequestsPerSession: z.literal(1),
3061
+ maxChatProcessesPerWorkspace: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER)
3062
+ })
3146
3063
  });
3147
- z.strictObject({
3064
+ const BudgetPolicySchema = BudgetPolicyWriteSchema.extend({ effectiveAt: z.iso.datetime({ offset: true }) });
3065
+ //#endregion
3066
+ //#region ../contracts/src/budgets/usage.ts
3067
+ const BudgetUsageSchema = z.strictObject({
3068
+ scopeId: z.uuid(),
3069
+ policyRevision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3070
+ periodStart: z.iso.datetime({ offset: true }),
3071
+ periodEnd: z.iso.datetime({ offset: true }),
3072
+ workspaceStarts: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
3073
+ activeWorkspaces: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
3074
+ asOf: z.iso.datetime({ offset: true })
3075
+ });
3076
+ const CleanupReceiptFieldsSchema = z.strictObject({
3077
+ workspaceId: z.uuid(),
3078
+ generationId: z.string().min(1).max(256),
3079
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3080
+ state: z.enum(["pending", "proved"]),
3081
+ basis: z.enum([
3082
+ "never_launched",
3083
+ "processes_exited",
3084
+ "provider_fenced"
3085
+ ]).nullable(),
3086
+ observedAt: z.iso.datetime({ offset: true }),
3087
+ capacityReleasedAt: z.iso.datetime({ offset: true }).nullable()
3088
+ });
3089
+ const CleanupReceiptSchema = z.union([CleanupReceiptFieldsSchema.extend({
3090
+ state: z.literal("pending"),
3091
+ basis: z.null(),
3092
+ capacityReleasedAt: z.null()
3093
+ }), CleanupReceiptFieldsSchema.extend({
3094
+ state: z.literal("proved"),
3095
+ basis: z.enum([
3096
+ "never_launched",
3097
+ "processes_exited",
3098
+ "provider_fenced"
3099
+ ])
3100
+ })]);
3101
+ //#endregion
3102
+ //#region ../contracts/src/workspaces/lifetime.ts
3103
+ const LifetimeExtensionSchema = z.strictObject({
3104
+ extensionId: z.uuid(),
3105
+ expectedRevision: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
3106
+ deadlineAt: z.iso.datetime()
3107
+ });
3108
+ const LifetimeReceiptSchema = LifetimeExtensionSchema.extend({
3109
+ workspaceId: z.uuid(),
3110
+ revision: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
3111
+ ceilingAt: z.iso.datetime()
3112
+ });
3113
+ //#endregion
3114
+ //#region ../contracts/src/workspaces/service-control.ts
3115
+ const ServiceStartSchema = z.strictObject({ startId: z.uuid() });
3116
+ const ServiceReceiptSchema = z.strictObject({
3148
3117
  workspaceId: z.uuid(),
3149
3118
  incarnationId: z.string().min(1).max(256),
3150
- profiles: z.array(WorkloadProfileSchema),
3151
- storageProfiles: z.array(z.enum(["controller-readonly/v1", "shared-writer-readonly/v1"])),
3152
- ceilings: WorkloadLimitsSchema,
3153
- now: z.iso.datetime(),
3154
- expiresAt: z.iso.datetime(),
3155
- installed: InstalledWorkloadSchema.optional()
3119
+ name: z.string().regex(/^[a-z][a-z0-9-]{0,62}$/),
3120
+ startId: z.uuid().nullable(),
3121
+ attemptId: z.uuid().nullable(),
3122
+ state: z.enum([
3123
+ "stopped",
3124
+ "starting",
3125
+ "running",
3126
+ "exited",
3127
+ "lost"
3128
+ ]),
3129
+ pid: z.number().int().positive().nullable(),
3130
+ exitCode: z.number().int().nullable(),
3131
+ listener: z.enum([
3132
+ "unknown",
3133
+ "healthy",
3134
+ "unhealthy"
3135
+ ])
3156
3136
  });
3157
3137
  //#endregion
3158
- //#region ../contracts/src/workspaces/execution-dispatch.ts
3159
- const ExecutionPhaseSchema = z.enum([
3160
- "accepted",
3161
- "dispatching",
3162
- "running",
3163
- "terminal",
3164
- "canceled",
3165
- "unknown",
3166
- "lost"
3167
- ]);
3168
- z.strictObject({
3169
- acceptance: WorkloadAcceptanceSchema,
3170
- conversationIdentity: ConversationRequestIdentitySchema.nullable(),
3171
- outcome: JsonValueSchema.nullable(),
3172
- acceptedAt: z.iso.datetime(),
3173
- dispatchClaimedAt: z.iso.datetime().nullable(),
3174
- phase: ExecutionPhaseSchema,
3175
- cancel: z.strictObject({
3176
- cancelId: z.uuid(),
3177
- requestedAt: z.iso.datetime()
3178
- }).nullable(),
3179
- settledAt: z.iso.datetime().nullable(),
3180
- acknowledgedAt: z.iso.datetime().nullable(),
3181
- finalizedAt: z.iso.datetime().nullable()
3138
+ //#region ../contracts/src/sessions/files.ts
3139
+ const MAX_SESSION_FILE_REFERENCES = 1e3;
3140
+ const InputReferenceSchema = z.strictObject({
3141
+ inputId: z.uuid(),
3142
+ versionId: z.uuid(),
3143
+ sha256: z.string().regex(/^sha256:[a-f0-9]{64}$/),
3144
+ name: z.string().min(1).max(255),
3145
+ mediaType: AttachmentMediaTypeSchema,
3146
+ sizeBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER)
3182
3147
  });
3183
- z.strictObject({
3184
- acceptance: WorkloadAcceptanceSchema,
3185
- conversationIdentity: ConversationRequestIdentitySchema.optional()
3186
- }).refine(({ acceptance, conversationIdentity }) => acceptance.execution.owner !== "conversation-request" || conversationIdentity !== void 0, {
3187
- path: ["conversationIdentity"],
3188
- message: "Conversation execution requires a conversation identity."
3148
+ const InputUploadSchema = z.strictObject({
3149
+ inputId: z.uuid(),
3150
+ name: z.string().min(1).max(255),
3151
+ mediaType: AttachmentMediaTypeSchema,
3152
+ sizeBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
3153
+ sha256: z.string().regex(/^sha256:[a-f0-9]{64}$/)
3189
3154
  });
3190
- WorkloadCancelSchema.refine((cancel) => cancel.scope === "operation", { message: "Use workspace release for workspace cancellation" });
3191
- z.strictObject({
3192
- workspaceId: z.uuid(),
3193
- callerPrincipalId: z.uuid(),
3194
- incarnationId: z.string().min(1),
3195
- template: WorkloadTemplateSnapshotSchema,
3196
- producer: InstalledWorkloadSchema,
3197
- readyAt: z.iso.datetime().nullable(),
3198
- endedAt: z.iso.datetime().nullable()
3155
+ const InputObjectSchema = z.strictObject({
3156
+ sessionId: z.uuid(),
3157
+ reference: InputReferenceSchema,
3158
+ state: z.enum([
3159
+ "uploading",
3160
+ "ready",
3161
+ "rejected",
3162
+ "expired"
3163
+ ]),
3164
+ expiresAt: z.iso.datetime({ offset: true })
3199
3165
  });
3200
- z.discriminatedUnion("phase", [z.strictObject({
3201
- execution: WorkloadExecutionReferenceSchema,
3202
- phase: z.literal("absent")
3203
- }), z.strictObject({
3204
- execution: WorkloadExecutionReferenceSchema,
3205
- fingerprint: WorkloadDigestSchema,
3206
- phase: z.enum([
3166
+ const ExportObjectSchema = z.strictObject({
3167
+ exportId: z.uuid(),
3168
+ sessionId: z.uuid(),
3169
+ requestId: z.uuid(),
3170
+ versionId: z.uuid(),
3171
+ sha256: z.string().regex(/^sha256:[a-f0-9]{64}$/),
3172
+ name: z.string().min(1).max(255),
3173
+ mediaType: AttachmentMediaTypeSchema,
3174
+ sizeBytes: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER),
3175
+ completeness: z.enum(["complete", "partial"]),
3176
+ availability: z.enum([
3177
+ "published",
3178
+ "expired",
3179
+ "unavailable"
3180
+ ]),
3181
+ expiresAt: z.iso.datetime({ offset: true })
3182
+ });
3183
+ //#endregion
3184
+ //#region ../contracts/src/sessions/collection.ts
3185
+ const fields = z.strictObject({
3186
+ sessionId: z.uuid(),
3187
+ requestId: z.uuid(),
3188
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3189
+ state: z.enum([
3190
+ "pending",
3191
+ "finalizing",
3192
+ "settled"
3193
+ ]),
3194
+ completeness: z.enum([
3195
+ "complete",
3196
+ "partial",
3197
+ "lost"
3198
+ ]).nullable(),
3199
+ manifestDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/).nullable(),
3200
+ objects: z.array(ExportObjectSchema).max(MAX_SESSION_FILE_REFERENCES),
3201
+ errors: z.array(z.string().min(1).max(512)).max(100),
3202
+ settledAt: z.iso.datetime({ offset: true }).nullable(),
3203
+ expiresAt: z.iso.datetime({ offset: true }).nullable(),
3204
+ cleanupState: z.enum([
3205
+ "not_required",
3206
+ "pending",
3207
+ "complete"
3208
+ ])
3209
+ });
3210
+ const CollectionResultSchema = z.union([fields.extend({
3211
+ state: z.enum(["pending", "finalizing"]),
3212
+ completeness: z.null(),
3213
+ manifestDigest: z.null(),
3214
+ settledAt: z.null(),
3215
+ expiresAt: z.null()
3216
+ }), fields.extend({
3217
+ state: z.literal("settled"),
3218
+ completeness: z.enum([
3219
+ "complete",
3220
+ "partial",
3221
+ "lost"
3222
+ ]),
3223
+ manifestDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),
3224
+ settledAt: z.iso.datetime({ offset: true }),
3225
+ expiresAt: z.iso.datetime({ offset: true })
3226
+ })]).superRefine((value, ctx) => {
3227
+ if (value.completeness && value.completeness === "complete" !== (value.errors.length === 0)) ctx.addIssue({
3228
+ code: "custom",
3229
+ path: ["errors"],
3230
+ message: "Collection errors must agree with completeness"
3231
+ });
3232
+ for (const object of value.objects) if (object.sessionId !== value.sessionId || object.requestId !== value.requestId) ctx.addIssue({
3233
+ code: "custom",
3234
+ path: ["objects"],
3235
+ message: "Collection object owner mismatch"
3236
+ });
3237
+ });
3238
+ //#endregion
3239
+ //#region ../contracts/src/sessions/profile.ts
3240
+ const ExecutionProfileSchema = z.strictObject({
3241
+ profileId: z.uuid(),
3242
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3243
+ isolationScopeId: z.uuid(),
3244
+ budgetScopeIds: z.array(z.uuid()).min(1).max(1e3).refine((items) => new Set(items).size === items.length, "Values must be unique"),
3245
+ templateDigest: z.string().regex(/^sha256:[a-f0-9]{64}$/),
3246
+ credentialBindingId: z.uuid().nullable()
3247
+ });
3248
+ const SessionCreateSchema = z.strictObject({
3249
+ sessionId: z.uuid(),
3250
+ profileId: z.uuid(),
3251
+ profileRevision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER)
3252
+ });
3253
+ const SessionSchema = z.strictObject({
3254
+ sessionId: z.uuid(),
3255
+ profileId: z.uuid(),
3256
+ profileRevision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3257
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3258
+ state: z.enum([
3259
+ "provisioning",
3260
+ "ready",
3261
+ "suspended",
3262
+ "closed",
3263
+ "failed"
3264
+ ]),
3265
+ reasonCode: z.string().min(1).max(256).nullable(),
3266
+ createdAt: z.iso.datetime({ offset: true }),
3267
+ updatedAt: z.iso.datetime({ offset: true })
3268
+ });
3269
+ //#endregion
3270
+ //#region ../contracts/src/sessions/request.ts
3271
+ const RequestInputSchema = z.strictObject({
3272
+ requestId: z.uuid(),
3273
+ message: z.string().min(1).max(262144).refine((value) => value.isWellFormed(), "Message must contain valid Unicode").refine((value) => new TextEncoder().encode(value).length <= 262144, "Message exceeds 256 KiB UTF-8"),
3274
+ attachments: z.array(InputReferenceSchema).max(MAX_SESSION_FILE_REFERENCES),
3275
+ dispatchDeadline: z.iso.datetime({ offset: true })
3276
+ });
3277
+ const RequestFieldsSchema = z.strictObject({
3278
+ sessionId: z.uuid(),
3279
+ requestId: z.uuid(),
3280
+ turnId: z.uuid(),
3281
+ inputFingerprint: z.string().regex(/^sha256:[a-f0-9]{64}$/),
3282
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3283
+ state: z.enum([
3207
3284
  "accepted",
3285
+ "waiting",
3208
3286
  "running",
3209
- "terminal",
3210
- "canceled"
3287
+ "checking_outcome",
3288
+ "terminal"
3211
3289
  ]),
3212
- outcome: JsonValueSchema.nullable()
3213
- })]);
3214
- WorkloadCancelSchema.extend({ fingerprint: WorkloadDigestSchema });
3215
- //#endregion
3216
- //#region src/resources/admin/admin.ts
3217
- var AdministrationApi = class {
3218
- transport;
3219
- constructor(transport) {
3220
- this.transport = transport;
3221
- }
3222
- warmPools(options = {}) {
3223
- return this.transport.request("/v1/warm-pools", WarmPoolInventorySchema, options);
3224
- }
3225
- storageInventory(options = {}) {
3226
- return this.transport.request("/v1/storage/inventory", StorageInventorySchema, options);
3227
- }
3228
- pruneStorage(options = {}) {
3229
- return this.transport.request("/v1/storage/prune", StoragePruneResultSchema, {
3230
- method: "POST",
3231
- signal: options.signal
3232
- });
3233
- }
3234
- };
3290
+ outcome: z.enum([
3291
+ "completed",
3292
+ "failed",
3293
+ "canceled",
3294
+ "interrupted",
3295
+ "lost"
3296
+ ]).nullable(),
3297
+ reasonCode: z.string().min(1).max(256).nullable(),
3298
+ acceptedAt: z.iso.datetime({ offset: true }),
3299
+ startedAt: z.iso.datetime({ offset: true }).nullable(),
3300
+ endedAt: z.iso.datetime({ offset: true }).nullable(),
3301
+ dispatchDeadline: z.iso.datetime({ offset: true }),
3302
+ collection: CollectionResultSchema,
3303
+ finalResponse: z.string().max(1048576).nullable()
3304
+ });
3305
+ const RequestSchema = z.union([RequestFieldsSchema.extend({
3306
+ state: z.literal("terminal"),
3307
+ outcome: z.enum([
3308
+ "completed",
3309
+ "failed",
3310
+ "canceled",
3311
+ "interrupted",
3312
+ "lost"
3313
+ ])
3314
+ }), RequestFieldsSchema.extend({
3315
+ state: z.enum([
3316
+ "accepted",
3317
+ "waiting",
3318
+ "running",
3319
+ "checking_outcome"
3320
+ ]),
3321
+ outcome: z.null(),
3322
+ endedAt: z.null()
3323
+ })]).superRefine((request, ctx) => {
3324
+ if (request.sessionId !== request.collection.sessionId || request.requestId !== request.collection.requestId) ctx.addIssue({
3325
+ code: "custom",
3326
+ path: ["collection"],
3327
+ message: "Collection owner mismatch"
3328
+ });
3329
+ });
3330
+ const CancelCommandSchema = z.strictObject({ cancelId: z.uuid() });
3331
+ const CancelReceiptFieldsSchema = z.strictObject({
3332
+ sessionId: z.uuid(),
3333
+ requestId: z.uuid().nullable(),
3334
+ cancelId: z.uuid(),
3335
+ scope: z.enum(["request", "session"]),
3336
+ state: z.enum(["pending", "completed"]),
3337
+ acceptedAt: z.iso.datetime({ offset: true }),
3338
+ completedAt: z.iso.datetime({ offset: true }).nullable(),
3339
+ cancelDeadline: z.iso.datetime({ offset: true })
3340
+ });
3341
+ const CancelReceiptSchema = z.union([CancelReceiptFieldsSchema.extend({
3342
+ scope: z.literal("request"),
3343
+ requestId: z.uuid()
3344
+ }), CancelReceiptFieldsSchema.extend({
3345
+ scope: z.literal("session"),
3346
+ requestId: z.null()
3347
+ })]).superRefine((receipt, ctx) => {
3348
+ if (receipt.state === "completed" !== (receipt.completedAt !== null)) ctx.addIssue({
3349
+ code: "custom",
3350
+ path: ["completedAt"],
3351
+ message: "Completion time must agree with state"
3352
+ });
3353
+ });
3235
3354
  //#endregion
3236
- //#region src/transport/errors.ts
3237
- z.enum(["client.non_json_response", "client.invalid_response"]);
3238
- var PocketCoderError = class extends Error {
3239
- code;
3240
- status;
3241
- requestId;
3242
- details;
3243
- constructor(input) {
3244
- super(input.message);
3245
- this.name = "PocketCoderError";
3246
- this.code = input.code;
3247
- this.status = input.status;
3248
- this.requestId = input.requestId;
3249
- this.details = input.details;
3250
- }
3355
+ //#region ../contracts/src/sessions/event.ts
3356
+ const RuntimeEventFieldsSchema = z.strictObject({
3357
+ eventId: z.uuid(),
3358
+ cursor: z.string().min(1).max(256),
3359
+ sessionId: z.uuid(),
3360
+ requestId: z.uuid().nullable(),
3361
+ sequence: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3362
+ revision: z.number().int().min(1).max(Number.MAX_SAFE_INTEGER),
3363
+ occurredAt: z.iso.datetime({ offset: true }).nullable(),
3364
+ recordedAt: z.iso.datetime({ offset: true }),
3365
+ kind: z.enum([
3366
+ "session.updated",
3367
+ "request.updated",
3368
+ "output.published"
3369
+ ]),
3370
+ data: z.union([
3371
+ SessionSchema,
3372
+ RequestSchema,
3373
+ ExportObjectSchema
3374
+ ])
3375
+ });
3376
+ const RuntimeEventSchema = z.discriminatedUnion("kind", [
3377
+ RuntimeEventFieldsSchema.extend({
3378
+ kind: z.literal("session.updated"),
3379
+ requestId: z.null(),
3380
+ data: SessionSchema
3381
+ }),
3382
+ RuntimeEventFieldsSchema.extend({
3383
+ kind: z.literal("request.updated"),
3384
+ requestId: z.uuid(),
3385
+ data: RequestSchema
3386
+ }),
3387
+ RuntimeEventFieldsSchema.extend({
3388
+ kind: z.literal("output.published"),
3389
+ requestId: z.uuid(),
3390
+ data: ExportObjectSchema
3391
+ })
3392
+ ]).superRefine((event, ctx) => {
3393
+ if (event.sessionId !== event.data.sessionId) ctx.addIssue({
3394
+ code: "custom",
3395
+ path: ["sessionId"],
3396
+ message: "Session identity mismatch"
3397
+ });
3398
+ if (event.kind !== "session.updated" && event.requestId !== event.data.requestId) ctx.addIssue({
3399
+ code: "custom",
3400
+ path: ["requestId"],
3401
+ message: "Request identity mismatch"
3402
+ });
3403
+ if (event.kind !== "output.published" && event.revision !== event.data.revision) ctx.addIssue({
3404
+ code: "custom",
3405
+ path: ["revision"],
3406
+ message: "Resource revision mismatch"
3407
+ });
3408
+ });
3409
+ const ErrorSchema = z.strictObject({ error: z.strictObject({
3410
+ code: z.string().min(1).max(256),
3411
+ message: z.string().max(512),
3412
+ retry: z.enum([
3413
+ "never",
3414
+ "same_identity",
3415
+ "after_capacity_change",
3416
+ "reconcile"
3417
+ ]),
3418
+ retryAfterSeconds: z.number().int().min(0).max(Number.MAX_SAFE_INTEGER).nullable(),
3419
+ requestId: z.uuid().nullable()
3420
+ }) });
3421
+ //#endregion
3422
+ //#region ../contracts/src/sessions/fingerprint.ts
3423
+ const LogicalRequestInputSchema = RequestInputSchema.extend({
3424
+ sessionId: z.uuid(),
3425
+ profileId: z.uuid(),
3426
+ profileRevision: z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
3427
+ }).superRefine((input, ctx) => {
3428
+ for (const [index, attachment] of input.attachments.entries()) for (const field of ["name", "mediaType"]) if (!attachment[field].isWellFormed()) ctx.addIssue({
3429
+ code: "custom",
3430
+ path: [
3431
+ "attachments",
3432
+ index,
3433
+ field
3434
+ ],
3435
+ message: "Invalid Unicode"
3436
+ });
3437
+ });
3438
+ function fingerprintRequest(input) {
3439
+ return digestOf(LogicalRequestInputSchema.parse(input));
3440
+ }
3441
+ //#endregion
3442
+ //#region ../contracts/src/sessions/pages.ts
3443
+ const ManagedHistoryQuerySchema = z.strictObject({
3444
+ cursor: z.string().min(1).max(4096).optional(),
3445
+ limit: z.number().int().min(1).max(200).optional()
3446
+ });
3447
+ const ManagedHistoryPageSchema = z.strictObject({
3448
+ records: z.array(ConversationRecordDocumentSchema),
3449
+ nextCursor: z.string().min(1).max(4096).nullable(),
3450
+ eventCursor: z.string().min(1).max(4096)
3451
+ });
3452
+ const ManagedExportPageSchema = z.strictObject({
3453
+ items: z.array(ExportObjectSchema),
3454
+ nextCursor: z.string().min(1).max(4096).nullable()
3455
+ });
3456
+ //#endregion
3457
+ //#region ../contracts/src/sessions/placement.ts
3458
+ function managedPlacement(principalId, sessionId, input) {
3459
+ const profile = ExecutionProfileSchema.parse(input);
3460
+ const mode = profile.credentialBindingId === null ? "shared" : "exclusive";
3461
+ return {
3462
+ mode,
3463
+ key: digestOf({
3464
+ principalId,
3465
+ profile,
3466
+ sessionId: mode === "exclusive" ? sessionId : null
3467
+ })
3468
+ };
3469
+ }
3470
+ const MANAGED_SESSION_METADATA = "pocketcoder.managed-session";
3471
+ //#endregion
3472
+ //#region ../contracts/src/sessions/provisioning.ts
3473
+ const BudgetScopeGrantSchema = z.strictObject({
3474
+ principalId: z.uuid(),
3475
+ installation: z.boolean()
3476
+ });
3477
+ const CredentialBindingSchema = z.strictObject({
3478
+ bindingId: z.uuid(),
3479
+ principalId: z.uuid(),
3480
+ secretName: z.string().min(1).max(128),
3481
+ secretVersionId: z.uuid().optional(),
3482
+ slots: z.array(z.string().min(1).max(128)).min(1).max(100),
3483
+ authorityExpiresAt: z.iso.datetime({ offset: true })
3484
+ });
3485
+ //#endregion
3486
+ //#region ../contracts/src/sessions/states.ts
3487
+ const requestTransitions = {
3488
+ accepted: [
3489
+ "waiting",
3490
+ "running",
3491
+ "checking_outcome",
3492
+ "terminal"
3493
+ ],
3494
+ waiting: [
3495
+ "running",
3496
+ "checking_outcome",
3497
+ "terminal"
3498
+ ],
3499
+ running: ["checking_outcome", "terminal"],
3500
+ checking_outcome: ["running", "terminal"],
3501
+ terminal: []
3251
3502
  };
3252
- var ConversationGoneError = class extends PocketCoderError {};
3253
- var WorkspaceTerminalError = class extends Error {
3254
- workspace;
3255
- constructor(workspace) {
3256
- const reason = workspace.reason_code ?? workspace.failure?.reason_code ?? "no reason";
3257
- const tail = workspace.failure?.log_tail.trim();
3258
- super([`workspace ${workspace.id} reached ${workspace.state} (${reason})`, ...tail ? [`failure log:\n${tail}`] : []].join("\n"));
3259
- this.name = "WorkspaceTerminalError";
3260
- this.workspace = workspace;
3261
- }
3503
+ const sessionTransitions = {
3504
+ provisioning: [
3505
+ "ready",
3506
+ "suspended",
3507
+ "closed",
3508
+ "failed"
3509
+ ],
3510
+ ready: [
3511
+ "provisioning",
3512
+ "suspended",
3513
+ "closed",
3514
+ "failed"
3515
+ ],
3516
+ suspended: [
3517
+ "provisioning",
3518
+ "closed",
3519
+ "failed"
3520
+ ],
3521
+ closed: [],
3522
+ failed: ["provisioning", "closed"]
3262
3523
  };
3263
- var AgentNotReadyError = class extends Error {
3264
- workspaceId;
3265
- agentState;
3266
- constructor(workspaceId, agentState, timeoutMs) {
3267
- super(`agent in workspace ${workspaceId} was still ${agentState} after ${timeoutMs}ms and cannot accept a message`);
3268
- this.name = "AgentNotReadyError";
3269
- this.workspaceId = workspaceId;
3270
- this.agentState = agentState;
3271
- }
3524
+ const canTransitionRequest = (from, to) => requestTransitions[from].includes(to);
3525
+ const canTransitionSession = (from, to) => sessionTransitions[from].includes(to);
3526
+ const ManagedQueueLimitsSchema = z.strictObject({
3527
+ requests: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),
3528
+ bytes: z.number().int().positive().max(Number.MAX_SAFE_INTEGER)
3529
+ });
3530
+ //#endregion
3531
+ //#region ../contracts/src/sessions/schemas.ts
3532
+ const MANAGED_CONTRACT_REVISION = "pocketcoder.managed/v1";
3533
+ const managedSchemas = {
3534
+ ExecutionProfile: ExecutionProfileSchema,
3535
+ BudgetScopeGrant: BudgetScopeGrantSchema,
3536
+ CredentialBinding: CredentialBindingSchema,
3537
+ SessionCreate: SessionCreateSchema,
3538
+ Session: SessionSchema,
3539
+ InputReference: InputReferenceSchema,
3540
+ InputUpload: InputUploadSchema,
3541
+ InputObject: InputObjectSchema,
3542
+ ExportObject: ExportObjectSchema,
3543
+ CollectionResult: CollectionResultSchema,
3544
+ RequestInput: RequestInputSchema,
3545
+ Request: RequestSchema,
3546
+ CancelCommand: CancelCommandSchema,
3547
+ CancelReceipt: CancelReceiptSchema,
3548
+ RuntimeEvent: RuntimeEventSchema,
3549
+ Error: ErrorSchema,
3550
+ WireError: ErrorEnvelopeSchema,
3551
+ BudgetPolicy: BudgetPolicySchema,
3552
+ BudgetPolicyWrite: BudgetPolicyWriteSchema,
3553
+ BudgetUsage: BudgetUsageSchema,
3554
+ CleanupReceipt: CleanupReceiptSchema,
3555
+ HistoryPage: ManagedHistoryPageSchema,
3556
+ OpenTurns: z.object({ turns: z.array(ConversationLiveEventSchema) }),
3557
+ ExportPage: ManagedExportPageSchema,
3558
+ ServiceStart: ServiceStartSchema,
3559
+ ServiceReceipt: ServiceReceiptSchema,
3560
+ LifetimeExtension: LifetimeExtensionSchema,
3561
+ LifetimeReceipt: LifetimeReceiptSchema,
3562
+ QueueLimits: ManagedQueueLimitsSchema
3272
3563
  };
3273
- function isPocketCoderErrorCode(value) {
3274
- return typeof value === "string" && value in ERROR_CODES;
3275
- }
3276
- function responseError(response, body) {
3277
- const parsed = ErrorEnvelopeSchema.safeParse(body);
3278
- if (!parsed.success) return new PocketCoderError({
3279
- message: `PocketCoder returned an invalid error response (${response.status})`,
3280
- code: "client.invalid_response",
3281
- status: response.status
3282
- });
3283
- const { code, message, request_id: requestId, details } = parsed.data.error;
3284
- return new (code === "conversation.deleted" || code === "conversation.expired" ? ConversationGoneError : PocketCoderError)({
3285
- message,
3286
- code,
3287
- status: response.status,
3288
- requestId,
3289
- details
3564
+ //#endregion
3565
+ //#region ../contracts/src/sessions/index.ts
3566
+ var sessions_exports = /* @__PURE__ */ __exportAll({
3567
+ BudgetPolicySchema: () => BudgetPolicySchema,
3568
+ BudgetPolicyWriteSchema: () => BudgetPolicyWriteSchema,
3569
+ BudgetUsageSchema: () => BudgetUsageSchema,
3570
+ CancelCommandSchema: () => CancelCommandSchema,
3571
+ CancelReceiptSchema: () => CancelReceiptSchema,
3572
+ CleanupReceiptSchema: () => CleanupReceiptSchema,
3573
+ CollectionResultSchema: () => CollectionResultSchema,
3574
+ ErrorSchema: () => ErrorSchema,
3575
+ ExecutionProfileSchema: () => ExecutionProfileSchema,
3576
+ ExportObjectSchema: () => ExportObjectSchema,
3577
+ InputObjectSchema: () => InputObjectSchema,
3578
+ InputReferenceSchema: () => InputReferenceSchema,
3579
+ InputUploadSchema: () => InputUploadSchema,
3580
+ LifetimeExtensionSchema: () => LifetimeExtensionSchema,
3581
+ LifetimeReceiptSchema: () => LifetimeReceiptSchema,
3582
+ LogicalRequestInputSchema: () => LogicalRequestInputSchema,
3583
+ MANAGED_CONTRACT_REVISION: () => MANAGED_CONTRACT_REVISION,
3584
+ MANAGED_SESSION_METADATA: () => MANAGED_SESSION_METADATA,
3585
+ MAX_SESSION_FILE_REFERENCES: () => MAX_SESSION_FILE_REFERENCES,
3586
+ ManagedExportPageSchema: () => ManagedExportPageSchema,
3587
+ ManagedHistoryPageSchema: () => ManagedHistoryPageSchema,
3588
+ ManagedHistoryQuerySchema: () => ManagedHistoryQuerySchema,
3589
+ ManagedQueueLimitsSchema: () => ManagedQueueLimitsSchema,
3590
+ RequestInputSchema: () => RequestInputSchema,
3591
+ RequestSchema: () => RequestSchema,
3592
+ RuntimeEventSchema: () => RuntimeEventSchema,
3593
+ ServiceReceiptSchema: () => ServiceReceiptSchema,
3594
+ ServiceStartSchema: () => ServiceStartSchema,
3595
+ SessionCreateSchema: () => SessionCreateSchema,
3596
+ SessionSchema: () => SessionSchema,
3597
+ canTransitionRequest: () => canTransitionRequest,
3598
+ canTransitionSession: () => canTransitionSession,
3599
+ fingerprintRequest: () => fingerprintRequest,
3600
+ managedPlacement: () => managedPlacement,
3601
+ managedSchemas: () => managedSchemas
3602
+ });
3603
+ //#endregion
3604
+ //#region ../contracts/src/templates/session-template.ts
3605
+ function sessionTemplate(input) {
3606
+ const protocol = "pocketcoder.execution/v1";
3607
+ const { producer } = input;
3608
+ return WorkloadTemplateSchema.parse({
3609
+ apiVersion: "pocketcoder.dev/v1",
3610
+ kind: "Template",
3611
+ metadata: { name: input.name },
3612
+ spec: {
3613
+ version: input.version,
3614
+ image: input.image,
3615
+ profile: "service",
3616
+ runtime: {
3617
+ protocol: "pocketcoder.workload/v1",
3618
+ digest: input.runtimeDigest
3619
+ },
3620
+ adapters: { session: {
3621
+ kind: "service",
3622
+ digest: producer.digest,
3623
+ protocol,
3624
+ service: "session",
3625
+ env: {}
3626
+ } },
3627
+ operations: { message: {
3628
+ adapter: "session",
3629
+ inputSchema: {
3630
+ type: "object",
3631
+ properties: { message: { type: "string" } },
3632
+ required: ["message"],
3633
+ additionalProperties: false
3634
+ },
3635
+ requiredCapabilities: [
3636
+ "request-lookup",
3637
+ "deduplicated-accept",
3638
+ "targeted-cancel"
3639
+ ],
3640
+ outputRoots: []
3641
+ } },
3642
+ services: { session: {
3643
+ ...ServiceSchema.parse({
3644
+ baseUrl: "http://127.0.0.1:3284",
3645
+ healthPath: "/healthz",
3646
+ routes: [
3647
+ "accept",
3648
+ "lookup",
3649
+ "cancel",
3650
+ "ack"
3651
+ ].map((action) => ({
3652
+ method: "POST",
3653
+ path: `/executions/${action}`,
3654
+ maxRequestBytes: 1048576,
3655
+ maxResponseBytes: 8388608,
3656
+ deadlineSeconds: 30
3657
+ }))
3658
+ }),
3659
+ process: {
3660
+ command: producer.command,
3661
+ env: producer.env ?? {},
3662
+ ...producer.cwd ? { cwd: producer.cwd } : {}
3663
+ }
3664
+ } },
3665
+ previews: {},
3666
+ credentialSlots: {},
3667
+ resources: {
3668
+ cpu: "1",
3669
+ memory: "1Gi"
3670
+ },
3671
+ network: { mode: "unrestricted" },
3672
+ security: SecuritySchema.parse({ writableMemoryPaths: ["/tmp"] }),
3673
+ lifecycle: { timeouts: TimeoutsSchema.parse({}) },
3674
+ limits: {
3675
+ deadlineSeconds: 7200,
3676
+ finalizationSeconds: 30,
3677
+ inputFileBytes: 16777216,
3678
+ stagedInputBytes: 67108864,
3679
+ inputFiles: 100,
3680
+ inFlightTransfers: 2,
3681
+ exportBytes: 16777216,
3682
+ exportFiles: 100,
3683
+ unreferencedInputRetentionSeconds: 3600,
3684
+ exportRetentionSeconds: 86400
3685
+ }
3686
+ }
3290
3687
  });
3291
3688
  }
3689
+ z.strictObject({ manifest: z.union([TemplateManifestSchema, WorkloadTemplateSchema]) });
3690
+ z.object({
3691
+ name: z.string().regex(/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/),
3692
+ version: z.string().min(1).max(256)
3693
+ });
3694
+ z.strictObject({
3695
+ workspaceId: z.uuid(),
3696
+ incarnationId: z.string().min(1).max(256),
3697
+ profiles: z.array(WorkloadProfileSchema),
3698
+ storageProfiles: z.array(z.enum(["controller-readonly/v1", "shared-writer-readonly/v1"])),
3699
+ ceilings: WorkloadLimitsSchema,
3700
+ now: z.iso.datetime(),
3701
+ expiresAt: z.iso.datetime(),
3702
+ installed: InstalledWorkloadSchema.optional()
3703
+ });
3704
+ z.strictObject({
3705
+ requestId: z.uuid(),
3706
+ conversationId: z.uuid(),
3707
+ message: z.string().min(1).max(262144),
3708
+ files: z.array(InputObjectReferenceSchema).max(1e3)
3709
+ });
3292
3710
  //#endregion
3293
- //#region src/resources/agent/agent.ts
3294
- const DEFAULT_READY_TIMEOUT_MS = 12e4;
3295
- var AgentApi = class {
3711
+ //#region ../contracts/src/workspaces/execution-dispatch.ts
3712
+ const ExecutionPhaseSchema = z.enum([
3713
+ "accepted",
3714
+ "dispatching",
3715
+ "running",
3716
+ "terminal",
3717
+ "canceled",
3718
+ "unknown",
3719
+ "lost"
3720
+ ]);
3721
+ const ExecutionRecordSchema = z.strictObject({
3722
+ acceptance: WorkloadAcceptanceSchema,
3723
+ conversationIdentity: ConversationRequestIdentitySchema.nullable(),
3724
+ outcome: JsonValueSchema.nullable(),
3725
+ acceptedAt: z.iso.datetime(),
3726
+ dispatchClaimedAt: z.iso.datetime().nullable(),
3727
+ producerSendClaimedAt: z.iso.datetime().optional(),
3728
+ finalizationBasis: z.enum([
3729
+ "never_sent",
3730
+ "producer_acknowledged",
3731
+ "runtime_fenced"
3732
+ ]).optional(),
3733
+ phase: ExecutionPhaseSchema,
3734
+ cancel: z.strictObject({
3735
+ cancelId: z.uuid(),
3736
+ requestedAt: z.iso.datetime()
3737
+ }).nullable(),
3738
+ settledAt: z.iso.datetime().nullable(),
3739
+ acknowledgedAt: z.iso.datetime().nullable(),
3740
+ finalizedAt: z.iso.datetime().nullable(),
3741
+ collection: WorkloadExportReferenceSchema.optional(),
3742
+ publicationComplete: z.boolean().optional()
3743
+ });
3744
+ z.strictObject({
3745
+ acceptance: WorkloadAcceptanceSchema,
3746
+ conversationIdentity: ConversationRequestIdentitySchema.optional()
3747
+ }).refine(({ acceptance, conversationIdentity }) => acceptance.execution.owner !== "conversation-request" || conversationIdentity !== void 0, {
3748
+ path: ["conversationIdentity"],
3749
+ message: "Conversation execution requires a conversation identity."
3750
+ });
3751
+ WorkloadCancelSchema.refine((cancel) => cancel.scope === "operation", { message: "Use workspace release for workspace cancellation" });
3752
+ z.strictObject({
3753
+ workspaceId: z.uuid(),
3754
+ callerPrincipalId: z.uuid(),
3755
+ incarnationId: z.string().min(1),
3756
+ template: WorkloadTemplateSnapshotSchema,
3757
+ producer: InstalledWorkloadSchema,
3758
+ readyAt: z.iso.datetime().nullable(),
3759
+ endedAt: z.iso.datetime().nullable()
3760
+ });
3761
+ z.discriminatedUnion("phase", [z.strictObject({
3762
+ execution: WorkloadExecutionReferenceSchema,
3763
+ phase: z.literal("absent")
3764
+ }), z.strictObject({
3765
+ execution: WorkloadExecutionReferenceSchema,
3766
+ fingerprint: WorkloadDigestSchema,
3767
+ phase: z.enum([
3768
+ "accepted",
3769
+ "running",
3770
+ "terminal",
3771
+ "canceled"
3772
+ ]),
3773
+ outcome: JsonValueSchema.nullable(),
3774
+ messages: z.array(ConversationMessageInputSchema).max(1024).optional(),
3775
+ publication: z.strictObject({
3776
+ complete: z.boolean(),
3777
+ objects: z.array(z.strictObject({
3778
+ publicationId: z.uuid(),
3779
+ name: z.string().min(1).max(255),
3780
+ mediaType: AttachmentMediaTypeSchema,
3781
+ sizeBytes: z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
3782
+ digest: WorkloadDigestSchema,
3783
+ contentBase64: z.string()
3784
+ })).max(1e3)
3785
+ }).optional()
3786
+ })]);
3787
+ WorkloadCancelSchema.extend({ fingerprint: WorkloadDigestSchema });
3788
+ //#endregion
3789
+ //#region src/resources/admin/admin.ts
3790
+ var AdministrationApi = class {
3296
3791
  transport;
3297
- workspaces;
3298
- constructor(transport, workspaces) {
3792
+ constructor(transport) {
3299
3793
  this.transport = transport;
3300
- this.workspaces = workspaces;
3301
3794
  }
3302
- async sendMessage(workspaceId, input) {
3303
- await this.workspaces.waitForAgentInput(workspaceId, input.readyTimeoutMs ?? DEFAULT_READY_TIMEOUT_MS, input.signal ? { signal: input.signal } : {});
3304
- const response = await this.transport.raw(`/v1/workspaces/${encodeURIComponent(workspaceId)}/agent/message`, {
3305
- method: "POST",
3306
- ...input.signal ? { signal: input.signal } : {},
3307
- headers: { "content-type": "application/json" },
3308
- body: JSON.stringify({
3309
- type: "user",
3310
- content: input.content,
3311
- ...input.attachmentIds?.length ? { attachment_ids: input.attachmentIds } : {}
3312
- })
3313
- });
3314
- if (response.ok) return;
3315
- const text = await response.text();
3316
- let body;
3317
- try {
3318
- body = JSON.parse(text);
3319
- } catch {
3320
- throw new PocketCoderError({
3321
- message: `PocketCoder returned a non-JSON response (${response.status})`,
3322
- code: "client.non_json_response",
3323
- status: response.status
3324
- });
3325
- }
3326
- throw responseError(response, body);
3795
+ warmPools(options = {}) {
3796
+ return this.transport.request("/v1/warm-pools", WarmPoolInventorySchema, options);
3327
3797
  }
3328
- interrupt(workspaceId, options = {}) {
3329
- return this.transport.request(`/v1/workspaces/${encodeURIComponent(workspaceId)}/agent/interrupt`, AgentInterruptResponseSchema, {
3798
+ storageInventory(options = {}) {
3799
+ return this.transport.request("/v1/storage/inventory", StorageInventorySchema, options);
3800
+ }
3801
+ pruneStorage(options = {}) {
3802
+ return this.transport.request("/v1/storage/prune", StoragePruneResultSchema, {
3330
3803
  method: "POST",
3331
3804
  signal: options.signal
3332
3805
  });
@@ -3379,6 +3852,50 @@ var AttachmentsApi = class {
3379
3852
  }
3380
3853
  };
3381
3854
  //#endregion
3855
+ //#region src/resources/budgets/budgets.ts
3856
+ const scopePath = (scopeId) => `/v1/budget-scopes/${encodeURIComponent(scopeId)}`;
3857
+ var ManagedAuthorityApi = class {
3858
+ transport;
3859
+ constructor(transport) {
3860
+ this.transport = transport;
3861
+ }
3862
+ async grantScope(scopeId, grant, options = {}) {
3863
+ await this.transport.request(`${scopePath(scopeId)}/grant`, z.undefined(), {
3864
+ ...options,
3865
+ method: "PUT",
3866
+ body: JSON.stringify(managedSchemas.BudgetScopeGrant.parse(grant))
3867
+ });
3868
+ }
3869
+ putPolicy(policy, expectedRevision, options = {}) {
3870
+ return this.transport.request(`${scopePath(policy.scopeId)}/policy`, BudgetPolicySchema, {
3871
+ ...options,
3872
+ method: "PUT",
3873
+ body: JSON.stringify(BudgetPolicyWriteSchema.parse(policy)),
3874
+ headers: expectedRevision === null ? { "if-none-match": "*" } : { "if-match": `"${expectedRevision}"` }
3875
+ });
3876
+ }
3877
+ getPolicy(scopeId, options = {}) {
3878
+ return this.transport.request(`${scopePath(scopeId)}/policy`, BudgetPolicySchema, options);
3879
+ }
3880
+ usage(scopeId, options = {}) {
3881
+ return this.transport.request(`${scopePath(scopeId)}/usage`, BudgetUsageSchema, options);
3882
+ }
3883
+ putProfile(principalId, profile, options = {}) {
3884
+ return this.transport.request(`/v1/execution-profiles/${encodeURIComponent(profile.profileId)}/revisions/${profile.revision}?principalId=${encodeURIComponent(principalId)}`, ExecutionProfileSchema, {
3885
+ ...options,
3886
+ method: "PUT",
3887
+ body: JSON.stringify(ExecutionProfileSchema.parse(profile))
3888
+ });
3889
+ }
3890
+ async putCredentialBinding(binding, options = {}) {
3891
+ await this.transport.request(`/v1/credential-bindings/${encodeURIComponent(binding.bindingId)}`, z.undefined(), {
3892
+ ...options,
3893
+ method: "PUT",
3894
+ body: JSON.stringify(managedSchemas.CredentialBinding.parse(binding))
3895
+ });
3896
+ }
3897
+ };
3898
+ //#endregion
3382
3899
  //#region src/transport/common.ts
3383
3900
  function queryString(values) {
3384
3901
  const params = new URLSearchParams();
@@ -3508,8 +4025,95 @@ var ConversationsApi = class {
3508
4025
  const response = await this.transport.stream(path, options.signal);
3509
4026
  if (response.body) yield* liveEvents(response.body);
3510
4027
  }
4028
+ async open(id, options = {}) {
4029
+ return this.transport.request(`${workspacePath(id)}/conversation/open${options.conversationId ? `?${queryString({ conversationId: options.conversationId })}` : ""}`, z.object({ turns: z.array(ConversationLiveEventSchema) }), options);
4030
+ }
4031
+ };
4032
+ //#endregion
4033
+ //#region src/resources/conversations/requests.ts
4034
+ const path = (workspaceId) => `/v1/workspaces/${encodeURIComponent(workspaceId)}/requests`;
4035
+ var WorkspaceRequestsApi = class {
4036
+ transport;
4037
+ constructor(transport) {
4038
+ this.transport = transport;
4039
+ }
4040
+ submit(workspaceId, input, options = {}) {
4041
+ return this.transport.request(path(workspaceId), ExecutionRecordSchema, {
4042
+ ...options,
4043
+ method: "POST",
4044
+ body: JSON.stringify(input)
4045
+ });
4046
+ }
4047
+ get(workspaceId, requestId, conversationId, options = {}) {
4048
+ return this.transport.request(`${path(workspaceId)}/${encodeURIComponent(requestId)}?${queryString({ conversationId })}`, ExecutionRecordSchema, options);
4049
+ }
4050
+ list(workspaceId, query, options = {}) {
4051
+ return this.transport.request(`${path(workspaceId)}?${queryString(query)}`, z.object({
4052
+ items: z.array(ExecutionRecordSchema),
4053
+ next_cursor: z.uuid().nullable()
4054
+ }), options);
4055
+ }
4056
+ cancel(record, cancelId, options = {}) {
4057
+ const execution = record.acceptance.execution;
4058
+ return this.transport.request(`/v1/workspaces/${encodeURIComponent(execution.workspaceId)}/executions/${encodeURIComponent(execution.requestId)}/cancel`, ExecutionRecordSchema, {
4059
+ ...options,
4060
+ method: "POST",
4061
+ body: JSON.stringify({
4062
+ execution,
4063
+ cancelId,
4064
+ scope: "operation"
4065
+ })
4066
+ });
4067
+ }
3511
4068
  };
3512
4069
  //#endregion
4070
+ //#region src/transport/errors.ts
4071
+ z.enum(["client.non_json_response", "client.invalid_response"]);
4072
+ var PocketCoderError = class extends Error {
4073
+ code;
4074
+ status;
4075
+ requestId;
4076
+ details;
4077
+ constructor(input) {
4078
+ super(input.message);
4079
+ this.name = "PocketCoderError";
4080
+ this.code = input.code;
4081
+ this.status = input.status;
4082
+ this.requestId = input.requestId;
4083
+ this.details = input.details;
4084
+ }
4085
+ };
4086
+ var ConversationGoneError = class extends PocketCoderError {};
4087
+ var WorkspaceTerminalError = class extends Error {
4088
+ workspace;
4089
+ constructor(workspace) {
4090
+ const reason = workspace.reason_code ?? workspace.failure?.reason_code ?? "no reason";
4091
+ const tail = workspace.failure?.log_tail.trim();
4092
+ super([`workspace ${workspace.id} reached ${workspace.state} (${reason})`, ...tail ? [`failure log:\n${tail}`] : []].join("\n"));
4093
+ this.name = "WorkspaceTerminalError";
4094
+ this.workspace = workspace;
4095
+ }
4096
+ };
4097
+ function isPocketCoderErrorCode(value) {
4098
+ return typeof value === "string" && value in ERROR_CODES;
4099
+ }
4100
+ function responseError(response, body) {
4101
+ const parsed = ErrorEnvelopeSchema.safeParse(body);
4102
+ if (!parsed.success) return new PocketCoderError({
4103
+ message: `PocketCoder returned an invalid error response (${response.status})`,
4104
+ code: "client.invalid_response",
4105
+ status: response.status
4106
+ });
4107
+ const { code, message, request_id: requestId, details } = parsed.data.error;
4108
+ return new (code === "conversation.deleted" || code === "conversation.expired" ? ConversationGoneError : PocketCoderError)({
4109
+ message,
4110
+ code,
4111
+ status: response.status,
4112
+ requestId,
4113
+ details
4114
+ });
4115
+ }
4116
+ //#endregion
3513
4117
  //#region src/resources/diagnostics/diagnostics.ts
3514
4118
  var WorkspaceCursorApi = class {
3515
4119
  transport;
@@ -3659,7 +4263,10 @@ var PreviewsApi = class {
3659
4263
  open(workspaceId, name, options = {}) {
3660
4264
  return this.transport.request(`/v1/workspaces/${encodeURIComponent(workspaceId)}/previews/${encodeURIComponent(name)}`, PreviewOpenResponseSchema, {
3661
4265
  method: "POST",
3662
- body: JSON.stringify({ session: options.session ?? { mode: "local" } }),
4266
+ body: JSON.stringify({
4267
+ session: options.session ?? { mode: "local" },
4268
+ ...options.grantId ? { grantId: options.grantId } : {}
4269
+ }),
3663
4270
  signal: options.signal
3664
4271
  });
3665
4272
  }
@@ -3717,6 +4324,204 @@ var SecretsApi = class {
3717
4324
  }
3718
4325
  };
3719
4326
  //#endregion
4327
+ //#region src/resources/sessions/events.ts
4328
+ async function* frames(body) {
4329
+ const decoder = new TextDecoder();
4330
+ let buffer = "";
4331
+ for await (const chunk of body) {
4332
+ buffer += decoder.decode(chunk, { stream: true });
4333
+ let end = buffer.indexOf("\n\n");
4334
+ while (end !== -1) {
4335
+ const block = buffer.slice(0, end).split("\n");
4336
+ buffer = buffer.slice(end + 2);
4337
+ const field = (name) => block.find((line) => line.startsWith(`${name}:`))?.slice(name.length + 1).trim();
4338
+ const data = block.filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
4339
+ yield {
4340
+ id: field("id") ?? null,
4341
+ event: field("event") ?? null,
4342
+ data
4343
+ };
4344
+ end = buffer.indexOf("\n\n");
4345
+ }
4346
+ }
4347
+ }
4348
+ async function* sessionEvents(transport, sessionId, options = {}) {
4349
+ let cursor = options.after ?? null;
4350
+ do {
4351
+ const query = cursor ? `?after=${encodeURIComponent(cursor)}` : "";
4352
+ const response = await transport.stream(`/v1/sessions/${encodeURIComponent(sessionId)}/events${query}`, options.signal, cursor ? { "last-event-id": cursor } : {});
4353
+ if (!response.body) return;
4354
+ for await (const frame of frames(response.body)) {
4355
+ if (frame.event === "keepalive") continue;
4356
+ if (frame.event === "error") {
4357
+ const { code } = JSON.parse(frame.data);
4358
+ throw new PocketCoderError({
4359
+ message: `Session event stream ended: ${code}`,
4360
+ code,
4361
+ status: 0
4362
+ });
4363
+ }
4364
+ const event = RuntimeEventSchema.parse(JSON.parse(frame.data));
4365
+ cursor = event.cursor;
4366
+ yield event;
4367
+ }
4368
+ } while (options.reconnect !== false && !options.signal?.aborted);
4369
+ }
4370
+ //#endregion
4371
+ //#region src/resources/sessions/sessions.ts
4372
+ function sessionPath(sessionId) {
4373
+ return `/v1/sessions/${encodeURIComponent(sessionId)}`;
4374
+ }
4375
+ const SessionPreviewSchema = PreviewOpenResponseSchema.extend({ grantId: z.uuid().nullable() });
4376
+ var SessionsApi = class {
4377
+ transport;
4378
+ constructor(transport) {
4379
+ this.transport = transport;
4380
+ }
4381
+ create(input, options = {}) {
4382
+ return this.transport.request("/v1/sessions", SessionSchema, {
4383
+ ...options,
4384
+ method: "POST",
4385
+ body: JSON.stringify(SessionCreateSchema.parse(input))
4386
+ });
4387
+ }
4388
+ get(sessionId, options = {}) {
4389
+ return this.transport.request(sessionPath(sessionId), SessionSchema, options);
4390
+ }
4391
+ resume(sessionId, options = {}) {
4392
+ return this.transport.request(`${sessionPath(sessionId)}/resume`, SessionSchema, {
4393
+ ...options,
4394
+ method: "POST"
4395
+ });
4396
+ }
4397
+ close(sessionId, command, options = {}) {
4398
+ return this.transport.request(`${sessionPath(sessionId)}/close`, CancelReceiptSchema, {
4399
+ ...options,
4400
+ method: "POST",
4401
+ body: JSON.stringify(CancelCommandSchema.parse(command))
4402
+ });
4403
+ }
4404
+ history(sessionId, query = {}, options = {}) {
4405
+ return this.transport.request(`${sessionPath(sessionId)}/history?${queryString({
4406
+ cursor: query.cursor,
4407
+ limit: query.limit ?? 50
4408
+ })}`, ManagedHistoryPageSchema, options);
4409
+ }
4410
+ async snapshot(sessionId, options = {}) {
4411
+ const records = [];
4412
+ let cursor;
4413
+ let eventCursor = "";
4414
+ do {
4415
+ const page = await this.history(sessionId, {
4416
+ cursor,
4417
+ limit: 200
4418
+ }, options);
4419
+ records.push(...page.records);
4420
+ eventCursor = page.eventCursor;
4421
+ cursor = page.nextCursor ?? void 0;
4422
+ } while (cursor);
4423
+ return {
4424
+ records,
4425
+ eventCursor
4426
+ };
4427
+ }
4428
+ events(sessionId, options = {}) {
4429
+ return sessionEvents(this.transport, sessionId, options);
4430
+ }
4431
+ open(sessionId, options = {}) {
4432
+ return this.transport.request(`${sessionPath(sessionId)}/conversation/open`, z.object({ turns: z.array(ConversationLiveEventSchema) }), options);
4433
+ }
4434
+ openPreview(sessionId, name, options = {}) {
4435
+ return this.transport.request(`${sessionPath(sessionId)}/previews/${encodeURIComponent(name)}`, SessionPreviewSchema, {
4436
+ method: "POST",
4437
+ body: JSON.stringify({
4438
+ session: options.session ?? { mode: "local" },
4439
+ ...options.grant ? { grant: options.grant } : {}
4440
+ }),
4441
+ signal: options.signal
4442
+ });
4443
+ }
4444
+ };
4445
+ //#endregion
4446
+ //#region src/resources/sessions/files.ts
4447
+ var SessionFilesApi = class {
4448
+ transport;
4449
+ constructor(transport) {
4450
+ this.transport = transport;
4451
+ }
4452
+ register(sessionId, input, options = {}) {
4453
+ return this.transport.request(`${sessionPath(sessionId)}/inputs`, InputObjectSchema, {
4454
+ ...options,
4455
+ method: "POST",
4456
+ body: JSON.stringify(InputUploadSchema.parse(input))
4457
+ });
4458
+ }
4459
+ upload(sessionId, inputId, bytes, options = {}) {
4460
+ return this.transport.request(`${sessionPath(sessionId)}/inputs/${encodeURIComponent(inputId)}/content`, InputObjectSchema, {
4461
+ ...options,
4462
+ method: "PUT",
4463
+ body: bytes,
4464
+ headers: { "content-type": "application/octet-stream" }
4465
+ });
4466
+ }
4467
+ async put(sessionId, file, options = {}) {
4468
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", file.bytes));
4469
+ const sha256 = `sha256:${Array.from(digest, (byte) => byte.toString(16).padStart(2, "0")).join("")}`;
4470
+ const registered = await this.register(sessionId, {
4471
+ inputId: file.inputId,
4472
+ name: file.name,
4473
+ mediaType: file.mediaType,
4474
+ sizeBytes: file.bytes.byteLength,
4475
+ sha256
4476
+ }, options);
4477
+ if (registered.state === "ready") return registered;
4478
+ return this.upload(sessionId, file.inputId, file.bytes, options);
4479
+ }
4480
+ get(sessionId, inputId, options = {}) {
4481
+ return this.transport.request(`${sessionPath(sessionId)}/inputs/${encodeURIComponent(inputId)}`, InputObjectSchema, options);
4482
+ }
4483
+ exports(sessionId, requestId, options = {}) {
4484
+ return this.transport.request(`${sessionPath(sessionId)}/exports?requestId=${encodeURIComponent(requestId)}`, ManagedExportPageSchema, options);
4485
+ }
4486
+ async content(sessionId, exportId, options = {}) {
4487
+ const response = await this.transport.raw(`${sessionPath(sessionId)}/exports/${encodeURIComponent(exportId)}/content`, options);
4488
+ if (!response.ok) {
4489
+ const text = await response.text();
4490
+ throw responseError(response, text ? JSON.parse(text) : void 0);
4491
+ }
4492
+ return new Uint8Array(await response.arrayBuffer());
4493
+ }
4494
+ };
4495
+ //#endregion
4496
+ //#region src/resources/sessions/requests.ts
4497
+ const requestPath = (sessionId, requestId) => `${sessionPath(sessionId)}/requests/${encodeURIComponent(requestId)}`;
4498
+ var SessionRequestsApi = class {
4499
+ transport;
4500
+ constructor(transport) {
4501
+ this.transport = transport;
4502
+ }
4503
+ submit(sessionId, input, options = {}) {
4504
+ return this.transport.request(`${sessionPath(sessionId)}/requests`, RequestSchema, {
4505
+ ...options,
4506
+ method: "POST",
4507
+ body: JSON.stringify(RequestInputSchema.parse(input))
4508
+ });
4509
+ }
4510
+ get(sessionId, requestId, options = {}) {
4511
+ return this.transport.request(requestPath(sessionId, requestId), RequestSchema, options);
4512
+ }
4513
+ cancel(sessionId, requestId, command, options = {}) {
4514
+ return this.transport.request(`${requestPath(sessionId, requestId)}/cancel`, CancelReceiptSchema, {
4515
+ ...options,
4516
+ method: "POST",
4517
+ body: JSON.stringify(CancelCommandSchema.parse(command))
4518
+ });
4519
+ }
4520
+ collection(sessionId, requestId, options = {}) {
4521
+ return this.transport.request(`${requestPath(sessionId, requestId)}/collection`, CollectionResultSchema, options);
4522
+ }
4523
+ };
4524
+ //#endregion
3720
4525
  //#region src/resources/templates/templates.ts
3721
4526
  var TemplatesApi = class {
3722
4527
  transport;
@@ -3925,17 +4730,6 @@ var WorkspacesApi = class {
3925
4730
  }
3926
4731
  return workspace;
3927
4732
  }
3928
- async waitForAgentInput(id, timeoutMs, options = {}) {
3929
- const deadline = Date.now() + timeoutMs;
3930
- let workspace = await this.get(id, options);
3931
- while (workspace.agent_state !== "stable") {
3932
- if (TERMINAL_STATES.includes(workspace.state)) throw new WorkspaceTerminalError(workspace);
3933
- const remainingMs = deadline - Date.now();
3934
- if (remainingMs <= 0) throw new AgentNotReadyError(workspace.id, workspace.agent_state, timeoutMs);
3935
- workspace = (await this.change(workspace.id, workspace.change_cursor, Math.max(1, Math.min(30, Math.ceil(remainingMs / 1e3))), options)).workspace;
3936
- }
3937
- return workspace;
3938
- }
3939
4733
  preserve(id, input, key, options = {}) {
3940
4734
  return this.jsonOperation(`/v1/workspaces/${encodeURIComponent(id)}/preserve`, input, key, PreserveResponseSchema, options);
3941
4735
  }
@@ -4014,11 +4808,12 @@ var PocketCoderTransport = class {
4014
4808
  await delay(100 * 2 ** attempt, signal);
4015
4809
  }
4016
4810
  }
4017
- async stream(path, signal) {
4811
+ async stream(path, signal, headers = {}) {
4018
4812
  const response = await this.fetchImpl(`${this.baseUrl}${path.startsWith("/") ? path : `/${path}`}`, {
4019
4813
  headers: {
4020
4814
  authorization: `Bearer ${this.apiKey}`,
4021
- accept: "text/event-stream"
4815
+ accept: "text/event-stream",
4816
+ ...headers
4022
4817
  },
4023
4818
  ...signal ? { signal } : {}
4024
4819
  });
@@ -4098,8 +4893,8 @@ var PocketCoderClient = class {
4098
4893
  previews;
4099
4894
  displays;
4100
4895
  attachments;
4101
- agent;
4102
4896
  conversations;
4897
+ workspaceRequests;
4103
4898
  checkpoints;
4104
4899
  operations;
4105
4900
  logs;
@@ -4110,6 +4905,10 @@ var PocketCoderClient = class {
4110
4905
  principals;
4111
4906
  keys;
4112
4907
  recovery;
4908
+ sessions;
4909
+ requests;
4910
+ files;
4911
+ authority;
4113
4912
  constructor(config, fetchImpl = fetch) {
4114
4913
  this.transport = new PocketCoderTransport(config, fetchImpl);
4115
4914
  this.secrets = new SecretsApi(this.transport);
@@ -4118,8 +4917,8 @@ var PocketCoderClient = class {
4118
4917
  this.previews = new PreviewsApi(this.transport);
4119
4918
  this.displays = new DisplaysApi(this.transport);
4120
4919
  this.attachments = new AttachmentsApi(this.transport);
4121
- this.agent = new AgentApi(this.transport, this.workspaces);
4122
4920
  this.conversations = new ConversationsApi(this.transport);
4921
+ this.workspaceRequests = new WorkspaceRequestsApi(this.transport);
4123
4922
  this.checkpoints = new CheckpointsApi(this.transport);
4124
4923
  this.operations = new OperationsApi(this.transport);
4125
4924
  this.logs = new LogsApi(this.transport);
@@ -4130,6 +4929,10 @@ var PocketCoderClient = class {
4130
4929
  this.principals = new PrincipalsApi(this.transport);
4131
4930
  this.keys = new KeysApi(this.transport);
4132
4931
  this.recovery = new RecoveryApi(this.transport);
4932
+ this.sessions = new SessionsApi(this.transport);
4933
+ this.requests = new SessionRequestsApi(this.transport);
4934
+ this.files = new SessionFilesApi(this.transport);
4935
+ this.authority = new ManagedAuthorityApi(this.transport);
4133
4936
  }
4134
4937
  raw(path, init = {}) {
4135
4938
  return this.transport.raw(path, init);
@@ -4280,4 +5083,4 @@ var WorkspaceTurnResolver = class {
4280
5083
  }
4281
5084
  };
4282
5085
  //#endregion
4283
- export { AdministrationApi, AgentApi, AgentNotReadyError, AttachmentsApi, CheckpointsApi, ConversationGoneError, ConversationsApi, KeysApi, LogsApi, NetworkEventsApi, OperationsApi, OutputsApi, PocketCoderClient, PocketCoderError, PrincipalsApi, RecoveryApi, SecretsApi, TERMINAL_WORKSPACE_STATES, TemplatesApi, TerminalConnection, TerminalsApi, WorkspaceTerminalError, WorkspaceTurnResolutionError, WorkspaceTurnResolver, WorkspacesApi, isPocketCoderErrorCode, splitAttachmentManifest };
5086
+ export { AdministrationApi, AttachmentsApi, CheckpointsApi, ConversationGoneError, ConversationsApi, KeysApi, LogsApi, ManagedAuthorityApi, NetworkEventsApi, OperationsApi, OutputsApi, PocketCoderClient, PocketCoderError, PrincipalsApi, RecoveryApi, SecretsApi, SessionFilesApi, SessionRequestsApi, SessionsApi, TERMINAL_WORKSPACE_STATES, TemplatesApi, TerminalConnection, TerminalsApi, WorkspaceRequestsApi, WorkspaceTerminalError, WorkspaceTurnResolutionError, WorkspaceTurnResolver, WorkspacesApi, isPocketCoderErrorCode, sessions_exports as managed, sessionTemplate };