@catamorphic/fastify-plugin 0.1.0-alpha.39 → 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.
- package/NOTICE.txt +7 -0
- package/dist/app.d.ts +2 -0
- package/dist/app.d.ts.map +1 -1
- package/dist/chunk-jytcc42y.js +592 -0
- package/dist/chunk-jytcc42y.js.map +11 -0
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1673 -411
- package/dist/index.js.map +29 -25
- package/dist/mcp-scopes.d.ts +12 -0
- package/dist/mcp-scopes.d.ts.map +1 -0
- package/dist/mcp-server.d.ts +158 -0
- package/dist/mcp-server.d.ts.map +1 -0
- package/dist/mcp-shared.d.ts +3 -50
- package/dist/mcp-shared.d.ts.map +1 -1
- package/dist/mcp.d.ts +4 -2
- package/dist/mcp.d.ts.map +1 -1
- package/dist/mcp.js +6 -4
- package/dist/mcp.js.map +1 -1
- package/dist/plugin.d.ts +26 -2
- package/dist/plugin.d.ts.map +1 -1
- package/dist/project-capabilities.d.ts.map +1 -1
- package/dist/project-mcp-surface.d.ts +3 -4
- package/dist/project-mcp-surface.d.ts.map +1 -1
- package/dist/routes/agent.d.ts.map +1 -1
- package/dist/routes/apps-mcp.d.ts.map +1 -1
- package/dist/routes/client-runners.d.ts.map +1 -1
- package/dist/routes/connection-mcp.d.ts.map +1 -1
- package/dist/routes/documents.d.ts.map +1 -1
- package/dist/routes/environments.d.ts.map +1 -1
- package/dist/routes/project-mcp.d.ts.map +1 -1
- package/dist/routes/projects.d.ts.map +1 -1
- package/dist/routes/publications.d.ts.map +1 -1
- package/dist/routes/run-errors.d.ts.map +1 -1
- package/dist/routes/runs.d.ts.map +1 -1
- package/dist/routes/server-mcp.d.ts +17 -0
- package/dist/routes/server-mcp.d.ts.map +1 -0
- package/dist/routes/session-mailboxes.d.ts.map +1 -1
- package/dist/routes/triggers.d.ts.map +1 -1
- package/dist/routes/watchers.d.ts.map +1 -1
- package/dist/routes/workflow-enablements.d.ts.map +1 -1
- package/dist/routes/workflows.d.ts.map +1 -1
- package/dist/schemas.d.ts +3684 -28
- package/dist/schemas.d.ts.map +1 -1
- package/dist/session-mcp.d.ts +54 -0
- package/dist/session-mcp.d.ts.map +1 -0
- package/dist/session-tools.d.ts +49 -0
- package/dist/session-tools.d.ts.map +1 -0
- package/package.json +12 -12
- package/src/app.ts +3 -0
- package/src/index.ts +1 -0
- package/src/mcp-scopes.ts +69 -0
- package/src/mcp-server.ts +827 -0
- package/src/mcp-shared.ts +3 -151
- package/src/mcp.ts +6 -5
- package/src/plugin.ts +73 -2
- package/src/project-capabilities.ts +5 -3
- package/src/project-mcp-program.ts +2 -2
- package/src/project-mcp-surface.ts +18 -239
- package/src/routes/agent.ts +384 -41
- package/src/routes/apps-mcp.ts +84 -82
- package/src/routes/client-runners.ts +3 -1
- package/src/routes/connection-mcp.ts +6 -13
- package/src/routes/documents.ts +4 -0
- package/src/routes/environments.ts +49 -1
- package/src/routes/project-mcp.ts +176 -154
- package/src/routes/projects.ts +6 -0
- package/src/routes/publications.ts +2 -0
- package/src/routes/run-errors.ts +5 -1
- package/src/routes/runs.ts +4 -0
- package/src/routes/server-mcp.ts +151 -0
- package/src/routes/session-mailboxes.ts +1 -0
- package/src/routes/triggers.ts +6 -1
- package/src/routes/watchers.ts +1 -0
- package/src/routes/workflow-enablements.ts +132 -1
- package/src/routes/workflows.ts +4 -0
- package/src/schemas.ts +347 -5
- package/src/session-mcp.ts +696 -0
- package/src/session-tools.ts +169 -0
- package/dist/chunk-baagvvm3.js +0 -164
- 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-
|
|
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
|
|
1218
|
-
|
|
1219
|
-
|
|
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()
|
|
@@ -1280,7 +1400,8 @@ var TurnErrorSchema = describes()(z.object({
|
|
|
1280
1400
|
"rate_limit",
|
|
1281
1401
|
"unavailable",
|
|
1282
1402
|
"model_incompat",
|
|
1283
|
-
"agent_missing"
|
|
1403
|
+
"agent_missing",
|
|
1404
|
+
"out_of_disk"
|
|
1284
1405
|
]).optional(),
|
|
1285
1406
|
retrySafe: z.boolean().optional()
|
|
1286
1407
|
}));
|
|
@@ -1304,7 +1425,6 @@ var AgentTurnUsageSchema = describes()(z.object({
|
|
|
1304
1425
|
var TurnOutcomeSchema = describes()(z.object({
|
|
1305
1426
|
changedFiles: z.array(z.object({ path: z.string(), kind: z.enum(["modified", "deleted"]) })),
|
|
1306
1427
|
usage: AgentTurnUsageSchema.optional(),
|
|
1307
|
-
storeSync: JsonObjectSchema.optional(),
|
|
1308
1428
|
workspaceSync: z.object({ error: z.string() }).optional(),
|
|
1309
1429
|
notification: z.object({ title: z.string().optional(), body: z.string().optional() }).optional()
|
|
1310
1430
|
}));
|
|
@@ -1353,7 +1473,13 @@ var AttemptSchema = describes()(z.object({
|
|
|
1353
1473
|
turnId: z.string(),
|
|
1354
1474
|
sessionId: z.string(),
|
|
1355
1475
|
ordinal: z.number().int(),
|
|
1356
|
-
reason: z.enum([
|
|
1476
|
+
reason: z.enum([
|
|
1477
|
+
"initial",
|
|
1478
|
+
"retry",
|
|
1479
|
+
"steer_restart",
|
|
1480
|
+
"recovery",
|
|
1481
|
+
"restart"
|
|
1482
|
+
]),
|
|
1357
1483
|
status: z.enum([
|
|
1358
1484
|
"preparing",
|
|
1359
1485
|
"running",
|
|
@@ -1361,7 +1487,8 @@ var AttemptSchema = describes()(z.object({
|
|
|
1361
1487
|
"failed",
|
|
1362
1488
|
"interrupted",
|
|
1363
1489
|
"lost",
|
|
1364
|
-
"superseded"
|
|
1490
|
+
"superseded",
|
|
1491
|
+
"restarted"
|
|
1365
1492
|
]),
|
|
1366
1493
|
providerThreadId: z.string().nullable(),
|
|
1367
1494
|
nativeTurnRef: NativeRefSchema.nullable(),
|
|
@@ -1502,6 +1629,22 @@ var ItemSchema = describes()(z.discriminatedUnion("kind", [
|
|
|
1502
1629
|
to: z.number().int()
|
|
1503
1630
|
}),
|
|
1504
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()
|
|
1505
1648
|
})
|
|
1506
1649
|
]).meta({ id: "Item" }));
|
|
1507
1650
|
var RuntimeRequestResponseSchema = describes()(z.discriminatedUnion("kind", [
|
|
@@ -1667,8 +1810,70 @@ var CommandReceiptSchema = describes()(z.object({
|
|
|
1667
1810
|
error: z.object({ code: z.string(), message: z.string() }).nullable()
|
|
1668
1811
|
}).meta({ id: "CommandReceipt" }));
|
|
1669
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
|
+
});
|
|
1670
1841
|
var AgentSessionDetailSchema = AgentSessionSchema.extend({
|
|
1671
|
-
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()
|
|
1672
1877
|
});
|
|
1673
1878
|
var SessionItemsQuerySchema = z.object({
|
|
1674
1879
|
before: z.coerce.number().int().positive(),
|
|
@@ -1678,9 +1883,41 @@ var SessionItemsPageSchema = z.object({
|
|
|
1678
1883
|
items: z.array(ItemSchema),
|
|
1679
1884
|
olderBefore: z.number().int().nullable()
|
|
1680
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
|
+
});
|
|
1681
1912
|
var SessionEventsQuerySchema = z.object({
|
|
1682
1913
|
after: z.coerce.number().int().nonnegative().optional()
|
|
1683
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
|
+
});
|
|
1684
1921
|
var SessionMirrorQuerySchema = z.object({
|
|
1685
1922
|
after: z.coerce.number().int().nonnegative().optional()
|
|
1686
1923
|
});
|
|
@@ -1878,7 +2115,10 @@ var ProjectAgentDefinitionSchema = z.object({
|
|
|
1878
2115
|
skills: z.array(z.string()).optional(),
|
|
1879
2116
|
acp: z.object({
|
|
1880
2117
|
endpoint: z.string().optional(),
|
|
1881
|
-
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()
|
|
1882
2122
|
}).optional()
|
|
1883
2123
|
});
|
|
1884
2124
|
var ProjectAgentEntrySchema = z.object({
|
|
@@ -2317,11 +2557,46 @@ data: ${JSON.stringify(message)}
|
|
|
2317
2557
|
}
|
|
2318
2558
|
|
|
2319
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
|
+
}
|
|
2320
2594
|
function registerAgentRoutes(app, ctx) {
|
|
2321
2595
|
const typed = app.withTypeProvider();
|
|
2322
2596
|
typed.route({
|
|
2323
2597
|
method: "POST",
|
|
2324
2598
|
url: "/projects/:projectId/agent/sessions",
|
|
2599
|
+
config: { tokenScope: "sessions:run" },
|
|
2325
2600
|
schema: {
|
|
2326
2601
|
params: ProjectIdParamsSchema,
|
|
2327
2602
|
body: CreateAgentSessionSchema,
|
|
@@ -2410,6 +2685,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2410
2685
|
typed.route({
|
|
2411
2686
|
method: "PATCH",
|
|
2412
2687
|
url: "/projects/:projectId/agent/sessions/:sessionId",
|
|
2688
|
+
config: { tokenScope: "sessions:run" },
|
|
2413
2689
|
schema: {
|
|
2414
2690
|
params: AgentSessionIdParamsSchema,
|
|
2415
2691
|
body: UpdateAgentSessionSchema,
|
|
@@ -2507,6 +2783,75 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2507
2783
|
}
|
|
2508
2784
|
}
|
|
2509
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
|
+
});
|
|
2510
2855
|
typed.route({
|
|
2511
2856
|
method: "GET",
|
|
2512
2857
|
url: "/projects/:projectId/agent/sessions/:sessionId",
|
|
@@ -2562,6 +2907,116 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2562
2907
|
}
|
|
2563
2908
|
}
|
|
2564
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
|
+
});
|
|
2565
3020
|
typed.route({
|
|
2566
3021
|
method: "GET",
|
|
2567
3022
|
url: "/projects/:projectId/agent/sessions/:sessionId/events",
|
|
@@ -2609,9 +3064,37 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2609
3064
|
return reply;
|
|
2610
3065
|
}
|
|
2611
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
|
+
});
|
|
2612
3094
|
typed.route({
|
|
2613
3095
|
method: "POST",
|
|
2614
3096
|
url: "/projects/:projectId/agent/sessions/:sessionId/commands",
|
|
3097
|
+
config: { tokenScope: "sessions:run" },
|
|
2615
3098
|
bodyLimit: 96 * 1024 * 1024,
|
|
2616
3099
|
schema: {
|
|
2617
3100
|
params: AgentSessionIdParamsSchema,
|
|
@@ -2650,6 +3133,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2650
3133
|
typed.route({
|
|
2651
3134
|
method: "POST",
|
|
2652
3135
|
url: "/projects/:projectId/agent/sessions/:sessionId/resume",
|
|
3136
|
+
config: { tokenScope: "sessions:run" },
|
|
2653
3137
|
schema: {
|
|
2654
3138
|
params: AgentSessionIdParamsSchema,
|
|
2655
3139
|
body: ResumeAgentSessionSchema,
|
|
@@ -2800,6 +3284,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2800
3284
|
typed.route({
|
|
2801
3285
|
method: "POST",
|
|
2802
3286
|
url: "/projects/:projectId/agent/sessions/:sessionId/attention/acknowledge",
|
|
3287
|
+
config: { tokenScope: "sessions:run" },
|
|
2803
3288
|
schema: {
|
|
2804
3289
|
params: AgentSessionIdParamsSchema,
|
|
2805
3290
|
body: z2.object({ observedRevision: z2.number().int().nonnegative().optional() }).nullish(),
|
|
@@ -2825,6 +3310,42 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2825
3310
|
}
|
|
2826
3311
|
}
|
|
2827
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
|
+
});
|
|
2828
3349
|
typed.route({
|
|
2829
3350
|
method: "GET",
|
|
2830
3351
|
url: "/projects/:projectId/agent/sessions/:sessionId/peers",
|
|
@@ -2854,6 +3375,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2854
3375
|
typed.route({
|
|
2855
3376
|
method: "POST",
|
|
2856
3377
|
url: "/projects/:projectId/agent/sessions/:sessionId/subsessions",
|
|
3378
|
+
config: { tokenScope: "sessions:run" },
|
|
2857
3379
|
schema: {
|
|
2858
3380
|
params: AgentSessionIdParamsSchema,
|
|
2859
3381
|
body: CreateAgentSubsessionSchema,
|
|
@@ -2917,36 +3439,10 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2917
3439
|
}
|
|
2918
3440
|
}
|
|
2919
3441
|
});
|
|
2920
|
-
typed.route({
|
|
2921
|
-
method: "POST",
|
|
2922
|
-
url: "/projects/:projectId/agent/sessions/:sessionId/subsessions/wait",
|
|
2923
|
-
schema: {
|
|
2924
|
-
params: AgentSessionIdParamsSchema,
|
|
2925
|
-
body: WaitForAgentSubsessionsSchema,
|
|
2926
|
-
response: {
|
|
2927
|
-
200: AgentSubsessionSchema.array(),
|
|
2928
|
-
404: ErrorSchema,
|
|
2929
|
-
503: ErrorSchema
|
|
2930
|
-
}
|
|
2931
|
-
},
|
|
2932
|
-
handler: async (request, reply) => {
|
|
2933
|
-
const agentSessions = ctx.core?.agentSessions;
|
|
2934
|
-
if (!agentSessions) {
|
|
2935
|
-
return reply.status(503).send({ error: "Coding agent not configured" });
|
|
2936
|
-
}
|
|
2937
|
-
try {
|
|
2938
|
-
return reply.send(await agentSessions.waitForSubsessions(resolveIdentity(request), request.params.projectId, request.params.sessionId, { ...request.body, stopWaiting: hungUp(reply) }));
|
|
2939
|
-
} catch (error) {
|
|
2940
|
-
if (error instanceof ProjectNotFoundError || error instanceof AgentSessionNotFoundError) {
|
|
2941
|
-
return reply.status(404).send({ error: "Session not found" });
|
|
2942
|
-
}
|
|
2943
|
-
throw error;
|
|
2944
|
-
}
|
|
2945
|
-
}
|
|
2946
|
-
});
|
|
2947
3442
|
typed.route({
|
|
2948
3443
|
method: "POST",
|
|
2949
3444
|
url: "/projects/:projectId/agent/sessions/:sessionId/subsessions/:childSessionId/interrupt",
|
|
3445
|
+
config: { tokenScope: "sessions:run" },
|
|
2950
3446
|
schema: {
|
|
2951
3447
|
params: AgentSubsessionIdParamsSchema,
|
|
2952
3448
|
response: {
|
|
@@ -2978,6 +3474,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
2978
3474
|
typed.route({
|
|
2979
3475
|
method: "POST",
|
|
2980
3476
|
url: "/projects/:projectId/agent/sessions/:sessionId/attention",
|
|
3477
|
+
config: { tokenScope: "sessions:run" },
|
|
2981
3478
|
schema: {
|
|
2982
3479
|
params: AgentSessionIdParamsSchema,
|
|
2983
3480
|
response: {
|
|
@@ -3004,6 +3501,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
3004
3501
|
typed.route({
|
|
3005
3502
|
method: "PATCH",
|
|
3006
3503
|
url: "/projects/:projectId/agent/sessions/:sessionId/activity",
|
|
3504
|
+
config: { tokenScope: "sessions:run" },
|
|
3007
3505
|
schema: {
|
|
3008
3506
|
params: AgentSessionIdParamsSchema,
|
|
3009
3507
|
body: UpdateAgentSessionActivitySchema,
|
|
@@ -3036,6 +3534,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
3036
3534
|
typed.route({
|
|
3037
3535
|
method: "PATCH",
|
|
3038
3536
|
url: "/projects/:projectId/agent/sessions/:sessionId/title",
|
|
3537
|
+
config: { tokenScope: "sessions:run" },
|
|
3039
3538
|
schema: {
|
|
3040
3539
|
params: AgentSessionIdParamsSchema,
|
|
3041
3540
|
body: RenameAgentSessionSchema,
|
|
@@ -3068,6 +3567,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
3068
3567
|
typed.route({
|
|
3069
3568
|
method: "PATCH",
|
|
3070
3569
|
url: "/projects/:projectId/agent/sessions/:sessionId/metadata",
|
|
3570
|
+
config: { tokenScope: "sessions:run" },
|
|
3071
3571
|
schema: {
|
|
3072
3572
|
params: AgentSessionIdParamsSchema,
|
|
3073
3573
|
body: UpdateAgentSessionMetadataSchema,
|
|
@@ -3110,6 +3610,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
3110
3610
|
typed.route({
|
|
3111
3611
|
method: "POST",
|
|
3112
3612
|
url: "/projects/:projectId/agent/sessions/:sessionId/fork",
|
|
3613
|
+
config: { tokenScope: "sessions:run" },
|
|
3113
3614
|
schema: {
|
|
3114
3615
|
params: AgentSessionIdParamsSchema,
|
|
3115
3616
|
body: ForkAgentSessionSchema,
|
|
@@ -3138,6 +3639,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
3138
3639
|
typed.route({
|
|
3139
3640
|
method: "DELETE",
|
|
3140
3641
|
url: "/projects/:projectId/agent/sessions/:sessionId",
|
|
3642
|
+
config: { tokenScope: "sessions:run" },
|
|
3141
3643
|
schema: {
|
|
3142
3644
|
params: AgentSessionIdParamsSchema,
|
|
3143
3645
|
response: { 200: AgentSessionSchema, 404: ErrorSchema, 503: ErrorSchema }
|
|
@@ -3195,6 +3697,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
3195
3697
|
typed.route({
|
|
3196
3698
|
method: "DELETE",
|
|
3197
3699
|
url: "/projects/:projectId/agent/chats/:key",
|
|
3700
|
+
config: { tokenScope: "sessions:run" },
|
|
3198
3701
|
schema: {
|
|
3199
3702
|
params: KeyedChatParamsSchema,
|
|
3200
3703
|
querystring: KeyedChatQuerySchema,
|
|
@@ -3256,6 +3759,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
3256
3759
|
typed.route({
|
|
3257
3760
|
method: "POST",
|
|
3258
3761
|
url: "/projects/:projectId/agent/sessions/:sessionId/archive",
|
|
3762
|
+
config: { tokenScope: "sessions:run" },
|
|
3259
3763
|
schema: {
|
|
3260
3764
|
params: AgentSessionIdParamsSchema,
|
|
3261
3765
|
body: ArchiveAgentSessionSchema,
|
|
@@ -3291,6 +3795,7 @@ function registerAgentRoutes(app, ctx) {
|
|
|
3291
3795
|
typed.route({
|
|
3292
3796
|
method: "POST",
|
|
3293
3797
|
url: "/projects/:projectId/agent/sessions/:sessionId/unarchive",
|
|
3798
|
+
config: { tokenScope: "sessions:run" },
|
|
3294
3799
|
schema: {
|
|
3295
3800
|
params: AgentSessionIdParamsSchema,
|
|
3296
3801
|
response: {
|
|
@@ -3536,6 +4041,7 @@ import {
|
|
|
3536
4041
|
RunCapabilityError,
|
|
3537
4042
|
RunEnrollmentConflictError,
|
|
3538
4043
|
RunInputInvalidError,
|
|
4044
|
+
RunQueueFullError,
|
|
3539
4045
|
SandboxProviderNotConfiguredError,
|
|
3540
4046
|
TenantActiveRunLimitError,
|
|
3541
4047
|
WorkflowNotFoundError
|
|
@@ -3550,7 +4056,7 @@ function replyForTriggerError(err, reply) {
|
|
|
3550
4056
|
if (err instanceof ProductionDeploymentNotFoundError) {
|
|
3551
4057
|
return reply.status(409).send({ error: err.message });
|
|
3552
4058
|
}
|
|
3553
|
-
if (err instanceof RunEnrollmentConflictError) {
|
|
4059
|
+
if (err instanceof RunEnrollmentConflictError || err instanceof RunQueueFullError) {
|
|
3554
4060
|
return reply.status(409).send({ error: err.message });
|
|
3555
4061
|
}
|
|
3556
4062
|
if (err instanceof AuthenticationRequiredError2) {
|
|
@@ -4084,56 +4590,95 @@ function registerAppRoutes(app, ctx) {
|
|
|
4084
4590
|
|
|
4085
4591
|
// src/routes/apps-mcp.ts
|
|
4086
4592
|
import { buildAppGuestDocument as buildAppGuestDocument2 } from "@catamorphic/app";
|
|
4087
|
-
|
|
4088
|
-
|
|
4089
|
-
|
|
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) => {
|
|
4090
4642
|
const core = ctx.core;
|
|
4091
4643
|
if (!core?.apps || !core.runs) {
|
|
4092
4644
|
return reply.status(503).send({ error: "Apps not configured" });
|
|
4093
4645
|
}
|
|
4094
4646
|
const { projectId } = request.params;
|
|
4095
|
-
|
|
4096
|
-
|
|
4097
|
-
|
|
4098
|
-
|
|
4099
|
-
|
|
4100
|
-
|
|
4101
|
-
|
|
4102
|
-
|
|
4103
|
-
|
|
4104
|
-
|
|
4105
|
-
|
|
4106
|
-
|
|
4107
|
-
|
|
4108
|
-
|
|
4109
|
-
|
|
4110
|
-
|
|
4111
|
-
|
|
4112
|
-
|
|
4113
|
-
|
|
4114
|
-
|
|
4115
|
-
|
|
4116
|
-
|
|
4117
|
-
|
|
4118
|
-
|
|
4119
|
-
|
|
4120
|
-
|
|
4121
|
-
}
|
|
4122
|
-
|
|
4123
|
-
|
|
4124
|
-
|
|
4125
|
-
|
|
4126
|
-
|
|
4127
|
-
|
|
4128
|
-
|
|
4129
|
-
|
|
4130
|
-
const apps = await loadPublishedApps(core, identity, projectId);
|
|
4131
|
-
const published = apps.find((candidate) => appResourceUri(candidate.name) === uri);
|
|
4132
|
-
if (!published) {
|
|
4133
|
-
throw new McpRequestError2(-32602, `Unknown resource ${uri}`);
|
|
4134
|
-
}
|
|
4135
|
-
return {
|
|
4136
|
-
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 [
|
|
4137
4682
|
{
|
|
4138
4683
|
uri,
|
|
4139
4684
|
mimeType: MCP_APP_MIME_TYPE,
|
|
@@ -4145,16 +4690,9 @@ function registerAppsMcpRoutes(app, ctx) {
|
|
|
4145
4690
|
}
|
|
4146
4691
|
}
|
|
4147
4692
|
}
|
|
4148
|
-
]
|
|
4149
|
-
}
|
|
4150
|
-
}
|
|
4151
|
-
case "tools/call": {
|
|
4152
|
-
const name = typeof params.name === "string" ? params.name : "";
|
|
4153
|
-
const args = typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {};
|
|
4154
|
-
return callTool(core, identity, projectId, name, args);
|
|
4693
|
+
];
|
|
4694
|
+
}
|
|
4155
4695
|
}
|
|
4156
|
-
default:
|
|
4157
|
-
throw new McpRequestError2(-32601, `Method not found: ${method}`);
|
|
4158
4696
|
}
|
|
4159
4697
|
});
|
|
4160
4698
|
});
|
|
@@ -4311,7 +4849,9 @@ function registerClientRunnerRoutes(app, ctx) {
|
|
|
4311
4849
|
"containers",
|
|
4312
4850
|
"network.policy",
|
|
4313
4851
|
"network.setup",
|
|
4314
|
-
"volumes"
|
|
4852
|
+
"volumes",
|
|
4853
|
+
"caches",
|
|
4854
|
+
"commands.separate"
|
|
4315
4855
|
])).optional(),
|
|
4316
4856
|
publicKey: ExecutorPublicKeySchema.optional()
|
|
4317
4857
|
}),
|
|
@@ -4678,8 +5218,8 @@ function registerConnectionMcpRoutes(app, ctx) {
|
|
|
4678
5218
|
}
|
|
4679
5219
|
const mcp = broker.servesMcp(binding.providerKind);
|
|
4680
5220
|
return serveForwardedTools2({
|
|
5221
|
+
request,
|
|
4681
5222
|
reply,
|
|
4682
|
-
body: request.body,
|
|
4683
5223
|
serverName: "catamorphic-connection-broker",
|
|
4684
5224
|
listTools: async () => {
|
|
4685
5225
|
try {
|
|
@@ -4694,12 +5234,12 @@ function registerConnectionMcpRoutes(app, ctx) {
|
|
|
4694
5234
|
outputSchema: undefined
|
|
4695
5235
|
}));
|
|
4696
5236
|
} catch {
|
|
4697
|
-
throw new
|
|
5237
|
+
throw new McpError2(-32000, "Connection action failed");
|
|
4698
5238
|
}
|
|
4699
5239
|
},
|
|
4700
5240
|
callTool: async (call) => {
|
|
4701
5241
|
if (!binding.capabilities.includes(call.name)) {
|
|
4702
|
-
throw new
|
|
5242
|
+
throw new McpError2(-32602, "Tool is outside the connection grant");
|
|
4703
5243
|
}
|
|
4704
5244
|
try {
|
|
4705
5245
|
const output = await broker.invoke({
|
|
@@ -4716,7 +5256,7 @@ function registerConnectionMcpRoutes(app, ctx) {
|
|
|
4716
5256
|
if (error instanceof ConnectionActionDeniedError || error instanceof ConnectionActionRefusedError) {
|
|
4717
5257
|
return toolError2(error.message);
|
|
4718
5258
|
}
|
|
4719
|
-
throw new
|
|
5259
|
+
throw new McpError2(-32000, "Connection action failed");
|
|
4720
5260
|
}
|
|
4721
5261
|
}
|
|
4722
5262
|
});
|
|
@@ -5307,6 +5847,7 @@ function registerDocumentRoutes(app, ctx) {
|
|
|
5307
5847
|
typed.route({
|
|
5308
5848
|
method: "PUT",
|
|
5309
5849
|
url: "/projects/:projectId/documents/content",
|
|
5850
|
+
config: { tokenScope: "documents:write" },
|
|
5310
5851
|
bodyLimit: Math.ceil(ctx.features.storeUploadMaxBytes * 4 / 3) + 65536,
|
|
5311
5852
|
schema: {
|
|
5312
5853
|
params: ProjectIdParamsSchema,
|
|
@@ -5345,6 +5886,7 @@ function registerDocumentRoutes(app, ctx) {
|
|
|
5345
5886
|
typed.route({
|
|
5346
5887
|
method: "DELETE",
|
|
5347
5888
|
url: "/projects/:projectId/documents/content",
|
|
5889
|
+
config: { tokenScope: "documents:write" },
|
|
5348
5890
|
schema: {
|
|
5349
5891
|
params: ProjectIdParamsSchema,
|
|
5350
5892
|
querystring: z8.object({
|
|
@@ -5429,6 +5971,7 @@ function registerDocumentRoutes(app, ctx) {
|
|
|
5429
5971
|
typed.route({
|
|
5430
5972
|
method: "POST",
|
|
5431
5973
|
url: "/projects/:projectId/proposals",
|
|
5974
|
+
config: { tokenScope: "program:write" },
|
|
5432
5975
|
schema: {
|
|
5433
5976
|
params: ProjectIdParamsSchema,
|
|
5434
5977
|
body: ProposeChangeSchema,
|
|
@@ -5566,6 +6109,7 @@ function registerDocumentRoutes(app, ctx) {
|
|
|
5566
6109
|
typed.route({
|
|
5567
6110
|
method: "POST",
|
|
5568
6111
|
url: "/projects/:projectId/proposals/:number/comments",
|
|
6112
|
+
config: { tokenScope: "program:write" },
|
|
5569
6113
|
schema: {
|
|
5570
6114
|
params: ProjectIdParamsSchema.extend({
|
|
5571
6115
|
number: z8.coerce.number().int().positive()
|
|
@@ -5595,7 +6139,11 @@ function registerDocumentRoutes(app, ctx) {
|
|
|
5595
6139
|
}
|
|
5596
6140
|
|
|
5597
6141
|
// src/routes/environments.ts
|
|
5598
|
-
import {
|
|
6142
|
+
import {
|
|
6143
|
+
AccessDeniedError as AccessDeniedError5,
|
|
6144
|
+
AgentNotConfiguredError as AgentNotConfiguredError2,
|
|
6145
|
+
hasProjectPermission
|
|
6146
|
+
} from "@catamorphic/core";
|
|
5599
6147
|
function registerEnvironmentRoutes(app, ctx) {
|
|
5600
6148
|
const typed = app.withTypeProvider();
|
|
5601
6149
|
typed.route({
|
|
@@ -5648,6 +6196,37 @@ function registerEnvironmentRoutes(app, ctx) {
|
|
|
5648
6196
|
}
|
|
5649
6197
|
}
|
|
5650
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
|
+
});
|
|
5651
6230
|
}
|
|
5652
6231
|
|
|
5653
6232
|
// src/routes/git-gateway.ts
|
|
@@ -6165,6 +6744,7 @@ import {
|
|
|
6165
6744
|
RunInputInvalidError as RunInputInvalidError2,
|
|
6166
6745
|
TenantActiveRunLimitError as TenantActiveRunLimitError2,
|
|
6167
6746
|
TriggerBindingsInvalidError,
|
|
6747
|
+
TriggerKindHostOnlyError,
|
|
6168
6748
|
TriggerKindNotRegisteredError,
|
|
6169
6749
|
TriggerModeNotAllowedError,
|
|
6170
6750
|
TriggerPayloadInvalidError
|
|
@@ -6235,6 +6815,7 @@ function registerTriggerRoutes(app, ctx) {
|
|
|
6235
6815
|
body: FireTriggerSchema,
|
|
6236
6816
|
response: {
|
|
6237
6817
|
200: TriggerFireResultSchema,
|
|
6818
|
+
403: ErrorSchema,
|
|
6238
6819
|
404: ErrorSchema,
|
|
6239
6820
|
409: ErrorSchema,
|
|
6240
6821
|
422: ErrorSchema,
|
|
@@ -6316,7 +6897,7 @@ function handleTriggerError(err, reply) {
|
|
|
6316
6897
|
requirements: [...err.requirements]
|
|
6317
6898
|
});
|
|
6318
6899
|
}
|
|
6319
|
-
if (err instanceof EnvironmentAccessDeniedError3) {
|
|
6900
|
+
if (err instanceof EnvironmentAccessDeniedError3 || err instanceof TriggerKindHostOnlyError) {
|
|
6320
6901
|
return reply.status(403).send({ error: err.message });
|
|
6321
6902
|
}
|
|
6322
6903
|
if (err instanceof EnvironmentNotFoundError3) {
|
|
@@ -7046,8 +7627,10 @@ import {
|
|
|
7046
7627
|
EnvironmentNotFoundError as EnvironmentNotFoundError4,
|
|
7047
7628
|
EnvironmentPolicyInvalidError,
|
|
7048
7629
|
ProductionDeploymentNotFoundError as ProductionDeploymentNotFoundError3,
|
|
7630
|
+
PublishedRevisionNotRetryableError,
|
|
7049
7631
|
WorkflowEnablementConflictError,
|
|
7050
7632
|
WorkflowEnablementConsentRequiredError,
|
|
7633
|
+
WorkflowEnablementFollowUnavailableError,
|
|
7051
7634
|
WorkflowEnablementNotFoundError,
|
|
7052
7635
|
WorkflowEnablementSuspendedError,
|
|
7053
7636
|
WorkflowNotFoundError as WorkflowNotFoundError2
|
|
@@ -7140,7 +7723,10 @@ function registerWorkflowEnablementRoutes(app, ctx) {
|
|
|
7140
7723
|
url: "/projects/:projectId/workflow-enablements",
|
|
7141
7724
|
schema: {
|
|
7142
7725
|
params: ProjectIdParamsSchema,
|
|
7143
|
-
body: PreviewBodySchema.extend({
|
|
7726
|
+
body: PreviewBodySchema.extend({
|
|
7727
|
+
consentDigest: z15.string().length(64),
|
|
7728
|
+
follow: z15.boolean().optional()
|
|
7729
|
+
}),
|
|
7144
7730
|
response: {
|
|
7145
7731
|
201: WorkflowEnablementSchema,
|
|
7146
7732
|
403: ErrorSchema,
|
|
@@ -7269,6 +7855,107 @@ function registerWorkflowEnablementRoutes(app, ctx) {
|
|
|
7269
7855
|
}
|
|
7270
7856
|
}
|
|
7271
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
|
+
});
|
|
7272
7959
|
}
|
|
7273
7960
|
function handleEnablementError(error, reply) {
|
|
7274
7961
|
if (error instanceof AuthenticationRequiredError4) {
|
|
@@ -7291,7 +7978,7 @@ function handleEnablementError(error, reply) {
|
|
|
7291
7978
|
if (error instanceof AccessDeniedError7 || error instanceof ConnectionPermissionDeniedError3 || error instanceof EnvironmentAccessDeniedError4) {
|
|
7292
7979
|
return reply.status(403).send({ error: error.message });
|
|
7293
7980
|
}
|
|
7294
|
-
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) {
|
|
7295
7982
|
return reply.status(409).send({ error: error.message });
|
|
7296
7983
|
}
|
|
7297
7984
|
throw error;
|
|
@@ -7494,7 +8181,7 @@ function registerPrivateCustomizationRoutes(app, ctx) {
|
|
|
7494
8181
|
|
|
7495
8182
|
// src/routes/project-mcp.ts
|
|
7496
8183
|
import { agentCapabilityTools } from "@catamorphic/sandbox";
|
|
7497
|
-
import { z as
|
|
8184
|
+
import { z as z22 } from "zod";
|
|
7498
8185
|
|
|
7499
8186
|
// src/project-mcp-program.ts
|
|
7500
8187
|
import {
|
|
@@ -7503,7 +8190,7 @@ import {
|
|
|
7503
8190
|
assertProjectPermission as assertProjectPermission2,
|
|
7504
8191
|
DeploymentBlockedError,
|
|
7505
8192
|
effectiveProjectPermissions as effectiveProjectPermissions2,
|
|
7506
|
-
hasProjectPermission,
|
|
8193
|
+
hasProjectPermission as hasProjectPermission2,
|
|
7507
8194
|
mayUseProject
|
|
7508
8195
|
} from "@catamorphic/core";
|
|
7509
8196
|
import { checkProject } from "@catamorphic/parser";
|
|
@@ -7519,7 +8206,7 @@ function programTools(core, identity, projectId) {
|
|
|
7519
8206
|
if (!mayUseProject(identity, projectId))
|
|
7520
8207
|
return [];
|
|
7521
8208
|
const tools = [overviewTool(core, identity, projectId)];
|
|
7522
|
-
const may = (permission) =>
|
|
8209
|
+
const may = (permission) => hasProjectPermission2(identity, projectId, permission);
|
|
7523
8210
|
if (may("program:write")) {
|
|
7524
8211
|
tools.push({
|
|
7525
8212
|
definition: {
|
|
@@ -7734,7 +8421,7 @@ function overviewTool(core, identity, projectId) {
|
|
|
7734
8421
|
return;
|
|
7735
8422
|
throw error;
|
|
7736
8423
|
});
|
|
7737
|
-
const may = (permission) =>
|
|
8424
|
+
const may = (permission) => hasProjectPermission2(identity, projectId, permission);
|
|
7738
8425
|
const [project, roles, agents, environments, workflows, apps, draft] = await Promise.all([
|
|
7739
8426
|
optional(() => core.projects.getOverview({ identity, projectId })),
|
|
7740
8427
|
optional(async () => core.memberships?.describeMember({
|
|
@@ -7908,8 +8595,8 @@ async function projectInstructions(args) {
|
|
|
7908
8595
|
if (has("list_skills"))
|
|
7909
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.");
|
|
7910
8597
|
lines.push("- Run deployed workflows with workflow_run and debug them with workflow_runs and run_details.");
|
|
7911
|
-
if (has("
|
|
7912
|
-
lines.push("-
|
|
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.");
|
|
7913
8600
|
if (args.host)
|
|
7914
8601
|
lines.push(args.host);
|
|
7915
8602
|
return lines.join(`
|
|
@@ -7924,15 +8611,10 @@ import {
|
|
|
7924
8611
|
} from "@catamorphic/agent-protocol";
|
|
7925
8612
|
import {
|
|
7926
8613
|
AccessDeniedError as AccessDeniedError9,
|
|
7927
|
-
AgentTurnUnsettledError,
|
|
7928
|
-
EVERY_ARTIFACT,
|
|
7929
8614
|
mayUseProject as mayUseProject2,
|
|
7930
|
-
|
|
7931
|
-
projectAgentId,
|
|
7932
|
-
resolveScope,
|
|
7933
|
-
SESSION_ACTION_SCHEMAS
|
|
8615
|
+
resolveScope
|
|
7934
8616
|
} from "@catamorphic/core";
|
|
7935
|
-
import { z as
|
|
8617
|
+
import { z as z20 } from "zod";
|
|
7936
8618
|
|
|
7937
8619
|
// src/app-presentation-tools.ts
|
|
7938
8620
|
import { APP_ICON_DESCRIPTIONS, APP_ICON_NAMES as APP_ICON_NAMES4 } from "@catamorphic/app";
|
|
@@ -8105,6 +8787,115 @@ function sessionArtifactTool(core, identity, projectId, currentSessionId) {
|
|
|
8105
8787
|
};
|
|
8106
8788
|
}
|
|
8107
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
|
+
|
|
8108
8899
|
// src/project-mcp-surface.ts
|
|
8109
8900
|
var READ_ONLY2 = { readOnlyHint: true };
|
|
8110
8901
|
async function allowedWorkflowNames(core, identity, projectId) {
|
|
@@ -8454,65 +9245,19 @@ function surfaceTools(core, identity, projectId, features = { publications: "pub
|
|
|
8454
9245
|
}
|
|
8455
9246
|
if (core.agentSessions) {
|
|
8456
9247
|
const sessions = core.agentSessions;
|
|
8457
|
-
|
|
8458
|
-
|
|
8459
|
-
|
|
8460
|
-
|
|
8461
|
-
|
|
8462
|
-
|
|
8463
|
-
inputSchema: {
|
|
8464
|
-
type: "object",
|
|
8465
|
-
properties: {
|
|
8466
|
-
agent: { type: "string", description: "The agent's slug" },
|
|
8467
|
-
message: { type: "string" },
|
|
8468
|
-
sessionId: { type: "string" },
|
|
8469
|
-
environment: {
|
|
8470
|
-
type: "string",
|
|
8471
|
-
description: "Environment for a new conversation (project_overview lists yours)"
|
|
8472
|
-
}
|
|
8473
|
-
},
|
|
8474
|
-
required: ["agent", "message"]
|
|
8475
|
-
}
|
|
8476
|
-
},
|
|
8477
|
-
call: guarded(async (args) => {
|
|
8478
|
-
const agent = str(args.agent);
|
|
8479
|
-
const message = str(args.message);
|
|
8480
|
-
if (!agent || !message)
|
|
8481
|
-
throw new Error("agent and message are required");
|
|
8482
|
-
const agentId = projectAgentId(projectId, agent);
|
|
8483
|
-
const sessionId = str(args.sessionId) ?? (await sessions.create(identity, projectId, {
|
|
8484
|
-
agentId,
|
|
8485
|
-
source: "mcp",
|
|
8486
|
-
...str(args.environment) ? { environment: str(args.environment) } : {}
|
|
8487
|
-
})).id;
|
|
8488
|
-
const from = currentSessionId ? {
|
|
8489
|
-
kind: "agent",
|
|
8490
|
-
sessionId: currentSessionId,
|
|
8491
|
-
agentId: (await sessions.get(identity, projectId, currentSessionId)).agentId
|
|
8492
|
-
} : {
|
|
8493
|
-
kind: "assistant",
|
|
8494
|
-
externalUserId: identity.externalUserId
|
|
8495
|
-
};
|
|
8496
|
-
try {
|
|
8497
|
-
const { reply } = await sessions.sendMessage(identity, projectId, sessionId, message, { from });
|
|
8498
|
-
return {
|
|
8499
|
-
sessionId,
|
|
8500
|
-
reply: reply?.kind === "assistant_message" ? reply.text : ""
|
|
8501
|
-
};
|
|
8502
|
-
} catch (error) {
|
|
8503
|
-
if (error instanceof AgentTurnUnsettledError)
|
|
8504
|
-
return { sessionId, state: error.state, reply: error.message };
|
|
8505
|
-
throw error;
|
|
8506
|
-
}
|
|
8507
|
-
})
|
|
8508
|
-
});
|
|
9248
|
+
tools.push(...sessionTools({
|
|
9249
|
+
core,
|
|
9250
|
+
identity,
|
|
9251
|
+
projectId,
|
|
9252
|
+
...currentSessionId ? { currentSessionId } : {}
|
|
9253
|
+
}));
|
|
8509
9254
|
if (currentSessionId) {
|
|
8510
9255
|
const sessionId = currentSessionId;
|
|
8511
9256
|
tools.push({
|
|
8512
9257
|
definition: {
|
|
8513
9258
|
name: "set_session_metadata",
|
|
8514
9259
|
description: SET_SESSION_METADATA_DESCRIPTION,
|
|
8515
|
-
inputSchema:
|
|
9260
|
+
inputSchema: z20.toJSONSchema(setSessionMetadataInputSchema)
|
|
8516
9261
|
},
|
|
8517
9262
|
call: guarded(async (args) => {
|
|
8518
9263
|
const values = sessionMetadataToolWrite(args);
|
|
@@ -8527,100 +9272,13 @@ function surfaceTools(core, identity, projectId, features = { publications: "pub
|
|
|
8527
9272
|
})
|
|
8528
9273
|
});
|
|
8529
9274
|
}
|
|
8530
|
-
tools.push({
|
|
8531
|
-
definition: {
|
|
8532
|
-
name: "send_agent_message",
|
|
8533
|
-
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.",
|
|
8534
|
-
inputSchema: {
|
|
8535
|
-
type: "object",
|
|
8536
|
-
properties: {
|
|
8537
|
-
fromSessionId: { type: "string" },
|
|
8538
|
-
toSessionId: { type: "string" },
|
|
8539
|
-
message: { type: "string" },
|
|
8540
|
-
mode: {
|
|
8541
|
-
type: "string",
|
|
8542
|
-
enum: ["queue", "steer", "interrupt", "message_only"],
|
|
8543
|
-
default: "queue"
|
|
8544
|
-
},
|
|
8545
|
-
attention: { type: "string", enum: ["none", "required"] },
|
|
8546
|
-
idempotencyKey: { type: "string" },
|
|
8547
|
-
workspace: {
|
|
8548
|
-
type: "object",
|
|
8549
|
-
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.",
|
|
8550
|
-
properties: {
|
|
8551
|
-
ref: { type: "string" },
|
|
8552
|
-
update: { type: "string", enum: ["reset", "rebase"] }
|
|
8553
|
-
},
|
|
8554
|
-
required: ["ref"],
|
|
8555
|
-
additionalProperties: false
|
|
8556
|
-
}
|
|
8557
|
-
},
|
|
8558
|
-
required: ["toSessionId", "message"]
|
|
8559
|
-
}
|
|
8560
|
-
},
|
|
8561
|
-
call: guarded(async (args) => {
|
|
8562
|
-
const fromSessionId = str(args.fromSessionId) ?? currentSessionId;
|
|
8563
|
-
const toSessionId = str(args.toSessionId);
|
|
8564
|
-
const message = str(args.message);
|
|
8565
|
-
const mode = args.mode === undefined ? "queue" : args.mode;
|
|
8566
|
-
if (!fromSessionId || !toSessionId || !message || mode !== "queue" && mode !== "steer" && mode !== "interrupt" && mode !== "message_only") {
|
|
8567
|
-
throw new Error("fromSessionId, toSessionId, message, and a valid mode are required");
|
|
8568
|
-
}
|
|
8569
|
-
if (args.attention !== undefined && args.attention !== "none" && args.attention !== "required")
|
|
8570
|
-
throw new Error("attention must be none or required");
|
|
8571
|
-
const source = await sessions.get(identity, projectId, fromSessionId);
|
|
8572
|
-
return sessions.deliver(identity, projectId, toSessionId, {
|
|
8573
|
-
content: message,
|
|
8574
|
-
author: {
|
|
8575
|
-
kind: "agent",
|
|
8576
|
-
sessionId: fromSessionId,
|
|
8577
|
-
agentId: source.agentId
|
|
8578
|
-
},
|
|
8579
|
-
mode,
|
|
8580
|
-
attention: args.attention,
|
|
8581
|
-
...str(args.idempotencyKey) ? { idempotencyKey: str(args.idempotencyKey) } : {},
|
|
8582
|
-
...args.workspace === undefined ? {} : { workspace: parseWorkspaceRequest(args.workspace) }
|
|
8583
|
-
});
|
|
8584
|
-
})
|
|
8585
|
-
});
|
|
8586
|
-
if (core.sessionActions) {
|
|
8587
|
-
const actions = core.sessionActions;
|
|
8588
|
-
for (const operation of Object.keys(SESSION_ACTION_SCHEMAS)) {
|
|
8589
|
-
tools.push({
|
|
8590
|
-
definition: {
|
|
8591
|
-
name: `session_${operation}`,
|
|
8592
|
-
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.`,
|
|
8593
|
-
inputSchema: z19.toJSONSchema(SESSION_ACTION_SCHEMAS[operation])
|
|
8594
|
-
},
|
|
8595
|
-
call: guarded(async (args) => {
|
|
8596
|
-
const source = currentSessionId ? await sessions.get(identity, projectId, currentSessionId) : undefined;
|
|
8597
|
-
return actions.execute({
|
|
8598
|
-
identity,
|
|
8599
|
-
projectId,
|
|
8600
|
-
operation,
|
|
8601
|
-
args,
|
|
8602
|
-
author: source ? {
|
|
8603
|
-
kind: "agent",
|
|
8604
|
-
sessionId: source.id,
|
|
8605
|
-
agentId: source.agentId
|
|
8606
|
-
} : { kind: "user", externalUserId: identity.externalUserId },
|
|
8607
|
-
causation: source ? await sessions.causalContext({
|
|
8608
|
-
identity,
|
|
8609
|
-
projectId,
|
|
8610
|
-
sessionId: source.id
|
|
8611
|
-
}) : []
|
|
8612
|
-
});
|
|
8613
|
-
})
|
|
8614
|
-
});
|
|
8615
|
-
}
|
|
8616
|
-
}
|
|
8617
9275
|
if (core.watchers) {
|
|
8618
9276
|
const watchers = core.watchers;
|
|
8619
9277
|
const eventSources = core.projectEventSources.map((source) => source.kind);
|
|
8620
9278
|
tools.push({
|
|
8621
9279
|
definition: {
|
|
8622
9280
|
name: "create_watcher",
|
|
8623
|
-
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
|
|
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/).` : ""}`,
|
|
8624
9282
|
inputSchema: {
|
|
8625
9283
|
type: "object",
|
|
8626
9284
|
properties: {
|
|
@@ -8693,47 +9351,513 @@ function surfaceTools(core, identity, projectId, features = { publications: "pub
|
|
|
8693
9351
|
sessionId
|
|
8694
9352
|
});
|
|
8695
9353
|
})
|
|
8696
|
-
}, {
|
|
8697
|
-
definition: {
|
|
8698
|
-
name: "stop_watcher",
|
|
8699
|
-
description: "Stop a temporary watcher owned by a session.",
|
|
8700
|
-
inputSchema: {
|
|
8701
|
-
type: "object",
|
|
8702
|
-
properties: {
|
|
8703
|
-
sessionId: { type: "string" },
|
|
8704
|
-
watcherId: { type: "string" }
|
|
8705
|
-
},
|
|
8706
|
-
required: ["watcherId"]
|
|
8707
|
-
}
|
|
8708
|
-
},
|
|
8709
|
-
call: guarded(async (args) => {
|
|
8710
|
-
const sessionId = str(args.sessionId) ?? currentSessionId;
|
|
8711
|
-
const watcherId = str(args.watcherId);
|
|
8712
|
-
if (!sessionId || !watcherId) {
|
|
8713
|
-
throw new Error("sessionId and watcherId are required");
|
|
8714
|
-
}
|
|
8715
|
-
return {
|
|
8716
|
-
stopped: await watchers.stop({
|
|
8717
|
-
identity,
|
|
8718
|
-
projectId,
|
|
8719
|
-
sessionId,
|
|
8720
|
-
watcherId
|
|
8721
|
-
})
|
|
8722
|
-
};
|
|
8723
|
-
})
|
|
8724
9354
|
});
|
|
8725
9355
|
}
|
|
8726
9356
|
}
|
|
8727
9357
|
return tools;
|
|
8728
9358
|
}
|
|
8729
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
|
+
|
|
8730
9854
|
// src/routes/project-mcp.ts
|
|
8731
9855
|
var TOOL_SYNC_BUDGET_MS2 = 30000;
|
|
8732
9856
|
function registerProjectMcpRoutes(app, ctx) {
|
|
8733
9857
|
const notAllowed = async (_request, reply) => reply.status(405).header("allow", "POST").send();
|
|
8734
9858
|
app.get("/projects/:projectId/mcp", notAllowed);
|
|
8735
|
-
app.delete("/projects/:projectId/mcp", notAllowed);
|
|
8736
|
-
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) => {
|
|
8737
9861
|
const core = ctx.core;
|
|
8738
9862
|
if (!core) {
|
|
8739
9863
|
return reply.status(503).send({ error: "Service not configured" });
|
|
@@ -8755,8 +9879,15 @@ function registerProjectMcpRoutes(app, ctx) {
|
|
|
8755
9879
|
sessionId,
|
|
8756
9880
|
allocationId
|
|
8757
9881
|
}), abort.signal) : [];
|
|
9882
|
+
const chats = sessionMcp({
|
|
9883
|
+
core,
|
|
9884
|
+
identity,
|
|
9885
|
+
projectId,
|
|
9886
|
+
...sessionId ? { currentSessionId: sessionId } : {},
|
|
9887
|
+
stateSecret: mcpStateSecret(ctx)
|
|
9888
|
+
});
|
|
8758
9889
|
const surface = [
|
|
8759
|
-
...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),
|
|
8760
9891
|
...programTools(core, identity, projectId),
|
|
8761
9892
|
...(ctx.projectMcp?.tools?.({ identity, projectId }) ?? []).map((tool) => ({
|
|
8762
9893
|
definition: tool.definition,
|
|
@@ -8769,74 +9900,69 @@ function registerProjectMcpRoutes(app, ctx) {
|
|
|
8769
9900
|
}
|
|
8770
9901
|
}))
|
|
8771
9902
|
];
|
|
8772
|
-
|
|
8773
|
-
|
|
8774
|
-
|
|
8775
|
-
|
|
8776
|
-
|
|
8777
|
-
|
|
8778
|
-
|
|
8779
|
-
|
|
8780
|
-
|
|
8781
|
-
|
|
8782
|
-
|
|
8783
|
-
}
|
|
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))
|
|
8784
9914
|
},
|
|
8785
|
-
|
|
8786
|
-
|
|
8787
|
-
|
|
8788
|
-
|
|
8789
|
-
|
|
8790
|
-
|
|
8791
|
-
|
|
8792
|
-
|
|
8793
|
-
|
|
8794
|
-
|
|
8795
|
-
|
|
8796
|
-
|
|
8797
|
-
|
|
8798
|
-
|
|
8799
|
-
|
|
8800
|
-
|
|
8801
|
-
|
|
8802
|
-
|
|
8803
|
-
|
|
8804
|
-
|
|
8805
|
-
|
|
8806
|
-
...tools.length > 0 || core.mcpToolKinds.length > 0 ? [POLL_RUN_TOOL_DEFINITION] : [],
|
|
8807
|
-
...surface.filter((tool) => !taken.has(String(tool.definition.name))).map((tool) => tool.definition)
|
|
8808
|
-
]
|
|
8809
|
-
};
|
|
8810
|
-
}
|
|
8811
|
-
case "resources/list":
|
|
8812
|
-
return { resources: [] };
|
|
8813
|
-
case "resources/templates/list":
|
|
8814
|
-
return { resourceTemplates: [] };
|
|
8815
|
-
case "prompts/list":
|
|
8816
|
-
return { prompts: [] };
|
|
8817
|
-
case "tools/call": {
|
|
8818
|
-
const name = typeof params.name === "string" ? params.name : "";
|
|
8819
|
-
const args = typeof params.arguments === "object" && params.arguments !== null ? params.arguments : {};
|
|
8820
|
-
const gatewayTool = gatewayTools.find((tool) => tool.name === name);
|
|
8821
|
-
if (gatewayTool) {
|
|
8822
|
-
try {
|
|
8823
|
-
return toolValue(await gatewayTool.execute(args, {
|
|
8824
|
-
projectId,
|
|
8825
|
-
sessionId,
|
|
8826
|
-
stopWaiting: abort.signal
|
|
8827
|
-
}));
|
|
8828
|
-
} catch (error) {
|
|
8829
|
-
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)
|
|
8830
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"
|
|
8831
9954
|
}
|
|
8832
|
-
|
|
8833
|
-
|
|
8834
|
-
|
|
8835
|
-
|
|
8836
|
-
|
|
8837
|
-
|
|
8838
|
-
|
|
8839
|
-
|
|
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 } : {}
|
|
8840
9966
|
}
|
|
8841
9967
|
});
|
|
8842
9968
|
});
|
|
@@ -8960,13 +10086,13 @@ import {
|
|
|
8960
10086
|
assertMayManageRolePolicy as assertMayManageRolePolicy2,
|
|
8961
10087
|
assertProjectPermission as assertProjectPermission3,
|
|
8962
10088
|
DeploymentBlockedError as DeploymentBlockedError2,
|
|
8963
|
-
hasProjectPermission as
|
|
10089
|
+
hasProjectPermission as hasProjectPermission3,
|
|
8964
10090
|
ProjectFileConflictError,
|
|
8965
10091
|
ProjectFileNotFoundError,
|
|
8966
10092
|
ProjectFileNotTextError,
|
|
8967
10093
|
ProjectNotFoundError as ProjectNotFoundError8
|
|
8968
10094
|
} from "@catamorphic/core";
|
|
8969
|
-
import { z as
|
|
10095
|
+
import { z as z23 } from "zod";
|
|
8970
10096
|
function toDto(project) {
|
|
8971
10097
|
return {
|
|
8972
10098
|
id: project.id,
|
|
@@ -9079,7 +10205,7 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9079
10205
|
schema: {
|
|
9080
10206
|
params: ProjectIdParamsSchema,
|
|
9081
10207
|
response: {
|
|
9082
|
-
200:
|
|
10208
|
+
200: z23.object({ deleted: z23.boolean() }),
|
|
9083
10209
|
404: ErrorSchema,
|
|
9084
10210
|
503: ErrorSchema
|
|
9085
10211
|
}
|
|
@@ -9165,6 +10291,7 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9165
10291
|
typed.route({
|
|
9166
10292
|
method: "PUT",
|
|
9167
10293
|
url: "/projects/:projectId/files/*",
|
|
10294
|
+
config: { tokenScope: "program:write" },
|
|
9168
10295
|
schema: {
|
|
9169
10296
|
params: ProjectFileParamsSchema,
|
|
9170
10297
|
body: WriteFileSchema,
|
|
@@ -9287,9 +10414,9 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9287
10414
|
url: "/projects/:projectId/diff",
|
|
9288
10415
|
schema: {
|
|
9289
10416
|
params: ProjectIdParamsSchema,
|
|
9290
|
-
querystring:
|
|
9291
|
-
base:
|
|
9292
|
-
head:
|
|
10417
|
+
querystring: z23.object({
|
|
10418
|
+
base: z23.string().min(1),
|
|
10419
|
+
head: z23.string().min(1)
|
|
9293
10420
|
}),
|
|
9294
10421
|
response: {
|
|
9295
10422
|
200: DiffEntrySchema.array(),
|
|
@@ -9317,6 +10444,7 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9317
10444
|
typed.route({
|
|
9318
10445
|
method: "POST",
|
|
9319
10446
|
url: "/projects/:projectId/deploy",
|
|
10447
|
+
config: { tokenScope: "program:publish" },
|
|
9320
10448
|
schema: {
|
|
9321
10449
|
params: ProjectIdParamsSchema,
|
|
9322
10450
|
body: DeployRequestSchema,
|
|
@@ -9357,6 +10485,7 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9357
10485
|
typed.route({
|
|
9358
10486
|
method: "POST",
|
|
9359
10487
|
url: "/projects/:projectId/pull",
|
|
10488
|
+
config: { tokenScope: "program:write" },
|
|
9360
10489
|
schema: {
|
|
9361
10490
|
params: ProjectIdParamsSchema,
|
|
9362
10491
|
body: PullRequestSchema,
|
|
@@ -9387,6 +10516,7 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9387
10516
|
typed.route({
|
|
9388
10517
|
method: "POST",
|
|
9389
10518
|
url: "/projects/:projectId/discard",
|
|
10519
|
+
config: { tokenScope: "program:write" },
|
|
9390
10520
|
schema: {
|
|
9391
10521
|
params: ProjectIdParamsSchema,
|
|
9392
10522
|
response: {
|
|
@@ -9416,11 +10546,12 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9416
10546
|
typed.route({
|
|
9417
10547
|
method: "POST",
|
|
9418
10548
|
url: "/projects/:projectId/resolve-conflicts",
|
|
10549
|
+
config: { tokenScope: "program:write" },
|
|
9419
10550
|
schema: {
|
|
9420
10551
|
params: ProjectIdParamsSchema,
|
|
9421
10552
|
body: ResolveConflictsSchema,
|
|
9422
10553
|
response: {
|
|
9423
|
-
200:
|
|
10554
|
+
200: z23.object({ commitSha: z23.string() }),
|
|
9424
10555
|
404: ErrorSchema,
|
|
9425
10556
|
503: ErrorSchema
|
|
9426
10557
|
}
|
|
@@ -9449,20 +10580,21 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9449
10580
|
typed.route({
|
|
9450
10581
|
method: "POST",
|
|
9451
10582
|
url: "/projects/:projectId/ai-resolve-conflicts",
|
|
10583
|
+
config: { tokenScope: "program:write" },
|
|
9452
10584
|
schema: {
|
|
9453
10585
|
params: ProjectIdParamsSchema,
|
|
9454
|
-
body:
|
|
9455
|
-
conflicts:
|
|
9456
|
-
path:
|
|
9457
|
-
base:
|
|
9458
|
-
ours:
|
|
9459
|
-
theirs:
|
|
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()
|
|
9460
10592
|
}))
|
|
9461
10593
|
}),
|
|
9462
10594
|
response: {
|
|
9463
|
-
200:
|
|
9464
|
-
resolutions:
|
|
9465
|
-
notes:
|
|
10595
|
+
200: z23.object({
|
|
10596
|
+
resolutions: z23.record(z23.string(), z23.string()),
|
|
10597
|
+
notes: z23.string().optional()
|
|
9466
10598
|
}),
|
|
9467
10599
|
503: ErrorSchema
|
|
9468
10600
|
}
|
|
@@ -9485,9 +10617,9 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9485
10617
|
url: "/projects/:projectId/files-at-ref",
|
|
9486
10618
|
schema: {
|
|
9487
10619
|
params: ProjectIdParamsSchema,
|
|
9488
|
-
querystring: RefQuerySchema.extend({ ref:
|
|
10620
|
+
querystring: RefQuerySchema.extend({ ref: z23.string().min(1) }),
|
|
9489
10621
|
response: {
|
|
9490
|
-
200:
|
|
10622
|
+
200: z23.record(z23.string(), z23.string()),
|
|
9491
10623
|
404: ErrorSchema,
|
|
9492
10624
|
503: ErrorSchema
|
|
9493
10625
|
}
|
|
@@ -9513,7 +10645,7 @@ function registerProjectRoutes(app, ctx) {
|
|
|
9513
10645
|
async function safeListWorkflows(core, identity, projectId) {
|
|
9514
10646
|
try {
|
|
9515
10647
|
const workflows = await core.workflows.list({ identity, projectId });
|
|
9516
|
-
if (!
|
|
10648
|
+
if (!hasProjectPermission3(identity, projectId, "program:read"))
|
|
9517
10649
|
return { workflows, files: [] };
|
|
9518
10650
|
const allFiles = await core.projects.readAllFiles(identity, projectId);
|
|
9519
10651
|
return { workflows, files: Object.keys(allFiles) };
|
|
@@ -9531,7 +10663,7 @@ import {
|
|
|
9531
10663
|
PublicationSlugError,
|
|
9532
10664
|
PublicationSlugTakenError
|
|
9533
10665
|
} from "@catamorphic/core";
|
|
9534
|
-
import { z as
|
|
10666
|
+
import { z as z24 } from "zod";
|
|
9535
10667
|
function registerPublicationRoutes(app, ctx) {
|
|
9536
10668
|
const typed = app.withTypeProvider();
|
|
9537
10669
|
const core = () => {
|
|
@@ -9564,6 +10696,7 @@ function registerPublicationRoutes(app, ctx) {
|
|
|
9564
10696
|
typed.route({
|
|
9565
10697
|
method: "POST",
|
|
9566
10698
|
url: "/projects/:projectId/publications",
|
|
10699
|
+
config: { tokenScope: "program:publish" },
|
|
9567
10700
|
schema: {
|
|
9568
10701
|
params: ProjectIdParamsSchema,
|
|
9569
10702
|
body: PublishSchema,
|
|
@@ -9618,9 +10751,10 @@ function registerPublicationRoutes(app, ctx) {
|
|
|
9618
10751
|
typed.route({
|
|
9619
10752
|
method: "DELETE",
|
|
9620
10753
|
url: "/projects/:projectId/publications/:slug",
|
|
10754
|
+
config: { tokenScope: "program:publish" },
|
|
9621
10755
|
schema: {
|
|
9622
10756
|
params: PublicationParamsSchema,
|
|
9623
|
-
response: { 204:
|
|
10757
|
+
response: { 204: z24.null(), 404: ErrorSchema }
|
|
9624
10758
|
},
|
|
9625
10759
|
handler: async (request, reply) => {
|
|
9626
10760
|
try {
|
|
@@ -9692,7 +10826,7 @@ import {
|
|
|
9692
10826
|
RunPauseNotFoundError,
|
|
9693
10827
|
RunResumeConflictError
|
|
9694
10828
|
} from "@catamorphic/core";
|
|
9695
|
-
import { z as
|
|
10829
|
+
import { z as z25 } from "zod";
|
|
9696
10830
|
function registerRunRoutes(app, ctx) {
|
|
9697
10831
|
const typed = app.withTypeProvider();
|
|
9698
10832
|
typed.route({
|
|
@@ -9721,6 +10855,7 @@ function registerRunRoutes(app, ctx) {
|
|
|
9721
10855
|
typed.route({
|
|
9722
10856
|
method: "POST",
|
|
9723
10857
|
url: "/runs/:runId/cancel",
|
|
10858
|
+
config: { tokenScope: "sessions:run" },
|
|
9724
10859
|
schema: {
|
|
9725
10860
|
params: RunIdParamsSchema,
|
|
9726
10861
|
body: CancelRunSchema,
|
|
@@ -9748,6 +10883,7 @@ function registerRunRoutes(app, ctx) {
|
|
|
9748
10883
|
typed.route({
|
|
9749
10884
|
method: "POST",
|
|
9750
10885
|
url: "/runs/:runId/pause",
|
|
10886
|
+
config: { tokenScope: "sessions:run" },
|
|
9751
10887
|
schema: {
|
|
9752
10888
|
params: RunIdParamsSchema,
|
|
9753
10889
|
response: {
|
|
@@ -9773,6 +10909,7 @@ function registerRunRoutes(app, ctx) {
|
|
|
9773
10909
|
typed.route({
|
|
9774
10910
|
method: "POST",
|
|
9775
10911
|
url: "/runs/:runId/resume",
|
|
10912
|
+
config: { tokenScope: "sessions:run" },
|
|
9776
10913
|
schema: {
|
|
9777
10914
|
params: RunIdParamsSchema,
|
|
9778
10915
|
response: {
|
|
@@ -9798,6 +10935,7 @@ function registerRunRoutes(app, ctx) {
|
|
|
9798
10935
|
typed.route({
|
|
9799
10936
|
method: "POST",
|
|
9800
10937
|
url: "/runs/:runId/pauses/:pauseId/resume",
|
|
10938
|
+
config: { tokenScope: "sessions:run" },
|
|
9801
10939
|
schema: {
|
|
9802
10940
|
params: RunPauseParamsSchema,
|
|
9803
10941
|
body: ResumeRunPauseSchema,
|
|
@@ -9860,7 +10998,7 @@ function registerRunRoutes(app, ctx) {
|
|
|
9860
10998
|
schema: {
|
|
9861
10999
|
params: RunItemParamsSchema,
|
|
9862
11000
|
response: {
|
|
9863
|
-
200:
|
|
11001
|
+
200: z25.array(BatchItemStepSchema),
|
|
9864
11002
|
404: ErrorSchema,
|
|
9865
11003
|
409: ErrorSchema,
|
|
9866
11004
|
503: ErrorSchema
|
|
@@ -9892,6 +11030,106 @@ function handleRunError(args) {
|
|
|
9892
11030
|
throw args.error;
|
|
9893
11031
|
}
|
|
9894
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
|
+
|
|
9895
11133
|
// src/routes/session-mailboxes.ts
|
|
9896
11134
|
import { SessionMailboxNotFoundError } from "@catamorphic/core";
|
|
9897
11135
|
function registerSessionMailboxRoutes(app, ctx) {
|
|
@@ -9919,6 +11157,7 @@ function registerSessionMailboxRoutes(app, ctx) {
|
|
|
9919
11157
|
typed.route({
|
|
9920
11158
|
method: "POST",
|
|
9921
11159
|
url: "/projects/:projectId/session-mailboxes/:mailboxId/acknowledge",
|
|
11160
|
+
config: { tokenScope: "sessions:run" },
|
|
9922
11161
|
schema: {
|
|
9923
11162
|
params: SessionMailboxIdParamsSchema,
|
|
9924
11163
|
body: AcknowledgeSessionMailboxSchema,
|
|
@@ -10278,6 +11517,7 @@ function registerWatcherRoutes(app, ctx) {
|
|
|
10278
11517
|
typed.route({
|
|
10279
11518
|
method: "DELETE",
|
|
10280
11519
|
url: "/projects/:projectId/agent/sessions/:sessionId/watchers/:watcherId",
|
|
11520
|
+
config: { tokenScope: "sessions:run" },
|
|
10281
11521
|
schema: {
|
|
10282
11522
|
params: WatcherIdParamsSchema,
|
|
10283
11523
|
response: {
|
|
@@ -10318,13 +11558,13 @@ import {
|
|
|
10318
11558
|
WebhookRejectedError,
|
|
10319
11559
|
WebhookTooLargeError
|
|
10320
11560
|
} from "@catamorphic/core";
|
|
10321
|
-
import { z as
|
|
10322
|
-
var WebhookSchema =
|
|
10323
|
-
name:
|
|
10324
|
-
url:
|
|
10325
|
-
workflows:
|
|
10326
|
-
listening:
|
|
10327
|
-
verified:
|
|
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()
|
|
10328
11568
|
});
|
|
10329
11569
|
function registerWebhookRoutes(app, ctx) {
|
|
10330
11570
|
const typed = app.withTypeProvider();
|
|
@@ -10339,14 +11579,14 @@ function registerWebhookRoutes(app, ctx) {
|
|
|
10339
11579
|
config: { public: true },
|
|
10340
11580
|
bodyLimit: hostMaxBytes,
|
|
10341
11581
|
schema: {
|
|
10342
|
-
params:
|
|
10343
|
-
projectId:
|
|
10344
|
-
name:
|
|
10345
|
-
token:
|
|
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)
|
|
10346
11586
|
}),
|
|
10347
11587
|
response: {
|
|
10348
|
-
200:
|
|
10349
|
-
202:
|
|
11588
|
+
200: z27.string(),
|
|
11589
|
+
202: z27.object({ id: z27.string(), duplicate: z27.boolean() }),
|
|
10350
11590
|
401: ErrorSchema,
|
|
10351
11591
|
404: ErrorSchema,
|
|
10352
11592
|
405: ErrorSchema,
|
|
@@ -10388,7 +11628,7 @@ function registerWebhookRoutes(app, ctx) {
|
|
|
10388
11628
|
url: "/projects/:projectId/webhooks",
|
|
10389
11629
|
schema: {
|
|
10390
11630
|
params: ProjectIdParamsSchema,
|
|
10391
|
-
response: { 200:
|
|
11631
|
+
response: { 200: z27.array(WebhookSchema), 503: ErrorSchema }
|
|
10392
11632
|
},
|
|
10393
11633
|
handler: async (request, reply) => {
|
|
10394
11634
|
const webhooks = ctx.core?.webhooks;
|
|
@@ -10409,7 +11649,7 @@ function registerWebhookRoutes(app, ctx) {
|
|
|
10409
11649
|
method: "POST",
|
|
10410
11650
|
url: "/projects/:projectId/webhooks/:name/rotate",
|
|
10411
11651
|
schema: {
|
|
10412
|
-
params: ProjectIdParamsSchema.extend({ name:
|
|
11652
|
+
params: ProjectIdParamsSchema.extend({ name: z27.string().min(1) }),
|
|
10413
11653
|
response: { 200: WebhookSchema, 404: ErrorSchema, 503: ErrorSchema }
|
|
10414
11654
|
},
|
|
10415
11655
|
handler: async (request, reply) => {
|
|
@@ -10450,7 +11690,7 @@ import {
|
|
|
10450
11690
|
RunSignalNotFoundError,
|
|
10451
11691
|
WorkflowNotFoundError as WorkflowNotFoundError3
|
|
10452
11692
|
} from "@catamorphic/core";
|
|
10453
|
-
import { z as
|
|
11693
|
+
import { z as z28 } from "zod";
|
|
10454
11694
|
function registerWorkflowRoutes(app, ctx) {
|
|
10455
11695
|
const typed = app.withTypeProvider();
|
|
10456
11696
|
typed.route({
|
|
@@ -10524,6 +11764,7 @@ function registerWorkflowRoutes(app, ctx) {
|
|
|
10524
11764
|
typed.route({
|
|
10525
11765
|
method: "POST",
|
|
10526
11766
|
url: "/projects/:projectId/workflows/:name/runs",
|
|
11767
|
+
config: { tokenScope: "sessions:run" },
|
|
10527
11768
|
schema: {
|
|
10528
11769
|
params: WorkflowNameParamsSchema,
|
|
10529
11770
|
body: TriggerRunSchema,
|
|
@@ -10562,6 +11803,7 @@ function registerWorkflowRoutes(app, ctx) {
|
|
|
10562
11803
|
typed.route({
|
|
10563
11804
|
method: "POST",
|
|
10564
11805
|
url: "/projects/:projectId/workflows/:name/calls",
|
|
11806
|
+
config: { tokenScope: "sessions:run" },
|
|
10565
11807
|
schema: {
|
|
10566
11808
|
params: WorkflowNameParamsSchema,
|
|
10567
11809
|
body: CallRunSchema,
|
|
@@ -10635,6 +11877,7 @@ function registerWorkflowRoutes(app, ctx) {
|
|
|
10635
11877
|
typed.route({
|
|
10636
11878
|
method: "POST",
|
|
10637
11879
|
url: "/projects/:projectId/workflows/:name/signals",
|
|
11880
|
+
config: { tokenScope: "sessions:run" },
|
|
10638
11881
|
schema: {
|
|
10639
11882
|
params: WorkflowNameParamsSchema,
|
|
10640
11883
|
body: SignalRunSchema,
|
|
@@ -10682,12 +11925,13 @@ function registerWorkflowRoutes(app, ctx) {
|
|
|
10682
11925
|
typed.route({
|
|
10683
11926
|
method: "POST",
|
|
10684
11927
|
url: "/projects/:projectId/workflows/:name/cancellations",
|
|
11928
|
+
config: { tokenScope: "sessions:run" },
|
|
10685
11929
|
schema: {
|
|
10686
11930
|
params: WorkflowNameParamsSchema,
|
|
10687
11931
|
body: CancelRunByKeySchema,
|
|
10688
11932
|
response: {
|
|
10689
11933
|
200: RunSchema,
|
|
10690
|
-
204:
|
|
11934
|
+
204: z28.null(),
|
|
10691
11935
|
404: ErrorSchema,
|
|
10692
11936
|
503: ErrorSchema
|
|
10693
11937
|
}
|
|
@@ -10721,6 +11965,14 @@ var DEFAULT_HOST_FEATURES = {
|
|
|
10721
11965
|
mcp: true,
|
|
10722
11966
|
storeUploadMaxBytes: 64 * 1024 * 1024
|
|
10723
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
|
+
}
|
|
10724
11976
|
var catamorphicPlugin = async (app, opts) => {
|
|
10725
11977
|
app.setValidatorCompiler(validatorCompiler);
|
|
10726
11978
|
app.setSerializerCompiler(serializerCompiler);
|
|
@@ -10731,6 +11983,8 @@ var catamorphicPlugin = async (app, opts) => {
|
|
|
10731
11983
|
if (err instanceof SessionArtifactNotFoundError2 || err instanceof SessionArtifactConflictError || err instanceof SessionArtifactValidationError) {
|
|
10732
11984
|
return reply.status(err.statusCode).send({ error: err.message });
|
|
10733
11985
|
}
|
|
11986
|
+
if (err instanceof TokenScopeRequiredError2)
|
|
11987
|
+
return insufficientScope(reply, err.scope, opts.mcp);
|
|
10734
11988
|
if (err instanceof AccessDeniedError10) {
|
|
10735
11989
|
return reply.status(403).send({ error: err.message });
|
|
10736
11990
|
}
|
|
@@ -10773,12 +12027,18 @@ var catamorphicPlugin = async (app, opts) => {
|
|
|
10773
12027
|
return;
|
|
10774
12028
|
return reply.status(401).send({ error: "Unauthorized" });
|
|
10775
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);
|
|
10776
12035
|
const runnerId = request.headers["x-catamorphic-runner"];
|
|
10777
12036
|
attachIdentity(request, typeof runnerId === "string" && /^[0-9a-f-]{36}$/i.test(runnerId) ? { ...identity, clientRunnerId: runnerId } : identity);
|
|
10778
12037
|
});
|
|
10779
12038
|
const ctx = {
|
|
10780
12039
|
core: opts.core,
|
|
10781
12040
|
...opts.projectMcp ? { projectMcp: opts.projectMcp } : {},
|
|
12041
|
+
...opts.mcp ? { mcp: opts.mcp } : {},
|
|
10782
12042
|
...opts.publicApiBase ? { publicApiBase: opts.publicApiBase.replace(/\/$/, "") } : {},
|
|
10783
12043
|
features: {
|
|
10784
12044
|
...DEFAULT_HOST_FEATURES,
|
|
@@ -10814,6 +12074,7 @@ var catamorphicPlugin = async (app, opts) => {
|
|
|
10814
12074
|
registerPrivateCustomizationRoutes(app, ctx);
|
|
10815
12075
|
registerAppsMcpRoutes(app, ctx);
|
|
10816
12076
|
registerProjectMcpRoutes(app, ctx);
|
|
12077
|
+
registerServerMcpRoutes(app, ctx);
|
|
10817
12078
|
registerAgentCapabilityRoutes(app, ctx);
|
|
10818
12079
|
registerCodeHostRoutes(app, ctx);
|
|
10819
12080
|
registerPluginRoutes(app, ctx);
|
|
@@ -10874,6 +12135,7 @@ function createApp(config) {
|
|
|
10874
12135
|
identity: config.identity,
|
|
10875
12136
|
...config.features ? { features: config.features } : {},
|
|
10876
12137
|
...config.projectMcp ? { projectMcp: config.projectMcp } : {},
|
|
12138
|
+
...config.mcp ? { mcp: config.mcp } : {},
|
|
10877
12139
|
...config.publicApiBase ? { publicApiBase: config.publicApiBase } : {},
|
|
10878
12140
|
prefix: "/api"
|
|
10879
12141
|
});
|
|
@@ -10883,7 +12145,7 @@ function createApp(config) {
|
|
|
10883
12145
|
import {
|
|
10884
12146
|
defineAgentCapability
|
|
10885
12147
|
} from "@catamorphic/core";
|
|
10886
|
-
import { z as
|
|
12148
|
+
import { z as z29 } from "zod";
|
|
10887
12149
|
var PUBLISHING_TOOLS = new Set([
|
|
10888
12150
|
"program_deploy",
|
|
10889
12151
|
"publish_document",
|
|
@@ -10894,11 +12156,11 @@ var OWN_CHAT_TOOLS = new Set([
|
|
|
10894
12156
|
"set_app_presentation",
|
|
10895
12157
|
"set_session_metadata"
|
|
10896
12158
|
]);
|
|
10897
|
-
var Definition =
|
|
10898
|
-
name:
|
|
10899
|
-
description:
|
|
10900
|
-
inputSchema:
|
|
10901
|
-
annotations:
|
|
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()
|
|
10902
12164
|
});
|
|
10903
12165
|
async function projectToolCapabilities(args) {
|
|
10904
12166
|
const { core, context } = args;
|
|
@@ -10933,8 +12195,8 @@ async function projectToolCapabilities(args) {
|
|
|
10933
12195
|
description: definition.description,
|
|
10934
12196
|
effect,
|
|
10935
12197
|
...PUBLISHING_TOOLS.has(definition.name) ? { sandboxing: "publish" } : OWN_CHAT_TOOLS.has(definition.name) ? { sandboxing: "contained" } : {},
|
|
10936
|
-
inputSchema:
|
|
10937
|
-
outputSchema:
|
|
12198
|
+
inputSchema: z29.fromJSONSchema(definition.inputSchema),
|
|
12199
|
+
outputSchema: z29.unknown(),
|
|
10938
12200
|
authorize: () => true,
|
|
10939
12201
|
beforeInvoke: (invocation, input) => args.beforeCall?.({
|
|
10940
12202
|
name: definition.name,
|
|
@@ -10944,22 +12206,22 @@ async function projectToolCapabilities(args) {
|
|
|
10944
12206
|
}) ?? Promise.resolve(),
|
|
10945
12207
|
execute: async (invocation, input) => {
|
|
10946
12208
|
invocation.signal?.throwIfAborted();
|
|
10947
|
-
const values =
|
|
12209
|
+
const values = z29.record(z29.string(), z29.unknown()).parse(input);
|
|
10948
12210
|
const owned = !taken.has(definition.name) && [
|
|
10949
12211
|
"session_artifact",
|
|
10950
12212
|
"create_watcher",
|
|
10951
12213
|
"list_watchers",
|
|
10952
|
-
"
|
|
12214
|
+
"session_stop_watcher"
|
|
10953
12215
|
].includes(definition.name);
|
|
10954
12216
|
const result = await tool.call(owned ? { ...values, sessionId: context.sessionId } : values);
|
|
10955
12217
|
if (result.isError) {
|
|
10956
|
-
const content =
|
|
12218
|
+
const content = z29.array(z29.object({ text: z29.string() })).parse(result.content);
|
|
10957
12219
|
throw new Error(content.map((part) => part.text).join(`
|
|
10958
12220
|
`));
|
|
10959
12221
|
}
|
|
10960
12222
|
if (result.structuredContent !== undefined)
|
|
10961
12223
|
return JSON.parse(JSON.stringify(result.structuredContent));
|
|
10962
|
-
const content =
|
|
12224
|
+
const content = z29.array(z29.object({ text: z29.string() })).parse(result.content);
|
|
10963
12225
|
const text = content.map((part) => part.text).join(`
|
|
10964
12226
|
`);
|
|
10965
12227
|
try {
|
|
@@ -11136,5 +12398,5 @@ export {
|
|
|
11136
12398
|
serveSpaDist
|
|
11137
12399
|
};
|
|
11138
12400
|
|
|
11139
|
-
//# debugId=
|
|
12401
|
+
//# debugId=4D3EA05EB4E27D3164756E2164756E21
|
|
11140
12402
|
//# sourceMappingURL=index.js.map
|