@catamorphic/fastify-plugin 0.0.0-stage → 0.1.0-alpha.30

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (160) hide show
  1. package/LICENSE.txt +202 -0
  2. package/NOTICE.txt +32 -0
  3. package/README.md +143 -2
  4. package/dist/app-presentation-tools.d.ts +4 -0
  5. package/dist/app-presentation-tools.d.ts.map +1 -0
  6. package/dist/app.d.ts +27 -0
  7. package/dist/app.d.ts.map +1 -0
  8. package/dist/chunk-baagvvm3.js +164 -0
  9. package/dist/chunk-baagvvm3.js.map +10 -0
  10. package/dist/http-identity.d.ts +52 -0
  11. package/dist/http-identity.d.ts.map +1 -0
  12. package/dist/hung-up.d.ts +7 -0
  13. package/dist/hung-up.d.ts.map +1 -0
  14. package/dist/index.d.ts +11 -0
  15. package/dist/index.d.ts.map +1 -0
  16. package/dist/index.js +10884 -0
  17. package/dist/index.js.map +56 -0
  18. package/dist/mcp-shared.d.ts +117 -0
  19. package/dist/mcp-shared.d.ts.map +1 -0
  20. package/dist/mcp.d.ts +6 -0
  21. package/dist/mcp.d.ts.map +1 -0
  22. package/dist/mcp.js +13 -0
  23. package/dist/mcp.js.map +9 -0
  24. package/dist/plugin.d.ts +113 -0
  25. package/dist/plugin.d.ts.map +1 -0
  26. package/dist/project-capabilities.d.ts +25 -0
  27. package/dist/project-capabilities.d.ts.map +1 -0
  28. package/dist/project-mcp-program.d.ts +15 -0
  29. package/dist/project-mcp-program.d.ts.map +1 -0
  30. package/dist/project-mcp-surface.d.ts +16 -0
  31. package/dist/project-mcp-surface.d.ts.map +1 -0
  32. package/dist/request-logging.d.ts +18 -0
  33. package/dist/request-logging.d.ts.map +1 -0
  34. package/dist/routes/agent-capabilities.d.ts +4 -0
  35. package/dist/routes/agent-capabilities.d.ts.map +1 -0
  36. package/dist/routes/agent.d.ts +4 -0
  37. package/dist/routes/agent.d.ts.map +1 -0
  38. package/dist/routes/apps-mcp.d.ts +4 -0
  39. package/dist/routes/apps-mcp.d.ts.map +1 -0
  40. package/dist/routes/apps.d.ts +12 -0
  41. package/dist/routes/apps.d.ts.map +1 -0
  42. package/dist/routes/client-runners.d.ts +11 -0
  43. package/dist/routes/client-runners.d.ts.map +1 -0
  44. package/dist/routes/code-hosts.d.ts +11 -0
  45. package/dist/routes/code-hosts.d.ts.map +1 -0
  46. package/dist/routes/connection-mcp.d.ts +10 -0
  47. package/dist/routes/connection-mcp.d.ts.map +1 -0
  48. package/dist/routes/connections.d.ts +4 -0
  49. package/dist/routes/connections.d.ts.map +1 -0
  50. package/dist/routes/documents.d.ts +11 -0
  51. package/dist/routes/documents.d.ts.map +1 -0
  52. package/dist/routes/environments.d.ts +4 -0
  53. package/dist/routes/environments.d.ts.map +1 -0
  54. package/dist/routes/git-gateway.d.ts +21 -0
  55. package/dist/routes/git-gateway.d.ts.map +1 -0
  56. package/dist/routes/http-gateway.d.ts +13 -0
  57. package/dist/routes/http-gateway.d.ts.map +1 -0
  58. package/dist/routes/me.d.ts +12 -0
  59. package/dist/routes/me.d.ts.map +1 -0
  60. package/dist/routes/memberships.d.ts +12 -0
  61. package/dist/routes/memberships.d.ts.map +1 -0
  62. package/dist/routes/model-gateway.d.ts +12 -0
  63. package/dist/routes/model-gateway.d.ts.map +1 -0
  64. package/dist/routes/notifications.d.ts +4 -0
  65. package/dist/routes/notifications.d.ts.map +1 -0
  66. package/dist/routes/parse.d.ts +5 -0
  67. package/dist/routes/parse.d.ts.map +1 -0
  68. package/dist/routes/personal-environment.d.ts +13 -0
  69. package/dist/routes/personal-environment.d.ts.map +1 -0
  70. package/dist/routes/plugins.d.ts +4 -0
  71. package/dist/routes/plugins.d.ts.map +1 -0
  72. package/dist/routes/project-mcp.d.ts +25 -0
  73. package/dist/routes/project-mcp.d.ts.map +1 -0
  74. package/dist/routes/projects.d.ts +4 -0
  75. package/dist/routes/projects.d.ts.map +1 -0
  76. package/dist/routes/publications.d.ts +15 -0
  77. package/dist/routes/publications.d.ts.map +1 -0
  78. package/dist/routes/run-errors.d.ts +8 -0
  79. package/dist/routes/run-errors.d.ts.map +1 -0
  80. package/dist/routes/runs.d.ts +4 -0
  81. package/dist/routes/runs.d.ts.map +1 -0
  82. package/dist/routes/session-artifacts.d.ts +27 -0
  83. package/dist/routes/session-artifacts.d.ts.map +1 -0
  84. package/dist/routes/session-mailboxes.d.ts +4 -0
  85. package/dist/routes/session-mailboxes.d.ts.map +1 -0
  86. package/dist/routes/session-previews.d.ts +40 -0
  87. package/dist/routes/session-previews.d.ts.map +1 -0
  88. package/dist/routes/session-terminals.d.ts +15 -0
  89. package/dist/routes/session-terminals.d.ts.map +1 -0
  90. package/dist/routes/triggers.d.ts +20 -0
  91. package/dist/routes/triggers.d.ts.map +1 -0
  92. package/dist/routes/watchers.d.ts +4 -0
  93. package/dist/routes/watchers.d.ts.map +1 -0
  94. package/dist/routes/webhooks.d.ts +11 -0
  95. package/dist/routes/webhooks.d.ts.map +1 -0
  96. package/dist/routes/workflow-enablements.d.ts +4 -0
  97. package/dist/routes/workflow-enablements.d.ts.map +1 -0
  98. package/dist/routes/workflows.d.ts +4 -0
  99. package/dist/routes/workflows.d.ts.map +1 -0
  100. package/dist/schemas.d.ts +17776 -0
  101. package/dist/schemas.d.ts.map +1 -0
  102. package/dist/session-artifact-tools.d.ts +5 -0
  103. package/dist/session-artifact-tools.d.ts.map +1 -0
  104. package/dist/session-event-stream.d.ts +45 -0
  105. package/dist/session-event-stream.d.ts.map +1 -0
  106. package/dist/spa.d.ts +24 -0
  107. package/dist/spa.d.ts.map +1 -0
  108. package/dist/telemetry.d.ts +4 -0
  109. package/dist/telemetry.d.ts.map +1 -0
  110. package/package.json +73 -4
  111. package/src/app-presentation-tools.ts +46 -0
  112. package/src/app.ts +115 -0
  113. package/src/http-identity.ts +145 -0
  114. package/src/hung-up.ts +13 -0
  115. package/src/index.ts +25 -0
  116. package/src/mcp-shared.ts +331 -0
  117. package/src/mcp.ts +10 -0
  118. package/src/plugin.ts +332 -0
  119. package/src/project-capabilities.ts +153 -0
  120. package/src/project-mcp-program.ts +607 -0
  121. package/src/project-mcp-surface.ts +881 -0
  122. package/src/request-logging.ts +47 -0
  123. package/src/routes/agent-capabilities.ts +109 -0
  124. package/src/routes/agent.ts +1566 -0
  125. package/src/routes/apps-mcp.ts +303 -0
  126. package/src/routes/apps.ts +692 -0
  127. package/src/routes/client-runners.ts +251 -0
  128. package/src/routes/code-hosts.ts +247 -0
  129. package/src/routes/connection-mcp.ts +135 -0
  130. package/src/routes/connections.ts +494 -0
  131. package/src/routes/documents.ts +538 -0
  132. package/src/routes/environments.ts +72 -0
  133. package/src/routes/git-gateway.ts +106 -0
  134. package/src/routes/http-gateway.ts +141 -0
  135. package/src/routes/me.ts +122 -0
  136. package/src/routes/memberships.ts +173 -0
  137. package/src/routes/model-gateway.ts +134 -0
  138. package/src/routes/notifications.ts +101 -0
  139. package/src/routes/parse.ts +32 -0
  140. package/src/routes/personal-environment.ts +146 -0
  141. package/src/routes/plugins.ts +341 -0
  142. package/src/routes/project-mcp.ts +394 -0
  143. package/src/routes/projects.ts +708 -0
  144. package/src/routes/publications.ts +222 -0
  145. package/src/routes/run-errors.ts +86 -0
  146. package/src/routes/runs.ts +253 -0
  147. package/src/routes/session-artifacts.ts +293 -0
  148. package/src/routes/session-mailboxes.ts +80 -0
  149. package/src/routes/session-previews.ts +224 -0
  150. package/src/routes/session-terminals.ts +209 -0
  151. package/src/routes/triggers.ts +241 -0
  152. package/src/routes/watchers.ts +94 -0
  153. package/src/routes/webhooks.ts +171 -0
  154. package/src/routes/workflow-enablements.ts +331 -0
  155. package/src/routes/workflows.ts +323 -0
  156. package/src/schemas.ts +2735 -0
  157. package/src/session-artifact-tools.ts +170 -0
  158. package/src/session-event-stream.ts +122 -0
  159. package/src/spa.ts +135 -0
  160. package/src/telemetry.ts +93 -0
@@ -0,0 +1,607 @@
1
+ import type {
2
+ CallRunInput,
3
+ CatamorphicCore,
4
+ Identity,
5
+ } from "@catamorphic/core";
6
+ import {
7
+ AccessDeniedError,
8
+ assertMayManageRolePolicy,
9
+ assertProjectPermission,
10
+ DeploymentBlockedError,
11
+ effectiveProjectPermissions,
12
+ hasProjectPermission,
13
+ mayUseProject,
14
+ } from "@catamorphic/core";
15
+ import { checkProject } from "@catamorphic/parser";
16
+ import {
17
+ isProjectPathWithin,
18
+ PROJECT_APPS_DIR,
19
+ PROJECT_CONTRACTS_DIR,
20
+ PROJECT_WORKFLOWS_DIR,
21
+ } from "@catamorphic/workflow/project-layout";
22
+ import { toolError, toolValue } from "./mcp-shared.js";
23
+ import type { SurfaceTool } from "./project-mcp-surface.js";
24
+
25
+ /**
26
+ * The member's working loop on the project MCP (ADR 0166): orient, draft a
27
+ * program change, check it, publish it, run it, and read what happened.
28
+ * Everything a member can do over REST, as tools a member's own agent
29
+ * (Claude Code or any MCP client) uses with the member's identity. Each
30
+ * call goes through the core service that already enforces the member's
31
+ * permissions; nothing is checked by hand beyond choosing what to list.
32
+ *
33
+ * The draft is the member's own, private draft of the program: on a server
34
+ * a ref in the project's origin (ADR 0191), so every replica sees every
35
+ * write. `program_write` changes it, `program_check` validates it, and
36
+ * `program_deploy` publishes it as one new production commit. The
37
+ * documents tools keep reading what is live.
38
+ */
39
+
40
+ const READ_ONLY = { readOnlyHint: true } as const;
41
+ const TOOL_SYNC_BUDGET_MS = 30_000;
42
+
43
+ export function programTools(
44
+ core: CatamorphicCore,
45
+ identity: Identity,
46
+ projectId: string,
47
+ ): SurfaceTool[] {
48
+ if (!mayUseProject(identity, projectId)) return [];
49
+ const tools: SurfaceTool[] = [overviewTool(core, identity, projectId)];
50
+ const may = (permission: string) =>
51
+ hasProjectPermission(identity, projectId, permission);
52
+
53
+ if (may("program:write")) {
54
+ tools.push(
55
+ {
56
+ definition: {
57
+ name: "program_files",
58
+ description:
59
+ "Your draft of the project's program (workflows, apps, agents, roles and skills under .work/, plus any other files). Without a path, lists files and your unpublished changes; with a path, returns that file from your draft.",
60
+ inputSchema: {
61
+ type: "object",
62
+ properties: {
63
+ path: { type: "string", description: "File to read" },
64
+ },
65
+ },
66
+ },
67
+ call: guarded(async (args) => {
68
+ const status = await refreshDraft(core, identity, projectId);
69
+ const path = str(args.path);
70
+ if (path)
71
+ return {
72
+ path,
73
+ content: await core.projects.readFile(identity, projectId, path),
74
+ };
75
+ const files = await core.projects.listFiles(identity, projectId);
76
+ return {
77
+ files: files.map((file) => file.path).sort(),
78
+ ...draftSummary(status),
79
+ };
80
+ }),
81
+ },
82
+ {
83
+ definition: {
84
+ name: "program_write",
85
+ description:
86
+ "Change files in your draft of the program. Nothing reaches members until program_deploy (or propose_change). Role files under .work/roles need roles:write.",
87
+ inputSchema: {
88
+ type: "object",
89
+ properties: {
90
+ changes: {
91
+ type: "array",
92
+ items: {
93
+ type: "object",
94
+ properties: {
95
+ path: { type: "string" },
96
+ content: { type: "string" },
97
+ delete: { type: "boolean" },
98
+ },
99
+ required: ["path"],
100
+ },
101
+ },
102
+ },
103
+ required: ["changes"],
104
+ },
105
+ },
106
+ call: guarded(async (args) => {
107
+ const changes = Array.isArray(args.changes) ? args.changes : [];
108
+ if (changes.length === 0) throw new Error("changes is required");
109
+ await refreshDraft(core, identity, projectId);
110
+ const draftChanges = changes.map((raw) => {
111
+ const change = asRecord(raw);
112
+ const path = str(change.path);
113
+ if (!path) throw new Error("Each change needs a path");
114
+ if (change.delete === true) return { path, delete: true as const };
115
+ const content = str(change.content);
116
+ if (content === undefined)
117
+ throw new Error(`${path}: pass content or delete: true`);
118
+ return { path, content };
119
+ });
120
+ // One draft commit: every change lands, or none does.
121
+ await core.projects.writeFiles({
122
+ identity,
123
+ projectId,
124
+ changes: draftChanges,
125
+ });
126
+ return { written: draftChanges.map((change) => change.path) };
127
+ }),
128
+ },
129
+ {
130
+ definition: {
131
+ name: "program_check",
132
+ description:
133
+ "Refresh your draft's generated types (the trigger kinds this server offers, in .work/workflows/src/work-triggers.d.ts, and each app's workflow API types), then validate it the way publishing does: workflow and app parse errors and trigger configurations. Run it after writing and before program_deploy.",
134
+ inputSchema: { type: "object", properties: {} },
135
+ },
136
+ call: guarded(async () => checkDraft(core, identity, projectId)),
137
+ },
138
+ );
139
+ }
140
+
141
+ // Deploying publishes the caller's own draft: it takes both.
142
+ if (may("program:write") && may("program:publish")) {
143
+ tools.push({
144
+ definition: {
145
+ name: "program_deploy",
146
+ description:
147
+ "Publish your draft as the project's production program: workflows move to it, and every app it changes (or that was never published) is built and published, with each app's result reported. Refused while program_check reports errors, and for projects whose program lives in a linked repository (use propose_change there).",
148
+ inputSchema: {
149
+ type: "object",
150
+ properties: {
151
+ message: {
152
+ type: "string",
153
+ description: "What changed and why, as a commit message",
154
+ },
155
+ },
156
+ required: ["message"],
157
+ },
158
+ },
159
+ call: guarded(async (args) => {
160
+ const message = str(args.message);
161
+ if (!message) throw new Error("message is required");
162
+ const project = await core.projects.get(identity, projectId);
163
+ if (project.remoteUrl)
164
+ throw new Error(
165
+ `This project's program is published from ${project.remoteUrl}. Open a pull request there, or use propose_change.`,
166
+ );
167
+ const check = await checkDraft(core, identity, projectId);
168
+ if (!check.ok) return { status: "blocked", ...check };
169
+ const before = await core.deployment.getStatus(
170
+ identity.tenantId,
171
+ projectId,
172
+ identity.externalUserId,
173
+ );
174
+ const result = await core.deployment.deploy(
175
+ identity.tenantId,
176
+ projectId,
177
+ identity.externalUserId,
178
+ {
179
+ message,
180
+ guardPublishedPaths: (paths) =>
181
+ assertMayManageRolePolicy(identity, projectId, paths),
182
+ },
183
+ );
184
+ // Nothing new to publish still publishes apps that never were.
185
+ const published =
186
+ result.status === "deployed"
187
+ ? result.commitSha
188
+ : result.status === "nothing-to-deploy"
189
+ ? before.remoteHead
190
+ : null;
191
+ const apps = published
192
+ ? await publishApps({
193
+ core,
194
+ identity,
195
+ projectId,
196
+ base:
197
+ result.status === "deployed" ? before.remoteHead : published,
198
+ head: published,
199
+ })
200
+ : [];
201
+ return { ...result, apps, warnings: check.findings };
202
+ }),
203
+ });
204
+ }
205
+
206
+ tools.push(
207
+ {
208
+ definition: {
209
+ name: "workflow_run",
210
+ description:
211
+ "Run a deployed workflow with an input. Waits up to 30 seconds: a finished run returns its output, a longer one returns its runId for run_details. Pass environment to choose where it runs (names in project_overview).",
212
+ inputSchema: {
213
+ type: "object",
214
+ properties: {
215
+ workflow: { type: "string" },
216
+ input: {
217
+ description:
218
+ "The workflow's input, as JSON of the workflow's input type",
219
+ type: ["object", "array", "string", "number", "boolean", "null"],
220
+ },
221
+ environment: { type: "string" },
222
+ },
223
+ required: ["workflow"],
224
+ },
225
+ },
226
+ call: guarded(async (args) => {
227
+ const workflowName = str(args.workflow);
228
+ if (!workflowName) throw new Error("workflow is required");
229
+ const environment = str(args.environment);
230
+ return core.runs.call({
231
+ identity,
232
+ projectId,
233
+ workflowName,
234
+ ...(environment ? { environment } : {}),
235
+ ...(args.input === undefined
236
+ ? {}
237
+ : { input: args.input as CallRunInput["input"] }),
238
+ budgetMs: TOOL_SYNC_BUDGET_MS,
239
+ });
240
+ }),
241
+ },
242
+ {
243
+ definition: {
244
+ name: "workflow_runs",
245
+ description:
246
+ "Recent runs of the project's workflows, newest first, with status and errors. Filter by workflow.",
247
+ inputSchema: {
248
+ type: "object",
249
+ properties: {
250
+ workflow: { type: "string" },
251
+ limit: { type: "integer", minimum: 1, maximum: 100 },
252
+ },
253
+ },
254
+ annotations: READ_ONLY,
255
+ },
256
+ call: guarded(async (args) => {
257
+ const workflowName = str(args.workflow);
258
+ return core.runs.list({
259
+ identity,
260
+ projectId,
261
+ ...(workflowName ? { workflowName } : {}),
262
+ limit: typeof args.limit === "number" ? args.limit : 20,
263
+ });
264
+ }),
265
+ },
266
+ {
267
+ definition: {
268
+ name: "run_details",
269
+ description:
270
+ "One run in full: status, input, output, error, and each step with its result, for debugging a workflow.",
271
+ inputSchema: {
272
+ type: "object",
273
+ properties: { runId: { type: "string" } },
274
+ required: ["runId"],
275
+ },
276
+ annotations: READ_ONLY,
277
+ },
278
+ call: guarded(async (args) => {
279
+ const runId = str(args.runId);
280
+ if (!runId) throw new Error("runId is required");
281
+ const run = await core.runs.get({ identity, runId });
282
+ if (run.projectId !== projectId) throw new Error("Run not found");
283
+ return run;
284
+ }),
285
+ },
286
+ );
287
+ return tools;
288
+ }
289
+
290
+ function overviewTool(
291
+ core: CatamorphicCore,
292
+ identity: Identity,
293
+ projectId: string,
294
+ ): SurfaceTool {
295
+ return {
296
+ definition: {
297
+ name: "project_overview",
298
+ description:
299
+ "Start here: the project, your roles and permissions, the agents you can ask, the Environments you can run in, its workflows and apps, and your unpublished draft.",
300
+ inputSchema: { type: "object", properties: {} },
301
+ },
302
+ call: guarded(async () => {
303
+ const optional = <T>(load: () => Promise<T>) =>
304
+ load().catch((error: unknown) => {
305
+ if (error instanceof AccessDeniedError) return undefined;
306
+ throw error;
307
+ });
308
+ const may = (permission: string) =>
309
+ hasProjectPermission(identity, projectId, permission);
310
+ const [project, roles, agents, environments, workflows, apps, draft] =
311
+ await Promise.all([
312
+ optional(() => core.projects.getOverview({ identity, projectId })),
313
+ optional(async () =>
314
+ core.memberships?.describeMember({
315
+ projectId,
316
+ tenantId: identity.tenantId,
317
+ externalUserId: identity.externalUserId,
318
+ }),
319
+ ),
320
+ optional(() => core.agentDefinitions.list(identity, projectId)),
321
+ optional(() => environmentsFor(core, identity, projectId)),
322
+ optional(() => core.workflows.list({ identity, projectId })),
323
+ may("program:read")
324
+ ? optional(async () => core.apps?.list({ identity, projectId }))
325
+ : undefined,
326
+ may("program:write")
327
+ ? optional(() => refreshDraft(core, identity, projectId))
328
+ : undefined,
329
+ ]);
330
+ return {
331
+ project: project
332
+ ? {
333
+ id: project.id,
334
+ name: project.name,
335
+ publishedFrom: project.remoteUrl ?? "this server",
336
+ // Accepted changes stop arriving while main has diverged
337
+ // from the code host's (ADR 0170).
338
+ ...(project.remoteDivergedAt
339
+ ? { divergedFromPublishedSince: project.remoteDivergedAt }
340
+ : {}),
341
+ }
342
+ : { id: projectId },
343
+ you: {
344
+ userId: identity.externalUserId,
345
+ roles: roles ?? [],
346
+ permissions: effectiveProjectPermissions(identity, projectId),
347
+ },
348
+ agents,
349
+ environments,
350
+ workflows,
351
+ apps,
352
+ draft: draft ? draftSummary(draft) : undefined,
353
+ };
354
+ }),
355
+ };
356
+ }
357
+
358
+ /**
359
+ * The caller's draft, first brought up to the published program when it has
360
+ * no unpublished edits, so a member never works from a stale draft. A draft
361
+ * with edits keeps them; publishing merges.
362
+ */
363
+ async function refreshDraft(
364
+ core: CatamorphicCore,
365
+ identity: Identity,
366
+ projectId: string,
367
+ ) {
368
+ const args = [identity.tenantId, projectId, identity.externalUserId] as const;
369
+ const status = await core.deployment.getStatus(...args);
370
+ if (status.dirty || status.behind === 0) return status;
371
+ // A local folder syncs through its own Git remote instead.
372
+ const pulled = await core.deployment
373
+ .pullFromRemote(...args)
374
+ .catch((error: unknown) => {
375
+ if (error instanceof DeploymentBlockedError) return null;
376
+ throw error;
377
+ });
378
+ return pulled ? core.deployment.getStatus(...args) : status;
379
+ }
380
+
381
+ function draftSummary(status: {
382
+ modifiedFiles: string[];
383
+ ahead: number;
384
+ behind: number;
385
+ }) {
386
+ return {
387
+ changed: status.modifiedFiles,
388
+ unpublishedCommits: status.ahead,
389
+ ...(status.behind > 0
390
+ ? {
391
+ behindPublished: status.behind,
392
+ note: "Others published since your draft began; program_deploy merges their changes with yours.",
393
+ }
394
+ : {}),
395
+ };
396
+ }
397
+
398
+ /** Each Environment once, with what it can run for this caller. */
399
+ async function environmentsFor(
400
+ core: CatamorphicCore,
401
+ identity: Identity,
402
+ projectId: string,
403
+ ) {
404
+ const service = core.executionEnvironments;
405
+ if (!service) return undefined;
406
+ const [agents, workflows] = await Promise.all(
407
+ (["agent", "workflow"] as const).map((workload) =>
408
+ service.discover({ identity, projectId, requirements: { workload } }),
409
+ ),
410
+ );
411
+ const workflowsByName = new Map(
412
+ (workflows?.items ?? []).map((item) => [item.name, item]),
413
+ );
414
+ const usable = (item?: {
415
+ allowed: boolean;
416
+ available: boolean;
417
+ compatible: boolean;
418
+ }) => Boolean(item?.allowed && item.available && item.compatible);
419
+ return {
420
+ items: (agents?.items ?? []).map((item) => ({
421
+ name: item.name,
422
+ description: item.description,
423
+ agents: usable(item),
424
+ workflows: usable(workflowsByName.get(item.name)),
425
+ ...(usable(item) || usable(workflowsByName.get(item.name))
426
+ ? {}
427
+ : { reasons: item.reasons }),
428
+ })),
429
+ defaultForAgents: agents?.defaultEnvironment,
430
+ defaultForWorkflows: workflows?.defaultEnvironment,
431
+ };
432
+ }
433
+
434
+ /**
435
+ * Publishing the program publishes its apps: each app whose source or
436
+ * workflow contract changed in this deploy, or that has no published
437
+ * version yet, is built at the new commit and published. A failed build
438
+ * keeps the app's previous version and reports why.
439
+ */
440
+ async function publishApps(args: {
441
+ core: CatamorphicCore;
442
+ identity: Identity;
443
+ projectId: string;
444
+ base: string | null;
445
+ head: string;
446
+ }) {
447
+ const { core, identity, projectId } = args;
448
+ const apps = core.apps;
449
+ if (!apps) return [];
450
+ const summaries = await apps.list({ identity, projectId });
451
+ if (summaries.length === 0) return [];
452
+ const changed = args.base
453
+ ? (
454
+ await core.deployment.diffRefs(
455
+ identity.tenantId,
456
+ projectId,
457
+ identity.externalUserId,
458
+ args.base,
459
+ args.head,
460
+ )
461
+ ).map((entry) => entry.path)
462
+ : undefined;
463
+ const contractChanged = changed?.some(
464
+ (path) =>
465
+ isProjectPathWithin(path, PROJECT_CONTRACTS_DIR) ||
466
+ isProjectPathWithin(path, PROJECT_WORKFLOWS_DIR),
467
+ );
468
+ const results: Array<{
469
+ app: string;
470
+ status: "published" | "failed";
471
+ error?: string;
472
+ }> = [];
473
+ for (const summary of summaries) {
474
+ const touched =
475
+ !changed ||
476
+ contractChanged ||
477
+ changed.some((path) =>
478
+ isProjectPathWithin(path, `${PROJECT_APPS_DIR}/${summary.name}`),
479
+ );
480
+ if (summary.activeVersionId && !touched) continue;
481
+ try {
482
+ const version = await apps.build({
483
+ identity,
484
+ projectId,
485
+ appName: summary.name,
486
+ kind: "published",
487
+ commitSha: args.head,
488
+ });
489
+ if (version.status !== "ready") {
490
+ results.push({
491
+ app: summary.name,
492
+ status: "failed",
493
+ error: version.error ?? "Build failed",
494
+ });
495
+ continue;
496
+ }
497
+ await apps.publish({ identity, projectId, versionId: version.id });
498
+ results.push({ app: summary.name, status: "published" });
499
+ } catch (error) {
500
+ results.push({
501
+ app: summary.name,
502
+ status: "failed",
503
+ error: error instanceof Error ? error.message : String(error),
504
+ });
505
+ }
506
+ }
507
+ return results;
508
+ }
509
+
510
+ async function checkDraft(
511
+ core: CatamorphicCore,
512
+ identity: Identity,
513
+ projectId: string,
514
+ ) {
515
+ assertProjectPermission(identity, projectId, "program:write");
516
+ const generated = await core.triggers.syncTypes({ identity, projectId });
517
+ const files = await core.projects.readAllFiles(identity, projectId);
518
+ const result = checkProject(files, {
519
+ triggerKinds: core.triggers.listKinds(),
520
+ });
521
+ return {
522
+ ok: result.ok,
523
+ findings: result.findings,
524
+ ...(generated.updated ? { refreshed: generated.paths } : {}),
525
+ };
526
+ }
527
+
528
+ function guarded(fn: (args: Record<string, unknown>) => Promise<unknown>) {
529
+ return async (args: Record<string, unknown>) => {
530
+ try {
531
+ return toolValue(await fn(args));
532
+ } catch (error) {
533
+ if (error instanceof AccessDeniedError)
534
+ return toolError("Your roles do not allow that.");
535
+ // Filesystem errors name server paths; say what happened instead.
536
+ const code =
537
+ typeof error === "object" && error !== null && "code" in error
538
+ ? error.code
539
+ : undefined;
540
+ if (code === "ENOENT") return toolError("No such file in your draft.");
541
+ if (code === "EISDIR") return toolError("That path is a folder.");
542
+ if (code === "ENOTDIR")
543
+ return toolError("A parent of that path is a file.");
544
+ return toolError(error instanceof Error ? error.message : String(error));
545
+ }
546
+ };
547
+ }
548
+
549
+ function str(value: unknown): string | undefined {
550
+ return typeof value === "string" ? value : undefined;
551
+ }
552
+
553
+ function asRecord(value: unknown): Record<string, unknown> {
554
+ return value !== null && typeof value === "object" && !Array.isArray(value)
555
+ ? (value as Record<string, unknown>)
556
+ : {};
557
+ }
558
+
559
+ /**
560
+ * The orientation a client receives at `initialize`: what this endpoint is
561
+ * and the member's working loop, naming only tools this caller has.
562
+ */
563
+ export async function projectInstructions(args: {
564
+ core: CatamorphicCore;
565
+ identity: Identity;
566
+ projectId: string;
567
+ toolNames: ReadonlySet<string>;
568
+ host?: string;
569
+ }): Promise<string> {
570
+ const { core, identity, projectId, toolNames } = args;
571
+ const has = (name: string) => toolNames.has(name);
572
+ const project = await Promise.resolve()
573
+ .then(() => core.projects.getOverview({ identity, projectId }))
574
+ .catch(() => undefined);
575
+ const lines = [
576
+ `This is the project${project ? ` "${project.name}"` : ""} on a shared server. Everything you do here acts as you, with your own roles; call project_overview first to see them.`,
577
+ ];
578
+ if (has("documents_read"))
579
+ lines.push(
580
+ "- Live material: documents_list, documents_read and documents_search read the published program and store/ documents. documents_write changes store/ documents directly.",
581
+ );
582
+ if (has("program_write"))
583
+ lines.push(
584
+ `- Program changes (workflows, apps, agents under .work/): program_write edits your private draft, program_files reads it, program_check validates it${
585
+ has("program_deploy")
586
+ ? ", program_deploy publishes it."
587
+ : ", and propose_change asks someone who may publish to review it."
588
+ }`,
589
+ );
590
+ else if (has("propose_change"))
591
+ lines.push(
592
+ "- Program changes go through propose_change, which a publisher reviews.",
593
+ );
594
+ if (has("list_skills"))
595
+ lines.push(
596
+ "- Read the project's skills (list_skills, read_skill) before writing workflows or apps: writing-workflows and building-apps hold the contracts.",
597
+ );
598
+ lines.push(
599
+ "- Run deployed workflows with workflow_run and debug them with workflow_runs and run_details.",
600
+ );
601
+ if (has("ask_agent"))
602
+ lines.push(
603
+ "- ask_agent runs one of the project's agents on the server, in an Environment you may use. Server agents reach connected systems, such as a production database, through the reviewed gateway; you never receive those credentials.",
604
+ );
605
+ if (args.host) lines.push(args.host);
606
+ return lines.join("\n");
607
+ }