@primitive.ai/prim 0.1.0-alpha.123 → 0.1.0-alpha.124

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 +63 -0
  2. package/dist/{chunk-5ME3WD3P.js → chunk-3OKVMKK2.js} +6 -3
  3. package/dist/chunk-5BZWFN62.js +206 -0
  4. package/dist/{chunk-FXXMDO7D.js → chunk-5KPDY5GF.js} +4 -4
  5. package/dist/{chunk-HLMC7VS4.js → chunk-5MH2C5QG.js} +3878 -2644
  6. package/dist/{chunk-NMZSCSMY.js → chunk-6PSCGY2A.js} +11 -1
  7. package/dist/{chunk-OXW6PSPT.js → chunk-6VJ7C2B5.js} +15 -3
  8. package/dist/{chunk-DQ4I3FLF.js → chunk-6W72SEXC.js} +3 -3
  9. package/dist/{chunk-4M23K2KZ.js → chunk-6WKJWW6D.js} +2 -2
  10. package/dist/{chunk-3WQ7SBOZ.js → chunk-A6YTFBQ4.js} +3 -3
  11. package/dist/{chunk-NL5VU7EU.js → chunk-DGZX3MID.js} +3 -3
  12. package/dist/{chunk-4NUGCUQC.js → chunk-EER7VG3P.js} +2 -2
  13. package/dist/{chunk-JZC2LHS6.js → chunk-EWV7VIZ3.js} +1 -1
  14. package/dist/{chunk-WN7OURQ3.js → chunk-KMWXI7KO.js} +1 -1
  15. package/dist/{chunk-LOFMI3D4.js → chunk-KTXJJE5K.js} +2 -2
  16. package/dist/{chunk-4GYJHN26.js → chunk-Q2PVD5W2.js} +1575 -549
  17. package/dist/{chunk-S3ZIMGXV.js → chunk-QZWLZH6D.js} +76 -2
  18. package/dist/{chunk-CWV5ZQR6.js → chunk-TS2NX6YT.js} +5 -5
  19. package/dist/{chunk-GOMEWFMG.js → chunk-WLVEXOHC.js} +143 -61
  20. package/dist/{chunk-RUEIVZ6T.js → chunk-WQFJ5TEG.js} +2 -2
  21. package/dist/{chunk-T2T45KF6.js → chunk-ZMH6GJUG.js} +4 -4
  22. package/dist/daemon/server.js +7795 -5449
  23. package/dist/hook-runtime/daemon/server.js +7795 -5449
  24. package/dist/hook-runtime/hooks/post-commit.js +5828 -4329
  25. package/dist/hook-runtime/hooks/post-rewrite.js +4331 -2833
  26. package/dist/hook-runtime/hooks/post-tool-use.js +5241 -2891
  27. package/dist/hook-runtime/hooks/pre-commit.js +1253 -280
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +4177 -1971
  29. package/dist/hook-runtime/hooks/prim-hook.js +4718 -2478
  30. package/dist/hook-runtime/hooks/session-end.js +392 -139
  31. package/dist/hook-runtime/hooks/session-start.js +4206 -1997
  32. package/dist/hook-runtime/index.js +6155 -3542
  33. package/dist/hook-runtime/statusline-main.js +368 -122
  34. package/dist/hooks/post-commit.js +7 -7
  35. package/dist/hooks/post-rewrite.js +6 -6
  36. package/dist/hooks/post-tool-use.js +31 -21
  37. package/dist/hooks/pre-commit.js +4 -4
  38. package/dist/hooks/pre-tool-use-worker.js +9 -9
  39. package/dist/hooks/prim-hook.js +16 -16
  40. package/dist/hooks/session-end.js +4 -4
  41. package/dist/hooks/session-start.js +16 -12
  42. package/dist/index.js +229 -149
  43. package/dist/statusline-main.js +368 -122
  44. package/package.json +3 -1
  45. package/dist/chunk-RRAC76LJ.js +0 -36
package/dist/index.js CHANGED
@@ -22,30 +22,35 @@ import {
22
22
  uninstallProjectGitHook,
23
23
  userTargetFor,
24
24
  welcomeSkillPathFor
25
- } from "./chunk-NL5VU7EU.js";
25
+ } from "./chunk-DGZX3MID.js";
26
26
  import {
27
- requireDurableIngestAcknowledgement
28
- } from "./chunk-RRAC76LJ.js";
27
+ InvalidJournalEnvelopeError,
28
+ buildOrganizationBoundMoveRequest,
29
+ classifyJournalBuckets,
30
+ inspectJournalDelivery,
31
+ requireDurableIngestAcknowledgement,
32
+ summarizeRetainedBuckets
33
+ } from "./chunk-5BZWFN62.js";
29
34
  import {
30
35
  checkAffectedDecisions,
31
36
  daemonOrDirectGet,
32
37
  formatDecisionsWarning
33
- } from "./chunk-DQ4I3FLF.js";
38
+ } from "./chunk-6W72SEXC.js";
34
39
  import {
35
40
  hasCompleteCoverage,
36
41
  requestPreflight2 as requestPreflight,
37
42
  waitForPreflight
38
- } from "./chunk-CWV5ZQR6.js";
43
+ } from "./chunk-TS2NX6YT.js";
39
44
  import {
40
45
  fetchFeedbackCapability
41
- } from "./chunk-JZC2LHS6.js";
46
+ } from "./chunk-EWV7VIZ3.js";
42
47
  import {
43
48
  POST_COMMIT_GRACE_MS,
44
49
  clearHooksWired,
45
50
  inspectPostCommitFiring,
46
51
  lastConversationCaptured,
47
52
  recordHooksWired
48
- } from "./chunk-WN7OURQ3.js";
53
+ } from "./chunk-KMWXI7KO.js";
49
54
  import {
50
55
  isUnattended,
51
56
  unattendedEnv
@@ -58,7 +63,7 @@ import {
58
63
  formatStatusline,
59
64
  formatTeammates,
60
65
  repositoryBindingDiagnosticLabel
61
- } from "./chunk-5ME3WD3P.js";
66
+ } from "./chunk-3OKVMKK2.js";
62
67
  import {
63
68
  JOURNAL_DIR,
64
69
  SESSIONS_DIR,
@@ -73,11 +78,11 @@ import {
73
78
  rotationIdentity,
74
79
  sweepOrphanedDrainProgress,
75
80
  writeDrainCheckpoint
76
- } from "./chunk-OXW6PSPT.js";
81
+ } from "./chunk-6VJ7C2B5.js";
77
82
  import {
78
83
  daemonIsLive,
79
84
  daemonRequest
80
- } from "./chunk-NMZSCSMY.js";
85
+ } from "./chunk-6PSCGY2A.js";
81
86
  import {
82
87
  RUN_ID,
83
88
  demoCommand,
@@ -98,7 +103,7 @@ import {
98
103
  readRun,
99
104
  runIds,
100
105
  saveRun
101
- } from "./chunk-3WQ7SBOZ.js";
106
+ } from "./chunk-A6YTFBQ4.js";
102
107
  import {
103
108
  MANAGED_GIT_HOOK_NAMES,
104
109
  assertOwnedHookRuntime,
@@ -124,8 +129,8 @@ import {
124
129
  stableNodePath,
125
130
  stageHookRuntime,
126
131
  stripCommand
127
- } from "./chunk-GOMEWFMG.js";
128
- import "./chunk-4NUGCUQC.js";
132
+ } from "./chunk-WLVEXOHC.js";
133
+ import "./chunk-EER7VG3P.js";
129
134
  import {
130
135
  bold,
131
136
  boundedHealthError,
@@ -147,10 +152,9 @@ import {
147
152
  isGitHubInstallIntentStartErrorResponse,
148
153
  isGitHubInstallIntentStartResponse,
149
154
  isGitHubInstallIntentStatusResponse,
150
- isMoveIngestRequest,
151
155
  isReconcileResolutionResponse,
152
156
  stripAnsi
153
- } from "./chunk-HLMC7VS4.js";
157
+ } from "./chunk-5MH2C5QG.js";
154
158
  import {
155
159
  CliManagementResponseError,
156
160
  HttpError,
@@ -168,27 +172,34 @@ import {
168
172
  setStoredToken,
169
173
  stripControlChars,
170
174
  terminalSafeLine
171
- } from "./chunk-S3ZIMGXV.js";
175
+ } from "./chunk-QZWLZH6D.js";
172
176
  import {
177
+ MachineAuthError,
173
178
  REFRESH_TOKEN_PATH,
174
179
  TOKEN_FILE_PATH,
175
180
  WorkosConnectProtocolError,
181
+ acquireMachineCredential,
176
182
  atomicWriteFile,
177
183
  binFile,
178
184
  canonicalGitRoot,
179
185
  canonicalRepositoryPath,
180
186
  clearDemoPause,
187
+ clearMachineCredentials,
181
188
  commandMatchesBin,
182
189
  compareSemver,
190
+ configureMachine,
183
191
  decisionIngestionStatus,
184
192
  discoverWorkosConnect,
185
193
  endDemoPause,
194
+ environmentCredentials,
186
195
  extendDemoPause,
187
196
  gitToplevel,
197
+ hasMachineConfiguration,
188
198
  healDemoPause,
189
199
  hookCommandResolutions,
190
200
  isRepoActiveForCapture,
191
201
  isValidRepoSyncId,
202
+ machineContext,
192
203
  mainWorktreeRoot,
193
204
  packageRoot,
194
205
  packageVersion,
@@ -198,6 +209,7 @@ import {
198
209
  primConfigDirectory,
199
210
  processIsAlive,
200
211
  readDemoPause,
212
+ readMachineProfile,
201
213
  repoActiveFlag,
202
214
  repoSyncId,
203
215
  repositoryBindingState,
@@ -206,9 +218,10 @@ import {
206
218
  setRepoActive,
207
219
  stableHookCommand,
208
220
  syncDirectory,
221
+ verifyMachineIdentity,
209
222
  withFileLock,
210
223
  withFileLockSync
211
- } from "./chunk-4GYJHN26.js";
224
+ } from "./chunk-Q2PVD5W2.js";
212
225
  import "./chunk-JSBRDJBE.js";
213
226
 
214
227
  // src/index.ts
@@ -224,8 +237,8 @@ function isNonInteractive(globals) {
224
237
  }
225
238
  async function askConfirmation(question, output = process.stdout) {
226
239
  if (!process.stdin.isTTY) return false;
227
- const { createInterface: createInterface2 } = await import("readline/promises");
228
- const rl = createInterface2({ input: process.stdin, output });
240
+ const { createInterface: createInterface3 } = await import("readline/promises");
241
+ const rl = createInterface3({ input: process.stdin, output });
229
242
  try {
230
243
  const answer = await rl.question(`${question} [y/N] `);
231
244
  const normalized = answer.trim().toLowerCase();
@@ -347,6 +360,8 @@ import { createHash, randomBytes as randomBytes2 } from "crypto";
347
360
  import { existsSync, readFileSync } from "fs";
348
361
  import { createServer } from "http";
349
362
  import { platform } from "os";
363
+ import { createInterface } from "readline";
364
+ import { Writable } from "stream";
350
365
 
351
366
  // src/auth/api-keys.ts
352
367
  import { randomBytes } from "crypto";
@@ -927,6 +942,62 @@ function authStatusResult(status2, reason, source, refreshTokenPresent) {
927
942
  };
928
943
  }
929
944
  async function verifyAuthStatus() {
945
+ let machineMetadata = {};
946
+ try {
947
+ if (hasMachineConfiguration()) {
948
+ const context = machineContext();
949
+ machineMetadata = {
950
+ principalKind: "machine",
951
+ machineId: context?.machineId,
952
+ displayName: context?.displayName,
953
+ organizationId: context?.organizationId,
954
+ storageBackend: process.env.PRIM_M2M_CLIENT_ID ? "environment" : readMachineProfile()?.storage
955
+ };
956
+ const machine = await acquireMachineCredential({
957
+ signal: AbortSignal.timeout(AUTH_PROBE_TIMEOUT_MS)
958
+ });
959
+ if (!machine) throw new Error("missing machine");
960
+ machineMetadata = {
961
+ ...machineMetadata,
962
+ accessTokenExpiresInMs: machine.expiresAt - Date.now(),
963
+ accessTokenExpired: machine.expiresAt <= Date.now()
964
+ };
965
+ const identity = await verifyMachineIdentity(
966
+ machine.apiUrl,
967
+ machine.accessToken,
968
+ machine.clientId
969
+ );
970
+ return {
971
+ ...authStatusResult("valid", "verified", "machine", false),
972
+ principalKind: "machine",
973
+ machineId: machine.machineId,
974
+ displayName: identity.displayName,
975
+ effectiveScopes: identity.scopes,
976
+ organizationId: machine.organizationId,
977
+ storageBackend: machine.storage,
978
+ accessTokenExpiresInMs: machine.expiresAt - Date.now(),
979
+ accessTokenExpired: machine.expiresAt <= Date.now()
980
+ };
981
+ }
982
+ } catch (error) {
983
+ const invalid = error instanceof MachineAuthError && (error.terminal || [
984
+ "incomplete_machine_credentials",
985
+ "conflicting_credentials",
986
+ "deployment_mismatch",
987
+ "invalid_storage"
988
+ ].includes(error.code));
989
+ return {
990
+ ...authStatusResult(
991
+ invalid ? "invalid" : "unreachable",
992
+ invalid ? "access_rejected" : "verification_unavailable",
993
+ void 0,
994
+ false
995
+ ),
996
+ ...machineMetadata,
997
+ principalKind: "machine",
998
+ recoveryReason: error instanceof MachineAuthError ? error.code : "verification_unavailable"
999
+ };
1000
+ }
930
1001
  const credential = resolveAuthCredential();
931
1002
  if (!credential) {
932
1003
  return authStatusResult("invalid", "missing_credentials", void 0, false);
@@ -992,6 +1063,12 @@ function authStatusExitCode(status2) {
992
1063
  return status2 === "invalid" ? EXIT_FAIL : EXIT_UNREACHABLE;
993
1064
  }
994
1065
  function writeHumanAuthStatus(result) {
1066
+ if (result.principalKind === "machine") {
1067
+ console.error(
1068
+ result.authenticated ? `Machine ${result.machineId}: verified (${result.storageBackend}); organization ${result.organizationId}.` : `Machine authentication ${result.status}: ${result.recoveryReason}. Check the credential store or run prim auth configure-machine with credentials from your administrator.`
1069
+ );
1070
+ return;
1071
+ }
995
1072
  if (result.status === "invalid") {
996
1073
  const detail = result.reason === "refresh_rejected" ? "The saved session was rejected." : result.reason === "access_rejected" ? "The selected access token was rejected." : "No credentials were found.";
997
1074
  console.log(`${detail} Run \`prim auth login\` to authenticate.`);
@@ -1021,10 +1098,54 @@ function writeHumanAuthStatus(result) {
1021
1098
  );
1022
1099
  for (const warning of result.warnings) console.log(`Warning: ${warning}`);
1023
1100
  }
1101
+ function requiresLegacyAuthentication() {
1102
+ if (!hasMachineConfiguration()) return true;
1103
+ reportFailure(
1104
+ "machine_operation_not_supported",
1105
+ "This installation uses machine credentials. Manage API keys and sign-in in the web application; use configure-machine to rotate machine credentials."
1106
+ );
1107
+ return false;
1108
+ }
1024
1109
  function registerAuthCommands(program2) {
1025
1110
  const auth = program2.command("auth").description("Manage CLI authentication");
1111
+ auth.command("configure-machine").description("Configure administrator-issued WorkOS machine credentials").requiredOption("--client-id <id>", "WorkOS M2M application client ID").option("--client-secret-stdin", "Read the client secret from standard input").action(async (options) => {
1112
+ try {
1113
+ if (!options.clientSecretStdin && (isNonInteractive(program2.optsWithGlobals()) || process.env.PRIM_UNATTENDED))
1114
+ throw new MachineAuthError(
1115
+ "secret_input_required",
1116
+ "Pass --client-secret-stdin or inject machine credentials in non-interactive sessions."
1117
+ );
1118
+ const secret = await readMachineSecret(options.clientSecretStdin === true);
1119
+ const profile = await configureMachine(options.clientId, secret);
1120
+ console.error(
1121
+ `Machine credentials saved in ${profile.storage === "keychain" ? "the OS credential store" : "an owner-only credential file (OS store unavailable)"}.`
1122
+ );
1123
+ const retained = classifyJournalBuckets(
1124
+ listBuckets().map(({ bucket }) => bucket),
1125
+ { ...profile, captureAuthorityKind: "workos_m2m" }
1126
+ ).retainedBuckets;
1127
+ if (retained.length)
1128
+ console.error(
1129
+ `Captured activity retained under its original authority: ${summarizeRetainedBuckets(retained)}.`
1130
+ );
1131
+ printJson({
1132
+ retainedJournalBuckets: retained,
1133
+ authenticated: true,
1134
+ principalKind: "machine",
1135
+ machineId: profile.machineId,
1136
+ organizationId: profile.organizationId,
1137
+ storageBackend: profile.storage
1138
+ });
1139
+ } catch (error) {
1140
+ reportFailure(
1141
+ error instanceof MachineAuthError ? error.code : "machine_configuration_failed",
1142
+ error instanceof MachineAuthError ? error.message : "Machine configuration failed; no provider response or secret was logged."
1143
+ );
1144
+ }
1145
+ });
1026
1146
  const apiKeys = auth.command("api-keys").description("Mint, list, and revoke WorkOS user API keys");
1027
1147
  apiKeys.command("mint").description("Mint a user API key and return its secret once").requiredOption("--name <name>", "Name for the API key").option("--expires-at <epoch-ms>", "Optional expiration as Unix epoch milliseconds").action(async (options) => {
1148
+ if (!requiresLegacyAuthentication()) return;
1028
1149
  const expiresAt = options.expiresAt === void 0 ? void 0 : Number(options.expiresAt);
1029
1150
  process.exitCode = await mintUserApiKey({
1030
1151
  name: options.name,
@@ -1032,15 +1153,18 @@ function registerAuthCommands(program2) {
1032
1153
  });
1033
1154
  });
1034
1155
  apiKeys.command("list").description("List user API-key metadata (never plaintext secrets)").option("--limit <count>", "Maximum keys to return (1-100)", "100").option("--after <api-key-id>", "Continue after this API-key ID").action(async (options) => {
1156
+ if (!requiresLegacyAuthentication()) return;
1035
1157
  process.exitCode = await listUserApiKeys({
1036
1158
  limit: Number(options.limit),
1037
1159
  ...options.after === void 0 ? {} : { after: options.after }
1038
1160
  });
1039
1161
  });
1040
1162
  apiKeys.command("revoke <apiKeyId>").description("Revoke one API key owned by the current user and organization").action(async (apiKeyId) => {
1163
+ if (!requiresLegacyAuthentication()) return;
1041
1164
  process.exitCode = await revokeUserApiKey(apiKeyId);
1042
1165
  });
1043
1166
  auth.command("login").description("Authenticate via browser (WorkOS OAuth)").option("--no-browser", "Print the verification URL without opening a browser").action(async (options) => {
1167
+ if (!requiresLegacyAuthentication()) return;
1044
1168
  const siteUrl = getSiteUrl();
1045
1169
  let discovery;
1046
1170
  try {
@@ -1172,10 +1296,12 @@ ${authUrl.toString()}
1172
1296
  }
1173
1297
  });
1174
1298
  auth.command("set-token <token>").description("Save a bearer token for authenticated CLI calls").action(async (token) => {
1299
+ if (!requiresLegacyAuthentication()) return;
1175
1300
  await setStoredToken(token);
1176
1301
  console.log(`Token saved to ${TOKEN_FILE_PATH}`);
1177
1302
  });
1178
1303
  auth.command("clear").description("Remove the saved authentication token").action(async () => {
1304
+ const machineRemoved = await clearMachineCredentials();
1179
1305
  const removed = await clearStoredCredentials({
1180
1306
  beforeClear: async (refreshTokenValue, metadata) => {
1181
1307
  if (!refreshTokenValue || metadata.state !== "legacy_broker") return;
@@ -1200,7 +1326,7 @@ ${authUrl.toString()}
1200
1326
  }
1201
1327
  }
1202
1328
  });
1203
- if (removed) {
1329
+ if (removed || machineRemoved) {
1204
1330
  console.log("Local tokens removed.");
1205
1331
  } else {
1206
1332
  console.log("No saved tokens found.");
@@ -1213,6 +1339,40 @@ ${authUrl.toString()}
1213
1339
  process.exit(authStatusExitCode(result.status));
1214
1340
  });
1215
1341
  }
1342
+ async function readMachineSecret(fromStdin) {
1343
+ if (fromStdin) {
1344
+ let input2 = "";
1345
+ for await (const chunk of process.stdin) {
1346
+ input2 += String(chunk);
1347
+ if (Buffer.byteLength(input2) > 4098)
1348
+ throw new MachineAuthError("invalid_credentials", "Machine secret is too long.");
1349
+ }
1350
+ return input2.replace(/\r?\n$/u, "");
1351
+ }
1352
+ if (!process.stdin.isTTY || process.env.CI || process.env.PRIM_NON_INTERACTIVE) {
1353
+ throw new MachineAuthError(
1354
+ "secret_input_required",
1355
+ "Pass --client-secret-stdin or inject PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET."
1356
+ );
1357
+ }
1358
+ const muted = new Writable({
1359
+ write(_chunk, _encoding, done) {
1360
+ done();
1361
+ }
1362
+ });
1363
+ const input = createInterface({ input: process.stdin, output: muted, terminal: true });
1364
+ console.error("Machine client secret (hidden):");
1365
+ return new Promise((resolve8, reject) => {
1366
+ input.once("SIGINT", () => {
1367
+ input.close();
1368
+ reject(new MachineAuthError("cancelled", "Machine configuration cancelled."));
1369
+ });
1370
+ input.question("", (secret) => {
1371
+ input.close();
1372
+ resolve8(secret);
1373
+ });
1374
+ });
1375
+ }
1216
1376
  async function exchangeCode(siteUrl, code, codeVerifier, redirectUri) {
1217
1377
  const response = await fetch(`${siteUrl}/mcp/broker/token`, {
1218
1378
  method: "POST",
@@ -3524,6 +3684,12 @@ function daemonDriftHealClaimPath(options = {}) {
3524
3684
  return daemonControlPaths(options).driftHealClaim;
3525
3685
  }
3526
3686
  async function ensureMacDaemon(options = {}) {
3687
+ if (environmentCredentials({ env: options.env })) {
3688
+ throw new MachineAuthError(
3689
+ "machine_daemon_requires_environment",
3690
+ "Injected machine credentials require `prim daemon start --foreground` in the same environment. Stop any existing daemon first. To use launchd across logins, configure saved credentials with `prim auth configure-machine`."
3691
+ );
3692
+ }
3527
3693
  return withDaemonLifecycleLock(() => ensureMacDaemonLocked(options), options);
3528
3694
  }
3529
3695
  async function ensureMacDaemonLocked(options) {
@@ -3742,7 +3908,7 @@ function formatCurrentDaemonLifecycleMessage(message, snapshot) {
3742
3908
  function daemonDegradedReason(snapshot) {
3743
3909
  if (!snapshot || snapshot.healthy !== false) return void 0;
3744
3910
  if (snapshot.needsReauth) {
3745
- return "authentication requires `prim auth login`";
3911
+ return "authentication ended \u2014 run `prim auth status` for recovery instructions";
3746
3912
  }
3747
3913
  if (snapshot.heartbeat?.healthy === false) {
3748
3914
  const detail = boundedHealthError(snapshot.heartbeat.lastError);
@@ -3903,6 +4069,9 @@ async function detachedDaemonStart(opts) {
3903
4069
  }
3904
4070
  if (opts.foreground) {
3905
4071
  const child2 = spawnDaemon({ stdio: "inherit" });
4072
+ for (const signal of ["SIGTERM", "SIGINT"]) {
4073
+ process.once(signal, () => child2.kill(signal));
4074
+ }
3906
4075
  child2.on("exit", (code) => {
3907
4076
  process.exit(code ?? 0);
3908
4077
  });
@@ -6864,7 +7033,7 @@ function registerDecisionsCommands(program2) {
6864
7033
  // src/commands/demo.ts
6865
7034
  import { createHash as createHash3 } from "crypto";
6866
7035
  import { join as join8, resolve as resolve3 } from "path";
6867
- import { createInterface } from "readline/promises";
7036
+ import { createInterface as createInterface2 } from "readline/promises";
6868
7037
  import { diffLines } from "diff";
6869
7038
 
6870
7039
  // src/demo/api.ts
@@ -7475,7 +7644,7 @@ function reportError(error) {
7475
7644
  process.exitCode = 1;
7476
7645
  }
7477
7646
  async function terminalTour(run) {
7478
- const rl = createInterface({ input: process.stdin, output: process.stderr });
7647
+ const rl = createInterface2({ input: process.stdin, output: process.stderr });
7479
7648
  const show = (result) => {
7480
7649
  const text = result.presentation.replace(/^```(?:text|ts|diff)?\n/gmu, "").replace(/```/gu, "").replace(/\*\*(.*?)\*\*/gu, (_match, title) => bold(title));
7481
7650
  process.stderr.write(
@@ -7625,128 +7794,6 @@ function registerDemoCommands(program2) {
7625
7794
  import { existsSync as existsSync7 } from "fs";
7626
7795
  import { Option as Option4 } from "commander";
7627
7796
 
7628
- // src/protocol/decision-lifecycle.ts
7629
- var DECISION_LIFECYCLE_PROTOCOL_VERSION = 2;
7630
-
7631
- // src/journal-organization.ts
7632
- var ORGANIZATION_BINDING_VERSION = 1;
7633
- var ORGANIZATION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
7634
- var UNBOUND_BUCKET = "_unbound";
7635
- var InvalidJournalEnvelopeError = class extends Error {
7636
- constructor() {
7637
- super("Invalid locally journaled move");
7638
- this.name = "InvalidJournalEnvelopeError";
7639
- }
7640
- };
7641
- function safeOrganizationId(value) {
7642
- return typeof value === "string" && ORGANIZATION_ID_RE.test(value);
7643
- }
7644
- function isCaptureAuthorityKind(value) {
7645
- return value === "workos" || value === "service_token";
7646
- }
7647
- function parseOrganizationBinding(value) {
7648
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
7649
- return { state: "server_contract_unavailable" };
7650
- }
7651
- const record3 = value;
7652
- if (record3.authenticated !== true || record3.organizationBindingVersion !== ORGANIZATION_BINDING_VERSION || !isCaptureAuthorityKind(record3.captureAuthorityKind)) {
7653
- return { state: "server_contract_unavailable" };
7654
- }
7655
- if (record3.organizationId === null && record3.workosOrganizationId === null) {
7656
- return { state: "no_current_organization" };
7657
- }
7658
- if (safeOrganizationId(record3.organizationId) && record3.workosOrganizationId === null) {
7659
- return { state: "organization_identity_unreconciled" };
7660
- }
7661
- if (!safeOrganizationId(record3.organizationId) || !safeOrganizationId(record3.workosOrganizationId)) {
7662
- return { state: "server_contract_unavailable" };
7663
- }
7664
- return {
7665
- state: "current",
7666
- binding: {
7667
- captureAuthorityKind: record3.captureAuthorityKind,
7668
- organizationId: record3.organizationId,
7669
- workosOrganizationId: record3.workosOrganizationId
7670
- }
7671
- };
7672
- }
7673
- function summarizeRetainedBuckets(retained) {
7674
- const counts = /* @__PURE__ */ new Map();
7675
- for (const item of retained) {
7676
- counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
7677
- }
7678
- return [...counts].sort(([left], [right]) => left.localeCompare(right)).map(([reason, count]) => `${reason}:${String(count)}`).join(", ");
7679
- }
7680
- function classifyJournalBuckets(buckets, binding) {
7681
- const deliverableBuckets = /* @__PURE__ */ new Set();
7682
- const retainedBuckets = [];
7683
- for (const bucket of [...new Set(buckets)].sort()) {
7684
- if (bucket === UNBOUND_BUCKET) {
7685
- retainedBuckets.push({ bucket, reason: "unbound" });
7686
- continue;
7687
- }
7688
- if (typeof binding === "string") {
7689
- retainedBuckets.push({ bucket, reason: binding });
7690
- continue;
7691
- }
7692
- if (bucket === binding.organizationId || bucket === binding.workosOrganizationId) {
7693
- deliverableBuckets.add(bucket);
7694
- } else {
7695
- retainedBuckets.push({ bucket, reason: "organization_mismatch" });
7696
- }
7697
- }
7698
- return { deliverableBuckets, retainedBuckets };
7699
- }
7700
- function buildOrganizationBoundMoveRequest(batch, binding) {
7701
- const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
7702
- const request = {
7703
- batch: batch.map((move) => {
7704
- if (typeof move !== "object" || move === null || Array.isArray(move)) {
7705
- return move;
7706
- }
7707
- return {
7708
- ...move,
7709
- envelopeVersion: 4,
7710
- capturedOrganizationId,
7711
- captureAuthorityKind: binding.captureAuthorityKind,
7712
- decisionLifecycleProtocolVersion: DECISION_LIFECYCLE_PROTOCOL_VERSION
7713
- };
7714
- })
7715
- };
7716
- if (!isMoveIngestRequest(request)) {
7717
- throw new InvalidJournalEnvelopeError();
7718
- }
7719
- return request;
7720
- }
7721
- async function inspectJournalDelivery(buckets, options = {}) {
7722
- const bucketList = [...new Set(buckets)];
7723
- let client;
7724
- try {
7725
- client = options.client ?? await (options.createClient ?? (() => getPinnedClient()))();
7726
- } catch {
7727
- return classifyJournalBuckets(bucketList, "identity_unavailable");
7728
- }
7729
- let parsed;
7730
- try {
7731
- parsed = parseOrganizationBinding(
7732
- await client.get("/api/cli/auth/status", {
7733
- signal: AbortSignal.timeout(1e4),
7734
- quietRefresh: true
7735
- })
7736
- );
7737
- } catch {
7738
- return classifyJournalBuckets(bucketList, "identity_unavailable");
7739
- }
7740
- if (parsed.state !== "current") {
7741
- return classifyJournalBuckets(bucketList, parsed.state);
7742
- }
7743
- return {
7744
- client,
7745
- binding: parsed.binding,
7746
- ...classifyJournalBuckets(bucketList, parsed.binding)
7747
- };
7748
- }
7749
-
7750
7797
  // src/commands/hermes-install.ts
7751
7798
  import { existsSync as existsSync6, readFileSync as readFileSync6, rmSync as rmSync2, statSync as statSync2 } from "fs";
7752
7799
  import { homedir as homedir5 } from "os";
@@ -8330,7 +8377,23 @@ function classifyAuthCredential(credential, expiresAt, hasRefresh) {
8330
8377
  const detail = expiresAt !== void 0 ? `valid (${String(Math.round((expiresAt - Date.now()) / MS_PER_SECOND))}s left)` : "valid";
8331
8378
  return { name: "auth", status: "ok", detail };
8332
8379
  }
8333
- function checkAuth() {
8380
+ async function checkAuth() {
8381
+ try {
8382
+ if (hasMachineConfiguration()) {
8383
+ const status2 = await verifyAuthStatus();
8384
+ return {
8385
+ name: "auth",
8386
+ status: status2.authenticated ? "ok" : "fail",
8387
+ detail: status2.authenticated ? `machine ${status2.displayName ?? status2.machineId} \xB7 ${status2.storageBackend} \xB7 expires in ${Math.round((status2.accessTokenExpiresInMs ?? 0) / 1e3)}s` : `machine authentication: ${status2.recoveryReason}; unlock the credential store or run prim auth configure-machine`
8388
+ };
8389
+ }
8390
+ } catch {
8391
+ return {
8392
+ name: "auth",
8393
+ status: "fail",
8394
+ detail: "Invalid machine credential configuration; run prim auth status for recovery details"
8395
+ };
8396
+ }
8334
8397
  const credential = resolveAuthCredential();
8335
8398
  const storedCredential = credential?.source === "token_file";
8336
8399
  return classifyAuthCredential(
@@ -8411,7 +8474,7 @@ function classifyDaemonHealth(snapshot, options = {}) {
8411
8474
  return {
8412
8475
  name: "daemon",
8413
8476
  status: "fail",
8414
- detail: "authentication ended \u2014 run `prim auth login`"
8477
+ detail: "authentication ended \u2014 run `prim auth status` for recovery instructions"
8415
8478
  };
8416
8479
  }
8417
8480
  if (!snapshot.heartbeat?.healthy) {
@@ -9123,7 +9186,7 @@ async function independentChecks() {
9123
9186
  const backend = await checkBackend();
9124
9187
  const firing = inspectFiringHere();
9125
9188
  return {
9126
- before: [checkAuth()],
9189
+ before: [await checkAuth()],
9127
9190
  after: [
9128
9191
  ...checkDemoPause(gitToplevel()),
9129
9192
  await checkJournalOrganization(),
@@ -10542,12 +10605,20 @@ function registerSetupCommand(program2, dependencies = {}) {
10542
10605
  if (detected && agent !== "claude") {
10543
10606
  note(`agent \xB7 detected ${agent} session (override with --agent <agent>)`);
10544
10607
  }
10608
+ const machine = hasMachineConfiguration();
10545
10609
  let authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
10546
10610
  if (authStatus === "unreachable") {
10547
10611
  note("auth \xB7 verification unavailable; no setup changes were made");
10548
10612
  exit(EXIT_USAGE3);
10549
10613
  return;
10550
10614
  }
10615
+ if (authStatus === "invalid" && machine) {
10616
+ note(
10617
+ "auth \xB7 machine credentials need attention; run prim auth status, then configure-machine with administrator-issued credentials"
10618
+ );
10619
+ exit(EXIT_INCOMPLETE);
10620
+ return;
10621
+ }
10551
10622
  if (authStatus === "invalid") {
10552
10623
  note("auth \xB7 opening browser to authenticate\u2026");
10553
10624
  const login = run(["auth", "login"]);
@@ -10600,7 +10671,7 @@ function registerSetupCommand(program2, dependencies = {}) {
10600
10671
  );
10601
10672
  }
10602
10673
  }
10603
- const welcomeHandoff = scope === "user" && (agent === "claude" && (opts.agent === "claude" || Boolean(process.env.CLAUDECODE)) || agent === "codex" && Boolean(process.env.CODEX_THREAD_ID));
10674
+ const welcomeHandoff = !machine && scope === "user" && (agent === "claude" && (opts.agent === "claude" || Boolean(process.env.CLAUDECODE)) || agent === "codex" && Boolean(process.env.CODEX_THREAD_ID));
10604
10675
  if (welcomeHandoff && gitToplevel() && !isNonInteractive(globals)) {
10605
10676
  note("GitHub \xB7 connecting this repository (finish in your browser)\u2026");
10606
10677
  results.github = run(["github", "connect"], false, GITHUB_CONNECT_TIMEOUT_MS).code === 0 ? "ok" : "skipped";
@@ -10624,6 +10695,15 @@ function registerSetupCommand(program2, dependencies = {}) {
10624
10695
  health = setupChildPayload(stdout);
10625
10696
  results[healthStep.key] = code !== 0 || health?.status === "fail" ? healthStep.required ? "failed" : "skipped" : health?.status === "warn" ? "warn" : "ok";
10626
10697
  }
10698
+ if (machine) {
10699
+ const failed2 = Object.keys(results).filter((key) => results[key] === "failed");
10700
+ note(
10701
+ "machine \xB7 GitHub App installation, API key administration, and personal onboarding are available in the web application"
10702
+ );
10703
+ printJson({ ok: failed2.length === 0, principalKind: "machine", results, failed: failed2, health });
10704
+ if (failed2.length) exit(EXIT_INCOMPLETE);
10705
+ return;
10706
+ }
10627
10707
  if (welcomeHandoff) {
10628
10708
  const welcomeSkill = agent === "codex" ? codexWelcomeSkillPath() : welcomeSkillPathFor(process.cwd(), scope);
10629
10709
  const mainSkill = agent === "codex" ? userTargetFor("codex") : join15(homedir7(), ".claude", "skills", "prim", "SKILL.md");