@catamorphic/fastify-plugin 0.1.0-alpha.38 → 0.1.0-alpha.41

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 (81) hide show
  1. package/NOTICE.txt +7 -0
  2. package/dist/app.d.ts +2 -0
  3. package/dist/app.d.ts.map +1 -1
  4. package/dist/chunk-jytcc42y.js +592 -0
  5. package/dist/chunk-jytcc42y.js.map +11 -0
  6. package/dist/index.d.ts +1 -1
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1679 -411
  9. package/dist/index.js.map +29 -25
  10. package/dist/mcp-scopes.d.ts +12 -0
  11. package/dist/mcp-scopes.d.ts.map +1 -0
  12. package/dist/mcp-server.d.ts +158 -0
  13. package/dist/mcp-server.d.ts.map +1 -0
  14. package/dist/mcp-shared.d.ts +3 -50
  15. package/dist/mcp-shared.d.ts.map +1 -1
  16. package/dist/mcp.d.ts +4 -2
  17. package/dist/mcp.d.ts.map +1 -1
  18. package/dist/mcp.js +6 -4
  19. package/dist/mcp.js.map +1 -1
  20. package/dist/plugin.d.ts +26 -2
  21. package/dist/plugin.d.ts.map +1 -1
  22. package/dist/project-capabilities.d.ts.map +1 -1
  23. package/dist/project-mcp-surface.d.ts +3 -4
  24. package/dist/project-mcp-surface.d.ts.map +1 -1
  25. package/dist/routes/agent.d.ts.map +1 -1
  26. package/dist/routes/apps-mcp.d.ts.map +1 -1
  27. package/dist/routes/client-runners.d.ts.map +1 -1
  28. package/dist/routes/connection-mcp.d.ts.map +1 -1
  29. package/dist/routes/documents.d.ts.map +1 -1
  30. package/dist/routes/environments.d.ts.map +1 -1
  31. package/dist/routes/project-mcp.d.ts.map +1 -1
  32. package/dist/routes/projects.d.ts.map +1 -1
  33. package/dist/routes/publications.d.ts.map +1 -1
  34. package/dist/routes/run-errors.d.ts.map +1 -1
  35. package/dist/routes/runs.d.ts.map +1 -1
  36. package/dist/routes/server-mcp.d.ts +17 -0
  37. package/dist/routes/server-mcp.d.ts.map +1 -0
  38. package/dist/routes/session-mailboxes.d.ts.map +1 -1
  39. package/dist/routes/triggers.d.ts.map +1 -1
  40. package/dist/routes/watchers.d.ts.map +1 -1
  41. package/dist/routes/workflow-enablements.d.ts.map +1 -1
  42. package/dist/routes/workflows.d.ts.map +1 -1
  43. package/dist/schemas.d.ts +3717 -28
  44. package/dist/schemas.d.ts.map +1 -1
  45. package/dist/session-mcp.d.ts +54 -0
  46. package/dist/session-mcp.d.ts.map +1 -0
  47. package/dist/session-tools.d.ts +49 -0
  48. package/dist/session-tools.d.ts.map +1 -0
  49. package/package.json +22 -20
  50. package/src/app.ts +3 -0
  51. package/src/index.ts +1 -0
  52. package/src/mcp-scopes.ts +69 -0
  53. package/src/mcp-server.ts +827 -0
  54. package/src/mcp-shared.ts +3 -151
  55. package/src/mcp.ts +6 -5
  56. package/src/plugin.ts +73 -2
  57. package/src/project-capabilities.ts +5 -3
  58. package/src/project-mcp-program.ts +2 -2
  59. package/src/project-mcp-surface.ts +18 -239
  60. package/src/routes/agent.ts +384 -41
  61. package/src/routes/apps-mcp.ts +84 -82
  62. package/src/routes/client-runners.ts +3 -1
  63. package/src/routes/connection-mcp.ts +6 -13
  64. package/src/routes/documents.ts +4 -0
  65. package/src/routes/environments.ts +49 -1
  66. package/src/routes/project-mcp.ts +176 -154
  67. package/src/routes/projects.ts +6 -0
  68. package/src/routes/publications.ts +2 -0
  69. package/src/routes/run-errors.ts +5 -1
  70. package/src/routes/runs.ts +4 -0
  71. package/src/routes/server-mcp.ts +151 -0
  72. package/src/routes/session-mailboxes.ts +1 -0
  73. package/src/routes/triggers.ts +6 -1
  74. package/src/routes/watchers.ts +1 -0
  75. package/src/routes/workflow-enablements.ts +132 -1
  76. package/src/routes/workflows.ts +4 -0
  77. package/src/schemas.ts +354 -6
  78. package/src/session-mcp.ts +696 -0
  79. package/src/session-tools.ts +169 -0
  80. package/dist/chunk-baagvvm3.js +0 -164
  81. package/dist/chunk-baagvvm3.js.map +0 -10
package/dist/index.js CHANGED
@@ -1,14 +1,16 @@
1
1
  import {
2
- negotiateProtocolVersion,
3
- McpRequestError2,
4
- handleMcpPost,
5
2
  toolValue,
6
3
  toolError2,
7
4
  POLL_RUN_TOOL,
8
5
  POLL_RUN_TOOL_DEFINITION,
9
6
  callPollRunTool,
7
+ MCP_ERROR2,
8
+ McpError2,
9
+ declaresTasks,
10
+ declaresElicitation,
11
+ serveMcp,
10
12
  serveForwardedTools2
11
- } from "./chunk-baagvvm3.js";
13
+ } from "./chunk-jytcc42y.js";
12
14
 
13
15
  // src/app.ts
14
16
  import fastifyCors from "@fastify/cors";
@@ -25,11 +27,14 @@ import {
25
27
  AccessDeniedError as AccessDeniedError10,
26
28
  DeploymentBlockedError as DeploymentBlockedError3,
27
29
  EnvironmentPolicyInvalidError as EnvironmentPolicyInvalidError2,
30
+ FULL_TOKEN_SCOPE,
31
+ hasTokenScope as hasTokenScope3,
28
32
  ProjectNotFoundError as ProjectNotFoundError12,
29
33
  ServerDraftError,
30
34
  SessionArtifactConflictError,
31
35
  SessionArtifactNotFoundError as SessionArtifactNotFoundError2,
32
- SessionArtifactValidationError
36
+ SessionArtifactValidationError,
37
+ TokenScopeRequiredError as TokenScopeRequiredError2
33
38
  } from "@catamorphic/core";
34
39
  import {
35
40
  DraftBinaryResolutionError,
@@ -178,8 +183,12 @@ import {
178
183
  NoCompatibleEnvironmentError,
179
184
  ProjectNotFoundError,
180
185
  parseChatKey,
186
+ SESSION_OPERATIONS as SESSION_OPERATIONS2,
187
+ SessionInputNotFoundError,
181
188
  SessionMirrorBehindError,
182
189
  SessionMirrorDivergedError,
190
+ sessionOperationError,
191
+ TokenScopeRequiredError,
183
192
  UnsupportedAgentTopologyError
184
193
  } from "@catamorphic/core";
185
194
  import { z as z2 } from "zod";
@@ -217,7 +226,9 @@ import { RUNNER_PROTOCOL_VERSION } from "@catamorphic/agent-protocol/runner";
217
226
  import { APP_ICON_NAMES } from "@catamorphic/app";
218
227
  import {
219
228
  RoleDefinitionSchema as CoreRoleDefinitionSchema,
220
- PROJECT_PERMISSION_PATTERN
229
+ PROJECT_PERMISSION_PATTERN,
230
+ SESSION_OPERATION_ERROR_CODES,
231
+ SESSION_OPERATIONS
221
232
  } from "@catamorphic/core";
222
233
  import {
223
234
  CLAUDE_CODE_PERMISSION_MODES,
@@ -370,6 +381,10 @@ var TriggerBindingInfoSchema = z.object({
370
381
  inputSchema: JsonOutSchema,
371
382
  outputSchema: JsonOutSchema
372
383
  });
384
+ var WorkflowDocumentAccessSchema = z.object({
385
+ path: z.string(),
386
+ access: z.enum(["read", "write"])
387
+ });
373
388
  var WorkflowEnablementOwnerSchema = z.discriminatedUnion("type", [
374
389
  z.object({ type: z.literal("member"), externalUserId: z.string().min(1) }),
375
390
  z.object({ type: z.literal("project") })
@@ -400,6 +415,7 @@ var WorkflowEnablementTargetSchema = z.object({
400
415
  connections: z.array(WorkflowEnablementConnectionSchema),
401
416
  capabilities: z.array(z.string()),
402
417
  permissions: z.array(z.string()),
418
+ documents: z.array(WorkflowDocumentAccessSchema),
403
419
  consentDigest: z.string().length(64)
404
420
  });
405
421
  var WorkflowEnablementPreviewSchema = WorkflowEnablementTargetSchema.extend({
@@ -417,6 +433,7 @@ var WorkflowEnablementSchema = WorkflowEnablementTargetSchema.extend({
417
433
  status: z.enum(["active", "suspended", "disabled"]),
418
434
  suspensionReason: z.string().nullable(),
419
435
  updateAvailable: z.boolean(),
436
+ follow: z.boolean(),
420
437
  temporary: z.boolean(),
421
438
  expiresAt: z.string().datetime().nullable(),
422
439
  revision: z.number().int().positive(),
@@ -424,6 +441,33 @@ var WorkflowEnablementSchema = WorkflowEnablementTargetSchema.extend({
424
441
  createdAt: z.string().datetime(),
425
442
  updatedAt: z.string().datetime()
426
443
  });
444
+ var PublishedRevisionSchema = z.object({
445
+ id: z.string().uuid(),
446
+ sequence: z.number().int(),
447
+ projectId: z.string().uuid(),
448
+ commitSha: z.string(),
449
+ status: z.enum([
450
+ "pending",
451
+ "deploying",
452
+ "applying",
453
+ "applied",
454
+ "superseded",
455
+ "failed"
456
+ ]),
457
+ deployWorkflow: z.string().nullable(),
458
+ deployRunId: z.string().uuid().nullable(),
459
+ previousCommitSha: z.string().nullable(),
460
+ error: z.string().nullable(),
461
+ report: z.array(z.object({
462
+ kind: z.enum(["moved", "needs_consent", "skipped", "retry", "unchanged"]),
463
+ enablementId: z.string().uuid(),
464
+ workflowName: z.string(),
465
+ commitSha: z.string().optional(),
466
+ reason: z.string().optional()
467
+ })),
468
+ createdAt: z.string().datetime(),
469
+ settledAt: z.string().datetime().nullable()
470
+ });
427
471
  var WorkflowSummarySchema = z.object({
428
472
  name: z.string(),
429
473
  capabilities: WorkflowCapabilitiesSchema,
@@ -547,6 +591,7 @@ var WorkflowGraphSchema = z.object({
547
591
  optional: z.boolean().optional()
548
592
  })),
549
593
  permissions: z.array(z.string()),
594
+ documents: z.array(WorkflowDocumentAccessSchema),
550
595
  canSuspend: z.boolean(),
551
596
  nodes: z.array(WorkflowNodeSchema),
552
597
  edges: z.array(WorkflowEdgeSchema),
@@ -557,6 +602,7 @@ var WorkflowDetailSchema = WorkflowGraphSchema.extend({
557
602
  allFiles: z.record(z.string(), z.string())
558
603
  });
559
604
  var RunStatusSchema = z.enum([
605
+ "queued",
560
606
  "pending",
561
607
  "running",
562
608
  "waiting",
@@ -690,7 +736,8 @@ var CorrelationKeySchema = z.string().min(1).max(500);
690
736
  var EnrollmentConflictPolicySchema = z.enum([
691
737
  "ignore",
692
738
  "error",
693
- "restart"
739
+ "restart",
740
+ "queue"
694
741
  ]);
695
742
  var TriggerRunSchema = z.object({
696
743
  input: JsonValueSchema.optional(),
@@ -702,6 +749,39 @@ var EnvironmentListQuerySchema = z.object({
702
749
  workload: z.enum(["agent", "workflow"]),
703
750
  agentId: z.string().min(1).optional()
704
751
  });
752
+ var CacheFillSchema = z.object({
753
+ id: z.string(),
754
+ environment: z.string(),
755
+ cache: z.string(),
756
+ machine: z.string().nullable(),
757
+ status: z.enum(["queued", "running", "succeeded", "failed", "evicted"]),
758
+ reason: z.enum(["requested", "first-use"]),
759
+ commit: z.string().nullable(),
760
+ generation: z.number().nullable(),
761
+ attempts: z.number(),
762
+ sizeBytes: z.number().nullable(),
763
+ error: z.string().nullable(),
764
+ createdAt: z.string(),
765
+ finishedAt: z.string().nullable(),
766
+ lastUsedAt: z.string().nullable()
767
+ });
768
+ var EnvironmentCacheListSchema = z.object({
769
+ items: z.array(z.object({
770
+ environment: z.string(),
771
+ cache: z.string(),
772
+ path: z.string(),
773
+ sizeMb: z.number(),
774
+ copies: z.array(z.object({
775
+ machine: z.string(),
776
+ generation: z.number(),
777
+ commit: z.string().nullable(),
778
+ filledAt: z.string().nullable(),
779
+ sizeBytes: z.number().nullable(),
780
+ lastUsedAt: z.string().nullable()
781
+ })),
782
+ fills: z.array(CacheFillSchema)
783
+ }))
784
+ });
705
785
  var EnvironmentListSchema = z.object({
706
786
  items: z.array(z.object({
707
787
  name: z.string(),
@@ -1134,6 +1214,7 @@ var AgentSessionSchema = z.object({
1134
1214
  forkedFromSessionId: z.string().uuid().nullable(),
1135
1215
  imported: ImportedSessionSchema.nullable(),
1136
1216
  parentSessionId: z.string().uuid().nullable(),
1217
+ workspaceSessionId: z.string().uuid().nullable(),
1137
1218
  visibility: z.enum(["latent", "promoted", "archived"]),
1138
1219
  archivedAt: z.string().datetime().nullable(),
1139
1220
  status: z.enum(["active", "closed"]),
@@ -1164,12 +1245,35 @@ var AgentSessionSchema = z.object({
1164
1245
  var AgentSessionIdParamsSchema = ProjectIdParamsSchema.extend({
1165
1246
  sessionId: z.string().uuid()
1166
1247
  });
1248
+ var AgentSessionUsageQuerySchema = z.object({
1249
+ family: z.enum(["true", "false"]).transform((value) => value === "true").optional()
1250
+ });
1251
+ var ModelUsageTotalsShape = {
1252
+ calls: z.number().int().nonnegative(),
1253
+ inputTokens: z.number().int().nonnegative(),
1254
+ cachedInputTokens: z.number().int().nonnegative(),
1255
+ cacheCreationTokens: z.number().int().nonnegative(),
1256
+ outputTokens: z.number().int().nonnegative(),
1257
+ reasoningTokens: z.number().int().nonnegative(),
1258
+ costUsd: z.number().nonnegative().nullable(),
1259
+ unpricedCalls: z.number().int().nonnegative(),
1260
+ unmeteredCalls: z.number().int().nonnegative()
1261
+ };
1262
+ var AgentSessionUsageSchema = z.object({
1263
+ sessionId: z.string().uuid(),
1264
+ family: z.boolean(),
1265
+ sessions: z.number().int().nonnegative(),
1266
+ openCalls: z.number().int().nonnegative(),
1267
+ ...ModelUsageTotalsShape,
1268
+ models: z.array(z.object({ model: z.string().nullable(), ...ModelUsageTotalsShape }))
1269
+ });
1167
1270
  var AgentSessionPeerSchema = z.object({
1168
1271
  id: z.string().uuid(),
1169
1272
  projectId: z.string().uuid(),
1170
1273
  title: z.string().nullable(),
1171
1274
  agentId: z.string().nullable(),
1172
1275
  parentSessionId: z.string().uuid().nullable(),
1276
+ workspaceSessionId: z.string().uuid().nullable(),
1173
1277
  forkedFromSessionId: z.string().uuid().nullable(),
1174
1278
  visibility: z.enum(["latent", "promoted", "archived"]),
1175
1279
  status: z.enum(["active", "closed"]),
@@ -1201,6 +1305,7 @@ var CreateAgentSubsessionSchema = z.object({
1201
1305
  effort: AgentEffortSchema.optional(),
1202
1306
  readOnly: z.boolean().optional(),
1203
1307
  delegate: z.boolean().optional(),
1308
+ workspace: z.enum(["shared", "own"]).optional(),
1204
1309
  task: z.string().min(1).max(1e5),
1205
1310
  contextMode: z.enum(["fresh", "inherit"]).optional(),
1206
1311
  title: z.string().min(1).max(500).optional()
@@ -1211,12 +1316,27 @@ var AgentSubsessionSchema = z.object({
1211
1316
  task: z.string(),
1212
1317
  contextMode: z.enum(["fresh", "inherit"]),
1213
1318
  allowFurtherDelegation: z.boolean(),
1319
+ workspace: z.enum(["shared", "own"]),
1214
1320
  status: z.enum(["running", "completed", "failed", "interrupted", "archived"]),
1215
- session: AgentSessionSchema
1321
+ session: AgentSessionSchema,
1322
+ results: z.array(z.object({
1323
+ id: z.string(),
1324
+ name: z.string(),
1325
+ value: JsonValueSchema,
1326
+ truncated: z.boolean(),
1327
+ current: z.boolean(),
1328
+ turnId: z.string().nullable(),
1329
+ recordedAt: z.string()
1330
+ }))
1331
+ });
1332
+ var StartSessionSchema = SESSION_OPERATIONS.session_start.input.omit({
1333
+ project: true
1216
1334
  });
1217
- var WaitForAgentSubsessionsSchema = z.object({
1218
- sessionIds: z.array(z.string().uuid()).max(100).optional(),
1219
- timeoutMs: z.number().int().min(0).max(60000).optional()
1335
+ var SessionOperationErrorSchema = z.object({
1336
+ error: z.string(),
1337
+ code: z.enum(SESSION_OPERATION_ERROR_CODES),
1338
+ retryable: z.boolean(),
1339
+ sessionId: z.string().optional()
1220
1340
  });
1221
1341
  var ArchiveAgentSessionSchema = z.object({
1222
1342
  confirmStop: z.boolean().optional()
@@ -1275,7 +1395,14 @@ var NativeRefSchema = describes()(z.object({
1275
1395
  }));
1276
1396
  var TurnErrorSchema = describes()(z.object({
1277
1397
  message: z.string(),
1278
- kind: z.enum(["auth", "rate_limit", "unavailable", "model_incompat"]).optional(),
1398
+ kind: z.enum([
1399
+ "auth",
1400
+ "rate_limit",
1401
+ "unavailable",
1402
+ "model_incompat",
1403
+ "agent_missing",
1404
+ "out_of_disk"
1405
+ ]).optional(),
1279
1406
  retrySafe: z.boolean().optional()
1280
1407
  }));
1281
1408
  var ProviderRetrySchema = z.object({
@@ -1298,7 +1425,6 @@ var AgentTurnUsageSchema = describes()(z.object({
1298
1425
  var TurnOutcomeSchema = describes()(z.object({
1299
1426
  changedFiles: z.array(z.object({ path: z.string(), kind: z.enum(["modified", "deleted"]) })),
1300
1427
  usage: AgentTurnUsageSchema.optional(),
1301
- storeSync: JsonObjectSchema.optional(),
1302
1428
  workspaceSync: z.object({ error: z.string() }).optional(),
1303
1429
  notification: z.object({ title: z.string().optional(), body: z.string().optional() }).optional()
1304
1430
  }));
@@ -1347,7 +1473,13 @@ var AttemptSchema = describes()(z.object({
1347
1473
  turnId: z.string(),
1348
1474
  sessionId: z.string(),
1349
1475
  ordinal: z.number().int(),
1350
- reason: z.enum(["initial", "retry", "steer_restart", "recovery"]),
1476
+ reason: z.enum([
1477
+ "initial",
1478
+ "retry",
1479
+ "steer_restart",
1480
+ "recovery",
1481
+ "restart"
1482
+ ]),
1351
1483
  status: z.enum([
1352
1484
  "preparing",
1353
1485
  "running",
@@ -1355,7 +1487,8 @@ var AttemptSchema = describes()(z.object({
1355
1487
  "failed",
1356
1488
  "interrupted",
1357
1489
  "lost",
1358
- "superseded"
1490
+ "superseded",
1491
+ "restarted"
1359
1492
  ]),
1360
1493
  providerThreadId: z.string().nullable(),
1361
1494
  nativeTurnRef: NativeRefSchema.nullable(),
@@ -1496,6 +1629,22 @@ var ItemSchema = describes()(z.discriminatedUnion("kind", [
1496
1629
  to: z.number().int()
1497
1630
  }),
1498
1631
  text: z.string()
1632
+ }),
1633
+ z.object({
1634
+ ...itemCommon,
1635
+ kind: z.literal("result"),
1636
+ name: z.string(),
1637
+ value: JsonValueSchema,
1638
+ input: z.object({
1639
+ itemId: z.string(),
1640
+ position: z.number().int(),
1641
+ kind: z.enum([
1642
+ "user_message",
1643
+ "inbound_message",
1644
+ "task_notification"
1645
+ ])
1646
+ }).nullable(),
1647
+ commit: z.string().nullable()
1499
1648
  })
1500
1649
  ]).meta({ id: "Item" }));
1501
1650
  var RuntimeRequestResponseSchema = describes()(z.discriminatedUnion("kind", [
@@ -1661,8 +1810,70 @@ var CommandReceiptSchema = describes()(z.object({
1661
1810
  error: z.object({ code: z.string(), message: z.string() }).nullable()
1662
1811
  }).meta({ id: "CommandReceipt" }));
1663
1812
  var SessionCommandSchema = describes()(sessionCommandSchema);
1813
+ var TurnProgressSchema = z.object({
1814
+ id: z.string(),
1815
+ ordinal: z.number().int(),
1816
+ status: z.enum(["preparing", "running", "waiting", "finalizing"]),
1817
+ attempt: z.object({
1818
+ id: z.string(),
1819
+ ordinal: z.number().int(),
1820
+ reason: z.string(),
1821
+ startedAt: z.string().nullable()
1822
+ }).nullable(),
1823
+ attempts: z.number().int(),
1824
+ restarts: z.number().int(),
1825
+ progressAt: z.string().nullable(),
1826
+ stalledAt: z.string().nullable(),
1827
+ stallMinutes: z.number().nullable(),
1828
+ activity: z.object({
1829
+ tools: z.array(z.object({
1830
+ name: z.string(),
1831
+ description: z.string().nullable(),
1832
+ since: z.string()
1833
+ })),
1834
+ commands: z.array(z.object({
1835
+ command: z.string(),
1836
+ description: z.string().nullable(),
1837
+ since: z.string()
1838
+ }))
1839
+ })
1840
+ });
1664
1841
  var AgentSessionDetailSchema = AgentSessionSchema.extend({
1665
- snapshot: SessionSnapshotSchema
1842
+ snapshot: SessionSnapshotSchema,
1843
+ turn: TurnProgressSchema.nullable()
1844
+ });
1845
+ var TurnAttemptsSchema = z.object({
1846
+ attempts: z.array(z.object({
1847
+ id: z.string(),
1848
+ ordinal: z.number().int(),
1849
+ reason: z.string(),
1850
+ status: z.string(),
1851
+ error: z.object({ message: z.string() }).nullable(),
1852
+ startedAt: z.string().nullable(),
1853
+ completedAt: z.string().nullable(),
1854
+ progressAt: z.string().nullable(),
1855
+ stalledAt: z.string().nullable(),
1856
+ diagnostics: z.object({ runner: z.string(), harness: z.string() }).nullable()
1857
+ }))
1858
+ });
1859
+ var TurnIdParamsSchema = z.object({
1860
+ projectId: z.string().uuid(),
1861
+ sessionId: z.string().uuid(),
1862
+ turnId: z.string().uuid()
1863
+ });
1864
+ var RestartTurnSchema = z.object({
1865
+ attemptId: z.string().uuid(),
1866
+ reason: z.string().min(1).max(500),
1867
+ onlyIfStalled: z.boolean().optional(),
1868
+ idempotencyKey: z.string().min(1).max(300)
1869
+ });
1870
+ var RestartTurnResultSchema = z.object({
1871
+ restarted: z.literal(true),
1872
+ turnId: z.string(),
1873
+ attemptId: z.string(),
1874
+ attempt: z.number().int(),
1875
+ attempts: z.number().int(),
1876
+ restarts: z.number().int()
1666
1877
  });
1667
1878
  var SessionItemsQuerySchema = z.object({
1668
1879
  before: z.coerce.number().int().positive(),
@@ -1672,9 +1883,41 @@ var SessionItemsPageSchema = z.object({
1672
1883
  items: z.array(ItemSchema),
1673
1884
  olderBefore: z.number().int().nullable()
1674
1885
  });
1886
+ var SessionResultSchema = z.object({
1887
+ id: z.string(),
1888
+ sessionId: z.string(),
1889
+ turnId: z.string().nullable(),
1890
+ attemptId: z.string().nullable(),
1891
+ name: z.string(),
1892
+ value: JsonValueSchema,
1893
+ input: z.object({
1894
+ itemId: z.string(),
1895
+ position: z.number().int(),
1896
+ kind: z.enum(["user_message", "inbound_message", "task_notification"])
1897
+ }).nullable(),
1898
+ current: z.boolean(),
1899
+ commit: z.string().nullable(),
1900
+ recordedAt: z.string()
1901
+ }).meta({ id: "SessionResult" });
1902
+ var SessionResultsQuerySchema = z.object({
1903
+ name: z.string().min(1).max(64).optional(),
1904
+ family: z.enum(["true", "false"]).transform((value) => value === "true").optional(),
1905
+ turnId: z.string().uuid().optional(),
1906
+ afterInput: z.string().uuid().optional(),
1907
+ limit: z.coerce.number().int().min(1).max(100).optional()
1908
+ });
1909
+ var SessionResultsSchema = z.object({
1910
+ results: z.array(SessionResultSchema)
1911
+ });
1675
1912
  var SessionEventsQuerySchema = z.object({
1676
1913
  after: z.coerce.number().int().nonnegative().optional()
1677
1914
  });
1915
+ var SessionMissedEventsQuerySchema = z.object({
1916
+ after: z.coerce.number().int().nonnegative()
1917
+ });
1918
+ var SessionMissedEventsSchema = z.object({
1919
+ messages: z.array(SessionStreamMessageSchema)
1920
+ });
1678
1921
  var SessionMirrorQuerySchema = z.object({
1679
1922
  after: z.coerce.number().int().nonnegative().optional()
1680
1923
  });
@@ -1872,7 +2115,10 @@ var ProjectAgentDefinitionSchema = z.object({
1872
2115
  skills: z.array(z.string()).optional(),
1873
2116
  acp: z.object({
1874
2117
  endpoint: z.string().optional(),
1875
- command: z.array(z.string()).optional()
2118
+ command: z.array(z.string()).optional(),
2119
+ shell: z.boolean().optional(),
2120
+ projectConfig: z.boolean().optional(),
2121
+ env: z.record(z.string(), z.string()).optional()
1876
2122
  }).optional()
1877
2123
  });
1878
2124
  var ProjectAgentEntrySchema = z.object({
@@ -2311,11 +2557,46 @@ data: ${JSON.stringify(message)}
2311
2557
  }
2312
2558
 
2313
2559
  // src/routes/agent.ts
2560
+ var SESSION_OPERATION_STATUS = {
2561
+ not_found: 404,
2562
+ not_authorized: 403,
2563
+ invalid_input: 400,
2564
+ agent_unknown: 400,
2565
+ environment_unavailable: 409,
2566
+ environment_full: 409,
2567
+ authentication_required: 428,
2568
+ session_closed: 409,
2569
+ session_elsewhere: 409,
2570
+ request_not_pending: 409,
2571
+ idempotency_conflict: 409,
2572
+ internal: 500
2573
+ };
2574
+ var SessionOperationErrorResponses = {
2575
+ 400: SessionOperationErrorSchema,
2576
+ 403: SessionOperationErrorSchema,
2577
+ 404: SessionOperationErrorSchema,
2578
+ 409: SessionOperationErrorSchema,
2579
+ 428: SessionOperationErrorSchema,
2580
+ 500: SessionOperationErrorSchema,
2581
+ 503: SessionOperationErrorSchema
2582
+ };
2583
+ function sendSessionOperationError(reply, error) {
2584
+ if (error instanceof TokenScopeRequiredError)
2585
+ throw error;
2586
+ const refused = sessionOperationError(error);
2587
+ return reply.status(SESSION_OPERATION_STATUS[refused.code]).send({
2588
+ error: refused.message,
2589
+ code: refused.code,
2590
+ retryable: refused.retryable,
2591
+ ...refused.sessionId ? { sessionId: refused.sessionId } : {}
2592
+ });
2593
+ }
2314
2594
  function registerAgentRoutes(app, ctx) {
2315
2595
  const typed = app.withTypeProvider();
2316
2596
  typed.route({
2317
2597
  method: "POST",
2318
2598
  url: "/projects/:projectId/agent/sessions",
2599
+ config: { tokenScope: "sessions:run" },
2319
2600
  schema: {
2320
2601
  params: ProjectIdParamsSchema,
2321
2602
  body: CreateAgentSessionSchema,
@@ -2404,6 +2685,7 @@ function registerAgentRoutes(app, ctx) {
2404
2685
  typed.route({
2405
2686
  method: "PATCH",
2406
2687
  url: "/projects/:projectId/agent/sessions/:sessionId",
2688
+ config: { tokenScope: "sessions:run" },
2407
2689
  schema: {
2408
2690
  params: AgentSessionIdParamsSchema,
2409
2691
  body: UpdateAgentSessionSchema,
@@ -2501,6 +2783,75 @@ function registerAgentRoutes(app, ctx) {
2501
2783
  }
2502
2784
  }
2503
2785
  });
2786
+ typed.route({
2787
+ method: "POST",
2788
+ url: "/projects/:projectId/agent/sessions/start",
2789
+ config: { tokenScope: "sessions:run" },
2790
+ schema: {
2791
+ params: ProjectIdParamsSchema,
2792
+ body: StartSessionSchema,
2793
+ response: {
2794
+ 200: SESSION_OPERATIONS2.session_start.output,
2795
+ ...SessionOperationErrorResponses
2796
+ }
2797
+ },
2798
+ handler: async (request, reply) => {
2799
+ const operations = ctx.core?.sessionOperations;
2800
+ if (!operations)
2801
+ return reply.status(503).send({
2802
+ error: "Coding agent not configured",
2803
+ code: "internal",
2804
+ retryable: true
2805
+ });
2806
+ const identity = resolveIdentity(request);
2807
+ try {
2808
+ return reply.send(SESSION_OPERATIONS2.session_start.output.parse(await operations.execute({
2809
+ identity,
2810
+ projectId: request.params.projectId,
2811
+ operation: "session_start",
2812
+ args: request.body,
2813
+ author: { kind: "user", externalUserId: identity.externalUserId }
2814
+ })));
2815
+ } catch (error) {
2816
+ return sendSessionOperationError(reply, error);
2817
+ }
2818
+ }
2819
+ });
2820
+ typed.route({
2821
+ method: "POST",
2822
+ url: "/projects/:projectId/agent/sessions/wait",
2823
+ config: { tokenScope: "work:read" },
2824
+ schema: {
2825
+ params: ProjectIdParamsSchema,
2826
+ body: SESSION_OPERATIONS2.session_wait.input,
2827
+ response: {
2828
+ 200: SESSION_OPERATIONS2.session_wait.output,
2829
+ ...SessionOperationErrorResponses
2830
+ }
2831
+ },
2832
+ handler: async (request, reply) => {
2833
+ const operations = ctx.core?.sessionOperations;
2834
+ if (!operations)
2835
+ return reply.status(503).send({
2836
+ error: "Coding agent not configured",
2837
+ code: "internal",
2838
+ retryable: true
2839
+ });
2840
+ const identity = resolveIdentity(request);
2841
+ try {
2842
+ return reply.send(SESSION_OPERATIONS2.session_wait.output.parse(await operations.execute({
2843
+ identity,
2844
+ projectId: request.params.projectId,
2845
+ operation: "session_wait",
2846
+ args: request.body,
2847
+ author: { kind: "user", externalUserId: identity.externalUserId },
2848
+ signal: hungUp(reply)
2849
+ })));
2850
+ } catch (error) {
2851
+ return sendSessionOperationError(reply, error);
2852
+ }
2853
+ }
2854
+ });
2504
2855
  typed.route({
2505
2856
  method: "GET",
2506
2857
  url: "/projects/:projectId/agent/sessions/:sessionId",
@@ -2556,6 +2907,116 @@ function registerAgentRoutes(app, ctx) {
2556
2907
  }
2557
2908
  }
2558
2909
  });
2910
+ typed.route({
2911
+ method: "GET",
2912
+ url: "/projects/:projectId/agent/sessions/:sessionId/results",
2913
+ schema: {
2914
+ params: AgentSessionIdParamsSchema,
2915
+ querystring: SessionResultsQuerySchema,
2916
+ response: {
2917
+ 200: SessionResultsSchema,
2918
+ 400: ErrorSchema,
2919
+ 404: ErrorSchema,
2920
+ 503: ErrorSchema
2921
+ }
2922
+ },
2923
+ handler: async (request, reply) => {
2924
+ const agentSessions = ctx.core?.agentSessions;
2925
+ if (!agentSessions)
2926
+ return reply.status(503).send({ error: "Coding agent not configured" });
2927
+ const query = request.query;
2928
+ try {
2929
+ const results = await agentSessions.results(resolveIdentity(request), request.params.projectId, request.params.sessionId, {
2930
+ ...query.name ? { name: query.name } : {},
2931
+ ...query.family ? { family: true } : {},
2932
+ ...query.turnId ? { turnId: query.turnId } : {},
2933
+ ...query.afterInput ? { afterInput: query.afterInput } : {},
2934
+ ...query.limit ? { limit: query.limit } : {}
2935
+ });
2936
+ return reply.send({ results });
2937
+ } catch (error) {
2938
+ if (error instanceof ProjectNotFoundError || error instanceof AgentSessionNotFoundError)
2939
+ return reply.status(404).send({ error: "Session not found" });
2940
+ if (error instanceof SessionInputNotFoundError)
2941
+ return reply.status(400).send({ error: error.message });
2942
+ throw error;
2943
+ }
2944
+ }
2945
+ });
2946
+ typed.route({
2947
+ method: "GET",
2948
+ url: "/projects/:projectId/agent/sessions/:sessionId/turns/:turnId/attempts",
2949
+ schema: {
2950
+ params: TurnIdParamsSchema,
2951
+ response: {
2952
+ 200: TurnAttemptsSchema,
2953
+ 404: ErrorSchema,
2954
+ 503: ErrorSchema
2955
+ }
2956
+ },
2957
+ handler: async (request, reply) => {
2958
+ const agentSessions = ctx.core?.agentSessions;
2959
+ if (!agentSessions)
2960
+ return reply.status(503).send({ error: "Coding agent not configured" });
2961
+ try {
2962
+ const attempts = await agentSessions.attempts(resolveIdentity(request), request.params.projectId, request.params.sessionId, { turnId: request.params.turnId });
2963
+ return reply.send({ attempts });
2964
+ } catch (error) {
2965
+ if (error instanceof ProjectNotFoundError || error instanceof AgentSessionNotFoundError)
2966
+ return reply.status(404).send({ error: "Session not found" });
2967
+ throw error;
2968
+ }
2969
+ }
2970
+ });
2971
+ typed.route({
2972
+ method: "POST",
2973
+ url: "/projects/:projectId/agent/sessions/:sessionId/turns/:turnId/restart",
2974
+ config: { tokenScope: "sessions:run" },
2975
+ schema: {
2976
+ params: TurnIdParamsSchema,
2977
+ body: RestartTurnSchema,
2978
+ response: {
2979
+ 200: RestartTurnResultSchema,
2980
+ 202: z2.object({ delivery: z2.literal("queued") }).passthrough(),
2981
+ 404: ErrorSchema,
2982
+ 409: ErrorSchema,
2983
+ 503: ErrorSchema
2984
+ }
2985
+ },
2986
+ handler: async (request, reply) => {
2987
+ const actions = ctx.core?.sessionOperations;
2988
+ if (!actions)
2989
+ return reply.status(503).send({ error: "Coding agent not configured" });
2990
+ const identity = resolveIdentity(request);
2991
+ try {
2992
+ const result = await actions.execute({
2993
+ identity,
2994
+ projectId: request.params.projectId,
2995
+ operation: "session_restart",
2996
+ args: {
2997
+ sessionId: request.params.sessionId,
2998
+ turnId: request.params.turnId,
2999
+ attemptId: request.body.attemptId,
3000
+ reason: request.body.reason,
3001
+ ...request.body.onlyIfStalled !== undefined ? { onlyIfStalled: request.body.onlyIfStalled } : {},
3002
+ idempotencyKey: request.body.idempotencyKey
3003
+ },
3004
+ author: { kind: "user", externalUserId: identity.externalUserId }
3005
+ });
3006
+ const parsed = RestartTurnResultSchema.safeParse(result);
3007
+ if (parsed.success)
3008
+ return reply.send(parsed.data);
3009
+ const refused = z2.object({ restarted: z2.literal(false), message: z2.string() }).safeParse(result);
3010
+ if (refused.success)
3011
+ return reply.status(409).send({ error: refused.data.message });
3012
+ return reply.status(202).send({ delivery: "queued" });
3013
+ } catch (error) {
3014
+ if (error instanceof ProjectNotFoundError || error instanceof AgentSessionNotFoundError)
3015
+ return reply.status(404).send({ error: "Session not found" });
3016
+ throw error;
3017
+ }
3018
+ }
3019
+ });
2559
3020
  typed.route({
2560
3021
  method: "GET",
2561
3022
  url: "/projects/:projectId/agent/sessions/:sessionId/events",
@@ -2603,9 +3064,37 @@ function registerAgentRoutes(app, ctx) {
2603
3064
  return reply;
2604
3065
  }
2605
3066
  });
3067
+ typed.route({
3068
+ method: "GET",
3069
+ url: "/projects/:projectId/agent/sessions/:sessionId/events/missed",
3070
+ schema: {
3071
+ params: AgentSessionIdParamsSchema,
3072
+ querystring: SessionMissedEventsQuerySchema,
3073
+ response: {
3074
+ 200: SessionMissedEventsSchema,
3075
+ 404: ErrorSchema,
3076
+ 503: ErrorSchema
3077
+ }
3078
+ },
3079
+ handler: async (request, reply) => {
3080
+ const agentSessions = ctx.core?.agentSessions;
3081
+ if (!agentSessions)
3082
+ return reply.status(503).send({ error: "Coding agent not configured" });
3083
+ try {
3084
+ return reply.send({
3085
+ messages: await agentSessions.missedEvents(resolveIdentity(request), request.params.projectId, request.params.sessionId, { after: request.query.after })
3086
+ });
3087
+ } catch (error) {
3088
+ if (error instanceof ProjectNotFoundError || error instanceof AgentSessionNotFoundError)
3089
+ return reply.status(404).send({ error: "Session not found" });
3090
+ throw error;
3091
+ }
3092
+ }
3093
+ });
2606
3094
  typed.route({
2607
3095
  method: "POST",
2608
3096
  url: "/projects/:projectId/agent/sessions/:sessionId/commands",
3097
+ config: { tokenScope: "sessions:run" },
2609
3098
  bodyLimit: 96 * 1024 * 1024,
2610
3099
  schema: {
2611
3100
  params: AgentSessionIdParamsSchema,
@@ -2644,6 +3133,7 @@ function registerAgentRoutes(app, ctx) {
2644
3133
  typed.route({
2645
3134
  method: "POST",
2646
3135
  url: "/projects/:projectId/agent/sessions/:sessionId/resume",
3136
+ config: { tokenScope: "sessions:run" },
2647
3137
  schema: {
2648
3138
  params: AgentSessionIdParamsSchema,
2649
3139
  body: ResumeAgentSessionSchema,
@@ -2794,6 +3284,7 @@ function registerAgentRoutes(app, ctx) {
2794
3284
  typed.route({
2795
3285
  method: "POST",
2796
3286
  url: "/projects/:projectId/agent/sessions/:sessionId/attention/acknowledge",
3287
+ config: { tokenScope: "sessions:run" },
2797
3288
  schema: {
2798
3289
  params: AgentSessionIdParamsSchema,
2799
3290
  body: z2.object({ observedRevision: z2.number().int().nonnegative().optional() }).nullish(),
@@ -2819,6 +3310,42 @@ function registerAgentRoutes(app, ctx) {
2819
3310
  }
2820
3311
  }
2821
3312
  });
3313
+ typed.route({
3314
+ method: "GET",
3315
+ url: "/projects/:projectId/agent/sessions/:sessionId/usage",
3316
+ schema: {
3317
+ params: AgentSessionIdParamsSchema,
3318
+ querystring: AgentSessionUsageQuerySchema,
3319
+ response: {
3320
+ 200: AgentSessionUsageSchema,
3321
+ 403: ErrorSchema,
3322
+ 404: ErrorSchema,
3323
+ 503: ErrorSchema
3324
+ }
3325
+ },
3326
+ handler: async (request, reply) => {
3327
+ const agentSessions = ctx.core?.agentSessions;
3328
+ if (!agentSessions) {
3329
+ return reply.status(503).send({ error: "Coding agent not configured" });
3330
+ }
3331
+ try {
3332
+ return reply.send(await agentSessions.usage({
3333
+ identity: resolveIdentity(request),
3334
+ projectId: request.params.projectId,
3335
+ sessionId: request.params.sessionId,
3336
+ family: request.query.family ?? false
3337
+ }));
3338
+ } catch (error) {
3339
+ if (error instanceof ProjectNotFoundError || error instanceof AgentSessionNotFoundError) {
3340
+ return reply.status(404).send({ error: "Session not found" });
3341
+ }
3342
+ if (error instanceof AccessDeniedError) {
3343
+ return reply.status(403).send({ error: error.message });
3344
+ }
3345
+ throw error;
3346
+ }
3347
+ }
3348
+ });
2822
3349
  typed.route({
2823
3350
  method: "GET",
2824
3351
  url: "/projects/:projectId/agent/sessions/:sessionId/peers",
@@ -2848,6 +3375,7 @@ function registerAgentRoutes(app, ctx) {
2848
3375
  typed.route({
2849
3376
  method: "POST",
2850
3377
  url: "/projects/:projectId/agent/sessions/:sessionId/subsessions",
3378
+ config: { tokenScope: "sessions:run" },
2851
3379
  schema: {
2852
3380
  params: AgentSessionIdParamsSchema,
2853
3381
  body: CreateAgentSubsessionSchema,
@@ -2911,36 +3439,10 @@ function registerAgentRoutes(app, ctx) {
2911
3439
  }
2912
3440
  }
2913
3441
  });
2914
- typed.route({
2915
- method: "POST",
2916
- url: "/projects/:projectId/agent/sessions/:sessionId/subsessions/wait",
2917
- schema: {
2918
- params: AgentSessionIdParamsSchema,
2919
- body: WaitForAgentSubsessionsSchema,
2920
- response: {
2921
- 200: AgentSubsessionSchema.array(),
2922
- 404: ErrorSchema,
2923
- 503: ErrorSchema
2924
- }
2925
- },
2926
- handler: async (request, reply) => {
2927
- const agentSessions = ctx.core?.agentSessions;
2928
- if (!agentSessions) {
2929
- return reply.status(503).send({ error: "Coding agent not configured" });
2930
- }
2931
- try {
2932
- return reply.send(await agentSessions.waitForSubsessions(resolveIdentity(request), request.params.projectId, request.params.sessionId, { ...request.body, stopWaiting: hungUp(reply) }));
2933
- } catch (error) {
2934
- if (error instanceof ProjectNotFoundError || error instanceof AgentSessionNotFoundError) {
2935
- return reply.status(404).send({ error: "Session not found" });
2936
- }
2937
- throw error;
2938
- }
2939
- }
2940
- });
2941
3442
  typed.route({
2942
3443
  method: "POST",
2943
3444
  url: "/projects/:projectId/agent/sessions/:sessionId/subsessions/:childSessionId/interrupt",
3445
+ config: { tokenScope: "sessions:run" },
2944
3446
  schema: {
2945
3447
  params: AgentSubsessionIdParamsSchema,
2946
3448
  response: {
@@ -2972,6 +3474,7 @@ function registerAgentRoutes(app, ctx) {
2972
3474
  typed.route({
2973
3475
  method: "POST",
2974
3476
  url: "/projects/:projectId/agent/sessions/:sessionId/attention",
3477
+ config: { tokenScope: "sessions:run" },
2975
3478
  schema: {
2976
3479
  params: AgentSessionIdParamsSchema,
2977
3480
  response: {
@@ -2998,6 +3501,7 @@ function registerAgentRoutes(app, ctx) {
2998
3501
  typed.route({
2999
3502
  method: "PATCH",
3000
3503
  url: "/projects/:projectId/agent/sessions/:sessionId/activity",
3504
+ config: { tokenScope: "sessions:run" },
3001
3505
  schema: {
3002
3506
  params: AgentSessionIdParamsSchema,
3003
3507
  body: UpdateAgentSessionActivitySchema,
@@ -3030,6 +3534,7 @@ function registerAgentRoutes(app, ctx) {
3030
3534
  typed.route({
3031
3535
  method: "PATCH",
3032
3536
  url: "/projects/:projectId/agent/sessions/:sessionId/title",
3537
+ config: { tokenScope: "sessions:run" },
3033
3538
  schema: {
3034
3539
  params: AgentSessionIdParamsSchema,
3035
3540
  body: RenameAgentSessionSchema,
@@ -3062,6 +3567,7 @@ function registerAgentRoutes(app, ctx) {
3062
3567
  typed.route({
3063
3568
  method: "PATCH",
3064
3569
  url: "/projects/:projectId/agent/sessions/:sessionId/metadata",
3570
+ config: { tokenScope: "sessions:run" },
3065
3571
  schema: {
3066
3572
  params: AgentSessionIdParamsSchema,
3067
3573
  body: UpdateAgentSessionMetadataSchema,
@@ -3104,6 +3610,7 @@ function registerAgentRoutes(app, ctx) {
3104
3610
  typed.route({
3105
3611
  method: "POST",
3106
3612
  url: "/projects/:projectId/agent/sessions/:sessionId/fork",
3613
+ config: { tokenScope: "sessions:run" },
3107
3614
  schema: {
3108
3615
  params: AgentSessionIdParamsSchema,
3109
3616
  body: ForkAgentSessionSchema,
@@ -3132,6 +3639,7 @@ function registerAgentRoutes(app, ctx) {
3132
3639
  typed.route({
3133
3640
  method: "DELETE",
3134
3641
  url: "/projects/:projectId/agent/sessions/:sessionId",
3642
+ config: { tokenScope: "sessions:run" },
3135
3643
  schema: {
3136
3644
  params: AgentSessionIdParamsSchema,
3137
3645
  response: { 200: AgentSessionSchema, 404: ErrorSchema, 503: ErrorSchema }
@@ -3189,6 +3697,7 @@ function registerAgentRoutes(app, ctx) {
3189
3697
  typed.route({
3190
3698
  method: "DELETE",
3191
3699
  url: "/projects/:projectId/agent/chats/:key",
3700
+ config: { tokenScope: "sessions:run" },
3192
3701
  schema: {
3193
3702
  params: KeyedChatParamsSchema,
3194
3703
  querystring: KeyedChatQuerySchema,
@@ -3250,6 +3759,7 @@ function registerAgentRoutes(app, ctx) {
3250
3759
  typed.route({
3251
3760
  method: "POST",
3252
3761
  url: "/projects/:projectId/agent/sessions/:sessionId/archive",
3762
+ config: { tokenScope: "sessions:run" },
3253
3763
  schema: {
3254
3764
  params: AgentSessionIdParamsSchema,
3255
3765
  body: ArchiveAgentSessionSchema,
@@ -3285,6 +3795,7 @@ function registerAgentRoutes(app, ctx) {
3285
3795
  typed.route({
3286
3796
  method: "POST",
3287
3797
  url: "/projects/:projectId/agent/sessions/:sessionId/unarchive",
3798
+ config: { tokenScope: "sessions:run" },
3288
3799
  schema: {
3289
3800
  params: AgentSessionIdParamsSchema,
3290
3801
  response: {
@@ -3530,6 +4041,7 @@ import {
3530
4041
  RunCapabilityError,
3531
4042
  RunEnrollmentConflictError,
3532
4043
  RunInputInvalidError,
4044
+ RunQueueFullError,
3533
4045
  SandboxProviderNotConfiguredError,
3534
4046
  TenantActiveRunLimitError,
3535
4047
  WorkflowNotFoundError
@@ -3544,7 +4056,7 @@ function replyForTriggerError(err, reply) {
3544
4056
  if (err instanceof ProductionDeploymentNotFoundError) {
3545
4057
  return reply.status(409).send({ error: err.message });
3546
4058
  }
3547
- if (err instanceof RunEnrollmentConflictError) {
4059
+ if (err instanceof RunEnrollmentConflictError || err instanceof RunQueueFullError) {
3548
4060
  return reply.status(409).send({ error: err.message });
3549
4061
  }
3550
4062
  if (err instanceof AuthenticationRequiredError2) {
@@ -4078,56 +4590,95 @@ function registerAppRoutes(app, ctx) {
4078
4590
 
4079
4591
  // src/routes/apps-mcp.ts
4080
4592
  import { buildAppGuestDocument as buildAppGuestDocument2 } from "@catamorphic/app";
4081
- var RUN_CALL_BUDGET_MS = 120000;
4082
- function registerAppsMcpRoutes(app, ctx) {
4083
- app.post("/projects/:projectId/apps-mcp", async (request, reply) => {
4593
+
4594
+ // src/mcp-scopes.ts
4595
+ import { randomBytes } from "node:crypto";
4596
+ import {
4597
+ hasTokenScope
4598
+ } from "@catamorphic/core";
4599
+ var DOCUMENT_WRITES = new Set(["documents_write", "documents_delete"]);
4600
+ var PROGRAM_WRITES = new Set([
4601
+ "program_write",
4602
+ "program_files",
4603
+ "program_check",
4604
+ "program_discard",
4605
+ "propose_change"
4606
+ ]);
4607
+ var PUBLISHES = new Set([
4608
+ "program_deploy",
4609
+ "publish_document",
4610
+ "revoke_publication",
4611
+ "share_create",
4612
+ "share_revoke"
4613
+ ]);
4614
+ function toolScope(tool) {
4615
+ if (tool.scope)
4616
+ return tool.scope;
4617
+ const name = String(tool.definition.name);
4618
+ if (DOCUMENT_WRITES.has(name))
4619
+ return "documents:write";
4620
+ if (PUBLISHES.has(name))
4621
+ return "program:publish";
4622
+ if (PROGRAM_WRITES.has(name))
4623
+ return "program:write";
4624
+ const annotations = Object(tool.definition.annotations);
4625
+ return annotations.readOnlyHint === true ? "work:read" : "sessions:run";
4626
+ }
4627
+ function mayCallTool(identity, tool) {
4628
+ return hasTokenScope(identity, toolScope(tool));
4629
+ }
4630
+ function withheldTools(identity, tools) {
4631
+ return new Map(tools.filter((tool) => !mayCallTool(identity, tool)).map((tool) => [String(tool.definition.name), toolScope(tool)]));
4632
+ }
4633
+ var PROCESS_SECRET = randomBytes(32).toString("hex");
4634
+ function mcpStateSecret(ctx) {
4635
+ return ctx.mcp?.stateSecret ?? PROCESS_SECRET;
4636
+ }
4637
+
4638
+ // src/routes/apps-mcp.ts
4639
+ var RUN_CALL_BUDGET_MS = 120000;
4640
+ function registerAppsMcpRoutes(app, ctx) {
4641
+ app.post("/projects/:projectId/apps-mcp", { config: { tokenScope: "work:read" } }, async (request, reply) => {
4084
4642
  const core = ctx.core;
4085
4643
  if (!core?.apps || !core.runs) {
4086
4644
  return reply.status(503).send({ error: "Apps not configured" });
4087
4645
  }
4088
4646
  const { projectId } = request.params;
4089
- return handleMcpPost(reply, request.body, async (method, params) => {
4090
- const identity = resolveIdentity(request);
4091
- switch (method) {
4092
- case "initialize":
4093
- return {
4094
- protocolVersion: negotiateProtocolVersion(params.protocolVersion),
4095
- capabilities: { tools: { listChanged: false }, resources: {} },
4096
- serverInfo: {
4097
- name: "catamorphic-apps",
4098
- title: "Catamorphic apps",
4099
- version: "1.0.0"
4100
- }
4101
- };
4102
- case "ping":
4103
- return {};
4104
- case "tools/list": {
4105
- const apps = await loadPublishedApps(core, identity, projectId);
4106
- return { tools: buildTools(apps) };
4107
- }
4108
- case "resources/list": {
4109
- const apps = await loadPublishedApps(core, identity, projectId);
4110
- return {
4111
- resources: apps.map((published) => ({
4112
- uri: appResourceUri(published.name),
4113
- name: `${published.name} app`,
4114
- mimeType: MCP_APP_MIME_TYPE
4115
- }))
4116
- };
4117
- }
4118
- case "resources/templates/list":
4119
- return { resourceTemplates: [] };
4120
- case "prompts/list":
4121
- return { prompts: [] };
4122
- case "resources/read": {
4123
- const uri = typeof params.uri === "string" ? params.uri : "";
4124
- const apps = await loadPublishedApps(core, identity, projectId);
4125
- const published = apps.find((candidate) => appResourceUri(candidate.name) === uri);
4126
- if (!published) {
4127
- throw new McpRequestError2(-32602, `Unknown resource ${uri}`);
4128
- }
4129
- return {
4130
- contents: [
4647
+ const identity = resolveIdentity(request);
4648
+ let loaded;
4649
+ const apps = () => {
4650
+ loaded ??= loadPublishedApps(core, identity, projectId);
4651
+ return loaded;
4652
+ };
4653
+ const tools = async () => buildTools(await apps()).map((definition) => ({
4654
+ definition,
4655
+ scope: definition.name === POLL_RUN_TOOL ? "work:read" : "sessions:run",
4656
+ call: (args) => callTool(core, identity, projectId, String(definition.name), args)
4657
+ }));
4658
+ return serveMcp({
4659
+ request,
4660
+ reply,
4661
+ resourceMetadataUrl: ctx.mcp?.resourceMetadataUrl,
4662
+ endpoint: {
4663
+ serverInfo: {
4664
+ name: "catamorphic-apps",
4665
+ title: "Catamorphic apps",
4666
+ version: "1.0.0"
4667
+ },
4668
+ tools: async () => (await tools()).filter((tool) => mayCallTool(identity, tool)),
4669
+ withheld: async () => withheldTools(identity, await tools()),
4670
+ resources: {
4671
+ list: async () => (await apps()).map((published) => ({
4672
+ uri: appResourceUri(published.name),
4673
+ name: `${published.name} app`,
4674
+ mimeType: MCP_APP_MIME_TYPE
4675
+ })),
4676
+ templates: async () => [],
4677
+ read: async (uri) => {
4678
+ const published = (await apps()).find((candidate) => appResourceUri(candidate.name) === uri);
4679
+ if (!published)
4680
+ throw new McpError2(MCP_ERROR2.invalidParams, `Unknown resource ${uri}`);
4681
+ return [
4131
4682
  {
4132
4683
  uri,
4133
4684
  mimeType: MCP_APP_MIME_TYPE,
@@ -4139,16 +4690,9 @@ function registerAppsMcpRoutes(app, ctx) {
4139
4690
  }
4140
4691
  }
4141
4692
  }
4142
- ]
4143
- };
4144
- }
4145
- case "tools/call": {
4146
- const name = typeof params.name === "string" ? params.name : "";
4147
- const args = typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {};
4148
- return callTool(core, identity, projectId, name, args);
4693
+ ];
4694
+ }
4149
4695
  }
4150
- default:
4151
- throw new McpRequestError2(-32601, `Method not found: ${method}`);
4152
4696
  }
4153
4697
  });
4154
4698
  });
@@ -4305,7 +4849,9 @@ function registerClientRunnerRoutes(app, ctx) {
4305
4849
  "containers",
4306
4850
  "network.policy",
4307
4851
  "network.setup",
4308
- "volumes"
4852
+ "volumes",
4853
+ "caches",
4854
+ "commands.separate"
4309
4855
  ])).optional(),
4310
4856
  publicKey: ExecutorPublicKeySchema.optional()
4311
4857
  }),
@@ -4672,8 +5218,8 @@ function registerConnectionMcpRoutes(app, ctx) {
4672
5218
  }
4673
5219
  const mcp = broker.servesMcp(binding.providerKind);
4674
5220
  return serveForwardedTools2({
5221
+ request,
4675
5222
  reply,
4676
- body: request.body,
4677
5223
  serverName: "catamorphic-connection-broker",
4678
5224
  listTools: async () => {
4679
5225
  try {
@@ -4688,12 +5234,12 @@ function registerConnectionMcpRoutes(app, ctx) {
4688
5234
  outputSchema: undefined
4689
5235
  }));
4690
5236
  } catch {
4691
- throw new McpRequestError2(-32000, "Connection action failed");
5237
+ throw new McpError2(-32000, "Connection action failed");
4692
5238
  }
4693
5239
  },
4694
5240
  callTool: async (call) => {
4695
5241
  if (!binding.capabilities.includes(call.name)) {
4696
- throw new McpRequestError2(-32602, "Tool is outside the connection grant");
5242
+ throw new McpError2(-32602, "Tool is outside the connection grant");
4697
5243
  }
4698
5244
  try {
4699
5245
  const output = await broker.invoke({
@@ -4710,7 +5256,7 @@ function registerConnectionMcpRoutes(app, ctx) {
4710
5256
  if (error instanceof ConnectionActionDeniedError || error instanceof ConnectionActionRefusedError) {
4711
5257
  return toolError2(error.message);
4712
5258
  }
4713
- throw new McpRequestError2(-32000, "Connection action failed");
5259
+ throw new McpError2(-32000, "Connection action failed");
4714
5260
  }
4715
5261
  }
4716
5262
  });
@@ -5301,6 +5847,7 @@ function registerDocumentRoutes(app, ctx) {
5301
5847
  typed.route({
5302
5848
  method: "PUT",
5303
5849
  url: "/projects/:projectId/documents/content",
5850
+ config: { tokenScope: "documents:write" },
5304
5851
  bodyLimit: Math.ceil(ctx.features.storeUploadMaxBytes * 4 / 3) + 65536,
5305
5852
  schema: {
5306
5853
  params: ProjectIdParamsSchema,
@@ -5339,6 +5886,7 @@ function registerDocumentRoutes(app, ctx) {
5339
5886
  typed.route({
5340
5887
  method: "DELETE",
5341
5888
  url: "/projects/:projectId/documents/content",
5889
+ config: { tokenScope: "documents:write" },
5342
5890
  schema: {
5343
5891
  params: ProjectIdParamsSchema,
5344
5892
  querystring: z8.object({
@@ -5423,6 +5971,7 @@ function registerDocumentRoutes(app, ctx) {
5423
5971
  typed.route({
5424
5972
  method: "POST",
5425
5973
  url: "/projects/:projectId/proposals",
5974
+ config: { tokenScope: "program:write" },
5426
5975
  schema: {
5427
5976
  params: ProjectIdParamsSchema,
5428
5977
  body: ProposeChangeSchema,
@@ -5560,6 +6109,7 @@ function registerDocumentRoutes(app, ctx) {
5560
6109
  typed.route({
5561
6110
  method: "POST",
5562
6111
  url: "/projects/:projectId/proposals/:number/comments",
6112
+ config: { tokenScope: "program:write" },
5563
6113
  schema: {
5564
6114
  params: ProjectIdParamsSchema.extend({
5565
6115
  number: z8.coerce.number().int().positive()
@@ -5589,7 +6139,11 @@ function registerDocumentRoutes(app, ctx) {
5589
6139
  }
5590
6140
 
5591
6141
  // src/routes/environments.ts
5592
- import { AccessDeniedError as AccessDeniedError5, AgentNotConfiguredError as AgentNotConfiguredError2 } from "@catamorphic/core";
6142
+ import {
6143
+ AccessDeniedError as AccessDeniedError5,
6144
+ AgentNotConfiguredError as AgentNotConfiguredError2,
6145
+ hasProjectPermission
6146
+ } from "@catamorphic/core";
5593
6147
  function registerEnvironmentRoutes(app, ctx) {
5594
6148
  const typed = app.withTypeProvider();
5595
6149
  typed.route({
@@ -5642,6 +6196,37 @@ function registerEnvironmentRoutes(app, ctx) {
5642
6196
  }
5643
6197
  }
5644
6198
  });
6199
+ typed.route({
6200
+ method: "GET",
6201
+ url: "/projects/:projectId/environment-caches",
6202
+ schema: {
6203
+ params: ProjectIdParamsSchema,
6204
+ response: {
6205
+ 200: EnvironmentCacheListSchema,
6206
+ 403: ErrorSchema,
6207
+ 503: ErrorSchema
6208
+ }
6209
+ },
6210
+ handler: async (request, reply) => {
6211
+ const service = ctx.core?.cacheFills;
6212
+ if (!service)
6213
+ return reply.status(503).send({ error: "Environment provider not configured" });
6214
+ const identity = resolveIdentity(request);
6215
+ if (!hasProjectPermission(identity, request.params.projectId, "automations:read"))
6216
+ return reply.status(403).send({ error: "Seeing caches needs automations:read" });
6217
+ try {
6218
+ const items = await service.list({
6219
+ identity,
6220
+ projectId: request.params.projectId
6221
+ });
6222
+ return reply.send(EnvironmentCacheListSchema.parse({ items }));
6223
+ } catch (error) {
6224
+ if (error instanceof AccessDeniedError5)
6225
+ return reply.status(403).send({ error: error.message });
6226
+ throw error;
6227
+ }
6228
+ }
6229
+ });
5645
6230
  }
5646
6231
 
5647
6232
  // src/routes/git-gateway.ts
@@ -6159,6 +6744,7 @@ import {
6159
6744
  RunInputInvalidError as RunInputInvalidError2,
6160
6745
  TenantActiveRunLimitError as TenantActiveRunLimitError2,
6161
6746
  TriggerBindingsInvalidError,
6747
+ TriggerKindHostOnlyError,
6162
6748
  TriggerKindNotRegisteredError,
6163
6749
  TriggerModeNotAllowedError,
6164
6750
  TriggerPayloadInvalidError
@@ -6229,6 +6815,7 @@ function registerTriggerRoutes(app, ctx) {
6229
6815
  body: FireTriggerSchema,
6230
6816
  response: {
6231
6817
  200: TriggerFireResultSchema,
6818
+ 403: ErrorSchema,
6232
6819
  404: ErrorSchema,
6233
6820
  409: ErrorSchema,
6234
6821
  422: ErrorSchema,
@@ -6310,7 +6897,7 @@ function handleTriggerError(err, reply) {
6310
6897
  requirements: [...err.requirements]
6311
6898
  });
6312
6899
  }
6313
- if (err instanceof EnvironmentAccessDeniedError3) {
6900
+ if (err instanceof EnvironmentAccessDeniedError3 || err instanceof TriggerKindHostOnlyError) {
6314
6901
  return reply.status(403).send({ error: err.message });
6315
6902
  }
6316
6903
  if (err instanceof EnvironmentNotFoundError3) {
@@ -7040,8 +7627,10 @@ import {
7040
7627
  EnvironmentNotFoundError as EnvironmentNotFoundError4,
7041
7628
  EnvironmentPolicyInvalidError,
7042
7629
  ProductionDeploymentNotFoundError as ProductionDeploymentNotFoundError3,
7630
+ PublishedRevisionNotRetryableError,
7043
7631
  WorkflowEnablementConflictError,
7044
7632
  WorkflowEnablementConsentRequiredError,
7633
+ WorkflowEnablementFollowUnavailableError,
7045
7634
  WorkflowEnablementNotFoundError,
7046
7635
  WorkflowEnablementSuspendedError,
7047
7636
  WorkflowNotFoundError as WorkflowNotFoundError2
@@ -7134,7 +7723,10 @@ function registerWorkflowEnablementRoutes(app, ctx) {
7134
7723
  url: "/projects/:projectId/workflow-enablements",
7135
7724
  schema: {
7136
7725
  params: ProjectIdParamsSchema,
7137
- body: PreviewBodySchema.extend({ consentDigest: z15.string().length(64) }),
7726
+ body: PreviewBodySchema.extend({
7727
+ consentDigest: z15.string().length(64),
7728
+ follow: z15.boolean().optional()
7729
+ }),
7138
7730
  response: {
7139
7731
  201: WorkflowEnablementSchema,
7140
7732
  403: ErrorSchema,
@@ -7263,6 +7855,107 @@ function registerWorkflowEnablementRoutes(app, ctx) {
7263
7855
  }
7264
7856
  }
7265
7857
  });
7858
+ typed.route({
7859
+ method: "POST",
7860
+ url: "/projects/:projectId/workflow-enablements/:enablementId/follow",
7861
+ schema: {
7862
+ params: EnablementParamsSchema,
7863
+ body: z15.object({ follow: z15.boolean() }),
7864
+ response: {
7865
+ 200: WorkflowEnablementSchema,
7866
+ 403: ErrorSchema,
7867
+ 404: ErrorSchema,
7868
+ 409: PreviewConflictSchema
7869
+ }
7870
+ },
7871
+ handler: async (request, reply) => {
7872
+ const workflowEnablements = service();
7873
+ if (!workflowEnablements) {
7874
+ return reply.status(404).send({ error: "Workflow enablement not found" });
7875
+ }
7876
+ try {
7877
+ const identity = resolveIdentity(request);
7878
+ const current = await workflowEnablements.get({
7879
+ identity,
7880
+ enablementId: request.params.enablementId
7881
+ });
7882
+ if (current.projectId !== request.params.projectId) {
7883
+ return reply.status(404).send({ error: "Workflow enablement not found" });
7884
+ }
7885
+ return reply.send(await workflowEnablements.setFollow({
7886
+ identity,
7887
+ enablementId: request.params.enablementId,
7888
+ follow: request.body.follow
7889
+ }));
7890
+ } catch (error) {
7891
+ return handleEnablementError(error, reply);
7892
+ }
7893
+ }
7894
+ });
7895
+ typed.route({
7896
+ method: "GET",
7897
+ url: "/projects/:projectId/published-revisions",
7898
+ schema: {
7899
+ params: ProjectIdParamsSchema,
7900
+ querystring: z15.object({
7901
+ limit: z15.coerce.number().int().min(1).max(100).optional()
7902
+ }),
7903
+ response: {
7904
+ 200: z15.object({ items: z15.array(PublishedRevisionSchema) }),
7905
+ 403: ErrorSchema,
7906
+ 503: ErrorSchema
7907
+ }
7908
+ },
7909
+ handler: async (request, reply) => {
7910
+ const revisions = ctx.core?.publishedRevisions;
7911
+ if (!revisions) {
7912
+ return reply.status(503).send({ error: "Published revisions unavailable" });
7913
+ }
7914
+ try {
7915
+ return reply.send({
7916
+ items: await revisions.list({
7917
+ identity: resolveIdentity(request),
7918
+ projectId: request.params.projectId,
7919
+ ...request.query.limit ? { limit: request.query.limit } : {}
7920
+ })
7921
+ });
7922
+ } catch (error) {
7923
+ return handleEnablementError(error, reply);
7924
+ }
7925
+ }
7926
+ });
7927
+ registerPublishedRevisionRetryRoute(app, ctx);
7928
+ }
7929
+ function registerPublishedRevisionRetryRoute(app, ctx) {
7930
+ app.withTypeProvider().route({
7931
+ method: "POST",
7932
+ url: "/projects/:projectId/published-revisions/retry",
7933
+ schema: {
7934
+ params: ProjectIdParamsSchema,
7935
+ response: {
7936
+ 200: PublishedRevisionSchema,
7937
+ 403: ErrorSchema,
7938
+ 409: ErrorSchema,
7939
+ 503: ErrorSchema
7940
+ }
7941
+ },
7942
+ handler: async (request, reply) => {
7943
+ const revisions = ctx.core?.publishedRevisions;
7944
+ if (!revisions) {
7945
+ return reply.status(503).send({ error: "Published revisions unavailable" });
7946
+ }
7947
+ try {
7948
+ return reply.send(await revisions.retry({
7949
+ identity: resolveIdentity(request),
7950
+ projectId: request.params.projectId
7951
+ }));
7952
+ } catch (error) {
7953
+ if (error instanceof PublishedRevisionNotRetryableError)
7954
+ return reply.status(409).send({ error: error.message });
7955
+ return handleEnablementError(error, reply);
7956
+ }
7957
+ }
7958
+ });
7266
7959
  }
7267
7960
  function handleEnablementError(error, reply) {
7268
7961
  if (error instanceof AuthenticationRequiredError4) {
@@ -7285,7 +7978,7 @@ function handleEnablementError(error, reply) {
7285
7978
  if (error instanceof AccessDeniedError7 || error instanceof ConnectionPermissionDeniedError3 || error instanceof EnvironmentAccessDeniedError4) {
7286
7979
  return reply.status(403).send({ error: error.message });
7287
7980
  }
7288
- if (error instanceof WorkflowEnablementConsentRequiredError || error instanceof WorkflowEnablementConflictError || error instanceof ConnectionUnavailableError3 || error instanceof EnvironmentNotFoundError4 || error instanceof EnvironmentPolicyInvalidError || error instanceof EnvironmentIncompatibleError4 || error instanceof EnvironmentBindingUnavailableError4 || error instanceof WorkflowEnablementSuspendedError) {
7981
+ if (error instanceof WorkflowEnablementConsentRequiredError || error instanceof WorkflowEnablementConflictError || error instanceof WorkflowEnablementFollowUnavailableError || error instanceof ConnectionUnavailableError3 || error instanceof EnvironmentNotFoundError4 || error instanceof EnvironmentPolicyInvalidError || error instanceof EnvironmentIncompatibleError4 || error instanceof EnvironmentBindingUnavailableError4 || error instanceof WorkflowEnablementSuspendedError) {
7289
7982
  return reply.status(409).send({ error: error.message });
7290
7983
  }
7291
7984
  throw error;
@@ -7488,7 +8181,7 @@ function registerPrivateCustomizationRoutes(app, ctx) {
7488
8181
 
7489
8182
  // src/routes/project-mcp.ts
7490
8183
  import { agentCapabilityTools } from "@catamorphic/sandbox";
7491
- import { z as z20 } from "zod";
8184
+ import { z as z22 } from "zod";
7492
8185
 
7493
8186
  // src/project-mcp-program.ts
7494
8187
  import {
@@ -7497,7 +8190,7 @@ import {
7497
8190
  assertProjectPermission as assertProjectPermission2,
7498
8191
  DeploymentBlockedError,
7499
8192
  effectiveProjectPermissions as effectiveProjectPermissions2,
7500
- hasProjectPermission,
8193
+ hasProjectPermission as hasProjectPermission2,
7501
8194
  mayUseProject
7502
8195
  } from "@catamorphic/core";
7503
8196
  import { checkProject } from "@catamorphic/parser";
@@ -7513,7 +8206,7 @@ function programTools(core, identity, projectId) {
7513
8206
  if (!mayUseProject(identity, projectId))
7514
8207
  return [];
7515
8208
  const tools = [overviewTool(core, identity, projectId)];
7516
- const may = (permission) => hasProjectPermission(identity, projectId, permission);
8209
+ const may = (permission) => hasProjectPermission2(identity, projectId, permission);
7517
8210
  if (may("program:write")) {
7518
8211
  tools.push({
7519
8212
  definition: {
@@ -7728,7 +8421,7 @@ function overviewTool(core, identity, projectId) {
7728
8421
  return;
7729
8422
  throw error;
7730
8423
  });
7731
- const may = (permission) => hasProjectPermission(identity, projectId, permission);
8424
+ const may = (permission) => hasProjectPermission2(identity, projectId, permission);
7732
8425
  const [project, roles, agents, environments, workflows, apps, draft] = await Promise.all([
7733
8426
  optional(() => core.projects.getOverview({ identity, projectId })),
7734
8427
  optional(async () => core.memberships?.describeMember({
@@ -7902,8 +8595,8 @@ async function projectInstructions(args) {
7902
8595
  if (has("list_skills"))
7903
8596
  lines.push("- Read the project's skills (list_skills, read_skill) before writing workflows or apps: writing-workflows and building-apps hold the contracts.");
7904
8597
  lines.push("- Run deployed workflows with workflow_run and debug them with workflow_runs and run_details.");
7905
- if (has("ask_agent"))
7906
- lines.push("- ask_agent runs one of the project's agents on the server, in an Environment you may use. Server agents reach connected systems, such as a production database, through the reviewed gateway; you never receive those credentials.");
8598
+ if (has("session_start"))
8599
+ lines.push("- Run one of the project's agents on the server with session_start: it returns a sessionId at once, so keep working and call session_wait with the returned cursor until state is idle, failed or needs_input. Answer its questions with session_answer; approvals go to your person. Server agents reach connected systems, such as a production database, through the reviewed gateway; you never receive those credentials.");
7907
8600
  if (args.host)
7908
8601
  lines.push(args.host);
7909
8602
  return lines.join(`
@@ -7918,15 +8611,10 @@ import {
7918
8611
  } from "@catamorphic/agent-protocol";
7919
8612
  import {
7920
8613
  AccessDeniedError as AccessDeniedError9,
7921
- AgentTurnUnsettledError,
7922
- EVERY_ARTIFACT,
7923
8614
  mayUseProject as mayUseProject2,
7924
- parseWorkspaceRequest,
7925
- projectAgentId,
7926
- resolveScope,
7927
- SESSION_ACTION_SCHEMAS
8615
+ resolveScope
7928
8616
  } from "@catamorphic/core";
7929
- import { z as z19 } from "zod";
8617
+ import { z as z20 } from "zod";
7930
8618
 
7931
8619
  // src/app-presentation-tools.ts
7932
8620
  import { APP_ICON_DESCRIPTIONS, APP_ICON_NAMES as APP_ICON_NAMES4 } from "@catamorphic/app";
@@ -8099,6 +8787,115 @@ function sessionArtifactTool(core, identity, projectId, currentSessionId) {
8099
8787
  };
8100
8788
  }
8101
8789
 
8790
+ // src/session-tools.ts
8791
+ import {
8792
+ SESSION_OPERATION_NAMES,
8793
+ SESSION_OPERATIONS as SESSION_OPERATIONS3,
8794
+ sessionOperationError as sessionOperationError2
8795
+ } from "@catamorphic/core";
8796
+ import { z as z19 } from "zod";
8797
+ function sessionResourceUri(sessionId) {
8798
+ return `work://sessions/${sessionId}`;
8799
+ }
8800
+ var ATTENTION_RESOURCE_URI = "work://attention";
8801
+ var Linked = z19.looseObject({
8802
+ sessionId: z19.string(),
8803
+ title: z19.string().nullable().optional()
8804
+ });
8805
+ function sessionToolResult(value) {
8806
+ const linked = Linked.safeParse(value);
8807
+ return {
8808
+ content: [
8809
+ { type: "text", text: JSON.stringify(value) ?? "null" },
8810
+ ...linked.success ? [
8811
+ {
8812
+ type: "resource_link",
8813
+ uri: sessionResourceUri(linked.data.sessionId),
8814
+ name: linked.data.title || "Chat",
8815
+ mimeType: "application/json"
8816
+ }
8817
+ ] : []
8818
+ ],
8819
+ structuredContent: value
8820
+ };
8821
+ }
8822
+ function sessionToolError(error) {
8823
+ return {
8824
+ content: [
8825
+ {
8826
+ type: "text",
8827
+ text: JSON.stringify(sessionOperationError2(error).toJSON())
8828
+ }
8829
+ ],
8830
+ isError: true
8831
+ };
8832
+ }
8833
+ async function sessionToolAuthor(args) {
8834
+ const sessions = args.core.agentSessions;
8835
+ if (!sessions || !args.currentSessionId || !args.projectId)
8836
+ return {
8837
+ author: {
8838
+ kind: "assistant",
8839
+ externalUserId: args.identity.externalUserId
8840
+ },
8841
+ causation: []
8842
+ };
8843
+ const source = await sessions.get(args.identity, args.projectId, args.currentSessionId);
8844
+ return {
8845
+ author: { kind: "agent", sessionId: source.id, agentId: source.agentId },
8846
+ causation: await sessions.causalContext({
8847
+ identity: args.identity,
8848
+ projectId: args.projectId,
8849
+ sessionId: source.id
8850
+ })
8851
+ };
8852
+ }
8853
+ function sessionTools(args) {
8854
+ const operations = args.core.sessionOperations;
8855
+ if (!operations)
8856
+ return [];
8857
+ return SESSION_OPERATION_NAMES.map((name) => {
8858
+ const definition = SESSION_OPERATIONS3[name];
8859
+ return {
8860
+ definition: {
8861
+ name,
8862
+ title: definition.title,
8863
+ description: definition.description,
8864
+ inputSchema: z19.toJSONSchema(definition.input, { io: "input" }),
8865
+ outputSchema: definition.outputSchema,
8866
+ annotations: {
8867
+ title: definition.title,
8868
+ ...definition.annotations,
8869
+ openWorldHint: false
8870
+ }
8871
+ },
8872
+ scope: definition.scope,
8873
+ call: async (input, context) => {
8874
+ try {
8875
+ const origin = await sessionToolAuthor({
8876
+ core: args.core,
8877
+ identity: args.identity,
8878
+ projectId: args.projectId,
8879
+ currentSessionId: args.currentSessionId
8880
+ });
8881
+ const value = await operations.execute({
8882
+ identity: args.identity,
8883
+ ...args.projectId ? { projectId: args.projectId } : {},
8884
+ operation: name,
8885
+ args: input,
8886
+ ...origin,
8887
+ ...context?.signal && definition.annotations.readOnlyHint ? { signal: context.signal } : {}
8888
+ });
8889
+ const shaped = definition.output.safeParse(value);
8890
+ return sessionToolResult(shaped.success ? shaped.data : value);
8891
+ } catch (error) {
8892
+ return sessionToolError(error);
8893
+ }
8894
+ }
8895
+ };
8896
+ });
8897
+ }
8898
+
8102
8899
  // src/project-mcp-surface.ts
8103
8900
  var READ_ONLY2 = { readOnlyHint: true };
8104
8901
  async function allowedWorkflowNames(core, identity, projectId) {
@@ -8448,65 +9245,19 @@ function surfaceTools(core, identity, projectId, features = { publications: "pub
8448
9245
  }
8449
9246
  if (core.agentSessions) {
8450
9247
  const sessions = core.agentSessions;
8451
- const agentNames = (identity.scope ?? []).filter((ref) => ref.kind === "agent" && ref.projectId === projectId).map((ref) => ref.name);
8452
- const hint = agentNames.includes(EVERY_ARTIFACT) || identity.scope === undefined ? "any committed project agent (.work/agents/<slug>.json)" : agentNames.length > 0 ? `one of: ${agentNames.join(", ")}` : "none available to you";
8453
- tools.push({
8454
- definition: {
8455
- name: "ask_agent",
8456
- description: `Ask one of the project's agents (${hint}) and get its reply — a full turn with the agent's own tools and persona. Pass sessionId to continue an earlier conversation, or environment to choose where a new one runs.`,
8457
- inputSchema: {
8458
- type: "object",
8459
- properties: {
8460
- agent: { type: "string", description: "The agent's slug" },
8461
- message: { type: "string" },
8462
- sessionId: { type: "string" },
8463
- environment: {
8464
- type: "string",
8465
- description: "Environment for a new conversation (project_overview lists yours)"
8466
- }
8467
- },
8468
- required: ["agent", "message"]
8469
- }
8470
- },
8471
- call: guarded(async (args) => {
8472
- const agent = str(args.agent);
8473
- const message = str(args.message);
8474
- if (!agent || !message)
8475
- throw new Error("agent and message are required");
8476
- const agentId = projectAgentId(projectId, agent);
8477
- const sessionId = str(args.sessionId) ?? (await sessions.create(identity, projectId, {
8478
- agentId,
8479
- source: "mcp",
8480
- ...str(args.environment) ? { environment: str(args.environment) } : {}
8481
- })).id;
8482
- const from = currentSessionId ? {
8483
- kind: "agent",
8484
- sessionId: currentSessionId,
8485
- agentId: (await sessions.get(identity, projectId, currentSessionId)).agentId
8486
- } : {
8487
- kind: "assistant",
8488
- externalUserId: identity.externalUserId
8489
- };
8490
- try {
8491
- const { reply } = await sessions.sendMessage(identity, projectId, sessionId, message, { from });
8492
- return {
8493
- sessionId,
8494
- reply: reply?.kind === "assistant_message" ? reply.text : ""
8495
- };
8496
- } catch (error) {
8497
- if (error instanceof AgentTurnUnsettledError)
8498
- return { sessionId, state: error.state, reply: error.message };
8499
- throw error;
8500
- }
8501
- })
8502
- });
9248
+ tools.push(...sessionTools({
9249
+ core,
9250
+ identity,
9251
+ projectId,
9252
+ ...currentSessionId ? { currentSessionId } : {}
9253
+ }));
8503
9254
  if (currentSessionId) {
8504
9255
  const sessionId = currentSessionId;
8505
9256
  tools.push({
8506
9257
  definition: {
8507
9258
  name: "set_session_metadata",
8508
9259
  description: SET_SESSION_METADATA_DESCRIPTION,
8509
- inputSchema: z19.toJSONSchema(setSessionMetadataInputSchema)
9260
+ inputSchema: z20.toJSONSchema(setSessionMetadataInputSchema)
8510
9261
  },
8511
9262
  call: guarded(async (args) => {
8512
9263
  const values = sessionMetadataToolWrite(args);
@@ -8521,100 +9272,13 @@ function surfaceTools(core, identity, projectId, features = { publications: "pub
8521
9272
  })
8522
9273
  });
8523
9274
  }
8524
- tools.push({
8525
- definition: {
8526
- name: "send_agent_message",
8527
- description: "Deliver an attributed message from your current session to this or another agent session. queue (the default) wakes an idle session or runs after its active turn; steer adds it to the active turn so the agent sees it while it works; interrupt stops the active turn and runs this next; message_only records it without waking the agent. Set attention to required to alert the user to this message, independently of whether the agent should run. Use interrupt only when delay would make the work wrong.",
8528
- inputSchema: {
8529
- type: "object",
8530
- properties: {
8531
- fromSessionId: { type: "string" },
8532
- toSessionId: { type: "string" },
8533
- message: { type: "string" },
8534
- mode: {
8535
- type: "string",
8536
- enum: ["queue", "steer", "interrupt", "message_only"],
8537
- default: "queue"
8538
- },
8539
- attention: { type: "string", enum: ["none", "required"] },
8540
- idempotencyKey: { type: "string" },
8541
- workspace: {
8542
- type: "object",
8543
- description: "Move the receiving session's workspace to a ref of the project's linked remote before its next turn (a branch, tag, commit, or refs/pull/<n>/head). update: rebase (default) keeps its commits, reset discards them.",
8544
- properties: {
8545
- ref: { type: "string" },
8546
- update: { type: "string", enum: ["reset", "rebase"] }
8547
- },
8548
- required: ["ref"],
8549
- additionalProperties: false
8550
- }
8551
- },
8552
- required: ["toSessionId", "message"]
8553
- }
8554
- },
8555
- call: guarded(async (args) => {
8556
- const fromSessionId = str(args.fromSessionId) ?? currentSessionId;
8557
- const toSessionId = str(args.toSessionId);
8558
- const message = str(args.message);
8559
- const mode = args.mode === undefined ? "queue" : args.mode;
8560
- if (!fromSessionId || !toSessionId || !message || mode !== "queue" && mode !== "steer" && mode !== "interrupt" && mode !== "message_only") {
8561
- throw new Error("fromSessionId, toSessionId, message, and a valid mode are required");
8562
- }
8563
- if (args.attention !== undefined && args.attention !== "none" && args.attention !== "required")
8564
- throw new Error("attention must be none or required");
8565
- const source = await sessions.get(identity, projectId, fromSessionId);
8566
- return sessions.deliver(identity, projectId, toSessionId, {
8567
- content: message,
8568
- author: {
8569
- kind: "agent",
8570
- sessionId: fromSessionId,
8571
- agentId: source.agentId
8572
- },
8573
- mode,
8574
- attention: args.attention,
8575
- ...str(args.idempotencyKey) ? { idempotencyKey: str(args.idempotencyKey) } : {},
8576
- ...args.workspace === undefined ? {} : { workspace: parseWorkspaceRequest(args.workspace) }
8577
- });
8578
- })
8579
- });
8580
- if (core.sessionActions) {
8581
- const actions = core.sessionActions;
8582
- for (const operation of Object.keys(SESSION_ACTION_SCHEMAS)) {
8583
- tools.push({
8584
- definition: {
8585
- name: `session_${operation}`,
8586
- description: `Session ${operation}. Uses the same authorized operation as workflows. Name the chat by sessionId, or by the project's key for it (key, with audience "project" for the project chat). Mutations require a stable idempotencyKey; retries return the existing result. Load the session-workflows skill for examples.`,
8587
- inputSchema: z19.toJSONSchema(SESSION_ACTION_SCHEMAS[operation])
8588
- },
8589
- call: guarded(async (args) => {
8590
- const source = currentSessionId ? await sessions.get(identity, projectId, currentSessionId) : undefined;
8591
- return actions.execute({
8592
- identity,
8593
- projectId,
8594
- operation,
8595
- args,
8596
- author: source ? {
8597
- kind: "agent",
8598
- sessionId: source.id,
8599
- agentId: source.agentId
8600
- } : { kind: "user", externalUserId: identity.externalUserId },
8601
- causation: source ? await sessions.causalContext({
8602
- identity,
8603
- projectId,
8604
- sessionId: source.id
8605
- }) : []
8606
- });
8607
- })
8608
- });
8609
- }
8610
- }
8611
9275
  if (core.watchers) {
8612
9276
  const watchers = core.watchers;
8613
9277
  const eventSources = core.projectEventSources.map((source) => source.kind);
8614
9278
  tools.push({
8615
9279
  definition: {
8616
9280
  name: "create_watcher",
8617
- description: `Temporarily enable an ordinary TypeScript workflow owned by this session. To repeat a shell check (a URL, a file, a CLI), use the host's watch_command when it is offered: it runs where your commands run. For periodic monitoring with workflow IO, declare a normal schedule trigger. For event-driven work, use normalized Project Events already supplied by this host. Stop, expiry, or session close/archive disables future invocations. The source must export the named defineWorkflow and declare one or more inline triggers, for example triggers: [trigger("issue.changed")]. Event triggers receive the normalized Project Event envelope; schedule triggers receive their normal scheduled payload. To notify or wake a session, return context.host["catamorphic.sessions"].deliver({ sessionId, content, mode, idempotencyKey }) from a boundary. Pass source directly; do not write it to the user working tree. The host places it at .work/workflows/src/artifacts/<id>.ts in an isolated committed-origin checkout, so imports must already exist in that origin. workflowName must be exported by this source. The workflow is committed to an isolated work/artifacts/<id> ref, pinned, and never merged into project main. This is temporary execution, not private storage. Call stop_watcher when the task is complete. Load the workflow-lifecycle skill for lifetime and publishing guidance.${eventSources.length ? ` This host can also observe outside systems that cannot reach it with a webhook: pass eventSource (${eventSources.join(", ")}) and the host polls for new events from now on and records them as Project Events shaped like the webhook deliveries the source replaces, so bind the project's trigger kinds for that webhook (for example from .work/triggers/).` : ""}`,
9281
+ description: `Temporarily enable an ordinary TypeScript workflow owned by this session. To repeat a shell check (a URL, a file, a CLI), use the host's watch_command when it is offered: it runs where your commands run. For periodic monitoring with workflow IO, declare a normal schedule trigger. For event-driven work, use normalized Project Events already supplied by this host. Stop, expiry, or session close/archive disables future invocations. The source must export the named defineWorkflow and declare one or more inline triggers, for example triggers: [trigger("issue.changed")]. Event triggers receive the normalized Project Event envelope; schedule triggers receive their normal scheduled payload. To notify or wake a session, return context.host["catamorphic.sessions"].deliver({ sessionId, content, mode, idempotencyKey }) from a boundary. Pass source directly; do not write it to the user working tree. The host places it at .work/workflows/src/artifacts/<id>.ts in an isolated committed-origin checkout, so imports must already exist in that origin. workflowName must be exported by this source. The workflow is committed to an isolated work/artifacts/<id> ref, pinned, and never merged into project main. This is temporary execution, not private storage. Call session_stop_watcher with the watcher's id when the task is complete. Load the workflow-lifecycle skill for lifetime and publishing guidance.${eventSources.length ? ` This host can also observe outside systems that cannot reach it with a webhook: pass eventSource (${eventSources.join(", ")}) and the host polls for new events from now on and records them as Project Events shaped like the webhook deliveries the source replaces, so bind the project's trigger kinds for that webhook (for example from .work/triggers/).` : ""}`,
8618
9282
  inputSchema: {
8619
9283
  type: "object",
8620
9284
  properties: {
@@ -8687,47 +9351,513 @@ function surfaceTools(core, identity, projectId, features = { publications: "pub
8687
9351
  sessionId
8688
9352
  });
8689
9353
  })
8690
- }, {
8691
- definition: {
8692
- name: "stop_watcher",
8693
- description: "Stop a temporary watcher owned by a session.",
8694
- inputSchema: {
8695
- type: "object",
8696
- properties: {
8697
- sessionId: { type: "string" },
8698
- watcherId: { type: "string" }
8699
- },
8700
- required: ["watcherId"]
8701
- }
8702
- },
8703
- call: guarded(async (args) => {
8704
- const sessionId = str(args.sessionId) ?? currentSessionId;
8705
- const watcherId = str(args.watcherId);
8706
- if (!sessionId || !watcherId) {
8707
- throw new Error("sessionId and watcherId are required");
8708
- }
8709
- return {
8710
- stopped: await watchers.stop({
8711
- identity,
8712
- projectId,
8713
- sessionId,
8714
- watcherId
8715
- })
8716
- };
8717
- })
8718
9354
  });
8719
9355
  }
8720
9356
  }
8721
9357
  return tools;
8722
9358
  }
8723
9359
 
9360
+ // src/session-mcp.ts
9361
+ import { createHmac, timingSafeEqual } from "node:crypto";
9362
+ import {
9363
+ hasTokenScope as hasTokenScope2,
9364
+ parseWaitCursor,
9365
+ SESSION_OPERATIONS as SESSION_OPERATIONS4,
9366
+ SessionStateSchema,
9367
+ sessionOperationError as sessionOperationError3
9368
+ } from "@catamorphic/core";
9369
+ import { z as z21 } from "zod";
9370
+ var REQUEST_STATE_TTL_MS = 30 * 60000;
9371
+ var TASK_POLL_INTERVAL_MS = 2000;
9372
+ var TASK_INLINE_WAIT_SECONDS = 2;
9373
+ function elicitationFor(request, options) {
9374
+ const form = (message, requestedSchema) => ({
9375
+ method: "elicitation/create",
9376
+ params: { mode: "form", message, requestedSchema }
9377
+ });
9378
+ if (request.kind === "question" && request.questions?.length) {
9379
+ const properties = {};
9380
+ request.questions.forEach((question, index) => {
9381
+ const labels = question.options.map((option) => option.label);
9382
+ const described = {
9383
+ title: question.header || `Question ${index + 1}`,
9384
+ description: question.question
9385
+ };
9386
+ properties[`answer${index + 1}`] = labels.length === 0 ? { type: "string", ...described } : question.multiSelect ? {
9387
+ type: "array",
9388
+ ...described,
9389
+ minItems: 1,
9390
+ items: { type: "string", enum: labels }
9391
+ } : { type: "string", ...described, enum: labels };
9392
+ });
9393
+ return form(request.title || "The agent has a question", {
9394
+ type: "object",
9395
+ properties,
9396
+ required: Object.keys(properties)
9397
+ });
9398
+ }
9399
+ if (request.kind === "approval" && request.approval && options.mayApprove)
9400
+ return form([request.title, request.approval.action, request.approval.details].filter(Boolean).join(`
9401
+ `), {
9402
+ type: "object",
9403
+ properties: {
9404
+ decision: {
9405
+ type: "string",
9406
+ title: "Decision",
9407
+ description: "always: approve, and allow this tool from now on without asking",
9408
+ enum: ["approve", "deny", "always"]
9409
+ }
9410
+ },
9411
+ required: ["decision"]
9412
+ });
9413
+ if (request.kind === "elicitation" && request.elicitation?.schema)
9414
+ return form(request.elicitation.message, request.elicitation.schema);
9415
+ return;
9416
+ }
9417
+ var Elicited = z21.looseObject({
9418
+ action: z21.enum(["accept", "decline", "cancel"]),
9419
+ content: z21.record(z21.string(), z21.unknown()).optional()
9420
+ });
9421
+ function responseFor(request, answer) {
9422
+ const elicited = Elicited.safeParse(answer);
9423
+ if (!elicited.success)
9424
+ return;
9425
+ const content = elicited.data.content ?? {};
9426
+ if (request.kind === "elicitation")
9427
+ return {
9428
+ kind: "elicitation",
9429
+ action: elicited.data.action,
9430
+ ...elicited.data.action === "accept" ? { content } : {}
9431
+ };
9432
+ if (elicited.data.action !== "accept")
9433
+ return;
9434
+ if (request.kind === "approval") {
9435
+ const decision = content.decision;
9436
+ if (decision !== "approve" && decision !== "deny" && decision !== "always")
9437
+ return;
9438
+ return {
9439
+ kind: "approval",
9440
+ decision: decision === "deny" ? "denied" : "approved",
9441
+ ...decision === "always" ? { remember: "always" } : {}
9442
+ };
9443
+ }
9444
+ const answers = (request.questions ?? []).map((_question, index) => {
9445
+ const value = content[`answer${index + 1}`];
9446
+ return Array.isArray(value) ? value.map(String).join(", ") : value;
9447
+ });
9448
+ if (answers.some((value) => typeof value !== "string" || value === ""))
9449
+ return;
9450
+ return { kind: "question", answers };
9451
+ }
9452
+ var RequestState = z21.object({
9453
+ sub: z21.string(),
9454
+ tool: z21.literal("session_wait"),
9455
+ sessions: z21.array(z21.string()),
9456
+ requests: z21.array(z21.string()),
9457
+ exp: z21.number()
9458
+ });
9459
+ function signRequestState(payload, secret) {
9460
+ const body = Buffer.from(JSON.stringify(payload)).toString("base64url");
9461
+ const mac = createHmac("sha256", secret).update(body).digest("base64url");
9462
+ return `${body}.${mac}`;
9463
+ }
9464
+ function verifyRequestState(state, expected) {
9465
+ const refuse = () => new McpError2(MCP_ERROR2.invalidParams, "Invalid or expired requestState: call session_wait again without it.", { status: 400 });
9466
+ const [body, mac, ...rest] = state.split(".");
9467
+ if (!body || !mac || rest.length > 0)
9468
+ throw refuse();
9469
+ const wanted = createHmac("sha256", expected.secret).update(body).digest();
9470
+ const given = Buffer.from(mac, "base64url");
9471
+ if (given.length !== wanted.length || !timingSafeEqual(given, wanted))
9472
+ throw refuse();
9473
+ let payload;
9474
+ try {
9475
+ payload = RequestState.parse(JSON.parse(Buffer.from(body, "base64url").toString("utf8")));
9476
+ } catch {
9477
+ throw refuse();
9478
+ }
9479
+ if (payload.sub !== expected.sub || payload.exp <= Date.now() || [...payload.sessions].sort().join() !== [...expected.sessions].sort().join())
9480
+ throw refuse();
9481
+ return payload;
9482
+ }
9483
+ var WaitArgs = SESSION_OPERATIONS4.session_wait.input;
9484
+ var WaitResult = SESSION_OPERATIONS4.session_wait.output;
9485
+ function sessionMcp(args) {
9486
+ const { core, identity } = args;
9487
+ const operations = core.sessionOperations;
9488
+ const sessions = core.agentSessions;
9489
+ if (!operations || !sessions)
9490
+ return;
9491
+ const principal = `${identity.tenantId}:${identity.externalUserId}`;
9492
+ const mayApprove = hasTokenScope2(identity, "sessions:approve");
9493
+ const projectOf = async (sessionId) => args.projectId ?? await sessions.projectOfSession({ identity, sessionId });
9494
+ const run = async (operation, input, signal) => operations.execute({
9495
+ identity,
9496
+ ...args.projectId ? { projectId: args.projectId } : {},
9497
+ operation,
9498
+ args: input,
9499
+ ...await sessionToolAuthor({
9500
+ core,
9501
+ identity,
9502
+ projectId: args.projectId,
9503
+ currentSessionId: args.currentSessionId
9504
+ }),
9505
+ ...signal ? { signal } : {}
9506
+ });
9507
+ const asks = (states) => {
9508
+ const inputRequests = {};
9509
+ for (const state of states)
9510
+ for (const request of state.requests) {
9511
+ const form = request.blocking ? elicitationFor(request, { mayApprove }) : undefined;
9512
+ if (form)
9513
+ inputRequests[request.requestId] = form;
9514
+ }
9515
+ return inputRequests;
9516
+ };
9517
+ const answer = async (states, inputResponses, salt) => {
9518
+ for (const state of states)
9519
+ for (const request of state.requests) {
9520
+ if (!(request.requestId in inputResponses))
9521
+ continue;
9522
+ const response = responseFor(request, inputResponses[request.requestId]);
9523
+ if (!response)
9524
+ continue;
9525
+ await run("session_answer", {
9526
+ sessionId: state.sessionId,
9527
+ requestId: request.requestId,
9528
+ response,
9529
+ idempotencyKey: `${salt}:${request.requestId}`
9530
+ });
9531
+ }
9532
+ };
9533
+ const statesOf = async (sessionIds) => {
9534
+ const chats = [];
9535
+ for (const sessionId of sessionIds)
9536
+ chats.push({ projectId: await projectOf(sessionId), sessionId });
9537
+ return sessions.states(identity, { sessions: chats, detail: true });
9538
+ };
9539
+ const waited = (value) => {
9540
+ const shaped = WaitResult.safeParse(value);
9541
+ const result = sessionToolResult(shaped.success ? shaped.data : value);
9542
+ return shaped.success && shaped.data.state === "failed" ? { ...result, isError: true } : result;
9543
+ };
9544
+ const base = sessionTools(args);
9545
+ const tools = base.map((tool) => {
9546
+ if (tool.definition.name !== "session_wait")
9547
+ return tool;
9548
+ return {
9549
+ ...tool,
9550
+ call: async (input, context) => {
9551
+ const parsed = WaitArgs.safeParse(input);
9552
+ if (!parsed.success)
9553
+ return sessionToolError(parsed.error);
9554
+ let wait = parsed.data;
9555
+ try {
9556
+ if (context?.requestState !== undefined) {
9557
+ const state = verifyRequestState(context.requestState, {
9558
+ sub: principal,
9559
+ sessions: wait.sessionIds,
9560
+ secret: args.stateSecret
9561
+ });
9562
+ await answer((await statesOf(wait.sessionIds)).map((chat) => ({
9563
+ ...chat,
9564
+ requests: chat.requests.filter((request) => state.requests.includes(request.requestId))
9565
+ })), context.inputResponses ?? {}, `mrtr:${state.exp}`);
9566
+ wait = {
9567
+ ...wait,
9568
+ cursor: undefined,
9569
+ ...Object.keys(context.inputResponses ?? {}).length === 0 ? { onInput: "return" } : {}
9570
+ };
9571
+ }
9572
+ if (declaresTasks(context)) {
9573
+ const quick = SessionStateSchema.extend({
9574
+ changed: z21.boolean()
9575
+ }).parse(await run("session_wait", { ...wait, timeoutSeconds: TASK_INLINE_WAIT_SECONDS }, context?.signal));
9576
+ if (quick.changed && quick.state !== "needs_input")
9577
+ return waited(quick);
9578
+ const after = parseWaitCursor(quick.cursor, wait.sessionIds);
9579
+ const watched = [];
9580
+ for (const sessionId of new Set(wait.sessionIds))
9581
+ watched.push({
9582
+ projectId: await projectOf(sessionId),
9583
+ sessionId,
9584
+ ...quick.state === "needs_input" ? {} : { after: after.get(sessionId) ?? 0 }
9585
+ });
9586
+ return taskOf(await core.sessionWaits.create({ identity, sessions: watched }), { status: "working", resultType: "task" });
9587
+ }
9588
+ const value = SessionStateSchema.extend({
9589
+ changed: z21.boolean()
9590
+ }).parse(await run("session_wait", wait, context?.signal));
9591
+ if (value.state === "needs_input" && wait.onInput === "ask" && declaresElicitation(context)) {
9592
+ const states = await statesOf(wait.sessionIds);
9593
+ const inputRequests = asks(states);
9594
+ if (Object.keys(inputRequests).length > 0)
9595
+ return {
9596
+ resultType: "input_required",
9597
+ inputRequests,
9598
+ requestState: signRequestState({
9599
+ sub: principal,
9600
+ tool: "session_wait",
9601
+ sessions: [...wait.sessionIds],
9602
+ requests: Object.keys(inputRequests),
9603
+ exp: Date.now() + REQUEST_STATE_TTL_MS
9604
+ }, args.stateSecret)
9605
+ };
9606
+ }
9607
+ return waited(value);
9608
+ } catch (error) {
9609
+ if (error instanceof McpError2)
9610
+ throw error;
9611
+ return sessionToolError(error);
9612
+ }
9613
+ }
9614
+ };
9615
+ });
9616
+ const taskOf = (wait, fields) => ({
9617
+ taskId: wait.id,
9618
+ createdAt: wait.createdAt,
9619
+ lastUpdatedAt: wait.updatedAt,
9620
+ ttlMs: Date.parse(wait.expiresAt) - Date.parse(wait.createdAt),
9621
+ pollIntervalMs: TASK_POLL_INTERVAL_MS,
9622
+ ...fields
9623
+ });
9624
+ const unknownTask = () => new McpError2(MCP_ERROR2.invalidParams, "Unknown task", { status: 404 });
9625
+ const task = async (taskId) => {
9626
+ const wait = await core.sessionWaits.get({ identity, id: taskId });
9627
+ if (!wait)
9628
+ throw unknownTask();
9629
+ if (wait.status === "cancelled")
9630
+ return taskOf(wait, { status: "cancelled" });
9631
+ if (wait.status === "completed")
9632
+ return taskOf(wait, { status: "completed", result: wait.outcome });
9633
+ try {
9634
+ const hit = await sessions.waitFor(identity, {
9635
+ sessions: wait.sessions,
9636
+ timeoutMs: 0
9637
+ });
9638
+ const states = await sessions.states(identity, {
9639
+ sessions: wait.sessions,
9640
+ detail: true
9641
+ });
9642
+ const asking = states.filter((state) => state.state === "needs_input");
9643
+ const inputRequests = asks(asking);
9644
+ if (Object.keys(inputRequests).length > 0)
9645
+ return taskOf(wait, {
9646
+ status: "input_required",
9647
+ statusMessage: "An agent is waiting for an answer",
9648
+ inputRequests
9649
+ });
9650
+ const first = states.find((state) => state.sessionId === hit);
9651
+ if (!first)
9652
+ return taskOf(wait, {
9653
+ status: "working",
9654
+ statusMessage: states.map((state) => state.waiting?.message ?? state.turn?.activity).find((line) => typeof line === "string" && line !== "") ?? "Working"
9655
+ });
9656
+ const others = states.filter((state) => state !== first);
9657
+ const outcome = waited({
9658
+ ...first,
9659
+ changed: true,
9660
+ cursor: states.length === 1 ? first.cursor : states.map((state) => `${state.sessionId}:${state.cursor}`).join(","),
9661
+ ...others.length ? {
9662
+ others: others.map((state) => ({
9663
+ sessionId: state.sessionId,
9664
+ state: state.state,
9665
+ cursor: state.cursor
9666
+ }))
9667
+ } : {}
9668
+ });
9669
+ const done = await core.sessionWaits.complete({
9670
+ identity,
9671
+ id: wait.id,
9672
+ outcome
9673
+ });
9674
+ return done?.status === "completed" ? taskOf(done, { status: "completed", result: done.outcome }) : done ? taskOf(done, { status: done.status }) : taskOf(wait, { status: "completed", result: outcome });
9675
+ } catch (error) {
9676
+ const outcome = sessionToolError(error);
9677
+ const done = await core.sessionWaits.complete({
9678
+ identity,
9679
+ id: wait.id,
9680
+ outcome
9681
+ });
9682
+ return taskOf(done ?? wait, {
9683
+ status: "completed",
9684
+ result: done?.outcome ?? outcome
9685
+ });
9686
+ }
9687
+ };
9688
+ const tasks = {
9689
+ get: task,
9690
+ update: async (taskId, inputResponses) => {
9691
+ const wait = await core.sessionWaits.get({ identity, id: taskId });
9692
+ if (!wait)
9693
+ throw unknownTask();
9694
+ if (wait.status !== "working")
9695
+ return;
9696
+ await answer(await sessions.states(identity, {
9697
+ sessions: wait.sessions,
9698
+ detail: true
9699
+ }), inputResponses, `task:${wait.id}`).catch((error) => {
9700
+ throw new McpError2(MCP_ERROR2.invalidParams, sessionOperationError3(error).message);
9701
+ });
9702
+ },
9703
+ cancel: async (taskId) => {
9704
+ if (!await core.sessionWaits.cancel({ identity, id: taskId }))
9705
+ throw unknownTask();
9706
+ },
9707
+ watch: async (taskIds, changed) => {
9708
+ const seen = new Map;
9709
+ const accepted = [];
9710
+ for (const taskId of taskIds)
9711
+ if (await core.sessionWaits.get({ identity, id: taskId }))
9712
+ accepted.push(taskId);
9713
+ let stopped = false;
9714
+ const look = async () => {
9715
+ for (const taskId of accepted) {
9716
+ if (stopped)
9717
+ return;
9718
+ const state = await task(taskId).catch(() => {
9719
+ return;
9720
+ });
9721
+ if (!state)
9722
+ continue;
9723
+ const print = JSON.stringify([
9724
+ state.status,
9725
+ Object.keys(typeof state.inputRequests === "object" && state.inputRequests ? state.inputRequests : {})
9726
+ ]);
9727
+ if (seen.get(taskId) === print)
9728
+ continue;
9729
+ const first = !seen.has(taskId);
9730
+ seen.set(taskId, print);
9731
+ if (!first || state.status !== "working")
9732
+ changed(state);
9733
+ }
9734
+ };
9735
+ await look();
9736
+ const timer = setInterval(() => void look(), TASK_POLL_INTERVAL_MS);
9737
+ timer.unref?.();
9738
+ return {
9739
+ accepted,
9740
+ stop: () => {
9741
+ stopped = true;
9742
+ clearInterval(timer);
9743
+ }
9744
+ };
9745
+ }
9746
+ };
9747
+ const attention = async () => {
9748
+ const waiting = (await sessions.attention({ identity })).filter((session) => !args.projectId || session.projectId === args.projectId);
9749
+ return sessions.states(identity, {
9750
+ sessions: waiting.map((session) => ({
9751
+ projectId: session.projectId,
9752
+ sessionId: session.id
9753
+ })),
9754
+ detail: false,
9755
+ listed: true
9756
+ });
9757
+ };
9758
+ const sessionIdOf = (uri) => /^work:\/\/sessions\/([0-9a-f-]{36})$/i.exec(uri)?.[1];
9759
+ const notFound = (uri) => new McpError2(MCP_ERROR2.invalidParams, `Resource not found: ${uri}`, {
9760
+ data: { uri }
9761
+ });
9762
+ const json = (uri, value) => [
9763
+ { uri, mimeType: "application/json", text: JSON.stringify(value) }
9764
+ ];
9765
+ const resources = {
9766
+ list: async () => [
9767
+ {
9768
+ uri: ATTENTION_RESOURCE_URI,
9769
+ name: "attention",
9770
+ title: "Chats that need you",
9771
+ description: "The chats waiting on you: an agent asked something, or a turn failed. Listen to it to hear when one does.",
9772
+ mimeType: "application/json"
9773
+ }
9774
+ ],
9775
+ templates: async () => [
9776
+ {
9777
+ uriTemplate: sessionResourceUri("{sessionId}"),
9778
+ name: "session",
9779
+ title: "A chat's state",
9780
+ description: "One chat as session_read returns it. Listen to it to hear when it changes.",
9781
+ mimeType: "application/json"
9782
+ }
9783
+ ],
9784
+ read: async (uri) => {
9785
+ if (uri === ATTENTION_RESOURCE_URI)
9786
+ return json(uri, { sessions: await attention() });
9787
+ const sessionId = sessionIdOf(uri);
9788
+ if (!sessionId)
9789
+ throw notFound(uri);
9790
+ const [state] = await statesOf([sessionId]).catch(() => []);
9791
+ if (!state)
9792
+ throw notFound(uri);
9793
+ return json(uri, state);
9794
+ },
9795
+ watch: async (uris, changed, ended) => {
9796
+ const stops = [];
9797
+ const accepted = [];
9798
+ const timers = new Map;
9799
+ const soon = (uri) => {
9800
+ if (timers.has(uri))
9801
+ return;
9802
+ timers.set(uri, setTimeout(() => {
9803
+ timers.delete(uri);
9804
+ changed(uri);
9805
+ }, 250));
9806
+ };
9807
+ for (const uri of new Set(uris)) {
9808
+ if (uri === ATTENTION_RESOURCE_URI) {
9809
+ const print = async () => JSON.stringify((await sessions.attention({ identity })).filter((session) => !args.projectId || session.projectId === args.projectId).map((session) => [session.id, session.attentionRevision]));
9810
+ let last = await print();
9811
+ const timer = setInterval(() => {
9812
+ print().then((next) => {
9813
+ if (next === last)
9814
+ return;
9815
+ last = next;
9816
+ changed(uri);
9817
+ }).catch(() => {});
9818
+ }, 2000);
9819
+ timer.unref?.();
9820
+ stops.push(() => clearInterval(timer));
9821
+ accepted.push(uri);
9822
+ continue;
9823
+ }
9824
+ const sessionId = sessionIdOf(uri);
9825
+ const [state] = sessionId ? await statesOf([sessionId]).catch(() => []) : [];
9826
+ if (!sessionId || !state)
9827
+ continue;
9828
+ stops.push(await sessions.subscribe(identity, state.projectId, sessionId, {
9829
+ after: Number(state.cursor),
9830
+ send: () => {
9831
+ soon(uri);
9832
+ return true;
9833
+ },
9834
+ onClose: ended
9835
+ }));
9836
+ accepted.push(uri);
9837
+ }
9838
+ const watch = {
9839
+ accepted,
9840
+ stop: () => {
9841
+ for (const stop of stops)
9842
+ stop();
9843
+ for (const timer of timers.values())
9844
+ clearTimeout(timer);
9845
+ timers.clear();
9846
+ }
9847
+ };
9848
+ return watch;
9849
+ }
9850
+ };
9851
+ return { tools, resources, tasks };
9852
+ }
9853
+
8724
9854
  // src/routes/project-mcp.ts
8725
9855
  var TOOL_SYNC_BUDGET_MS2 = 30000;
8726
9856
  function registerProjectMcpRoutes(app, ctx) {
8727
9857
  const notAllowed = async (_request, reply) => reply.status(405).header("allow", "POST").send();
8728
9858
  app.get("/projects/:projectId/mcp", notAllowed);
8729
- app.delete("/projects/:projectId/mcp", notAllowed);
8730
- app.post("/projects/:projectId/mcp", async (request, reply) => {
9859
+ app.delete("/projects/:projectId/mcp", { config: { tokenScope: "work:read" } }, notAllowed);
9860
+ app.post("/projects/:projectId/mcp", { config: { tokenScope: "work:read" } }, async (request, reply) => {
8731
9861
  const core = ctx.core;
8732
9862
  if (!core) {
8733
9863
  return reply.status(503).send({ error: "Service not configured" });
@@ -8749,8 +9879,15 @@ function registerProjectMcpRoutes(app, ctx) {
8749
9879
  sessionId,
8750
9880
  allocationId
8751
9881
  }), abort.signal) : [];
9882
+ const chats = sessionMcp({
9883
+ core,
9884
+ identity,
9885
+ projectId,
9886
+ ...sessionId ? { currentSessionId: sessionId } : {},
9887
+ stateSecret: mcpStateSecret(ctx)
9888
+ });
8752
9889
  const surface = [
8753
- ...surfaceTools(core, identity, projectId, ctx.features, sessionId),
9890
+ ...surfaceTools(core, identity, projectId, ctx.features, sessionId).map((tool) => chats?.tools.find((chat) => chat.definition.name === tool.definition.name) ?? tool),
8754
9891
  ...programTools(core, identity, projectId),
8755
9892
  ...(ctx.projectMcp?.tools?.({ identity, projectId }) ?? []).map((tool) => ({
8756
9893
  definition: tool.definition,
@@ -8763,74 +9900,69 @@ function registerProjectMcpRoutes(app, ctx) {
8763
9900
  }
8764
9901
  }))
8765
9902
  ];
8766
- return handleMcpPost(reply, request.body, async (method, params) => {
8767
- switch (method) {
8768
- case "initialize":
8769
- return {
8770
- protocolVersion: negotiateProtocolVersion(params.protocolVersion),
8771
- capabilities: { tools: { listChanged: false } },
8772
- serverInfo: {
8773
- version: "1.0.0",
8774
- ...ctx.projectMcp?.serverInfo ?? {
8775
- name: "catamorphic",
8776
- title: "Catamorphic project"
8777
- }
9903
+ let roster;
9904
+ const allTools = () => {
9905
+ roster ??= (async () => {
9906
+ const workflows = await loadProjectTools(core, identity, projectId);
9907
+ const taken = new Set(workflows.map((tool) => tool.name));
9908
+ return [
9909
+ ...gatewayTools.map((tool) => ({
9910
+ definition: {
9911
+ name: tool.name,
9912
+ description: tool.description,
9913
+ inputSchema: z22.toJSONSchema(z22.object(tool.parameters))
8778
9914
  },
8779
- instructions: await projectInstructions({
8780
- core,
8781
- identity,
8782
- projectId,
8783
- toolNames: new Set(surface.map((tool) => String(tool.definition.name))),
8784
- ...ctx.projectMcp?.instructions ? { host: ctx.projectMcp.instructions } : {}
8785
- })
8786
- };
8787
- case "ping":
8788
- return {};
8789
- case "tools/list": {
8790
- const tools = await loadProjectTools(core, identity, projectId);
8791
- const taken = new Set(tools.map((tool) => tool.name));
8792
- return {
8793
- tools: [
8794
- ...gatewayTools.map((tool) => ({
8795
- name: tool.name,
8796
- description: tool.description,
8797
- inputSchema: z20.toJSONSchema(z20.object(tool.parameters))
8798
- })),
8799
- ...tools.filter((tool) => !gatewayTools.some((gateway) => gateway.name === tool.name)).map(toolDefinition),
8800
- ...tools.length > 0 || core.mcpToolKinds.length > 0 ? [POLL_RUN_TOOL_DEFINITION] : [],
8801
- ...surface.filter((tool) => !taken.has(String(tool.definition.name))).map((tool) => tool.definition)
8802
- ]
8803
- };
8804
- }
8805
- case "resources/list":
8806
- return { resources: [] };
8807
- case "resources/templates/list":
8808
- return { resourceTemplates: [] };
8809
- case "prompts/list":
8810
- return { prompts: [] };
8811
- case "tools/call": {
8812
- const name = typeof params.name === "string" ? params.name : "";
8813
- const args = typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {};
8814
- const gatewayTool = gatewayTools.find((tool) => tool.name === name);
8815
- if (gatewayTool) {
8816
- try {
8817
- return toolValue(await gatewayTool.execute(args, {
8818
- projectId,
8819
- sessionId,
8820
- stopWaiting: abort.signal
8821
- }));
8822
- } catch (error) {
8823
- return toolError2(error instanceof Error ? error.message : "Capability failed");
9915
+ call: async (input) => {
9916
+ try {
9917
+ return toolValue(await tool.execute(input, {
9918
+ projectId,
9919
+ sessionId,
9920
+ stopWaiting: abort.signal
9921
+ }));
9922
+ } catch (error) {
9923
+ return toolError2(error instanceof Error ? error.message : "Capability failed");
9924
+ }
9925
+ }
9926
+ })),
9927
+ ...workflows.filter((tool) => !gatewayTools.some((gateway) => gateway.name === tool.name)).map((tool) => ({
9928
+ definition: toolDefinition(tool),
9929
+ scope: "sessions:run",
9930
+ call: (input) => callTool2(core, identity, projectId, tool.name, input)
9931
+ })),
9932
+ ...workflows.length > 0 || core.mcpToolKinds.length > 0 ? [
9933
+ {
9934
+ definition: POLL_RUN_TOOL_DEFINITION,
9935
+ call: (input) => callPollRunTool(core, identity, input)
8824
9936
  }
9937
+ ] : [],
9938
+ ...surface.filter((tool) => !taken.has(String(tool.definition.name)))
9939
+ ];
9940
+ })();
9941
+ return roster;
9942
+ };
9943
+ const tools = async () => (await allTools()).filter((tool) => mayCallTool(identity, tool));
9944
+ return serveMcp({
9945
+ request,
9946
+ reply,
9947
+ ...ctx.mcp?.resourceMetadataUrl ? { resourceMetadataUrl: ctx.mcp.resourceMetadataUrl } : {},
9948
+ endpoint: {
9949
+ serverInfo: {
9950
+ version: "1.0.0",
9951
+ ...ctx.projectMcp?.serverInfo ?? {
9952
+ name: "catamorphic",
9953
+ title: "Catamorphic project"
8825
9954
  }
8826
- const workflowTools = await loadProjectTools(core, identity, projectId);
8827
- const surfaced = workflowTools.some((tool) => tool.name === name) ? undefined : surface.find((tool) => tool.definition.name === name);
8828
- if (surfaced)
8829
- return surfaced.call(args);
8830
- return callTool2(core, identity, projectId, name, args);
8831
- }
8832
- default:
8833
- throw new McpRequestError2(-32601, `Method not found: ${method}`);
9955
+ },
9956
+ instructions: async () => projectInstructions({
9957
+ core,
9958
+ identity,
9959
+ projectId,
9960
+ toolNames: new Set((await tools()).map((tool) => String(tool.definition.name))),
9961
+ ...ctx.projectMcp?.instructions ? { host: ctx.projectMcp.instructions } : {}
9962
+ }),
9963
+ tools,
9964
+ withheld: async () => withheldTools(identity, await allTools()),
9965
+ ...chats ? { resources: chats.resources, tasks: chats.tasks } : {}
8834
9966
  }
8835
9967
  });
8836
9968
  });
@@ -8954,13 +10086,13 @@ import {
8954
10086
  assertMayManageRolePolicy as assertMayManageRolePolicy2,
8955
10087
  assertProjectPermission as assertProjectPermission3,
8956
10088
  DeploymentBlockedError as DeploymentBlockedError2,
8957
- hasProjectPermission as hasProjectPermission2,
10089
+ hasProjectPermission as hasProjectPermission3,
8958
10090
  ProjectFileConflictError,
8959
10091
  ProjectFileNotFoundError,
8960
10092
  ProjectFileNotTextError,
8961
10093
  ProjectNotFoundError as ProjectNotFoundError8
8962
10094
  } from "@catamorphic/core";
8963
- import { z as z21 } from "zod";
10095
+ import { z as z23 } from "zod";
8964
10096
  function toDto(project) {
8965
10097
  return {
8966
10098
  id: project.id,
@@ -9073,7 +10205,7 @@ function registerProjectRoutes(app, ctx) {
9073
10205
  schema: {
9074
10206
  params: ProjectIdParamsSchema,
9075
10207
  response: {
9076
- 200: z21.object({ deleted: z21.boolean() }),
10208
+ 200: z23.object({ deleted: z23.boolean() }),
9077
10209
  404: ErrorSchema,
9078
10210
  503: ErrorSchema
9079
10211
  }
@@ -9159,6 +10291,7 @@ function registerProjectRoutes(app, ctx) {
9159
10291
  typed.route({
9160
10292
  method: "PUT",
9161
10293
  url: "/projects/:projectId/files/*",
10294
+ config: { tokenScope: "program:write" },
9162
10295
  schema: {
9163
10296
  params: ProjectFileParamsSchema,
9164
10297
  body: WriteFileSchema,
@@ -9281,9 +10414,9 @@ function registerProjectRoutes(app, ctx) {
9281
10414
  url: "/projects/:projectId/diff",
9282
10415
  schema: {
9283
10416
  params: ProjectIdParamsSchema,
9284
- querystring: z21.object({
9285
- base: z21.string().min(1),
9286
- head: z21.string().min(1)
10417
+ querystring: z23.object({
10418
+ base: z23.string().min(1),
10419
+ head: z23.string().min(1)
9287
10420
  }),
9288
10421
  response: {
9289
10422
  200: DiffEntrySchema.array(),
@@ -9311,6 +10444,7 @@ function registerProjectRoutes(app, ctx) {
9311
10444
  typed.route({
9312
10445
  method: "POST",
9313
10446
  url: "/projects/:projectId/deploy",
10447
+ config: { tokenScope: "program:publish" },
9314
10448
  schema: {
9315
10449
  params: ProjectIdParamsSchema,
9316
10450
  body: DeployRequestSchema,
@@ -9351,6 +10485,7 @@ function registerProjectRoutes(app, ctx) {
9351
10485
  typed.route({
9352
10486
  method: "POST",
9353
10487
  url: "/projects/:projectId/pull",
10488
+ config: { tokenScope: "program:write" },
9354
10489
  schema: {
9355
10490
  params: ProjectIdParamsSchema,
9356
10491
  body: PullRequestSchema,
@@ -9381,6 +10516,7 @@ function registerProjectRoutes(app, ctx) {
9381
10516
  typed.route({
9382
10517
  method: "POST",
9383
10518
  url: "/projects/:projectId/discard",
10519
+ config: { tokenScope: "program:write" },
9384
10520
  schema: {
9385
10521
  params: ProjectIdParamsSchema,
9386
10522
  response: {
@@ -9410,11 +10546,12 @@ function registerProjectRoutes(app, ctx) {
9410
10546
  typed.route({
9411
10547
  method: "POST",
9412
10548
  url: "/projects/:projectId/resolve-conflicts",
10549
+ config: { tokenScope: "program:write" },
9413
10550
  schema: {
9414
10551
  params: ProjectIdParamsSchema,
9415
10552
  body: ResolveConflictsSchema,
9416
10553
  response: {
9417
- 200: z21.object({ commitSha: z21.string() }),
10554
+ 200: z23.object({ commitSha: z23.string() }),
9418
10555
  404: ErrorSchema,
9419
10556
  503: ErrorSchema
9420
10557
  }
@@ -9443,20 +10580,21 @@ function registerProjectRoutes(app, ctx) {
9443
10580
  typed.route({
9444
10581
  method: "POST",
9445
10582
  url: "/projects/:projectId/ai-resolve-conflicts",
10583
+ config: { tokenScope: "program:write" },
9446
10584
  schema: {
9447
10585
  params: ProjectIdParamsSchema,
9448
- body: z21.object({
9449
- conflicts: z21.array(z21.object({
9450
- path: z21.string(),
9451
- base: z21.string().nullable(),
9452
- ours: z21.string().nullable(),
9453
- theirs: z21.string().nullable()
10586
+ body: z23.object({
10587
+ conflicts: z23.array(z23.object({
10588
+ path: z23.string(),
10589
+ base: z23.string().nullable(),
10590
+ ours: z23.string().nullable(),
10591
+ theirs: z23.string().nullable()
9454
10592
  }))
9455
10593
  }),
9456
10594
  response: {
9457
- 200: z21.object({
9458
- resolutions: z21.record(z21.string(), z21.string()),
9459
- notes: z21.string().optional()
10595
+ 200: z23.object({
10596
+ resolutions: z23.record(z23.string(), z23.string()),
10597
+ notes: z23.string().optional()
9460
10598
  }),
9461
10599
  503: ErrorSchema
9462
10600
  }
@@ -9479,9 +10617,9 @@ function registerProjectRoutes(app, ctx) {
9479
10617
  url: "/projects/:projectId/files-at-ref",
9480
10618
  schema: {
9481
10619
  params: ProjectIdParamsSchema,
9482
- querystring: RefQuerySchema.extend({ ref: z21.string().min(1) }),
10620
+ querystring: RefQuerySchema.extend({ ref: z23.string().min(1) }),
9483
10621
  response: {
9484
- 200: z21.record(z21.string(), z21.string()),
10622
+ 200: z23.record(z23.string(), z23.string()),
9485
10623
  404: ErrorSchema,
9486
10624
  503: ErrorSchema
9487
10625
  }
@@ -9507,7 +10645,7 @@ function registerProjectRoutes(app, ctx) {
9507
10645
  async function safeListWorkflows(core, identity, projectId) {
9508
10646
  try {
9509
10647
  const workflows = await core.workflows.list({ identity, projectId });
9510
- if (!hasProjectPermission2(identity, projectId, "program:read"))
10648
+ if (!hasProjectPermission3(identity, projectId, "program:read"))
9511
10649
  return { workflows, files: [] };
9512
10650
  const allFiles = await core.projects.readAllFiles(identity, projectId);
9513
10651
  return { workflows, files: Object.keys(allFiles) };
@@ -9525,7 +10663,7 @@ import {
9525
10663
  PublicationSlugError,
9526
10664
  PublicationSlugTakenError
9527
10665
  } from "@catamorphic/core";
9528
- import { z as z22 } from "zod";
10666
+ import { z as z24 } from "zod";
9529
10667
  function registerPublicationRoutes(app, ctx) {
9530
10668
  const typed = app.withTypeProvider();
9531
10669
  const core = () => {
@@ -9558,6 +10696,7 @@ function registerPublicationRoutes(app, ctx) {
9558
10696
  typed.route({
9559
10697
  method: "POST",
9560
10698
  url: "/projects/:projectId/publications",
10699
+ config: { tokenScope: "program:publish" },
9561
10700
  schema: {
9562
10701
  params: ProjectIdParamsSchema,
9563
10702
  body: PublishSchema,
@@ -9612,9 +10751,10 @@ function registerPublicationRoutes(app, ctx) {
9612
10751
  typed.route({
9613
10752
  method: "DELETE",
9614
10753
  url: "/projects/:projectId/publications/:slug",
10754
+ config: { tokenScope: "program:publish" },
9615
10755
  schema: {
9616
10756
  params: PublicationParamsSchema,
9617
- response: { 204: z22.null(), 404: ErrorSchema }
10757
+ response: { 204: z24.null(), 404: ErrorSchema }
9618
10758
  },
9619
10759
  handler: async (request, reply) => {
9620
10760
  try {
@@ -9686,7 +10826,7 @@ import {
9686
10826
  RunPauseNotFoundError,
9687
10827
  RunResumeConflictError
9688
10828
  } from "@catamorphic/core";
9689
- import { z as z23 } from "zod";
10829
+ import { z as z25 } from "zod";
9690
10830
  function registerRunRoutes(app, ctx) {
9691
10831
  const typed = app.withTypeProvider();
9692
10832
  typed.route({
@@ -9715,6 +10855,7 @@ function registerRunRoutes(app, ctx) {
9715
10855
  typed.route({
9716
10856
  method: "POST",
9717
10857
  url: "/runs/:runId/cancel",
10858
+ config: { tokenScope: "sessions:run" },
9718
10859
  schema: {
9719
10860
  params: RunIdParamsSchema,
9720
10861
  body: CancelRunSchema,
@@ -9742,6 +10883,7 @@ function registerRunRoutes(app, ctx) {
9742
10883
  typed.route({
9743
10884
  method: "POST",
9744
10885
  url: "/runs/:runId/pause",
10886
+ config: { tokenScope: "sessions:run" },
9745
10887
  schema: {
9746
10888
  params: RunIdParamsSchema,
9747
10889
  response: {
@@ -9767,6 +10909,7 @@ function registerRunRoutes(app, ctx) {
9767
10909
  typed.route({
9768
10910
  method: "POST",
9769
10911
  url: "/runs/:runId/resume",
10912
+ config: { tokenScope: "sessions:run" },
9770
10913
  schema: {
9771
10914
  params: RunIdParamsSchema,
9772
10915
  response: {
@@ -9792,6 +10935,7 @@ function registerRunRoutes(app, ctx) {
9792
10935
  typed.route({
9793
10936
  method: "POST",
9794
10937
  url: "/runs/:runId/pauses/:pauseId/resume",
10938
+ config: { tokenScope: "sessions:run" },
9795
10939
  schema: {
9796
10940
  params: RunPauseParamsSchema,
9797
10941
  body: ResumeRunPauseSchema,
@@ -9854,7 +10998,7 @@ function registerRunRoutes(app, ctx) {
9854
10998
  schema: {
9855
10999
  params: RunItemParamsSchema,
9856
11000
  response: {
9857
- 200: z23.array(BatchItemStepSchema),
11001
+ 200: z25.array(BatchItemStepSchema),
9858
11002
  404: ErrorSchema,
9859
11003
  409: ErrorSchema,
9860
11004
  503: ErrorSchema
@@ -9886,6 +11030,106 @@ function handleRunError(args) {
9886
11030
  throw args.error;
9887
11031
  }
9888
11032
 
11033
+ // src/routes/server-mcp.ts
11034
+ import { z as z26 } from "zod";
11035
+ var SERVER_MCP_INSTRUCTIONS = `Work runs coding agents on this server as you. Start one with session_start (it returns a sessionId at once), keep working, then call session_wait with the returned cursor until state is idle, failed or needs_input. needs_input lists requests: answer questions with session_answer; approvals go to your person. Read replies, typed results and pull requests with session_read. Steer with session_send, stop with session_interrupt. Retry any call with the same idempotencyKey.
11036
+
11037
+ project_list names the projects you may use and their agents: pass a project's id as project to session_start and session_list. Every chat tool answers with the chat's state (working, needs_input, idle, failed or closed) and a cursor. A wait returns within 50 seconds; changed false means nothing happened yet, so call it again with the same cursor. A project's own endpoint, at /projects/<id>/mcp beside this one, adds its documents, program and workflows.`;
11038
+ var ProjectListOutput = z26.object({
11039
+ projects: z26.array(z26.object({
11040
+ id: z26.string(),
11041
+ name: z26.string(),
11042
+ agents: z26.array(z26.object({
11043
+ id: z26.string(),
11044
+ name: z26.string(),
11045
+ description: z26.string().optional(),
11046
+ default: z26.boolean().optional()
11047
+ }))
11048
+ }))
11049
+ });
11050
+ function projectListTool(core, identity) {
11051
+ return {
11052
+ definition: {
11053
+ name: "project_list",
11054
+ title: "List projects",
11055
+ description: "List the projects you may use on this server, each with the agents you can start a chat on. Use it first: session_start and session_list take a project's id. Next: session_start.",
11056
+ inputSchema: { type: "object", properties: {} },
11057
+ outputSchema: z26.toJSONSchema(ProjectListOutput),
11058
+ annotations: {
11059
+ title: "List projects",
11060
+ readOnlyHint: true,
11061
+ idempotentHint: true,
11062
+ openWorldHint: false
11063
+ }
11064
+ },
11065
+ scope: "work:read",
11066
+ call: async () => {
11067
+ try {
11068
+ const { items } = await core.projects.list(identity, { limit: 100 });
11069
+ const projects = [];
11070
+ for (const project of items) {
11071
+ const catalog = await core.agentSessions?.catalog({ identity, projectId: project.id }).catch(() => {
11072
+ return;
11073
+ });
11074
+ projects.push({
11075
+ id: project.id,
11076
+ name: project.name,
11077
+ agents: (catalog?.items ?? []).filter((agent) => agent.available).map((agent) => ({
11078
+ id: agent.id,
11079
+ name: agent.name,
11080
+ ...agent.description ? { description: agent.description } : {},
11081
+ ...agent.id === catalog?.defaultAgentId ? { default: true } : {}
11082
+ }))
11083
+ });
11084
+ }
11085
+ return toolValue(ProjectListOutput.parse({ projects }));
11086
+ } catch (error) {
11087
+ return toolError2(error instanceof Error ? error.message : String(error));
11088
+ }
11089
+ }
11090
+ };
11091
+ }
11092
+ function registerServerMcpRoutes(app, ctx) {
11093
+ const notAllowed = async (_request, reply) => reply.status(405).header("allow", "POST").send();
11094
+ app.get("/mcp", notAllowed);
11095
+ app.delete("/mcp", { config: { tokenScope: "work:read" } }, notAllowed);
11096
+ app.post("/mcp", { config: { tokenScope: "work:read" } }, async (request, reply) => {
11097
+ const core = ctx.core;
11098
+ if (!core)
11099
+ return reply.status(503).send({ error: "Service not configured" });
11100
+ if (!ctx.features.mcp)
11101
+ return reply.status(404).send({ error: "MCP is turned off on this server" });
11102
+ const identity = resolveIdentity(request);
11103
+ const chats = sessionMcp({
11104
+ core,
11105
+ identity,
11106
+ stateSecret: mcpStateSecret(ctx)
11107
+ });
11108
+ const all = [
11109
+ projectListTool(core, identity),
11110
+ ...chats?.tools ?? []
11111
+ ];
11112
+ return serveMcp({
11113
+ request,
11114
+ reply,
11115
+ ...ctx.mcp?.resourceMetadataUrl ? { resourceMetadataUrl: ctx.mcp.resourceMetadataUrl } : {},
11116
+ endpoint: {
11117
+ serverInfo: {
11118
+ version: "1.0.0",
11119
+ ...ctx.projectMcp?.serverInfo ?? {
11120
+ name: "catamorphic",
11121
+ title: "Catamorphic"
11122
+ }
11123
+ },
11124
+ instructions: async () => SERVER_MCP_INSTRUCTIONS,
11125
+ tools: async () => all.filter((tool) => mayCallTool(identity, tool)),
11126
+ withheld: async () => withheldTools(identity, all),
11127
+ ...chats ? { resources: chats.resources, tasks: chats.tasks } : {}
11128
+ }
11129
+ });
11130
+ });
11131
+ }
11132
+
9889
11133
  // src/routes/session-mailboxes.ts
9890
11134
  import { SessionMailboxNotFoundError } from "@catamorphic/core";
9891
11135
  function registerSessionMailboxRoutes(app, ctx) {
@@ -9913,6 +11157,7 @@ function registerSessionMailboxRoutes(app, ctx) {
9913
11157
  typed.route({
9914
11158
  method: "POST",
9915
11159
  url: "/projects/:projectId/session-mailboxes/:mailboxId/acknowledge",
11160
+ config: { tokenScope: "sessions:run" },
9916
11161
  schema: {
9917
11162
  params: SessionMailboxIdParamsSchema,
9918
11163
  body: AcknowledgeSessionMailboxSchema,
@@ -10272,6 +11517,7 @@ function registerWatcherRoutes(app, ctx) {
10272
11517
  typed.route({
10273
11518
  method: "DELETE",
10274
11519
  url: "/projects/:projectId/agent/sessions/:sessionId/watchers/:watcherId",
11520
+ config: { tokenScope: "sessions:run" },
10275
11521
  schema: {
10276
11522
  params: WatcherIdParamsSchema,
10277
11523
  response: {
@@ -10312,13 +11558,13 @@ import {
10312
11558
  WebhookRejectedError,
10313
11559
  WebhookTooLargeError
10314
11560
  } from "@catamorphic/core";
10315
- import { z as z24 } from "zod";
10316
- var WebhookSchema = z24.object({
10317
- name: z24.string(),
10318
- url: z24.string(),
10319
- workflows: z24.array(z24.string()),
10320
- listening: z24.boolean(),
10321
- verified: z24.boolean()
11561
+ import { z as z27 } from "zod";
11562
+ var WebhookSchema = z27.object({
11563
+ name: z27.string(),
11564
+ url: z27.string(),
11565
+ workflows: z27.array(z27.string()),
11566
+ listening: z27.boolean(),
11567
+ verified: z27.boolean()
10322
11568
  });
10323
11569
  function registerWebhookRoutes(app, ctx) {
10324
11570
  const typed = app.withTypeProvider();
@@ -10333,14 +11579,14 @@ function registerWebhookRoutes(app, ctx) {
10333
11579
  config: { public: true },
10334
11580
  bodyLimit: hostMaxBytes,
10335
11581
  schema: {
10336
- params: z24.object({
10337
- projectId: z24.string().uuid(),
10338
- name: z24.string().min(1).max(63),
10339
- token: z24.string().min(1).max(200)
11582
+ params: z27.object({
11583
+ projectId: z27.string().uuid(),
11584
+ name: z27.string().min(1).max(63),
11585
+ token: z27.string().min(1).max(200)
10340
11586
  }),
10341
11587
  response: {
10342
- 200: z24.string(),
10343
- 202: z24.object({ id: z24.string(), duplicate: z24.boolean() }),
11588
+ 200: z27.string(),
11589
+ 202: z27.object({ id: z27.string(), duplicate: z27.boolean() }),
10344
11590
  401: ErrorSchema,
10345
11591
  404: ErrorSchema,
10346
11592
  405: ErrorSchema,
@@ -10382,7 +11628,7 @@ function registerWebhookRoutes(app, ctx) {
10382
11628
  url: "/projects/:projectId/webhooks",
10383
11629
  schema: {
10384
11630
  params: ProjectIdParamsSchema,
10385
- response: { 200: z24.array(WebhookSchema), 503: ErrorSchema }
11631
+ response: { 200: z27.array(WebhookSchema), 503: ErrorSchema }
10386
11632
  },
10387
11633
  handler: async (request, reply) => {
10388
11634
  const webhooks = ctx.core?.webhooks;
@@ -10403,7 +11649,7 @@ function registerWebhookRoutes(app, ctx) {
10403
11649
  method: "POST",
10404
11650
  url: "/projects/:projectId/webhooks/:name/rotate",
10405
11651
  schema: {
10406
- params: ProjectIdParamsSchema.extend({ name: z24.string().min(1) }),
11652
+ params: ProjectIdParamsSchema.extend({ name: z27.string().min(1) }),
10407
11653
  response: { 200: WebhookSchema, 404: ErrorSchema, 503: ErrorSchema }
10408
11654
  },
10409
11655
  handler: async (request, reply) => {
@@ -10444,7 +11690,7 @@ import {
10444
11690
  RunSignalNotFoundError,
10445
11691
  WorkflowNotFoundError as WorkflowNotFoundError3
10446
11692
  } from "@catamorphic/core";
10447
- import { z as z25 } from "zod";
11693
+ import { z as z28 } from "zod";
10448
11694
  function registerWorkflowRoutes(app, ctx) {
10449
11695
  const typed = app.withTypeProvider();
10450
11696
  typed.route({
@@ -10518,6 +11764,7 @@ function registerWorkflowRoutes(app, ctx) {
10518
11764
  typed.route({
10519
11765
  method: "POST",
10520
11766
  url: "/projects/:projectId/workflows/:name/runs",
11767
+ config: { tokenScope: "sessions:run" },
10521
11768
  schema: {
10522
11769
  params: WorkflowNameParamsSchema,
10523
11770
  body: TriggerRunSchema,
@@ -10556,6 +11803,7 @@ function registerWorkflowRoutes(app, ctx) {
10556
11803
  typed.route({
10557
11804
  method: "POST",
10558
11805
  url: "/projects/:projectId/workflows/:name/calls",
11806
+ config: { tokenScope: "sessions:run" },
10559
11807
  schema: {
10560
11808
  params: WorkflowNameParamsSchema,
10561
11809
  body: CallRunSchema,
@@ -10629,6 +11877,7 @@ function registerWorkflowRoutes(app, ctx) {
10629
11877
  typed.route({
10630
11878
  method: "POST",
10631
11879
  url: "/projects/:projectId/workflows/:name/signals",
11880
+ config: { tokenScope: "sessions:run" },
10632
11881
  schema: {
10633
11882
  params: WorkflowNameParamsSchema,
10634
11883
  body: SignalRunSchema,
@@ -10676,12 +11925,13 @@ function registerWorkflowRoutes(app, ctx) {
10676
11925
  typed.route({
10677
11926
  method: "POST",
10678
11927
  url: "/projects/:projectId/workflows/:name/cancellations",
11928
+ config: { tokenScope: "sessions:run" },
10679
11929
  schema: {
10680
11930
  params: WorkflowNameParamsSchema,
10681
11931
  body: CancelRunByKeySchema,
10682
11932
  response: {
10683
11933
  200: RunSchema,
10684
- 204: z25.null(),
11934
+ 204: z28.null(),
10685
11935
  404: ErrorSchema,
10686
11936
  503: ErrorSchema
10687
11937
  }
@@ -10715,6 +11965,14 @@ var DEFAULT_HOST_FEATURES = {
10715
11965
  mcp: true,
10716
11966
  storeUploadMaxBytes: 64 * 1024 * 1024
10717
11967
  };
11968
+ function insufficientScope(reply, scope, mcp) {
11969
+ return reply.status(403).header("www-authenticate", `Bearer error="insufficient_scope", scope="${scope}"${mcp?.resourceMetadataUrl ? `, resource_metadata="${mcp.resourceMetadataUrl}"` : ""}`).send({
11970
+ error: `This needs the ${scope} scope, which this client was not granted.`,
11971
+ code: "not_authorized",
11972
+ retryable: false,
11973
+ scope
11974
+ });
11975
+ }
10718
11976
  var catamorphicPlugin = async (app, opts) => {
10719
11977
  app.setValidatorCompiler(validatorCompiler);
10720
11978
  app.setSerializerCompiler(serializerCompiler);
@@ -10725,6 +11983,8 @@ var catamorphicPlugin = async (app, opts) => {
10725
11983
  if (err instanceof SessionArtifactNotFoundError2 || err instanceof SessionArtifactConflictError || err instanceof SessionArtifactValidationError) {
10726
11984
  return reply.status(err.statusCode).send({ error: err.message });
10727
11985
  }
11986
+ if (err instanceof TokenScopeRequiredError2)
11987
+ return insufficientScope(reply, err.scope, opts.mcp);
10728
11988
  if (err instanceof AccessDeniedError10) {
10729
11989
  return reply.status(403).send({ error: err.message });
10730
11990
  }
@@ -10767,12 +12027,18 @@ var catamorphicPlugin = async (app, opts) => {
10767
12027
  return;
10768
12028
  return reply.status(401).send({ error: "Unauthorized" });
10769
12029
  }
12030
+ if (!isPublic && !hasTokenScope3(identity, "work:read"))
12031
+ return insufficientScope(reply, "work:read", opts.mcp);
12032
+ const tokenScope = request.routeOptions.config.tokenScope ?? (request.method === "GET" || request.method === "HEAD" ? "work:read" : FULL_TOKEN_SCOPE);
12033
+ if (!isPublic && !hasTokenScope3(identity, tokenScope))
12034
+ return insufficientScope(reply, tokenScope, opts.mcp);
10770
12035
  const runnerId = request.headers["x-catamorphic-runner"];
10771
12036
  attachIdentity(request, typeof runnerId === "string" && /^[0-9a-f-]{36}$/i.test(runnerId) ? { ...identity, clientRunnerId: runnerId } : identity);
10772
12037
  });
10773
12038
  const ctx = {
10774
12039
  core: opts.core,
10775
12040
  ...opts.projectMcp ? { projectMcp: opts.projectMcp } : {},
12041
+ ...opts.mcp ? { mcp: opts.mcp } : {},
10776
12042
  ...opts.publicApiBase ? { publicApiBase: opts.publicApiBase.replace(/\/$/, "") } : {},
10777
12043
  features: {
10778
12044
  ...DEFAULT_HOST_FEATURES,
@@ -10808,6 +12074,7 @@ var catamorphicPlugin = async (app, opts) => {
10808
12074
  registerPrivateCustomizationRoutes(app, ctx);
10809
12075
  registerAppsMcpRoutes(app, ctx);
10810
12076
  registerProjectMcpRoutes(app, ctx);
12077
+ registerServerMcpRoutes(app, ctx);
10811
12078
  registerAgentCapabilityRoutes(app, ctx);
10812
12079
  registerCodeHostRoutes(app, ctx);
10813
12080
  registerPluginRoutes(app, ctx);
@@ -10868,6 +12135,7 @@ function createApp(config) {
10868
12135
  identity: config.identity,
10869
12136
  ...config.features ? { features: config.features } : {},
10870
12137
  ...config.projectMcp ? { projectMcp: config.projectMcp } : {},
12138
+ ...config.mcp ? { mcp: config.mcp } : {},
10871
12139
  ...config.publicApiBase ? { publicApiBase: config.publicApiBase } : {},
10872
12140
  prefix: "/api"
10873
12141
  });
@@ -10877,7 +12145,7 @@ function createApp(config) {
10877
12145
  import {
10878
12146
  defineAgentCapability
10879
12147
  } from "@catamorphic/core";
10880
- import { z as z26 } from "zod";
12148
+ import { z as z29 } from "zod";
10881
12149
  var PUBLISHING_TOOLS = new Set([
10882
12150
  "program_deploy",
10883
12151
  "publish_document",
@@ -10888,11 +12156,11 @@ var OWN_CHAT_TOOLS = new Set([
10888
12156
  "set_app_presentation",
10889
12157
  "set_session_metadata"
10890
12158
  ]);
10891
- var Definition = z26.object({
10892
- name: z26.string(),
10893
- description: z26.string().default(""),
10894
- inputSchema: z26.record(z26.string(), z26.unknown()),
10895
- annotations: z26.object({ readOnlyHint: z26.boolean().optional() }).optional()
12159
+ var Definition = z29.looseObject({
12160
+ name: z29.string(),
12161
+ description: z29.string().default(""),
12162
+ inputSchema: z29.record(z29.string(), z29.unknown()),
12163
+ annotations: z29.looseObject({ readOnlyHint: z29.boolean().optional() }).optional()
10896
12164
  });
10897
12165
  async function projectToolCapabilities(args) {
10898
12166
  const { core, context } = args;
@@ -10927,8 +12195,8 @@ async function projectToolCapabilities(args) {
10927
12195
  description: definition.description,
10928
12196
  effect,
10929
12197
  ...PUBLISHING_TOOLS.has(definition.name) ? { sandboxing: "publish" } : OWN_CHAT_TOOLS.has(definition.name) ? { sandboxing: "contained" } : {},
10930
- inputSchema: z26.fromJSONSchema(definition.inputSchema),
10931
- outputSchema: z26.unknown(),
12198
+ inputSchema: z29.fromJSONSchema(definition.inputSchema),
12199
+ outputSchema: z29.unknown(),
10932
12200
  authorize: () => true,
10933
12201
  beforeInvoke: (invocation, input) => args.beforeCall?.({
10934
12202
  name: definition.name,
@@ -10938,22 +12206,22 @@ async function projectToolCapabilities(args) {
10938
12206
  }) ?? Promise.resolve(),
10939
12207
  execute: async (invocation, input) => {
10940
12208
  invocation.signal?.throwIfAborted();
10941
- const values = z26.record(z26.string(), z26.unknown()).parse(input);
12209
+ const values = z29.record(z29.string(), z29.unknown()).parse(input);
10942
12210
  const owned = !taken.has(definition.name) && [
10943
12211
  "session_artifact",
10944
12212
  "create_watcher",
10945
12213
  "list_watchers",
10946
- "stop_watcher"
12214
+ "session_stop_watcher"
10947
12215
  ].includes(definition.name);
10948
12216
  const result = await tool.call(owned ? { ...values, sessionId: context.sessionId } : values);
10949
12217
  if (result.isError) {
10950
- const content = z26.array(z26.object({ text: z26.string() })).parse(result.content);
12218
+ const content = z29.array(z29.object({ text: z29.string() })).parse(result.content);
10951
12219
  throw new Error(content.map((part) => part.text).join(`
10952
12220
  `));
10953
12221
  }
10954
12222
  if (result.structuredContent !== undefined)
10955
12223
  return JSON.parse(JSON.stringify(result.structuredContent));
10956
- const content = z26.array(z26.object({ text: z26.string() })).parse(result.content);
12224
+ const content = z29.array(z29.object({ text: z29.string() })).parse(result.content);
10957
12225
  const text = content.map((part) => part.text).join(`
10958
12226
  `);
10959
12227
  try {
@@ -11130,5 +12398,5 @@ export {
11130
12398
  serveSpaDist
11131
12399
  };
11132
12400
 
11133
- //# debugId=BDC9E1010DAF3A1B64756E2164756E21
12401
+ //# debugId=4D3EA05EB4E27D3164756E2164756E21
11134
12402
  //# sourceMappingURL=index.js.map