@primitive.ai/prim 0.1.0-alpha.127 → 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 (44) hide show
  1. package/README.md +76 -5
  2. package/dist/{chunk-NVDPKW7Z.js → chunk-3KPTVK4N.js} +3 -51
  3. package/dist/{chunk-URYZDQFH.js → chunk-4DYEBYKM.js} +3 -5
  4. package/dist/{chunk-HZI5PBN4.js → chunk-6QAXVFRJ.js} +1129 -39
  5. package/dist/{chunk-A5VTE43F.js → chunk-ANMNGGTN.js} +2 -2
  6. package/dist/{chunk-TNWI3JWK.js → chunk-B3ICJZXV.js} +4 -2
  7. package/dist/{chunk-RV3JFSMX.js → chunk-C357P37M.js} +4 -4
  8. package/dist/{chunk-KFRGVHGB.js → chunk-E57UVUJL.js} +6 -6
  9. package/dist/{chunk-MGKSZSTV.js → chunk-EQWUCFXK.js} +3 -3
  10. package/dist/{chunk-72NIZMZN.js → chunk-M6KIDB5R.js} +8 -3
  11. package/dist/{chunk-O65UVJZH.js → chunk-N6PZE7HX.js} +2 -2
  12. package/dist/{chunk-WGTUNUIS.js → chunk-NYDM4HSS.js} +5 -5
  13. package/dist/{chunk-R4EYLEIK.js → chunk-P4O7L7JZ.js} +2 -2
  14. package/dist/{chunk-UUQT5GMO.js → chunk-PRJ7P6J5.js} +1 -1
  15. package/dist/{chunk-H74RDXKP.js → chunk-PTZ6BWSU.js} +2 -2
  16. package/dist/{chunk-F3FDVHR7.js → chunk-QQ3G5SXX.js} +1 -1
  17. package/dist/{chunk-VVFVENU4.js → chunk-RDT2IV2Z.js} +6 -6
  18. package/dist/{chunk-L6IL4N6Y.js → chunk-VLT2KGPE.js} +34 -34
  19. package/dist/{chunk-H6X52UVF.js → chunk-WEGZGF3K.js} +1 -1
  20. package/dist/{chunk-C4QNBSWB.js → chunk-XINFTNA2.js} +8 -8
  21. package/dist/{chunk-JCKOW45X.js → chunk-ZCT23NBS.js} +2 -2
  22. package/dist/daemon/server.js +1311 -364
  23. package/dist/hook-runtime/daemon/server.js +1311 -364
  24. package/dist/hook-runtime/hooks/post-commit.js +395 -242
  25. package/dist/hook-runtime/hooks/post-rewrite.js +391 -238
  26. package/dist/hook-runtime/hooks/post-tool-use.js +1442 -498
  27. package/dist/hook-runtime/hooks/pre-commit.js +1293 -349
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1087 -143
  29. package/dist/hook-runtime/hooks/prim-hook.js +1457 -513
  30. package/dist/hook-runtime/hooks/session-end.js +369 -216
  31. package/dist/hook-runtime/hooks/session-start.js +1209 -219
  32. package/dist/hook-runtime/index.js +2406 -1036
  33. package/dist/hook-runtime/statusline-main.js +360 -207
  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 +18 -18
  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 +63 -20
  42. package/dist/index.js +387 -43
  43. package/dist/statusline-main.js +360 -207
  44. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ import {
26
26
  uninstallProjectGitHook,
27
27
  userTargetFor,
28
28
  welcomeSkillPathFor
29
- } from "./chunk-72NIZMZN.js";
29
+ } from "./chunk-M6KIDB5R.js";
30
30
  import {
31
31
  InvalidJournalEnvelopeError,
32
32
  buildOrganizationBoundMoveRequest,
@@ -34,27 +34,27 @@ import {
34
34
  inspectJournalDelivery,
35
35
  requireDurableIngestAcknowledgement,
36
36
  summarizeRetainedBuckets
37
- } from "./chunk-L6IL4N6Y.js";
37
+ } from "./chunk-VLT2KGPE.js";
38
38
  import {
39
39
  checkAffectedDecisions,
40
40
  daemonOrDirectGet,
41
41
  formatDecisionsWarning
42
- } from "./chunk-VVFVENU4.js";
42
+ } from "./chunk-RDT2IV2Z.js";
43
43
  import {
44
44
  hasCompleteCoverage,
45
45
  requestPreflight2 as requestPreflight,
46
46
  waitForPreflight
47
- } from "./chunk-C4QNBSWB.js";
47
+ } from "./chunk-XINFTNA2.js";
48
48
  import {
49
49
  fetchFeedbackCapability
50
- } from "./chunk-TNWI3JWK.js";
50
+ } from "./chunk-B3ICJZXV.js";
51
51
  import {
52
52
  POST_COMMIT_GRACE_MS,
53
53
  clearHooksWired,
54
54
  inspectPostCommitFiring,
55
55
  lastConversationCaptured,
56
56
  recordHooksWired
57
- } from "./chunk-F3FDVHR7.js";
57
+ } from "./chunk-QQ3G5SXX.js";
58
58
  import {
59
59
  isUnattended,
60
60
  unattendedEnv
@@ -67,7 +67,7 @@ import {
67
67
  formatStatusline,
68
68
  formatTeammates,
69
69
  repositoryBindingDiagnosticLabel
70
- } from "./chunk-URYZDQFH.js";
70
+ } from "./chunk-4DYEBYKM.js";
71
71
  import {
72
72
  JOURNAL_DIR,
73
73
  SESSIONS_DIR,
@@ -82,11 +82,11 @@ import {
82
82
  rotationIdentity,
83
83
  sweepOrphanedDrainProgress,
84
84
  writeDrainCheckpoint
85
- } from "./chunk-O65UVJZH.js";
85
+ } from "./chunk-N6PZE7HX.js";
86
86
  import {
87
87
  daemonIsLive,
88
88
  daemonRequest
89
- } from "./chunk-H6X52UVF.js";
89
+ } from "./chunk-WEGZGF3K.js";
90
90
  import {
91
91
  RUN_ID,
92
92
  demoCommand,
@@ -107,7 +107,7 @@ import {
107
107
  readRun,
108
108
  runIds,
109
109
  saveRun
110
- } from "./chunk-MGKSZSTV.js";
110
+ } from "./chunk-EQWUCFXK.js";
111
111
  import {
112
112
  MANAGED_GIT_HOOK_NAMES,
113
113
  assertOwnedHookRuntime,
@@ -137,8 +137,8 @@ import {
137
137
  stableNodePath,
138
138
  stageHookRuntime,
139
139
  stripCommand
140
- } from "./chunk-UUQT5GMO.js";
141
- import "./chunk-R4EYLEIK.js";
140
+ } from "./chunk-PRJ7P6J5.js";
141
+ import "./chunk-P4O7L7JZ.js";
142
142
  import {
143
143
  MAX_SCOPE_GLOB_CHARS,
144
144
  bold,
@@ -167,7 +167,7 @@ import {
167
167
  isScopeDirectoryPrefix,
168
168
  isScopeGlobPattern,
169
169
  stripAnsi
170
- } from "./chunk-WGTUNUIS.js";
170
+ } from "./chunk-NYDM4HSS.js";
171
171
  import {
172
172
  CliManagementResponseError,
173
173
  DEFAULT_API_URL,
@@ -184,10 +184,8 @@ import {
184
184
  getTokenExpiresAt,
185
185
  isSessionEnded,
186
186
  refreshToken,
187
- setStoredToken,
188
- stripControlChars,
189
- terminalSafeLine
190
- } from "./chunk-NVDPKW7Z.js";
187
+ setStoredToken
188
+ } from "./chunk-3KPTVK4N.js";
191
189
  import {
192
190
  CLOUD_CREDENTIALS_REMEDY,
193
191
  CLOUD_GITHUB_CONNECT_REMEDY,
@@ -195,6 +193,8 @@ import {
195
193
  MachineAuthError,
196
194
  REFRESH_TOKEN_PATH,
197
195
  SERVER_WAIT_PREFIX,
196
+ SESSION_IDENTITY_VALUE,
197
+ SESSION_IDENTITY_VARIABLE,
198
198
  TOKEN_FILE_PATH,
199
199
  WorkosConnectProtocolError,
200
200
  acquireMachineCredential,
@@ -214,6 +214,7 @@ import {
214
214
  discoverMachineConfiguration,
215
215
  discoverWorkosConnect,
216
216
  endDemoPause,
217
+ ensureSessionIdentity,
217
218
  environmentCredentials,
218
219
  exchangeMachineCredentials,
219
220
  explicitlyActive,
@@ -230,6 +231,7 @@ import {
230
231
  isPreparedCloudSession,
231
232
  isRepoActiveForCapture,
232
233
  isValidRepoSyncId,
234
+ linkSessionIdentity,
233
235
  machineApiUrl,
234
236
  machineContext,
235
237
  machineRecord,
@@ -254,15 +256,19 @@ import {
254
256
  requestWorkosDeviceAuthorization,
255
257
  resolveAuthCredential,
256
258
  resolveStoredCredential,
259
+ sessionIdentityMessage,
260
+ sessionIdentityMode,
257
261
  setRepoActive,
258
262
  stableHookCommand,
263
+ stripControlChars,
259
264
  syncDirectory,
265
+ terminalSafeLine,
260
266
  verifyAcquiredMachineIdentity,
261
267
  verifyMachineIdentity,
262
268
  withFileLock,
263
269
  withFileLockSync,
264
270
  writeMachineMetadata
265
- } from "./chunk-HZI5PBN4.js";
271
+ } from "./chunk-6QAXVFRJ.js";
266
272
  import "./chunk-JSBRDJBE.js";
267
273
 
268
274
  // src/index.ts
@@ -395,19 +401,6 @@ async function pollGitHubInstallIntent(client, start, options = {}) {
395
401
  }
396
402
  }
397
403
 
398
- // src/lib/developer-enrollment.ts
399
- import {
400
- constants as constants2,
401
- createHash as createHash2,
402
- generateKeyPairSync,
403
- privateDecrypt,
404
- randomBytes as randomBytes2,
405
- randomUUID
406
- } from "crypto";
407
- import { readFileSync } from "fs";
408
- import { hostname } from "os";
409
- import { join as join3 } from "path";
410
-
411
404
  // src/flusher.ts
412
405
  import { createReadStream, renameSync as renameSync2, statSync, unlinkSync } from "fs";
413
406
  import { dirname as dirname2, join as join2 } from "path";
@@ -916,6 +909,17 @@ function journalNeedsFlush(now = Date.now()) {
916
909
  }
917
910
 
918
911
  // src/lib/developer-enrollment.ts
912
+ import {
913
+ constants as constants2,
914
+ createHash as createHash2,
915
+ generateKeyPairSync,
916
+ privateDecrypt,
917
+ randomBytes as randomBytes2,
918
+ randomUUID
919
+ } from "crypto";
920
+ import { readFileSync } from "fs";
921
+ import { hostname } from "os";
922
+ import { join as join3 } from "path";
919
923
  function installationPath(owner, directory = primConfigDirectory()) {
920
924
  return join3(
921
925
  directory,
@@ -946,6 +950,13 @@ async function activatePending(identity) {
946
950
  return true;
947
951
  }
948
952
  }
953
+ var ENROLLMENT_KIND_FIELD = "kind";
954
+ var ENVIRONMENT_ENROLLMENT_KIND = "environment";
955
+ var SESSION_IDENTITY_ENVIRONMENT_LINE = "PRIM_CLOUD_IDENTITY=session";
956
+ var SESSION_IDENTITY_SCOPE = "cli:session-identity";
957
+ function isEnvironmentRedeem(response) {
958
+ return response.kind === ENVIRONMENT_ENROLLMENT_KIND && Array.isArray(response.scopes) && response.scopes.length === 1 && response.scopes[0] === SESSION_IDENTITY_SCOPE && !("authorizedUserId" in response);
959
+ }
949
960
  async function exchangeEnrollment(client, request, onStarted) {
950
961
  const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
951
962
  const verifier = randomBytes2(32).toString("hex");
@@ -958,7 +969,8 @@ async function exchangeEnrollment(client, request, onStarted) {
958
969
  requestId: randomUUID(),
959
970
  displayName: request.displayName,
960
971
  publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),
961
- challenge: createHash2("sha256").update(verifier).digest("hex")
972
+ challenge: createHash2("sha256").update(verifier).digest("hex"),
973
+ ...request.environment ? { [ENROLLMENT_KIND_FIELD]: ENVIRONMENT_ENROLLMENT_KIND } : {}
962
974
  },
963
975
  { signal }
964
976
  )
@@ -973,7 +985,13 @@ async function exchangeEnrollment(client, request, onStarted) {
973
985
  { signal }
974
986
  )
975
987
  );
976
- if (!isCliEnrollmentRedeemResponse(response) || !machineString(response.clientId, 256) || !machineString(response.ciphertext, 4096) || !machineString(response.machineId, 128) || response.authorizedUserId !== request.authorizedUserId)
988
+ if (
989
+ // An environment credential is delegated to no one and may only identify
990
+ // sessions: its answer names no user, says it is an environment, and
991
+ // grants exactly the session identity scope. Anything else is refused
992
+ // before a secret is decrypted, let alone printed.
993
+ !(request.environment ? isEnvironmentRedeem(response) : isCliEnrollmentRedeemResponse(response)) || !machineString(response.clientId, 256) || !machineString(response.ciphertext, 4096) || !machineString(response.machineId, 128) || (request.environment ? response.authorizedUserId !== void 0 : response.authorizedUserId !== request.authorizedUserId)
994
+ )
977
995
  throw new MachineAuthError(
978
996
  "invalid_enrollment",
979
997
  "The server returned an invalid enrollment exchange."
@@ -1043,7 +1061,13 @@ async function prepareEnvironmentEnrollment(displayName) {
1043
1061
  );
1044
1062
  return { name, siteUrl, configuration };
1045
1063
  }
1046
- async function enrollEnvironmentInstallation({ name, siteUrl, configuration }, humanAccessToken) {
1064
+ async function enrollEnvironmentInstallation(enrollment, humanAccessToken) {
1065
+ return enrollSeparateCredential(enrollment, humanAccessToken, false);
1066
+ }
1067
+ async function enrollOrganizationEnvironment(enrollment, humanAccessToken) {
1068
+ return enrollSeparateCredential(enrollment, humanAccessToken, true);
1069
+ }
1070
+ async function enrollSeparateCredential({ name, siteUrl, configuration }, humanAccessToken, environment) {
1047
1071
  const client = getBearerClient(humanAccessToken, siteUrl);
1048
1072
  const owner = await enrollmentOwner(
1049
1073
  client,
@@ -1053,21 +1077,27 @@ async function enrollEnvironmentInstallation({ name, siteUrl, configuration }, h
1053
1077
  try {
1054
1078
  const { clientId, machineId, secret } = await exchangeEnrollment(
1055
1079
  client,
1056
- { installationId: randomUUID(), displayName: name, authorizedUserId: owner.authorizedUserId },
1080
+ {
1081
+ installationId: randomUUID(),
1082
+ displayName: name,
1083
+ authorizedUserId: owner.authorizedUserId,
1084
+ environment
1085
+ },
1057
1086
  () => {
1058
1087
  registered = true;
1059
1088
  }
1060
1089
  );
1061
1090
  const tokens = await exchangeMachineCredentials(configuration, clientId, secret);
1062
1091
  const identity = await verifyMachineIdentity(siteUrl, tokens.accessToken, clientId);
1063
- if (identity.machineId !== machineId || identity.authorizedUserId !== owner.authorizedUserId || identity.organizationId !== owner.organizationId)
1092
+ if (identity.machineId !== machineId || identity.authorizedUserId !== (environment ? void 0 : owner.authorizedUserId) || identity.organizationId !== owner.organizationId)
1064
1093
  throw new MachineAuthError(
1065
1094
  "delegation_mismatch",
1066
- "The new installation does not carry the signed-in user's delegation.",
1095
+ environment ? "The new environment credential is not an organization-level credential of your organization." : "The new installation does not carry the signed-in user's delegation.",
1067
1096
  true
1068
1097
  );
1098
+ const lines = installationEnvironment({ clientId, clientSecret: secret }, siteUrl);
1069
1099
  return {
1070
- environment: installationEnvironment({ clientId, clientSecret: secret }, siteUrl),
1100
+ environment: environment ? [...lines, SESSION_IDENTITY_ENVIRONMENT_LINE] : lines,
1071
1101
  displayName: name,
1072
1102
  clientId,
1073
1103
  clientSecret: secret,
@@ -1081,7 +1111,7 @@ async function enrollEnvironmentInstallation({ name, siteUrl, configuration }, h
1081
1111
  const cause = error instanceof MachineAuthError ? error.message : "Enrollment could not finish.";
1082
1112
  throw new MachineAuthError(
1083
1113
  error instanceof MachineAuthError ? error.code : "enrollment_failed",
1084
- `${cause} Installation "${name}" ${registered ? "was already registered" : "may have been registered"}; ask an organization admin to revoke it in Settings \u2192 Developer installations.`
1114
+ `${cause} ${environment ? "Environment credential" : "Installation"} "${name}" ${registered ? "was already registered" : "may have been registered"}; ask an organization admin to revoke it in Settings \u2192 Developer installations.`
1085
1115
  );
1086
1116
  }
1087
1117
  }
@@ -1786,9 +1816,85 @@ function authStatusResult(status2, reason, source, refreshTokenPresent) {
1786
1816
  warnings: source === "token_file" && !refreshTokenPresent ? ["no refresh token"] : []
1787
1817
  };
1788
1818
  }
1819
+ var SESSION_UNREACHABLE_CODES = /* @__PURE__ */ new Set([
1820
+ "identity_unavailable",
1821
+ "verification_unavailable",
1822
+ "authentication_unavailable",
1823
+ "broker_unavailable",
1824
+ "remote_unavailable",
1825
+ "push_timeout",
1826
+ "webhook_timeout",
1827
+ "not_identified",
1828
+ "challenge_open",
1829
+ "too_many_challenges"
1830
+ ]);
1831
+ async function verifySessionStatus() {
1832
+ const session = { principalKind: "session", identity: "github" };
1833
+ try {
1834
+ let machine = await acquireMachineCredential({
1835
+ signal: AbortSignal.timeout(AUTH_PROBE_TIMEOUT_MS)
1836
+ });
1837
+ if (!machine?.session)
1838
+ throw new MachineAuthError("not_identified", "This session has no identity yet.");
1839
+ let identity;
1840
+ try {
1841
+ identity = await verifyAcquiredMachineIdentity(machine);
1842
+ } catch (error) {
1843
+ if (!(error instanceof MachineAuthError && error.code === "machine_access_rejected"))
1844
+ throw error;
1845
+ machine = await acquireMachineCredential({
1846
+ force: true,
1847
+ signal: AbortSignal.timeout(AUTH_PROBE_TIMEOUT_MS)
1848
+ });
1849
+ if (!machine?.session)
1850
+ throw new MachineAuthError("not_identified", "This session has no identity yet.");
1851
+ identity = await verifyAcquiredMachineIdentity(machine).catch((retry) => {
1852
+ throw retry instanceof MachineAuthError && retry.code === "machine_access_rejected" ? new MachineAuthError(
1853
+ "session_rejected",
1854
+ "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub.",
1855
+ true
1856
+ ) : retry;
1857
+ });
1858
+ }
1859
+ if (identity.authorizedUserId !== machine.session.userId)
1860
+ throw new MachineAuthError(
1861
+ "identity_changed",
1862
+ "Primitive answered for another member than the one this session identified.",
1863
+ true
1864
+ );
1865
+ return {
1866
+ ...authStatusResult("valid", "verified", "machine", false),
1867
+ ...session,
1868
+ machineId: machine.machineId,
1869
+ authorizedUserId: machine.session.userId,
1870
+ displayName: machine.session.displayName,
1871
+ ...machine.session.githubLogin ? { githubLogin: machine.session.githubLogin } : {},
1872
+ effectiveScopes: identity.scopes,
1873
+ organizationId: machine.organizationId,
1874
+ storageBackend: machine.storage,
1875
+ accessTokenExpiresInMs: machine.expiresAt - Date.now(),
1876
+ accessTokenExpired: machine.expiresAt <= Date.now()
1877
+ };
1878
+ } catch (error) {
1879
+ const code = error instanceof MachineAuthError ? error.code : "verification_unavailable";
1880
+ const unreachable = !(error instanceof MachineAuthError) || SESSION_UNREACHABLE_CODES.has(code);
1881
+ return {
1882
+ ...authStatusResult(
1883
+ unreachable ? "unreachable" : "invalid",
1884
+ unreachable ? "verification_unavailable" : "access_rejected",
1885
+ void 0,
1886
+ false
1887
+ ),
1888
+ ...session,
1889
+ recoveryReason: code,
1890
+ ...error instanceof MachineAuthError ? { recoveryDetail: error.message } : {}
1891
+ };
1892
+ }
1893
+ }
1789
1894
  async function verifyAuthStatus() {
1790
1895
  let machineMetadata = {};
1791
1896
  try {
1897
+ if (hasMachineConfiguration() && sessionIdentityMode()) return await verifySessionStatus();
1792
1898
  if (hasMachineConfiguration()) {
1793
1899
  const context = machineContext();
1794
1900
  machineMetadata = {
@@ -1921,6 +2027,12 @@ function authStatusExitCode(status2) {
1921
2027
  return status2 === "invalid" ? EXIT_FAIL : EXIT_UNREACHABLE;
1922
2028
  }
1923
2029
  function writeHumanAuthStatus(result) {
2030
+ if (result.principalKind === "session") {
2031
+ console.error(
2032
+ result.authenticated ? `Session attributed to ${stripControlChars(result.displayName ?? "")}${result.githubLogin ? ` (GitHub @${stripControlChars(result.githubLogin)})` : ""}: identified through GitHub; organization ${result.organizationId}.` : `Session identity ${result.status}: ${result.recoveryReason}. ${result.recoveryDetail ? stripControlChars(result.recoveryDetail) : "Run prim setup --cloud for details."}`
2033
+ );
2034
+ return;
2035
+ }
1924
2036
  if (result.principalKind === "machine") {
1925
2037
  console.error(
1926
2038
  result.authenticated ? `Installation ${result.machineId}: verified (${result.storageBackend}); organization ${result.organizationId}${result.authorizedUserId ? `; acting for user ${result.authorizedUserId}` : "; service identity"}.` : `Machine authentication ${result.status}: ${result.recoveryReason}. ${result.recoveryDetail ? stripControlChars(result.recoveryDetail) : "Check the credential store or run prim auth configure-machine with credentials from your administrator."}`
@@ -2010,6 +2122,12 @@ ${verificationUrl}`);
2010
2122
  };
2011
2123
  }
2012
2124
  }
2125
+ if (options.deviceOnly)
2126
+ return {
2127
+ ok: false,
2128
+ error: "device_sign_in_unavailable",
2129
+ detail: "This Primitive server does not offer device sign-in, which linking from a cloud session needs."
2130
+ };
2013
2131
  let config;
2014
2132
  try {
2015
2133
  config = await fetchAuthBrokerConfig(siteUrl);
@@ -2113,6 +2231,52 @@ function reportEnrollmentFailure(error, detail) {
2113
2231
  console.error(`Enrollment failed: ${human}`);
2114
2232
  process.exitCode = EXIT_FAIL;
2115
2233
  }
2234
+ async function enrollNewEnvironment(options) {
2235
+ if (!options.newEnvironment || !options.printEnv || options.ifSupported || options.newInstallation) {
2236
+ reportEnrollmentFailure(
2237
+ "invalid_arguments",
2238
+ "Use --new-environment <name> together with --print-env (and without --new-installation or --if-supported)."
2239
+ );
2240
+ return;
2241
+ }
2242
+ try {
2243
+ const enrollment = await prepareEnvironmentEnrollment(options.newEnvironment);
2244
+ console.error(
2245
+ `Sign in as an organization admin to create an environment credential named "${stripControlChars(enrollment.name)}" for a Claude Code cloud environment your organization shares. This machine's own credentials are not changed.`
2246
+ );
2247
+ const signIn = await signInInteractively({ browser: options.browser });
2248
+ if (!signIn.ok) {
2249
+ reportEnrollmentFailure(signIn.error, signIn.detail);
2250
+ return;
2251
+ }
2252
+ const credential = await enrollOrganizationEnvironment(
2253
+ enrollment,
2254
+ signIn.credentials.accessToken
2255
+ );
2256
+ process.stdout.write(`${credential.environment.join("\n")}
2257
+ `);
2258
+ const signInHostName = signInHost(enrollment.configuration.issuer);
2259
+ const apiHost = new URL(enrollment.siteUrl).hostname;
2260
+ console.error(
2261
+ [
2262
+ `Environment credential "${stripControlChars(credential.displayName)}" belongs to your organization. It can only identify sessions: each session acts as the member whose GitHub account started it, once that member has linked their GitHub account (once, with \`prim auth link\` in their first session).`,
2263
+ "The secret is shown only once and is not stored on this machine.",
2264
+ // Every member of a shared environment can read its variables; its
2265
+ // network secrets cannot be read back, so this is the way to hold it.
2266
+ `Keep the secret out of the environment's variables: add a "Username and password" network secret for ${signInHostName} (username: the client ID, password: the client secret). As its variables, set PRIM_M2M_CLIENT_AUTH=network-secret and every line printed above except PRIM_M2M_CLIENT_SECRET.`,
2267
+ "Put PRIM_M2M_CLIENT_SECRET in the variables only in an environment no one else uses: every member who uses a shared environment can read them.",
2268
+ `Under Network access, allow ${[.../* @__PURE__ */ new Set([apiHost, signInHostName])].join(" and ")}, and run \`npx --yes @primitive.ai/prim@latest setup --cloud --prepare\` in the environment's setup script.`,
2269
+ "An organization admin can revoke the credential in Settings \u2192 Developer installations."
2270
+ ].join("\n")
2271
+ );
2272
+ process.exitCode = EXIT_OK;
2273
+ } catch (error) {
2274
+ reportEnrollmentFailure(
2275
+ error instanceof MachineAuthError ? error.code : "enrollment_failed",
2276
+ error instanceof MachineAuthError ? error.message : "Enrollment could not finish. Check that you are an admin of the organization and its enrollment policy, then retry."
2277
+ );
2278
+ }
2279
+ }
2116
2280
  async function enrollNewInstallation(options) {
2117
2281
  if (!options.newInstallation || !options.printEnv || options.ifSupported) {
2118
2282
  reportEnrollmentFailure(
@@ -2169,13 +2333,17 @@ function registerAuthCommands(program2) {
2169
2333
  auth.command("enroll").description("Authorize this developer installation using your signed-in account").option("--if-supported", "Keep legacy authentication when server enrollment is unavailable").option(
2170
2334
  "--new-installation <name>",
2171
2335
  "Enroll a separate installation that runs elsewhere, such as a Claude Code cloud environment (requires --print-env)"
2336
+ ).option(
2337
+ "--new-environment <name>",
2338
+ "Create an organization-level credential for a Claude Code cloud environment your organization shares; each session acts as the member who started it (requires --print-env)"
2172
2339
  ).option(
2173
2340
  "--print-env",
2174
2341
  "Print the new installation's PRIM_M2M_* credentials to STDOUT as .env lines for an environment"
2175
2342
  ).option("--no-browser", "Print the sign-in URL without opening a browser").action(async (options) => {
2176
- if (options.newInstallation !== void 0 || options.printEnv) {
2343
+ if (options.newInstallation !== void 0 || options.newEnvironment !== void 0 || options.printEnv) {
2177
2344
  if (refuseCloudSignIn(reportEnrollmentFailure)) return;
2178
- await enrollNewInstallation(options);
2345
+ if (options.newEnvironment !== void 0) await enrollNewEnvironment(options);
2346
+ else await enrollNewInstallation(options);
2179
2347
  return;
2180
2348
  }
2181
2349
  try {
@@ -2311,6 +2479,21 @@ function registerAuthCommands(program2) {
2311
2479
  console.log("No saved tokens found.");
2312
2480
  }
2313
2481
  });
2482
+ auth.command("identify").description(
2483
+ "Identify who started this Claude Code cloud session through GitHub (environments with PRIM_CLOUD_IDENTITY=session)"
2484
+ ).option("--json", "Output as JSON (the default; kept for symmetry with auth status)").action(async () => {
2485
+ if (refuseOutsideSessionIdentity()) return;
2486
+ const outcome = await ensureSessionIdentity({ cwd: process.cwd(), explicit: true });
2487
+ console.error(identityLine(outcome));
2488
+ printJson(identityResult(outcome));
2489
+ process.exitCode = outcome.status === "ok" ? EXIT_OK : EXIT_FAIL;
2490
+ });
2491
+ auth.command("link").description(
2492
+ "Link your GitHub account to your Primitive account, once, from a Claude Code cloud session that identifies people through GitHub"
2493
+ ).action(async () => {
2494
+ if (refuseOutsideSessionIdentity()) return;
2495
+ await linkGithubAccount();
2496
+ });
2314
2497
  auth.command("status").description("Check authentication status and token expiry").option("--json", "Output as JSON").action(async (opts) => {
2315
2498
  const result = await verifyAuthStatus();
2316
2499
  if (opts.json) printJson(result);
@@ -2318,6 +2501,113 @@ function registerAuthCommands(program2) {
2318
2501
  process.exit(authStatusExitCode(result.status));
2319
2502
  });
2320
2503
  }
2504
+ var SESSION_IDENTITY_NOT_CONFIGURED = `prim auth identify and prim auth link apply only in a Claude Code cloud session whose environment sets ${SESSION_IDENTITY_VARIABLE}=${SESSION_IDENTITY_VALUE} together with its environment credential (PRIM_M2M_CLIENT_ID); this session does not.`;
2505
+ function refuseOutsideSessionIdentity() {
2506
+ let mode = false;
2507
+ try {
2508
+ mode = sessionIdentityMode() && hasMachineConfiguration();
2509
+ } catch (error) {
2510
+ reportFailure(
2511
+ error instanceof MachineAuthError ? error.code : "invalid_machine_configuration",
2512
+ error instanceof MachineAuthError ? error.message : String(error)
2513
+ );
2514
+ return true;
2515
+ }
2516
+ if (mode) return false;
2517
+ reportFailure("session_identity_not_configured", SESSION_IDENTITY_NOT_CONFIGURED);
2518
+ return true;
2519
+ }
2520
+ function identityLine(outcome) {
2521
+ if (outcome.status === "ok")
2522
+ return `identity \xB7 ok: this session is attributed to ${stripControlChars(outcome.displayName)}${outcome.githubLogin ? ` (GitHub @${stripControlChars(outcome.githubLogin)})` : ""}`;
2523
+ return `identity \xB7 ${outcome.status === "link_required" ? "link required" : "failed"}: ${stripControlChars(sessionIdentityMessage(outcome))}`;
2524
+ }
2525
+ function identityResult(outcome) {
2526
+ if (outcome.status === "ok")
2527
+ return {
2528
+ status: "ok",
2529
+ identity: "github",
2530
+ displayName: outcome.displayName,
2531
+ ...outcome.githubLogin ? { githubLogin: outcome.githubLogin } : {},
2532
+ reused: outcome.reused
2533
+ };
2534
+ if (outcome.status === "link_required")
2535
+ return {
2536
+ status: "link_required",
2537
+ githubLogin: outcome.githubLogin,
2538
+ message: sessionIdentityMessage(outcome),
2539
+ remedy: "run `prim auth link` and sign in at the URL it prints with the code it shows"
2540
+ };
2541
+ return {
2542
+ status: "failed",
2543
+ code: outcome.code,
2544
+ cause: outcome.cause,
2545
+ remedy: outcome.remedy,
2546
+ message: sessionIdentityMessage(outcome)
2547
+ };
2548
+ }
2549
+ async function linkGithubAccount() {
2550
+ const cwd = process.cwd();
2551
+ const outcome = await ensureSessionIdentity({ cwd, explicit: true });
2552
+ if (outcome.status === "ok") {
2553
+ console.error(
2554
+ `Already linked: this session is attributed to ${stripControlChars(outcome.displayName)}${outcome.githubLogin ? ` (GitHub @${stripControlChars(outcome.githubLogin)})` : ""}.`
2555
+ );
2556
+ printJson({ ...identityResult(outcome), linked: true, alreadyLinked: true });
2557
+ process.exitCode = EXIT_OK;
2558
+ return;
2559
+ }
2560
+ if (outcome.status === "failed") {
2561
+ reportFailure(outcome.code, sessionIdentityMessage(outcome));
2562
+ return;
2563
+ }
2564
+ const login = stripControlChars(outcome.githubLogin);
2565
+ console.error(
2566
+ `GitHub account @${login} started this session. Sign in to Primitive as yourself to link it; this is needed once.`
2567
+ );
2568
+ const signIn = await signInInteractively({ browser: false, deviceOnly: true });
2569
+ if (!signIn.ok) {
2570
+ reportFailure(signIn.error, signIn.detail);
2571
+ return;
2572
+ }
2573
+ const linked = await linkSessionIdentity(outcome, signIn.credentials.accessToken, { cwd });
2574
+ if (linked.status !== "ok") {
2575
+ reportFailure(
2576
+ linked.status === "failed" ? linked.code : "link_failed",
2577
+ sessionIdentityMessage(linked)
2578
+ );
2579
+ return;
2580
+ }
2581
+ const name = stripControlChars(linked.displayName);
2582
+ console.error(
2583
+ `Linked GitHub account @${login} to ${name}. This session's work is now attributed to ${name}, and later sessions started from @${login} identify you automatically.`
2584
+ );
2585
+ const setup = await completeLinkedSession(cwd);
2586
+ printJson({ ...identityResult(linked), linked: true, ...setup });
2587
+ process.exitCode = EXIT_OK;
2588
+ }
2589
+ async function completeLinkedSession(cwd) {
2590
+ const result = {};
2591
+ try {
2592
+ const binding = await bindRepository(gitToplevel(cwd) ?? cwd, {
2593
+ signal: AbortSignal.timeout(AUTH_PROBE_TIMEOUT_MS),
2594
+ quietRefresh: true
2595
+ });
2596
+ result.repository = binding.status;
2597
+ console.error(
2598
+ binding.status === "connected" ? `Repository ${stripControlChars(binding.repositoryFullName)} is connected.` : `Repository ${stripControlChars(binding.repositoryFullName)} is not connected to Primitive; run \`prim setup --cloud\` for the fix.`
2599
+ );
2600
+ } catch {
2601
+ console.error(
2602
+ "The repository could not be connected yet; run `prim setup --cloud` for details."
2603
+ );
2604
+ }
2605
+ try {
2606
+ result.flushed = (await flush()).flushed;
2607
+ } catch {
2608
+ }
2609
+ return result;
2610
+ }
2321
2611
  async function readMachineSecret(fromStdin) {
2322
2612
  if (fromStdin) {
2323
2613
  let input2 = "";
@@ -9528,10 +9818,24 @@ function classifyAuthCredential(credential, expiresAt, hasRefresh) {
9528
9818
  const detail = expiresAt !== void 0 ? `valid (${String(Math.round((expiresAt - Date.now()) / MS_PER_SECOND))}s left)` : "valid";
9529
9819
  return { name: "auth", status: "ok", detail };
9530
9820
  }
9821
+ function classifySessionAuth(status2) {
9822
+ if (status2.authenticated)
9823
+ return {
9824
+ name: "auth",
9825
+ status: "ok",
9826
+ detail: `session attributed to ${stripControlChars(status2.displayName ?? status2.authorizedUserId ?? "unknown")}${status2.githubLogin ? ` (GitHub @${stripControlChars(status2.githubLogin)})` : ""} \xB7 identified through GitHub \xB7 expires in ${Math.round((status2.accessTokenExpiresInMs ?? 0) / 1e3)}s`
9827
+ };
9828
+ return {
9829
+ name: "auth",
9830
+ status: "fail",
9831
+ detail: `session identity: ${status2.recoveryDetail ? stripControlChars(status2.recoveryDetail) : `${status2.recoveryReason ?? "unknown"}; run prim setup --cloud for the fix`}`
9832
+ };
9833
+ }
9531
9834
  async function checkAuth() {
9532
9835
  try {
9533
9836
  if (hasMachineConfiguration()) {
9534
9837
  const status2 = await verifyAuthStatus();
9838
+ if (status2.principalKind === "session") return classifySessionAuth(status2);
9535
9839
  return {
9536
9840
  name: "auth",
9537
9841
  status: status2.authenticated ? "ok" : "fail",
@@ -11161,6 +11465,46 @@ function prepareSteps(deps, results, remedies, origin = "image") {
11161
11465
  () => (deps.markPrepared ?? ((from) => markCloudPrepared(env, from)))(origin)
11162
11466
  );
11163
11467
  }
11468
+ function identityReady({ deps, results, remedy, env }) {
11469
+ let mode = false;
11470
+ try {
11471
+ mode = sessionIdentityMode({ env });
11472
+ } catch {
11473
+ return true;
11474
+ }
11475
+ if (!mode) return true;
11476
+ deps.note("identity \xB7 identifying who started this session through GitHub\u2026");
11477
+ const ran = deps.run(["auth", "identify", "--json"], true);
11478
+ let parsed = {};
11479
+ try {
11480
+ parsed = JSON.parse(ran.stdout || "{}");
11481
+ } catch {
11482
+ parsed = {};
11483
+ }
11484
+ const text = (value) => typeof value === "string" ? stripControlChars(value).replace(/\.$/u, "") : void 0;
11485
+ if (parsed.status === "ok") {
11486
+ const login = text(parsed.githubLogin);
11487
+ deps.note(
11488
+ `identity \xB7 ok: attributed to ${text(parsed.displayName) ?? "the linked member"}${login ? ` (GitHub @${login})` : ""}`
11489
+ );
11490
+ results.identity = "ok";
11491
+ return true;
11492
+ }
11493
+ if (parsed.status === "link_required") {
11494
+ remedy(
11495
+ `identity \xB7 link required: GitHub account @${text(parsed.githubLogin) ?? "unknown"} is not linked to a Primitive account yet; run \`prim auth link\` and sign in at the URL it prints with the code it shows (once; later sessions identify you automatically)`
11496
+ );
11497
+ results.identity = "link_required";
11498
+ return false;
11499
+ }
11500
+ const cause = text(parsed.cause);
11501
+ const fix = text(parsed.remedy);
11502
+ remedy(
11503
+ cause && fix ? `identity \xB7 failed: ${cause}; to fix it, ${fix}` : "identity \xB7 failed; run `prim auth identify` to see why"
11504
+ );
11505
+ results.identity = "failed";
11506
+ return false;
11507
+ }
11164
11508
  function credentialsReady({ deps, results, remedy, env }) {
11165
11509
  let machine;
11166
11510
  try {
@@ -11247,7 +11591,7 @@ function sessionSteps(deps, results, remedies, options = {}, outcome = {}) {
11247
11591
  remedies.push(message);
11248
11592
  };
11249
11593
  const check = { deps, results, remedy, env: deps.env ?? process.env };
11250
- const credentials = credentialsReady(check);
11594
+ const credentials = identityReady(check) && credentialsReady(check);
11251
11595
  const root = repositoryRoot(check, outcome);
11252
11596
  if (!outcome.optedOut) sessionHooks(check, root ?? gitToplevel(deps.cwd) ?? void 0, options);
11253
11597
  if (!credentials || !root) return;
@@ -11303,7 +11647,7 @@ function finish(deps, mode, results, remedies, optedOut = false) {
11303
11647
  deps.note(
11304
11648
  failed.length === 0 ? `cloud ${mode} complete` : `cloud ${mode} incomplete (${failed.join(", ")})`
11305
11649
  );
11306
- const instructions = failed.length === 0 ? mode === "prepare" ? "The cloud environment is prepared; sessions started from it load prim's hooks." : optedOut ? "This repository opts out of Primitive (PRIM_ACTIVE=false in its .claude/settings.json), so nothing was activated. Tell the user in one sentence, then continue their task; do not run prim enable unless they ask." : "Primitive is set up in this Claude Code cloud session. Tell the user in one sentence, then continue their task. There is no welcome or demo in cloud sessions." : "Cloud setup is incomplete. Tell the user each remedy in one sentence before continuing; do not run prim auth login or prim auth enroll, which cannot work in a cloud session.";
11650
+ const instructions = failed.length === 0 ? mode === "prepare" ? "The cloud environment is prepared; sessions started from it load prim's hooks." : optedOut ? "This repository opts out of Primitive (PRIM_ACTIVE=false in its .claude/settings.json), so nothing was activated. Tell the user in one sentence, then continue their task; do not run prim enable unless they ask." : "Primitive is set up in this Claude Code cloud session. Tell the user in one sentence, then continue their task. There is no welcome or demo in cloud sessions." : results.identity === "link_required" ? "Cloud setup is waiting for a one-time GitHub link. Tell the user each remedy in one sentence before continuing. When they agree, run `prim auth link` as a background command (it waits until they finish signing in), give them the sign-in URL and code it prints, then run `prim setup --cloud` again; do not run prim auth login or prim auth enroll." : "Cloud setup is incomplete. Tell the user each remedy in one sentence before continuing; do not run prim auth login or prim auth enroll, which cannot work in a cloud session.";
11307
11651
  printJson({
11308
11652
  ok: failed.length === 0,
11309
11653
  cloud: mode,