@catamorphic/work-server 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.
Files changed (114) hide show
  1. package/NOTICE.txt +7 -0
  2. package/README.md +9 -9
  3. package/dist/admission/routes.d.ts +1 -1
  4. package/dist/admission/routes.d.ts.map +1 -1
  5. package/dist/agent-capabilities.d.ts.map +1 -1
  6. package/dist/agents.d.ts +5 -6
  7. package/dist/agents.d.ts.map +1 -1
  8. package/dist/auth/fastify-auth.d.ts.map +1 -1
  9. package/dist/auth/work-auth-types.d.ts +2 -0
  10. package/dist/auth/work-auth-types.d.ts.map +1 -1
  11. package/dist/auth/work-auth.d.ts.map +1 -1
  12. package/dist/chunk-kcck20aw.js +676 -0
  13. package/dist/chunk-kcck20aw.js.map +11 -0
  14. package/dist/cluster.d.ts +8 -7
  15. package/dist/cluster.d.ts.map +1 -1
  16. package/dist/config.d.ts +5 -15
  17. package/dist/config.d.ts.map +1 -1
  18. package/dist/execution-config.d.ts +22 -0
  19. package/dist/execution-config.d.ts.map +1 -1
  20. package/dist/fake-agent.d.ts +1 -0
  21. package/dist/fake-agent.d.ts.map +1 -1
  22. package/dist/index.d.ts +3 -2
  23. package/dist/index.d.ts.map +1 -1
  24. package/dist/index.js +2730 -2851
  25. package/dist/index.js.map +28 -28
  26. package/dist/machines/contract-kit.d.ts +91 -0
  27. package/dist/machines/contract-kit.d.ts.map +1 -0
  28. package/dist/machines/contract.d.ts +383 -0
  29. package/dist/machines/contract.d.ts.map +1 -0
  30. package/dist/machines/sequencer.d.ts +267 -0
  31. package/dist/machines/sequencer.d.ts.map +1 -0
  32. package/dist/machines/simulation.d.ts +124 -0
  33. package/dist/machines/simulation.d.ts.map +1 -0
  34. package/dist/machines/work-machines.d.ts +61 -0
  35. package/dist/machines/work-machines.d.ts.map +1 -0
  36. package/dist/server.d.ts +15 -11
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/setup/machines.d.ts +9 -17
  39. package/dist/setup/machines.d.ts.map +1 -1
  40. package/dist/shares/share-routes.d.ts +1 -1
  41. package/dist/shares/share-routes.d.ts.map +1 -1
  42. package/dist/testing.d.ts +8 -0
  43. package/dist/testing.d.ts.map +1 -0
  44. package/dist/testing.js +1013 -0
  45. package/dist/testing.js.map +11 -0
  46. package/dist/workers/disk-care.d.ts +41 -0
  47. package/dist/workers/disk-care.d.ts.map +1 -0
  48. package/dist/workers/harness-sign-ins.d.ts +146 -0
  49. package/dist/workers/harness-sign-ins.d.ts.map +1 -0
  50. package/dist/workers/machine-store.d.ts +196 -0
  51. package/dist/workers/machine-store.d.ts.map +1 -0
  52. package/dist/workers/member-machine-routes.d.ts +5 -3
  53. package/dist/workers/member-machine-routes.d.ts.map +1 -1
  54. package/dist/workers/member-machines.d.ts +47 -28
  55. package/dist/workers/member-machines.d.ts.map +1 -1
  56. package/dist/workers/placement.d.ts +23 -40
  57. package/dist/workers/placement.d.ts.map +1 -1
  58. package/dist/workers/sign-ins.d.ts +44 -17
  59. package/dist/workers/sign-ins.d.ts.map +1 -1
  60. package/dist/workers/worker-protocol.d.ts +5 -2
  61. package/dist/workers/worker-protocol.d.ts.map +1 -1
  62. package/dist/workers/worker-registry.d.ts +174 -223
  63. package/dist/workers/worker-registry.d.ts.map +1 -1
  64. package/dist/workers/worker-routes.d.ts.map +1 -1
  65. package/dist/workers/worker-runtime.d.ts.map +1 -1
  66. package/package.json +31 -21
  67. package/src/admission/routes.ts +5 -2
  68. package/src/agent-capabilities.ts +22 -8
  69. package/src/agents.ts +52 -23
  70. package/src/auth/fastify-auth.ts +149 -17
  71. package/src/auth/work-auth-types.ts +2 -0
  72. package/src/auth/work-auth.ts +27 -0
  73. package/src/cluster.ts +115 -42
  74. package/src/config.ts +15 -41
  75. package/src/execution-config.ts +40 -0
  76. package/src/fake-agent.ts +21 -4
  77. package/src/index.ts +26 -12
  78. package/src/machines/contract-kit.ts +648 -0
  79. package/src/machines/contract.ts +522 -0
  80. package/src/machines/sequencer.ts +1010 -0
  81. package/src/machines/simulation.ts +833 -0
  82. package/src/machines/work-machines.ts +231 -0
  83. package/src/server.ts +235 -150
  84. package/src/setup/machines.ts +128 -121
  85. package/src/shares/share-routes.ts +17 -1
  86. package/src/testing.ts +22 -0
  87. package/src/workers/disk-care.ts +121 -0
  88. package/src/workers/fake-claude-cli.ts +95 -0
  89. package/src/workers/fake-codex-cli.ts +11 -4
  90. package/src/workers/harness-sign-ins.ts +580 -0
  91. package/src/workers/machine-store.ts +1065 -0
  92. package/src/workers/member-machine-routes.ts +92 -20
  93. package/src/workers/member-machines.ts +163 -99
  94. package/src/workers/placement.ts +59 -70
  95. package/src/workers/sign-ins.ts +109 -52
  96. package/src/workers/worker-protocol.ts +5 -2
  97. package/src/workers/worker-registry.ts +894 -754
  98. package/src/workers/worker-routes.ts +4 -1
  99. package/src/workers/worker-runtime.ts +55 -23
  100. package/dist/test-support.d.ts +0 -133
  101. package/dist/test-support.d.ts.map +0 -1
  102. package/dist/workers/codex-sign-ins.d.ts +0 -107
  103. package/dist/workers/codex-sign-ins.d.ts.map +0 -1
  104. package/dist/workers/install-script.d.ts +0 -71
  105. package/dist/workers/install-script.d.ts.map +0 -1
  106. package/dist/workers/machine-classes.d.ts +0 -115
  107. package/dist/workers/machine-classes.d.ts.map +0 -1
  108. package/dist/workers/machine-rules.d.ts +0 -402
  109. package/dist/workers/machine-rules.d.ts.map +0 -1
  110. package/src/test-support.ts +0 -404
  111. package/src/workers/codex-sign-ins.ts +0 -360
  112. package/src/workers/install-script.ts +0 -394
  113. package/src/workers/machine-classes.ts +0 -152
  114. package/src/workers/machine-rules.ts +0 -1954
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@catamorphic/work-server",
3
- "version": "0.1.0-alpha.39",
3
+ "version": "0.1.0-alpha.41",
4
4
  "type": "module",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -9,17 +9,23 @@
9
9
  "bun": "./src/index.ts",
10
10
  "import": "./dist/index.js",
11
11
  "types": "./dist/index.d.ts"
12
+ },
13
+ "./testing": {
14
+ "bun": "./src/testing.ts",
15
+ "import": "./dist/testing.js",
16
+ "types": "./dist/testing.d.ts"
12
17
  }
13
18
  },
14
19
  "scripts": {
15
20
  "build": "bun ../../scripts/build-package.ts && tsc --project tsconfig.json --noEmit false --emitDeclarationOnly",
16
21
  "dev": "bun ../../scripts/build-package.ts --watch",
17
- "typecheck": "bun check --project ./tsconfig.json",
22
+ "typecheck": "bun check --project ./tsconfig.json && bun check --project ./tsconfig.recipes.json",
18
23
  "test": "bun ../../scripts/tool-runtime.ts vitest --tool-cwd packages/work-server --config ../../vitest.config.ts --pool=forks"
19
24
  },
20
25
  "bundle": {
21
26
  "entry": [
22
- "src/index.ts"
27
+ "src/index.ts",
28
+ "src/testing.ts"
23
29
  ]
24
30
  },
25
31
  "dependencies": {
@@ -27,23 +33,22 @@
27
33
  "@ai-sdk/openai": "^4.0.115",
28
34
  "@better-auth/mcp": "1.7.21",
29
35
  "@better-auth/oauth-provider": "1.7.21",
30
- "@catamorphic/agent-protocol": "0.1.0-alpha.39",
31
- "@catamorphic/agent-runner": "0.1.0-alpha.39",
32
- "@catamorphic/ai-sdk": "0.1.0-alpha.39",
33
- "@catamorphic/app": "0.1.0-alpha.39",
34
- "@catamorphic/container": "0.1.0-alpha.39",
35
- "@catamorphic/core": "0.1.0-alpha.39",
36
- "@catamorphic/db": "0.1.0-alpha.39",
37
- "@catamorphic/fastify-plugin": "0.1.0-alpha.39",
38
- "@catamorphic/hetzner": "0.1.0-alpha.39",
39
- "@catamorphic/local-process": "0.1.0-alpha.39",
40
- "@catamorphic/mcp": "0.1.0-alpha.39",
41
- "@catamorphic/microsandbox": "0.1.0-alpha.39",
42
- "@catamorphic/otel": "0.1.0-alpha.39",
43
- "@catamorphic/registry": "0.1.0-alpha.39",
44
- "@catamorphic/sandbox": "0.1.0-alpha.39",
45
- "@catamorphic/server-sdk": "0.1.0-alpha.39",
46
- "@catamorphic/workflow": "0.1.0-alpha.39",
36
+ "@catamorphic/agent-protocol": "0.1.0-alpha.41",
37
+ "@catamorphic/agent-runner": "0.1.0-alpha.41",
38
+ "@catamorphic/ai-sdk": "0.1.0-alpha.41",
39
+ "@catamorphic/app": "0.1.0-alpha.41",
40
+ "@catamorphic/container": "0.1.0-alpha.41",
41
+ "@catamorphic/core": "0.1.0-alpha.41",
42
+ "@catamorphic/db": "0.1.0-alpha.41",
43
+ "@catamorphic/fastify-plugin": "0.1.0-alpha.41",
44
+ "@catamorphic/local-process": "0.1.0-alpha.41",
45
+ "@catamorphic/mcp": "0.1.0-alpha.41",
46
+ "@catamorphic/microsandbox": "0.1.0-alpha.41",
47
+ "@catamorphic/otel": "0.1.0-alpha.41",
48
+ "@catamorphic/registry": "0.1.0-alpha.41",
49
+ "@catamorphic/sandbox": "0.1.0-alpha.41",
50
+ "@catamorphic/server-sdk": "0.1.0-alpha.41",
51
+ "@catamorphic/workflow": "0.1.0-alpha.41",
47
52
  "@electric-sql/pglite": "^0.5.16",
48
53
  "@openai/codex": "0.169.0",
49
54
  "better-auth": "1.7.21",
@@ -54,6 +59,9 @@
54
59
  "zod": "4.6.7"
55
60
  },
56
61
  "devDependencies": {
62
+ "@aws-sdk/client-ec2": "3.1171.0",
63
+ "@catamorphic/claude-code": "0.1.0-alpha.41",
64
+ "@modelcontextprotocol/client": "^2.4.0",
57
65
  "@types/node": "^26.6.6",
58
66
  "@types/pg": "8.23.1"
59
67
  },
@@ -76,6 +84,8 @@
76
84
  "!**/*.spec.*",
77
85
  "!**/__tests__/**",
78
86
  "!**/__fixtures__/**",
79
- "!**/fixtures/**"
87
+ "!**/fixtures/**",
88
+ "!**/testing/**",
89
+ "!**/test-support.*"
80
90
  ]
81
91
  }
@@ -1,4 +1,4 @@
1
- import type { Identity } from "@catamorphic/core";
1
+ import { FULL_TOKEN_SCOPE, type Identity } from "@catamorphic/core";
2
2
  import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
3
3
  import { z } from "zod";
4
4
  import type { WorkAuth } from "../auth/work-auth-types.js";
@@ -237,7 +237,10 @@ async function resolveCaller(
237
237
  const authenticated = await options.auth.resolveAccessToken({
238
238
  authorization,
239
239
  });
240
- if (!authenticated || !(await options.mayAct(authenticated.userId)))
240
+ if (
241
+ !authenticated?.scopes.includes(FULL_TOKEN_SCOPE) ||
242
+ !(await options.mayAct(authenticated.userId))
243
+ )
241
244
  return null;
242
245
  return {
243
246
  identity: await options.identityForUser({
@@ -7,20 +7,20 @@ import {
7
7
  defineRegistryCapability,
8
8
  hasProjectPermission,
9
9
  parseRegistryCatalog,
10
+ pullRequestCapability,
10
11
  } from "@catamorphic/core";
11
12
  import { projectToolCapabilities } from "@catamorphic/fastify-plugin";
12
13
  import { z } from "zod";
13
14
  import type { WorkAuth } from "./auth/work-auth-types.js";
14
15
 
15
16
  /**
16
- * Project tools the server's own agents reach through discovery: proposing
17
- * a change, and setting what their chat shows (its metadata, ADR 0226).
18
- * Replica memory (c): a constant, the same on every replica.
17
+ * Project tools the server's own agents reach through discovery: setting
18
+ * what their chat shows (its metadata, ADR 0226). Their changes leave as a
19
+ * pull request from their own branch (`project.create_pull_request`, ADR
20
+ * 0345), never as files handed to `propose_change`: every server chat has
21
+ * a workspace. Replica memory (c): a constant, the same on every replica.
19
22
  */
20
- const SERVER_PROJECT_TOOLS = new Set([
21
- "propose_change",
22
- "set_session_metadata",
23
- ]);
23
+ const SERVER_PROJECT_TOOLS = new Set(["set_session_metadata"]);
24
24
 
25
25
  /**
26
26
  * The packs the server's agents can install into a project (ADR 0262): the
@@ -90,6 +90,20 @@ export function workAgentCapabilities(args: {
90
90
  };
91
91
  },
92
92
  });
93
+ // Core's one pull request tool, over the chat's saved branch.
94
+ const pullRequest = pullRequestCapability(({ identity, ...request }) => {
95
+ const sessions = args.core().agentSessions;
96
+ if (!sessions) throw new Error("This server runs no chats.");
97
+ return sessions.createPullRequest(
98
+ identity,
99
+ request.projectId,
100
+ request.sessionId,
101
+ {
102
+ title: request.title,
103
+ ...(request.body !== undefined ? { body: request.body } : {}),
104
+ },
105
+ );
106
+ });
93
107
  return {
94
108
  ...args.custom,
95
109
  currentUser:
@@ -117,7 +131,7 @@ export function workAgentCapabilities(args: {
117
131
  ],
118
132
  capabilities: [
119
133
  // A host's own capability of the same name replaces the built-in one.
120
- ...[directory, registry].filter(
134
+ ...[directory, registry, pullRequest].filter(
121
135
  (builtIn) =>
122
136
  !args.custom?.capabilities?.some(
123
137
  (item) => item.name === builtIn.name,
package/src/agents.ts CHANGED
@@ -8,7 +8,11 @@ import {
8
8
  normalizeConnectionRequirement,
9
9
  type RegisteredCodingAgent,
10
10
  } from "@catamorphic/core";
11
- import type { SignInHarness } from "@catamorphic/sandbox";
11
+ import {
12
+ SIGN_IN_HARNESSES,
13
+ type SignInHarness,
14
+ signInHarness,
15
+ } from "@catamorphic/sandbox";
12
16
  import type { WorkAgentSettings } from "./config.js";
13
17
  import { createFakeAgentAdapter } from "./fake-agent.js";
14
18
 
@@ -60,19 +64,19 @@ export function buildAgentRegistry(deps: {
60
64
  };
61
65
  }
62
66
  // Without an organization model the assistant is off, but members can
63
- // still chat with Codex on their own sign-ins on a machine of their own
64
- // they signed in on (ADRs 0199, 0213).
67
+ // still chat with Claude Code and Codex on their own sign-ins on a
68
+ // machine of their own they signed in on (ADRs 0199, 0213, 0342).
65
69
  if (!resolveModel || !providerName) {
66
70
  return {
67
71
  registry: assistantRegistry({ effort }),
68
72
  description:
69
- "assistant off (set ANTHROPIC_API_KEY, OPENROUTER_API_KEY or OPENAI_API_KEY); Codex on members' own sign-ins",
73
+ "assistant off (set ANTHROPIC_API_KEY, OPENROUTER_API_KEY or OPENAI_API_KEY); Claude Code and Codex on members' own sign-ins",
70
74
  };
71
75
  }
72
76
  if (!modelId) {
73
77
  return {
74
78
  registry: assistantRegistry({ effort }),
75
- description: `assistant off (${providerName} needs WORK_MODEL set to a model id); Codex on members' own sign-ins`,
79
+ description: `assistant off (${providerName} needs WORK_MODEL set to a model id); Claude Code and Codex on members' own sign-ins`,
76
80
  };
77
81
  }
78
82
 
@@ -98,15 +102,18 @@ export function buildAgentRegistry(deps: {
98
102
  export const ASSISTANT_SLUG = "assistant";
99
103
 
100
104
  /**
101
- * Codex on the chat owner's own sign-in, made on the machine that runs the
102
- * chat (ADR 0199). Offered in projects with an Environment that allows
103
- * personal credentials; a chat places only on a machine of the owner's
104
- * that reports their sign-in (ADR 0213). Claude Code subscriptions run
105
- * only on the member's own computer, so the server offers none.
105
+ * Claude Code and Codex on the chat owner's own sign-in, made on the
106
+ * machine that runs the chat (ADR 0199). Offered in projects with an
107
+ * Environment that allows personal credentials; a chat places only on a
108
+ * machine of the owner's that reports their sign-in (ADRs 0213, 0342).
106
109
  */
107
110
  export const SIGN_IN_AGENTS: Readonly<
108
111
  Record<SignInHarness, { name: string; description: string }>
109
112
  > = {
113
+ "claude-code": {
114
+ name: "Claude Code",
115
+ description: "Claude Code on your own Claude sign-in on the machine",
116
+ },
110
117
  codex: {
111
118
  name: "Codex",
112
119
  description: "Codex on your own ChatGPT sign-in on the machine",
@@ -119,7 +126,7 @@ export function projectAssistantId(projectId: string): string {
119
126
  }
120
127
 
121
128
  const SYSTEM_PROMPT =
122
- "You work through a company server. Unless execution context explicitly identifies an authenticated member device, the working directory and home directory belong to the server or its sandbox, not the user's device. New personal files should stay local to the user's device by default. Do not claim that writing outside the project on the server satisfies device-local or private storage. If no device file tool is available, provide the requested content in chat and clearly explain that it has not been saved to their device. Use only host-supported private storage for private output. Saving, proposing, and publishing are separate actions: never add personal output to shared project source or store/ unless the user explicitly requests sharing. When asked to propose or prepare shared content for review, discover project.propose_change and pass only the intended file paths and desired content. Submit the proposal before writing shared project files: shared checkout writes can be checkpointed and synchronized immediately. If the proposal capability is unavailable, explain that and keep the proposed content in chat; do not silently publish it instead. A chat or ordinary document change alone does not require a new worktree.";
129
+ "You work through a company server. Unless execution context explicitly identifies an authenticated member device, the working directory and home directory belong to the server or its sandbox, not the user's device. New personal files should stay local to the user's device by default. Do not claim that writing outside the project on the server satisfies device-local or private storage. If no device file tool is available, provide the requested content in chat and clearly explain that it has not been saved to their device. Use only host-supported private storage for private output. Saving, proposing, and publishing are separate actions: never add personal output to shared project source or store/ unless the user explicitly requests sharing. Your project folder is a Git checkout that is this chat's alone: a branch of its own, starting from the default branch of the project's repository (or the ref this chat was given). Nothing you write there reaches the shared project by itself. Work saves the branch you are on with its commits, and your uncommitted changes, and gives them back when the workspace returns; other local branches, ignored files, a rebase in progress and anything outside the project folder are not kept, so commit what matters on your current branch. When asked to propose or prepare shared content for review, commit it and discover project.create_pull_request: it pushes your commits as this chat's own branch and opens a pull request, or updates the one this chat already opened, and records it on the chat. If that capability is unavailable or the project has no repository, explain that and keep the work on your branch; do not silently publish it instead. A chat or ordinary document change alone does not require a new worktree.";
123
130
 
124
131
  /**
125
132
  * Claude Code and Codex on the server (ADRs 0180, 0198): the runner bundle
@@ -165,7 +172,7 @@ function assistantRegistry(config: {
165
172
  defaults,
166
173
  };
167
174
  const projectForm = /^project:[0-9a-f-]+:assistant$/;
168
- // Codex on the member's own sign-in (ADRs 0199, 0213).
175
+ // Claude Code and Codex on the member's own sign-in (ADRs 0199, 0342).
169
176
  const signInAgent = (kind: SignInHarness): RegisteredCodingAgent => ({
170
177
  id: kind,
171
178
  name: SIGN_IN_AGENTS[kind].name,
@@ -176,8 +183,8 @@ function assistantRegistry(config: {
176
183
  signIn: kind,
177
184
  systemPrompt: SYSTEM_PROMPT,
178
185
  });
179
- const signInAgents = [signInAgent("codex")];
180
- const signInForm = /^project:[0-9a-f-]+:(codex)$/;
186
+ const signInAgents = SIGN_IN_HARNESSES.map(signInAgent);
187
+ const signInForm = /^project:[0-9a-f-]+:(claude-code|codex)$/;
181
188
  return {
182
189
  // Without an org model, a chat starts on the member's own Codex.
183
190
  defaultAgentId: (projectId) =>
@@ -239,9 +246,8 @@ function assistantRegistry(config: {
239
246
  * A committed agent whose harness runs in its chat's sandbox (ADRs 0180,
240
247
  * 0198): `claude-code`, `codex`, or an ACP agent's own command (ADR 0255).
241
248
  * Served when its credentials name a model connection of its Environment,
242
- * or, for Codex, `personal`: the chat owner's own sign-in on a machine of
243
- * theirs (ADRs 0199, 0213). A personal Claude Code agent is not served
244
- * here: Claude Code subscriptions run only on the member's own computer.
249
+ * or, for Claude Code and Codex, `personal`: the chat owner's own sign-in
250
+ * on a machine of theirs (ADRs 0199, 0213, 0342).
245
251
  * An ACP agent runs only on a model connection: on a server it has no
246
252
  * sign-in of its own, and its command comes from the Environment's image.
247
253
  */
@@ -258,7 +264,13 @@ function sandboxProjectAgent(input: {
258
264
  const harness =
259
265
  definition.kind === "acp"
260
266
  ? command?.[0]
261
- ? acpHarness({ id: input.id, command })
267
+ ? acpHarness({
268
+ id: input.id,
269
+ command,
270
+ shell: definition.acp?.shell === true,
271
+ projectConfig: definition.acp?.projectConfig,
272
+ env: definition.acp?.env,
273
+ })
262
274
  : undefined
263
275
  : sandboxHarness(definition.kind === "codex" ? "codex" : "claude-code");
264
276
  if (!harness) return undefined;
@@ -277,10 +289,12 @@ function sandboxProjectAgent(input: {
277
289
  ...(definition.effort ? { effort: definition.effort } : {}),
278
290
  },
279
291
  };
280
- if (definition.credentials?.source === "personal")
281
- return definition.kind === "codex"
282
- ? { ...common, connectionRequirements: requirements, signIn: "codex" }
292
+ if (definition.credentials?.source === "personal") {
293
+ const signIn = signInHarness(definition.kind);
294
+ return signIn
295
+ ? { ...common, connectionRequirements: requirements, signIn }
283
296
  : undefined;
297
+ }
284
298
  const alias =
285
299
  definition.credentials?.source === "connection"
286
300
  ? definition.credentials.connection
@@ -303,12 +317,27 @@ function sandboxProjectAgent(input: {
303
317
  * adapter, under a harness of its own so a chat stays with its agent. The
304
318
  * sandbox is the boundary, so the command needs no member's approval here.
305
319
  */
306
- function acpHarness(input: { id: string; command: readonly string[] }): {
320
+ function acpHarness(input: {
321
+ id: string;
322
+ command: readonly string[];
323
+ /** It runs its commands with `$SHELL` (ADR 0332). */
324
+ shell: boolean;
325
+ /** `false`: it loads nothing from the checkout (ADR 0332). */
326
+ projectConfig: boolean | undefined;
327
+ env: Record<string, string> | undefined;
328
+ }): {
307
329
  harness: AgentHarness;
308
330
  options: RegisteredCodingAgent["options"];
309
331
  } {
310
332
  return {
311
333
  harness: { placement: "sandbox", id: `acp:${input.id}` },
312
- options: { command: [...input.command] },
334
+ options: {
335
+ command: [...input.command],
336
+ ...(input.shell ? { shell: true } : {}),
337
+ ...(input.projectConfig !== undefined
338
+ ? { projectConfig: input.projectConfig }
339
+ : {}),
340
+ ...(input.env ? { env: { ...input.env } } : {}),
341
+ },
313
342
  };
314
343
  }
@@ -1,4 +1,10 @@
1
1
  import { randomBytes } from "node:crypto";
2
+ import {
3
+ DEFAULT_TOKEN_SCOPES,
4
+ FULL_TOKEN_SCOPE,
5
+ TOKEN_SCOPES,
6
+ tokenScopesOf,
7
+ } from "@catamorphic/core";
2
8
  import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
3
9
  import { workMark } from "../brand.js";
4
10
  import type {
@@ -121,6 +127,41 @@ export function registerWorkAuthRoutes(
121
127
  }
122
128
  return sendResponse(response, reply);
123
129
  }
130
+ // Every grant names what its client may do (ADR 0347). A client that
131
+ // asks for none of Work's scopes is offered the default set, which
132
+ // its person can untick at consent.
133
+ if (
134
+ request.method === "GET" &&
135
+ rawPath === "/api/auth/oauth2/authorize"
136
+ ) {
137
+ const query = new URL(request.url, options.baseURL).searchParams;
138
+ // A query Better Auth signed is its own continuation, as it stands.
139
+ if (!query.has("sig")) {
140
+ query.set("scope", withWorkScopes(query.get("scope") ?? ""));
141
+ return sendResponse(
142
+ await callBetterAuth(routed, request, {
143
+ search: query.toString(),
144
+ }),
145
+ reply,
146
+ );
147
+ }
148
+ }
149
+ // A client that registers the scopes it will ask for may still be
150
+ // granted Work's: which ones is its person's choice at consent.
151
+ if (
152
+ request.method === "POST" &&
153
+ rawPath === "/api/auth/oauth2/register"
154
+ ) {
155
+ const registration = registrationWithWorkScopes(request.body);
156
+ if (registration)
157
+ return sendResponse(
158
+ await callBetterAuth(routed, request, {
159
+ body: registration,
160
+ contentType: "application/json",
161
+ }),
162
+ reply,
163
+ );
164
+ }
124
165
  return forward(request, reply);
125
166
  },
126
167
  });
@@ -294,11 +335,24 @@ export function registerWorkAuthRoutes(
294
335
  });
295
336
  app.post("/oauth/consent", async (request, reply) => {
296
337
  const form = formBody(request.body);
338
+ const signedQuery = form.get("oauth_query") ?? "";
339
+ const requested = (new URLSearchParams(signedQuery).get("scope") ?? "")
340
+ .split(/\s+/)
341
+ .filter(Boolean);
342
+ // Grant only what the submitted form selected from the signed request.
343
+ const ticked = new Set(form.getAll("scope"));
344
+ const granted = requested.filter((scope) => ticked.has(scope));
345
+ // A grant with none of Work's scopes could do nothing: unticking them
346
+ // all is declining.
347
+ const usable = tokenScopesOf(granted).length > 0;
297
348
  const response = await callBetterAuth(routed, request, {
298
349
  pathname: "/api/auth/oauth2/consent",
299
350
  body: JSON.stringify({
300
- accept: form.get("accept") === "true",
301
- oauth_query: form.get("oauth_query") ?? "",
351
+ accept: form.get("accept") === "true" && usable,
352
+ oauth_query: signedQuery,
353
+ ...(granted.length > 0 && granted.length < requested.length
354
+ ? { scope: granted.join(" ") }
355
+ : {}),
302
356
  }),
303
357
  contentType: "application/json",
304
358
  });
@@ -399,6 +453,8 @@ async function callBetterAuth(
399
453
  request: FastifyRequest,
400
454
  overrides: {
401
455
  pathname?: string;
456
+ /** The query to send instead of the request's own. */
457
+ search?: string;
402
458
  body?: string;
403
459
  contentType?: string;
404
460
  },
@@ -408,6 +464,7 @@ async function callBetterAuth(
408
464
  incoming.pathname = overrides.pathname;
409
465
  incoming.search = "";
410
466
  }
467
+ if (overrides.search !== undefined) incoming.search = overrides.search;
411
468
  const headers = new Headers();
412
469
  for (const [name, value] of Object.entries(request.headers)) {
413
470
  for (const entry of Array.isArray(value) ? value : [value]) {
@@ -533,11 +590,30 @@ function loginPage(
533
590
  function consentPage(signedQuery: string, nonce: string): string {
534
591
  const query = new URLSearchParams(signedQuery);
535
592
  const client = escapeHtml(query.get("client_id") ?? "this client");
536
- const scopes = (query.get("scope") ?? "basic identity")
537
- .split(/\s+/)
538
- .filter(Boolean)
539
- .map((scope) => `<li>${escapeHtml(scope.replaceAll("_", " "))}</li>`)
540
- .join("");
593
+ // Work's own scopes are the person's to grant one by one (ADR 0347).
594
+ // Approving for them is never ticked for them. Full access is one plain
595
+ // line to allow or deny: it is everything, so nothing else is listed.
596
+ const requested = (query.get("scope") ?? "").split(/\s+/).filter(Boolean);
597
+ const full = requested.includes(FULL_TOKEN_SCOPE);
598
+ const scopes =
599
+ requested.length === 0
600
+ ? "<li>basic identity</li>"
601
+ : requested
602
+ .map((scope) => {
603
+ const value = escapeHtml(scope);
604
+ const description = workScopeDescription(scope);
605
+ const kept = `<input type="hidden" name="scope" value="${value}">`;
606
+ if (!description)
607
+ return `<li>${kept}${escapeHtml(scope.replaceAll("_", " "))}</li>`;
608
+ if (scope === FULL_TOKEN_SCOPE)
609
+ return `<li class="scope-full">${kept}${escapeHtml(description)}</li>`;
610
+ // Covered by full access: granted with it, not listed again.
611
+ if (full) return "";
612
+ return `<li><label class="scope-choice"><input type="checkbox" name="scope" value="${value}"${
613
+ scope === "sessions:approve" ? "" : " checked"
614
+ }> ${escapeHtml(description)}</label></li>`;
615
+ })
616
+ .join("");
541
617
  return authPage({
542
618
  title: "Review access | Work",
543
619
  nonce,
@@ -547,22 +623,72 @@ function consentPage(signedQuery: string, nonce: string): string {
547
623
  <h1 id="page-title">Allow this connection?</h1>
548
624
  <p>Review what the connecting app is asking to use.</p>
549
625
  </header>
550
- <div class="access-summary">
551
- <p class="summary-label">Connecting client</p>
552
- <code>${client}</code>
553
- <p class="summary-label">Requested access</p>
554
- <ul class="scope-list">${scopes}</ul>
555
- </div>
556
- <form class="consent-actions" action="/oauth/consent" method="post">
557
- <input type="hidden" name="oauth_query" value="${escapeHtml(signedQuery)}">
558
- <button class="button button-secondary" name="accept" value="false">Deny</button>
559
- <button class="button button-primary" name="accept" value="true">Allow access</button>
626
+ <form action="/oauth/consent" method="post">
627
+ <div class="access-summary">
628
+ <p class="summary-label">Connecting client</p>
629
+ <code>${client}</code>
630
+ <p class="summary-label">Requested access</p>
631
+ <ul class="scope-list">${scopes}</ul>
632
+ </div>
633
+ <div class="consent-actions">
634
+ <input type="hidden" name="oauth_query" value="${escapeHtml(signedQuery)}">
635
+ <button class="button button-secondary" name="accept" value="false">Deny</button>
636
+ <button class="button button-primary" name="accept" value="true">Allow access</button>
637
+ </div>
560
638
  </form>
561
639
  <p class="privacy-note">You can remove access later from your server.</p>
562
640
  </section>`,
563
641
  });
564
642
  }
565
643
 
644
+ /**
645
+ * The scopes of an authorization request, with the default set added when
646
+ * it names none of Work's (ADR 0347).
647
+ */
648
+ function withWorkScopes(scope: string): string {
649
+ const requested = scope.split(/\s+/).filter(Boolean);
650
+ return [
651
+ ...requested,
652
+ ...(tokenScopesOf(requested).length === 0 ? DEFAULT_TOKEN_SCOPES : []),
653
+ ].join(" ");
654
+ }
655
+
656
+ /**
657
+ * A dynamic registration that lists its scopes, with Work's added so the
658
+ * client may be granted them; nothing for one that lists none (it may ask
659
+ * for any) or is not a JSON object.
660
+ */
661
+ function registrationWithWorkScopes(body: unknown): string | undefined {
662
+ const parsed: unknown =
663
+ typeof body === "string"
664
+ ? (() => {
665
+ try {
666
+ return JSON.parse(body);
667
+ } catch {
668
+ return undefined;
669
+ }
670
+ })()
671
+ : body;
672
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
673
+ return undefined;
674
+ const scope = "scope" in parsed ? parsed.scope : undefined;
675
+ if (typeof scope !== "string") return undefined;
676
+ return JSON.stringify({
677
+ ...parsed,
678
+ scope: [
679
+ ...new Set([
680
+ ...scope.split(/\s+/).filter(Boolean),
681
+ ...Object.keys(TOKEN_SCOPES),
682
+ ]),
683
+ ].join(" "),
684
+ });
685
+ }
686
+
687
+ /** What one of Work's scopes lets a client do, for the consent page. */
688
+ function workScopeDescription(scope: string): string | undefined {
689
+ return Object.entries(TOKEN_SCOPES).find(([name]) => name === scope)?.[1];
690
+ }
691
+
566
692
  function messagePage(title: string, message: string, nonce: string): string {
567
693
  return authPage({
568
694
  title: `${title} | Work`,
@@ -803,6 +929,12 @@ function authPage(options: {
803
929
  padding: 0;
804
930
  list-style: none;
805
931
  }
932
+ .scope-choice {
933
+ display: flex;
934
+ gap: 0.5rem;
935
+ align-items: baseline;
936
+ cursor: pointer;
937
+ }
806
938
  .scope-list li {
807
939
  padding: 3px 7px;
808
940
  border: 1px solid var(--border);
@@ -45,6 +45,8 @@ export interface WorkAuth {
45
45
  sessionFromCookies(args: { cookie: string }): Promise<WorkAuthUser | null>;
46
46
  findUserById(args: { userId: string }): Promise<WorkAuthUser | null>;
47
47
  findUserByEmail(args: { email: string }): Promise<WorkAuthUser | null>;
48
+ /** Every account that ever signed in or was created here. */
49
+ listUsers(): Promise<WorkAuthUser[]>;
48
50
  resolveAccessToken(args: { authorization: string }): Promise<{
49
51
  userId: string;
50
52
  email: string;
@@ -3,6 +3,7 @@ import fs from "node:fs";
3
3
  import path from "node:path";
4
4
  import { mcp } from "@better-auth/mcp";
5
5
  import { verifyOAuthQueryParams } from "@better-auth/oauth-provider";
6
+ import { TOKEN_SCOPES } from "@catamorphic/core";
6
7
  import { betterAuth } from "better-auth";
7
8
  import { bearer, genericOAuth, username } from "better-auth/plugins";
8
9
  import { z } from "zod";
@@ -23,6 +24,11 @@ import type {
23
24
  /** Provider sign-in starts per client address (Better Auth's window is seconds). */
24
25
  const PROVIDER_SIGN_IN_LIMIT = { window: 10, max: 30 };
25
26
 
27
+ /** The OpenID scopes a client signs in with. */
28
+ const SIGN_IN_SCOPES = ["openid", "profile", "email", "offline_access"];
29
+ /** Work's scopes: what a client may do as its person (ADR 0347). */
30
+ const WORK_SCOPES = Object.keys(TOKEN_SCOPES);
31
+
26
32
  export function createWorkAuth(options: {
27
33
  database: WorkAuthDatabase;
28
34
  baseURL: string;
@@ -104,6 +110,10 @@ export function createWorkAuth(options: {
104
110
  resource: `${options.baseURL}/api`,
105
111
  // Work checks and revokes opaque grants on every request (ADR 0161).
106
112
  disableJwtPlugin: true,
113
+ // What a client may be granted (ADR 0347): OpenID's own scopes
114
+ // for signing in, and Work's, which narrow what the client does as
115
+ // its person. The protected-resource metadata lists Work's.
116
+ scopes: [...SIGN_IN_SCOPES, ...WORK_SCOPES],
107
117
  allowDynamicClientRegistration: true,
108
118
  allowUnauthenticatedClientRegistration: true,
109
119
  clientRegistrationDefaultApplicationType: "infer",
@@ -182,6 +192,14 @@ export function createWorkAuth(options: {
182
192
  );
183
193
  return found ? workAuthUser(found.user) : null;
184
194
  },
195
+ listUsers: async () => {
196
+ const context = await auth.$context;
197
+ const rows = await context.adapter.findMany({ model: "user" });
198
+ return rows.flatMap((row) => {
199
+ const user = ListedUser.safeParse(row);
200
+ return user.success ? [workAuthUser(user.data)] : [];
201
+ });
202
+ },
185
203
  resolveAccessToken: async ({ authorization }) => {
186
204
  const bearerToken = /^Bearer ([^\s]+)$/i.exec(authorization)?.[1];
187
205
  if (!bearerToken) return null;
@@ -453,6 +471,15 @@ export function loadWorkAuthSecret(options: {
453
471
  }
454
472
  }
455
473
 
474
+ /** A user row as the adapter lists it. */
475
+ const ListedUser = z.object({
476
+ id: z.string(),
477
+ email: z.string(),
478
+ emailVerified: z.boolean(),
479
+ name: z.string(),
480
+ username: z.string().nullish(),
481
+ });
482
+
456
483
  function workAuthUser(user: {
457
484
  id: string;
458
485
  email: string;