@primitive.ai/prim 0.1.0-alpha.126 → 0.1.0-alpha.128

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 (45) hide show
  1. package/README.md +211 -1
  2. package/SKILL.md +6 -1
  3. package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
  4. package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
  5. package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
  6. package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
  7. package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
  8. package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
  9. package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
  10. package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
  11. package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
  12. package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
  13. package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
  14. package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
  15. package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
  16. package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
  17. package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
  18. package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
  19. package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
  20. package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
  21. package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
  22. package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
  23. package/dist/daemon/server.js +1976 -442
  24. package/dist/hook-runtime/daemon/server.js +1976 -442
  25. package/dist/hook-runtime/hooks/post-commit.js +592 -212
  26. package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
  27. package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
  28. package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
  29. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
  30. package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
  31. package/dist/hook-runtime/hooks/session-end.js +549 -180
  32. package/dist/hook-runtime/hooks/session-start.js +2213 -596
  33. package/dist/hook-runtime/index.js +5318 -2423
  34. package/dist/hook-runtime/statusline-main.js +531 -150
  35. package/dist/hooks/post-commit.js +7 -7
  36. package/dist/hooks/post-rewrite.js +6 -6
  37. package/dist/hooks/post-tool-use.js +18 -18
  38. package/dist/hooks/pre-commit.js +4 -4
  39. package/dist/hooks/pre-tool-use-worker.js +14 -15
  40. package/dist/hooks/prim-hook.js +16 -16
  41. package/dist/hooks/session-end.js +4 -4
  42. package/dist/hooks/session-start.js +95 -21
  43. package/dist/index.js +1386 -299
  44. package/dist/statusline-main.js +531 -150
  45. package/package.json +1 -1
package/README.md CHANGED
@@ -154,6 +154,200 @@ process (auth → session hooks → daemon → skill → activate this repositor
154
154
  step-by-step the agent follows — and the manual fallback — live in
155
155
  [`setup.md`](./setup.md).
156
156
 
157
+ ### Claude Code cloud environments
158
+
159
+ Prim runs in [Claude Code cloud sessions](https://code.claude.com/docs/en/claude-code-on-the-web).
160
+ Configure it once; each session then connects without manual steps. The repository must
161
+ already be connected to Primitive (`npx --yes @primitive.ai/prim@latest github connect`
162
+ in a clone of it, from your own machine).
163
+
164
+ 1. **Mint credentials for the environment** on your own machine. This signs you in once,
165
+ enrolls a separate installation in your name, and prints its credentials. Nothing is
166
+ stored locally, and your machine's own credentials are untouched:
167
+
168
+ ```bash
169
+ npx --yes @primitive.ai/prim@latest auth enroll --new-installation "Claude Code cloud" --print-env
170
+ ```
171
+
172
+ 2. **Configure the [cloud environment](https://code.claude.com/docs/en/cloud-environments)**:
173
+ - **Network access**: Limited, with `api.getprimitive.ai` and `signin.getprimitive.ai`
174
+ under Allowed domains (both are blocked by default), and **Allow package managers**
175
+ left on so the setup script can fetch prim. A change to Allowed domains reaches
176
+ prim only in sessions started after it: a running session keeps the network rules
177
+ it started with.
178
+ - **Credentials**: give the secret to the environment's proxy, which no session can
179
+ read back. Under **Network secrets**, add a **Username and password** secret for host
180
+ `signin.getprimitive.ai`: the `PRIM_M2M_CLIENT_ID` value step 1 printed as the
181
+ username, the `PRIM_M2M_CLIENT_SECRET` value as the password. Then set these
182
+ **Environment variables**, leaving the `PRIM_M2M_CLIENT_SECRET` line out and
183
+ keeping any other line step 1 printed, such as `PRIM_API_URL`:
184
+
185
+ ```text
186
+ PRIM_M2M_CLIENT_ID=client_...
187
+ PRIM_M2M_CLIENT_AUTH=network-secret
188
+ ```
189
+
190
+ The simpler alternative is to paste every line step 1 printed into the variables.
191
+ Anyone who uses the environment can read its variables, so do that only in an
192
+ environment you keep to yourself.
193
+ - **Setup script**:
194
+
195
+ ```bash
196
+ #!/bin/bash
197
+ set -euo pipefail
198
+ npx --yes @primitive.ai/prim@latest setup --cloud --prepare
199
+ ```
200
+
201
+ No global install is needed: the hooks run from a runtime `--prepare` stages in
202
+ the image, and in a session prim's commands run as
203
+ `npx --yes @primitive.ai/prim@latest ...`. To have `prim` on the VM's PATH as well,
204
+ use `npm install -g @primitive.ai/prim@latest` followed by
205
+ `prim setup --cloud --prepare` instead.
206
+
207
+ `--prepare` needs no credentials or network to Primitive. It wires prim into the
208
+ VM's user-scope Claude Code settings, which every session reads at startup, so
209
+ repositories need no commit. It marks the environment so sessions activate the
210
+ repositories they open, and turns the daemon off: the VM pauses between messages, so
211
+ capture delivers directly instead. `prim disable` opts a repository out for the rest of
212
+ that session only, because each session starts from a fresh clone. To keep prim out of
213
+ a repository for good, run `prim disable --scope project` in it and commit
214
+ `.claude/settings.json` (with `git add -f` where the repository ignores `.claude`;
215
+ prim says so): that records `PRIM_ACTIVE=false` there, every clone carries
216
+ it, and prim then stays off in that repository unless someone turns it on themselves
217
+ (`prim enable` in their own clone). `prim enable --scope project` removes it again.
218
+
219
+ With the network secret, the proxy adds the secret to prim's token request as HTTP Basic
220
+ authentication, so no process in the session can read the secret or carry it out of the
221
+ VM; processes in the
222
+ session can still obtain short-lived tokens through the proxy, as prim does. Keep
223
+ `signin.getprimitive.ai` under Allowed domains. Prim's token broker, the one process
224
+ that requests tokens, sends its own requests through that proxy; nothing else in the VM
225
+ has to. An environment set up for an earlier prim may still carry `NODE_USE_ENV_PROXY=1`
226
+ (and `NODE_NO_WARNINGS=1`) in its variables: both are harmless and can be removed.
227
+
228
+ To keep the tokens out of the VM as well, let the proxy request them. In the settings
229
+ of an existing environment (the New environment dialog offers only the simpler secret
230
+ types), add a **Network secret** of type **OAuth 2.0 client credentials** in place of
231
+ the username-and-password secret:
232
+
233
+ - **Allowed websites**: `api.getprimitive.ai`
234
+ - **Token URL**: `https://signin.getprimitive.ai/oauth2/token`
235
+ - **Client ID** and **Client secret**: the `PRIM_M2M_CLIENT_ID` and
236
+ `PRIM_M2M_CLIENT_SECRET` values step 1 printed
237
+ - **Scopes**, **Resource** and **Audience**: leave empty
238
+
239
+ and set the variables to:
240
+
241
+ ```text
242
+ PRIM_M2M_CLIENT_ID=client_...
243
+ PRIM_M2M_CLIENT_AUTH=network-token
244
+ ```
245
+
246
+ The proxy then obtains the tokens itself and attaches one to each request for
247
+ `api.getprimitive.ai`. Prim requests no token and sends no credential: its commands and
248
+ hooks hand their API requests to prim's broker, the one process that sends through the
249
+ proxy, and `prim auth status` verifies the identity the proxy authenticates as. No
250
+ process in the session can read the secret or a token, though any process in it can
251
+ still reach Primitive through the proxy as that installation, so keep the environment
252
+ personal. Only `api.getprimitive.ai` has to be under Allowed domains in this mode, and
253
+ `prim setup --cloud` names the network secret's fields if the proxy's token is refused.
254
+
255
+ Running plain `prim setup` inside a cloud session (for example through the agent prompt
256
+ above) detects the session and does the cloud setup; browser sign-in, the daemon, and
257
+ onboarding are skipped there, and `prim auth login` explains why it cannot run.
258
+ `--prepare` belongs in the setup script: Claude Code reads its hooks when it starts, and
259
+ new sessions start from the environment's image. Run inside a session, it wires only
260
+ that VM and says the image was not prepared by that run (a VM the image had already
261
+ prepared stays prepared).
262
+
263
+ Each session, prim's SessionStart hook activates the repository the session was started
264
+ on and connects it to Primitive. If the hook cannot connect it, it says why: missing
265
+ credentials, a blocked domain, or a checkout that does not identify its repository. The
266
+ git pre-commit check is not wired automatically; run `prim setup --cloud` in a session to
267
+ verify it step by step and install it. A second repository the agent clones during the
268
+ session is not connected or given git hooks at session start; run `prim setup --cloud`
269
+ from that clone to set it up. Decisions captured in the environment belong to you; an
270
+ organization admin can revoke the installation in Settings → Developer installations.
271
+
272
+ Prim identifies the repository from its GitHub origin. A session started with
273
+ `claude --cloud` from a checkout the Claude GitHub App cannot clone receives an upload
274
+ with no origin. For those, commit prim's project install from a clone whose origin is on
275
+ GitHub; besides the hooks, it records the repository declaration (`PRIM_REPOSITORY`) in
276
+ `.claude/settings.json`:
277
+
278
+ ```bash
279
+ prim claude install --scope project
280
+ git add .claude/settings.json && git commit -m "chore: enable prim in Claude Code"
281
+ ```
282
+
283
+ A repository that commits prim's project install keeps using it: the user-scope hooks
284
+ step aside there, so nothing fires twice. Committed hooks run for everyone who opens the
285
+ repository in Claude Code; where prim is not installed they do nothing. Upgrade prim
286
+ across a team before committing a new project install: older releases fail `prim doctor`
287
+ on such a file, and the reinstall they suggest restores the earlier text.
288
+
289
+ #### An environment your organization shares
290
+
291
+ The credentials above belong to one person: in an environment several people use, every
292
+ session's work would be attributed to whoever minted them. For an environment the whole
293
+ organization shares, an organization admin creates an environment credential instead.
294
+ It can do one thing: identify sessions. Each session's work is then attributed to the
295
+ member who started it.
296
+
297
+ 1. **The admin creates the credential once**, on their own machine:
298
+
299
+ ```bash
300
+ npx --yes @primitive.ai/prim@latest auth enroll --new-environment "Team cloud" --print-env
301
+ ```
302
+
303
+ It prints `PRIM_M2M_CLIENT_ID`, `PRIM_M2M_CLIENT_SECRET`, and
304
+ `PRIM_CLOUD_IDENTITY=session` (plus `PRIM_API_URL` for a non-default deployment).
305
+
306
+ 2. **The admin configures the shared environment** as in the steps above, with these
307
+ differences:
308
+ - **Credentials**: every member can read a shared environment's variables, so hold
309
+ the secret as a **Username and password** network secret for host
310
+ `signin.getprimitive.ai` (username: the client ID, password: the client secret).
311
+ Set these **Environment variables**, keeping any other line the command printed
312
+ except `PRIM_M2M_CLIENT_SECRET`:
313
+
314
+ ```text
315
+ PRIM_M2M_CLIENT_ID=client_...
316
+ PRIM_M2M_CLIENT_AUTH=network-secret
317
+ PRIM_CLOUD_IDENTITY=session
318
+ ```
319
+
320
+ Put `PRIM_M2M_CLIENT_SECRET` in the variables only in an environment no one else
321
+ uses.
322
+ - **Network access** and the **Setup script** are the same as above:
323
+ `api.getprimitive.ai` and `signin.getprimitive.ai` under Allowed domains, and
324
+ `npx --yes @primitive.ai/prim@latest setup --cloud --prepare`.
325
+
326
+ 3. **Each member links their GitHub account once**, in their first session. Session
327
+ start tells them their GitHub account is not linked yet; the agent runs
328
+ `prim auth link`, which prints a sign-in URL and a code. The member signs in to
329
+ Primitive as themselves, and the session is attributed to them from then on. The
330
+ sign-in is used for the link alone and is not stored.
331
+
332
+ After that, every session identifies its member with no action. At the start of each
333
+ session, prim creates the session's `claude/…` branch on GitHub at its starting commit
334
+ (Claude Code would create the same branch when it first pushes); Claude Code pushes as
335
+ the GitHub account of the person who started the session, which is how Primitive learns
336
+ whose session it is. Prim never force-pushes it, sets no upstream, and pushes nothing
337
+ else. The member's token stays in the session's VM (owner-only, in prim's config
338
+ directory) and lasts 12 hours, renewed while the session runs; a new session identifies
339
+ again. Until a session is identified, nothing it captures is sent to Primitive, and a
340
+ session that never identifies sends nothing as anyone.
341
+
342
+ `prim setup --cloud` reports this as its `identity` step, `prim auth status` names the
343
+ member the session acts as, and `prim doctor`'s `auth` line names the person the
344
+ session is attributed to. Identification fails, with the fix named, when the session's
345
+ checkout is not on its `claude/…` branch, when that branch is already on GitHub (a
346
+ resumed session whose token lapsed, or one whose branch was pushed first: start a new
347
+ session), when the push is refused, when GitHub's notice of the push does not reach
348
+ Primitive within 15 seconds (check that Primitive's GitHub App has access to the
349
+ repository), or when the repository is not connected to Primitive.
350
+
157
351
  ## Commands
158
352
 
159
353
  ### Setup
@@ -165,6 +359,8 @@ prim setup --agent codex # Same, for OpenAI Codex
165
359
  prim setup --agent hermes # Same, for Hermes Agent (global-only config)
166
360
  prim setup --no-daemon # Stop it and persistently opt out of supervised delivery
167
361
  prim setup --global-hooks-path # Also route every repository's git hooks through prim
362
+ prim setup --cloud --prepare # Claude Code cloud setup script: stage the hook runtime
363
+ prim setup --cloud # Claude Code cloud session: verify credentials, wire git hooks, activate
168
364
  ```
169
365
 
170
366
  Orchestrates auth → session hooks → supervised daemon → git hooks (`--scope project`, or `--global-hooks-path`) → skill → activate this repo (which wires its git hooks) → capture-health gate → welcome,
@@ -199,6 +395,10 @@ prim auth login # Authenticate via browser
199
395
  prim auth set-token <token> # Save a bearer token (e.g. for CI)
200
396
  prim auth clear # Remove saved tokens
201
397
  prim auth status # Check authentication status
398
+ prim auth enroll --new-installation <name> --print-env # Credentials for a cloud environment
399
+ prim auth enroll --new-environment <name> --print-env # Organization credential for a shared cloud environment
400
+ prim auth identify # Identify who started this cloud session (shared environments)
401
+ prim auth link # Link your GitHub account to Primitive, once, from a cloud session
202
402
  prim auth api-keys mint --name <name> [--expires-at <epoch-ms>] # Mint a user key; secret prints once
203
403
  prim auth api-keys list [--limit <count>] [--after <api-key-id>] # List user-key metadata
204
404
  prim auth api-keys revoke <api-key-id> # Revoke a user key
@@ -263,7 +463,17 @@ but the edit gate sees the changed gameplan path.
263
463
 
264
464
  Passive capture is repo-scoped even when these integrations are installed at user
265
465
  scope. `prim enable` marks the current Git repo active; `prim disable` makes it
266
- inactive. A project-scoped install activates its repo automatically. In an inactive
466
+ inactive. A project-scoped install activates its repo automatically. Both commands
467
+ act on your clone alone. `prim disable --scope project` also records the repository's
468
+ own opt-out, `PRIM_ACTIVE=false` under `env` in `.claude/settings.json`, for you to
469
+ commit: prim reads it from that file (never from the environment), and it turns off
470
+ automatic activation in every clone, including a project-scoped install's and a
471
+ prepared Claude Code cloud environment's. A `prim.active=true` you set yourself still
472
+ wins: `prim enable` in a clone, or the global flag for every repository. A clone that
473
+ prim had already activated automatically is turned off at its next agent session
474
+ after it receives the opt-out; one activated that way by an earlier prim version
475
+ cannot be told apart from `prim enable` and stays on until `prim disable`.
476
+ `prim enable --scope project` removes the opt-out. In an inactive
267
477
  repo, session content is not passively captured. Here “inactive” means Prim's normal
268
478
  effective capture check is false, including an explicit local `prim.active=false`.
269
479
 
package/SKILL.md CHANGED
@@ -17,6 +17,8 @@ Low-level capture runs automatically in active repos through the session hooks i
17
17
 
18
18
  Run `npx --yes @primitive.ai/prim auth status` first. It exits **0 if authenticated, 1 if not** -- branch on the exit code, don't parse the message.
19
19
 
20
+ **Claude Code cloud sessions** (`CLAUDE_CODE_REMOTE=true`): never run `auth login` or `auth enroll` there; prim authenticates cloud sessions only with credentials from the environment and refuses interactive sign-in. Use machine credentials (a fixed `PRIM_TOKEN` also works): `PRIM_M2M_CLIENT_ID` with `PRIM_M2M_CLIENT_SECRET`, or with `PRIM_M2M_CLIENT_AUTH=network-secret` when the secret is a network secret, or `PRIM_M2M_CLIENT_AUTH=network-token` when the environment's proxy holds the tokens too (an OAuth 2.0 client credentials network secret). When `auth status` fails, run `npx --yes @primitive.ai/prim setup --cloud` and relay each entry of its `remedies` to the user; the user mints credentials on their own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`.
21
+
20
22
  Three ways to authenticate, in priority order:
21
23
 
22
24
  1. **`PRIM_TOKEN` environment variable** -- preferred for agents and CI. Set it before invoking prim and you're done; no interactive flow, no token files.
@@ -108,7 +110,10 @@ These questions share the interruption budget below; never ask separate question
108
110
 
109
111
  When passive capture is inactive for the current repo, do not silently turn a durable
110
112
  decision into a write. “Inactive” means Prim's effective repo-capture check is false;
111
- an explicit local `prim.active=false` is always inactive. Every
113
+ an explicit local `prim.active=false` is always inactive, and so is a repository
114
+ that commits its own opt-out (`PRIM_ACTIVE=false` under `env` in
115
+ `.claude/settings.json`) unless the user turned prim on themselves (`prim enable`
116
+ in that clone, or a global `prim.active=true`). Every
112
117
  `prim decisions create` invocation needs fresh user approval:
113
118
 
114
119
  - An explicit request to record or create that Decision is approval for that one
@@ -1,4 +1,5 @@
1
1
  import {
2
+ CLOUD_CREDENTIALS_REMEDY,
2
3
  CREDENTIAL_FAMILY_PATH,
3
4
  CREDENTIAL_LOCK_PATH,
4
5
  CREDENTIAL_METADATA_PATH,
@@ -15,7 +16,9 @@ import {
15
16
  atomicWriteFile,
16
17
  cachedMachineCredential,
17
18
  ensureDurableDirectory,
19
+ forwardMachineRequest,
18
20
  hasMachineConfiguration,
21
+ isClaudeCloudSession,
19
22
  jwtExpiresAt,
20
23
  machineContext,
21
24
  machineSessionEnded,
@@ -25,11 +28,13 @@ import {
25
28
  readBoundedJson,
26
29
  readCredentialMigrationState,
27
30
  readStoredCredentialMetadata,
31
+ rejectedCredentialsMessage,
28
32
  resolveAuthCredential,
29
33
  syncDirectory,
34
+ terminalSafeLine,
30
35
  withFileLock,
31
36
  workosConnectTokenEndpoint
32
- } from "./chunk-NJBN3WXF.js";
37
+ } from "./chunk-6QAXVFRJ.js";
33
38
 
34
39
  // src/decisions/identity.ts
35
40
  var PUBLIC_ID = /^dec_[0-9a-f]{8}$/u;
@@ -108,51 +113,6 @@ function publicDecisionResponse(value) {
108
113
  return replace(projected);
109
114
  }
110
115
 
111
- // src/lib/terminal-safe.ts
112
- function replaceIsolatedSurrogates(value) {
113
- let out = "";
114
- for (let index = 0; index < value.length; index += 1) {
115
- const unit = value.charCodeAt(index);
116
- if (unit >= 55296 && unit <= 56319) {
117
- const next = value.charCodeAt(index + 1);
118
- if (next >= 56320 && next <= 57343) {
119
- out += value[index] + value[index + 1];
120
- index += 1;
121
- } else {
122
- out += "\uFFFD";
123
- }
124
- } else if (unit >= 56320 && unit <= 57343) {
125
- out += "\uFFFD";
126
- } else {
127
- out += value[index];
128
- }
129
- }
130
- return out;
131
- }
132
- function isUnsafeTerminalCodePoint(point) {
133
- const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
134
- const bidiOrZeroWidth = point === 173 || // soft hyphen
135
- point === 1564 || // Arabic letter mark
136
- point === 6158 || // Mongolian vowel separator
137
- point >= 8203 && point <= 8207 || // zero-width + directional marks
138
- point >= 8234 && point <= 8238 || // bidi embeddings/overrides
139
- point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
140
- point >= 65529 && point <= 65531 || // interlinear annotation controls
141
- point === 65279 || // zero-width no-break space / BOM
142
- point >= 917504 && point <= 917631;
143
- return c0OrC1 || bidiOrZeroWidth;
144
- }
145
- function terminalSafeText(value) {
146
- return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
147
- }
148
- function terminalSafeLine(value) {
149
- return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
150
- }
151
- function isTerminalSafeText(value) {
152
- return terminalSafeText(value) === value;
153
- }
154
- var stripControlChars = terminalSafeText;
155
-
156
116
  // src/client.ts
157
117
  import { createHash } from "crypto";
158
118
  import { chmodSync as chmodSync2, existsSync, mkdirSync, readFileSync as readFileSync2, rmSync } from "fs";
@@ -263,6 +223,9 @@ var CREDENTIAL_FILE_MODE = 384;
263
223
  var REFRESH_THRESHOLD_MS = 6e4;
264
224
  var DEFAULT_API_URL = "https://api.getprimitive.ai";
265
225
  var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
226
+ function authExpiredMessage() {
227
+ return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
228
+ }
266
229
  function readTrimmed(path) {
267
230
  try {
268
231
  const value = readFileSync2(path, "utf8").trim();
@@ -699,7 +662,7 @@ var CliManagementResponseError = class extends Error {
699
662
  var CLI_MANAGEMENT_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
700
663
  async function managementResponseValue(response) {
701
664
  if (response.status === 401) {
702
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
665
+ throw new HttpError(401, authExpiredMessage());
703
666
  }
704
667
  let value;
705
668
  try {
@@ -721,23 +684,50 @@ function selectedCredential() {
721
684
  }
722
685
  return _cachedCredential;
723
686
  }
687
+ async function requestHeaders(method, path) {
688
+ return {
689
+ "Content-Type": "application/json",
690
+ ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
691
+ };
692
+ }
724
693
  async function fetchWithToken(method, path, body, options, token, siteUrl) {
725
694
  return fetch(`${siteUrl}${path}`, {
726
695
  method,
727
- headers: {
728
- Authorization: `Bearer ${token}`,
729
- "Content-Type": "application/json",
730
- ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
731
- },
696
+ headers: { Authorization: `Bearer ${token}`, ...await requestHeaders(method, path) },
732
697
  body: body === void 0 ? void 0 : JSON.stringify(body),
733
698
  signal: options?.signal,
734
699
  redirect: options?.redirect
735
700
  });
736
701
  }
702
+ async function fetchAsMachine(credential, method, path, body, options) {
703
+ if (!credential.tokenInjection)
704
+ return fetchWithToken(
705
+ method,
706
+ path,
707
+ body,
708
+ { ...options, redirect: "error" },
709
+ credential.accessToken,
710
+ credential.apiUrl
711
+ );
712
+ try {
713
+ return await forwardMachineRequest(
714
+ {
715
+ method,
716
+ path,
717
+ headers: await requestHeaders(method, path),
718
+ ...body === void 0 ? {} : { body: JSON.stringify(body) }
719
+ },
720
+ options.signal
721
+ );
722
+ } catch (error) {
723
+ if (!(error instanceof MachineAuthError)) throw error;
724
+ throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
725
+ }
726
+ }
737
727
  async function responseValue(response) {
738
728
  if (!response.ok) {
739
729
  if (response.status === 401) {
740
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
730
+ throw new HttpError(401, authExpiredMessage());
741
731
  }
742
732
  const errorBody = await response.json().catch(() => null);
743
733
  const errorRecord = typeof errorBody === "object" && errorBody !== null && !Array.isArray(errorBody) ? errorBody : void 0;
@@ -764,14 +754,7 @@ async function machineClient(options = {}, management = false) {
764
754
  const current = await acquireMachineCredential({ signal: requestOptions.signal });
765
755
  if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
766
756
  throw new HttpError(409, "Machine identity changed; restart the operation.");
767
- let response = await fetchWithToken(
768
- method,
769
- path,
770
- body,
771
- { ...requestOptions, redirect: "error" },
772
- current.accessToken,
773
- selected.apiUrl
774
- );
757
+ let response = await fetchAsMachine(current, method, path, body, requestOptions);
775
758
  if (response.status === 401) {
776
759
  const renewed = await acquireMachineCredential({
777
760
  force: true,
@@ -780,19 +763,14 @@ async function machineClient(options = {}, management = false) {
780
763
  if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
781
764
  throw new HttpError(409, "Machine identity changed; restart the operation.");
782
765
  }
783
- response = await fetchWithToken(
784
- method,
785
- path,
786
- body,
787
- { ...requestOptions, redirect: "error" },
788
- renewed.accessToken,
789
- renewed.apiUrl
790
- );
766
+ response = await fetchAsMachine(renewed, method, path, body, requestOptions);
791
767
  }
792
768
  if (response.status === 401)
793
769
  throw new HttpError(
794
770
  401,
795
- "Machine access was rejected. Ask your administrator to check or rotate its credentials."
771
+ selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
772
+ "Machine access was rejected. Ask your administrator to check or rotate its credentials."
773
+ )
796
774
  );
797
775
  return parse(response);
798
776
  };
@@ -818,10 +796,10 @@ async function request(method, path, body, options) {
818
796
  if (token) credential = { token, source: "token_file" };
819
797
  }
820
798
  if (!credential) {
821
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
799
+ throw new HttpError(401, authExpiredMessage());
822
800
  }
823
801
  if (isTokenExpiringSoon(credential) && isSessionEnded()) {
824
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
802
+ throw new HttpError(401, authExpiredMessage());
825
803
  }
826
804
  const tokenUsed = credential.token;
827
805
  let response = await fetchWithToken(method, path, body, options, tokenUsed, siteUrl);
@@ -861,7 +839,7 @@ async function getPinnedClient(options = {}) {
861
839
  if (token2) credential = { token: token2, source: "token_file" };
862
840
  }
863
841
  if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
864
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
842
+ throw new HttpError(401, authExpiredMessage());
865
843
  }
866
844
  const token = credential.token;
867
845
  const pinnedRequest = async (method, path, body, requestOptions) => responseValue(await fetchWithToken(method, path, body, requestOptions, token, siteUrl));
@@ -870,6 +848,22 @@ async function getPinnedClient(options = {}) {
870
848
  post: (path, body, requestOptions) => pinnedRequest("POST", path, body, requestOptions)
871
849
  };
872
850
  }
851
+ function getBearerClient(token, siteUrl) {
852
+ const pinnedRequest = async (method, path, body, requestOptions) => responseValue(
853
+ await fetchWithToken(
854
+ method,
855
+ path,
856
+ body,
857
+ { ...requestOptions, redirect: "error" },
858
+ token,
859
+ siteUrl
860
+ )
861
+ );
862
+ return {
863
+ get: (path, requestOptions) => pinnedRequest("GET", path, void 0, requestOptions),
864
+ post: (path, body, requestOptions) => pinnedRequest("POST", path, body, requestOptions)
865
+ };
866
+ }
873
867
  async function getPinnedManagementClient(options = {}) {
874
868
  const machine = await machineClient(options, true);
875
869
  if (machine) return machine;
@@ -883,7 +877,7 @@ async function getPinnedManagementClient(options = {}) {
883
877
  if (token2) credential = { token: token2, source: "token_file" };
884
878
  }
885
879
  if (!credential || isTokenExpiringSoon(credential) && isSessionEnded()) {
886
- throw new HttpError(401, AUTH_EXPIRED_MESSAGE);
880
+ throw new HttpError(401, authExpiredMessage());
887
881
  }
888
882
  const token = credential.token;
889
883
  const pinnedRequest = async (method, path, body, requestOptions) => managementResponseValue(
@@ -898,10 +892,7 @@ async function getPinnedManagementClient(options = {}) {
898
892
 
899
893
  export {
900
894
  decisionIdentifier,
901
- terminalSafeText,
902
- terminalSafeLine,
903
- isTerminalSafeText,
904
- stripControlChars,
895
+ DEFAULT_API_URL,
905
896
  getSiteUrl,
906
897
  getSiteUrlForEnvironment,
907
898
  getTokenExpiresAt,
@@ -914,5 +905,6 @@ export {
914
905
  CliManagementResponseError,
915
906
  getClient,
916
907
  getPinnedClient,
908
+ getBearerClient,
917
909
  getPinnedManagementClient
918
910
  };
@@ -1,12 +1,10 @@
1
1
  import {
2
2
  boundedHealthError
3
- } from "./chunk-O73J3KQQ.js";
3
+ } from "./chunk-NYDM4HSS.js";
4
4
  import {
5
+ hasMachineConfiguration,
5
6
  stripControlChars
6
- } from "./chunk-ZKXNJB6U.js";
7
- import {
8
- hasMachineConfiguration
9
- } from "./chunk-NJBN3WXF.js";
7
+ } from "./chunk-6QAXVFRJ.js";
10
8
 
11
9
  // src/lib/delivery-backlog.ts
12
10
  var MS_PER_SECOND = 1e3;