@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.
- package/README.md +211 -1
- package/SKILL.md +6 -1
- package/dist/{chunk-ZKXNJB6U.js → chunk-3KPTVK4N.js} +70 -78
- package/dist/{chunk-6KXQQ7CQ.js → chunk-4DYEBYKM.js} +3 -5
- package/dist/{chunk-NJBN3WXF.js → chunk-6QAXVFRJ.js} +1900 -179
- package/dist/{chunk-R6NDP7OF.js → chunk-ANMNGGTN.js} +2 -2
- package/dist/{chunk-PPZ56EVJ.js → chunk-B3ICJZXV.js} +4 -2
- package/dist/{chunk-5D2C6RCH.js → chunk-C357P37M.js} +4 -4
- package/dist/{chunk-DT7E3SD5.js → chunk-E57UVUJL.js} +6 -6
- package/dist/{chunk-KKUDAQQZ.js → chunk-EQWUCFXK.js} +3 -3
- package/dist/{chunk-JFWJN2ME.js → chunk-M6KIDB5R.js} +119 -5
- package/dist/{chunk-NBNQI3YJ.js → chunk-N6PZE7HX.js} +6 -3
- package/dist/{chunk-O73J3KQQ.js → chunk-NYDM4HSS.js} +8 -5
- package/dist/{chunk-74DQDWLW.js → chunk-P4O7L7JZ.js} +7 -2
- package/dist/{chunk-L32WYFJT.js → chunk-PRJ7P6J5.js} +135 -12
- package/dist/{chunk-ND6TYHNI.js → chunk-PTZ6BWSU.js} +2 -2
- package/dist/{chunk-BFYJLI7V.js → chunk-QQ3G5SXX.js} +1 -1
- package/dist/{chunk-EZXIKEMA.js → chunk-RDT2IV2Z.js} +9 -7
- package/dist/{chunk-TI37ME2D.js → chunk-VLT2KGPE.js} +47 -38
- package/dist/{chunk-YP4OXKNX.js → chunk-WEGZGF3K.js} +1 -1
- package/dist/{chunk-C5VBPHOS.js → chunk-XINFTNA2.js} +23 -9
- package/dist/{chunk-FYYHBOOM.js → chunk-ZCT23NBS.js} +2 -2
- package/dist/daemon/server.js +1976 -442
- package/dist/hook-runtime/daemon/server.js +1976 -442
- package/dist/hook-runtime/hooks/post-commit.js +592 -212
- package/dist/hook-runtime/hooks/post-rewrite.js +584 -204
- package/dist/hook-runtime/hooks/post-tool-use.js +1997 -575
- package/dist/hook-runtime/hooks/pre-commit.js +1742 -350
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1656 -261
- package/dist/hook-runtime/hooks/prim-hook.js +1992 -573
- package/dist/hook-runtime/hooks/session-end.js +549 -180
- package/dist/hook-runtime/hooks/session-start.js +2213 -596
- package/dist/hook-runtime/index.js +5318 -2423
- package/dist/hook-runtime/statusline-main.js +531 -150
- package/dist/hooks/post-commit.js +7 -7
- package/dist/hooks/post-rewrite.js +6 -6
- package/dist/hooks/post-tool-use.js +18 -18
- package/dist/hooks/pre-commit.js +4 -4
- package/dist/hooks/pre-tool-use-worker.js +14 -15
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +95 -21
- package/dist/index.js +1386 -299
- package/dist/statusline-main.js +531 -150
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
import {
|
|
3
3
|
bindRepository,
|
|
4
4
|
bindRepositoryWithClient,
|
|
5
|
+
cloudAllowedDomains,
|
|
6
|
+
cloudEgressRemedy,
|
|
5
7
|
codexWelcomeSkillPath,
|
|
6
8
|
ensureEffectiveGitHook,
|
|
7
9
|
ensureGitHookAtPath,
|
|
@@ -9,6 +11,7 @@ import {
|
|
|
9
11
|
gitHooksMode,
|
|
10
12
|
hasCurrentHookBlock,
|
|
11
13
|
inspectEffectiveGitHook,
|
|
14
|
+
isCloudMachineSession,
|
|
12
15
|
isLegacyOwnedGlobalHook,
|
|
13
16
|
isOwnedStandalonePreCommit,
|
|
14
17
|
kickDaemonEnsure,
|
|
@@ -16,13 +19,14 @@ import {
|
|
|
16
19
|
projectGitHookTarget,
|
|
17
20
|
projectHooksDir,
|
|
18
21
|
registerSkillCommands,
|
|
22
|
+
repositoryIdentityRemedy,
|
|
19
23
|
resolveEffectiveGitHook,
|
|
20
24
|
resolveRepositoryBinding,
|
|
21
25
|
uninstallGitHookAtPath,
|
|
22
26
|
uninstallProjectGitHook,
|
|
23
27
|
userTargetFor,
|
|
24
28
|
welcomeSkillPathFor
|
|
25
|
-
} from "./chunk-
|
|
29
|
+
} from "./chunk-M6KIDB5R.js";
|
|
26
30
|
import {
|
|
27
31
|
InvalidJournalEnvelopeError,
|
|
28
32
|
buildOrganizationBoundMoveRequest,
|
|
@@ -30,27 +34,27 @@ import {
|
|
|
30
34
|
inspectJournalDelivery,
|
|
31
35
|
requireDurableIngestAcknowledgement,
|
|
32
36
|
summarizeRetainedBuckets
|
|
33
|
-
} from "./chunk-
|
|
37
|
+
} from "./chunk-VLT2KGPE.js";
|
|
34
38
|
import {
|
|
35
39
|
checkAffectedDecisions,
|
|
36
40
|
daemonOrDirectGet,
|
|
37
41
|
formatDecisionsWarning
|
|
38
|
-
} from "./chunk-
|
|
42
|
+
} from "./chunk-RDT2IV2Z.js";
|
|
39
43
|
import {
|
|
40
44
|
hasCompleteCoverage,
|
|
41
45
|
requestPreflight2 as requestPreflight,
|
|
42
46
|
waitForPreflight
|
|
43
|
-
} from "./chunk-
|
|
47
|
+
} from "./chunk-XINFTNA2.js";
|
|
44
48
|
import {
|
|
45
49
|
fetchFeedbackCapability
|
|
46
|
-
} from "./chunk-
|
|
50
|
+
} from "./chunk-B3ICJZXV.js";
|
|
47
51
|
import {
|
|
48
52
|
POST_COMMIT_GRACE_MS,
|
|
49
53
|
clearHooksWired,
|
|
50
54
|
inspectPostCommitFiring,
|
|
51
55
|
lastConversationCaptured,
|
|
52
56
|
recordHooksWired
|
|
53
|
-
} from "./chunk-
|
|
57
|
+
} from "./chunk-QQ3G5SXX.js";
|
|
54
58
|
import {
|
|
55
59
|
isUnattended,
|
|
56
60
|
unattendedEnv
|
|
@@ -63,7 +67,7 @@ import {
|
|
|
63
67
|
formatStatusline,
|
|
64
68
|
formatTeammates,
|
|
65
69
|
repositoryBindingDiagnosticLabel
|
|
66
|
-
} from "./chunk-
|
|
70
|
+
} from "./chunk-4DYEBYKM.js";
|
|
67
71
|
import {
|
|
68
72
|
JOURNAL_DIR,
|
|
69
73
|
SESSIONS_DIR,
|
|
@@ -78,11 +82,11 @@ import {
|
|
|
78
82
|
rotationIdentity,
|
|
79
83
|
sweepOrphanedDrainProgress,
|
|
80
84
|
writeDrainCheckpoint
|
|
81
|
-
} from "./chunk-
|
|
85
|
+
} from "./chunk-N6PZE7HX.js";
|
|
82
86
|
import {
|
|
83
87
|
daemonIsLive,
|
|
84
88
|
daemonRequest
|
|
85
|
-
} from "./chunk-
|
|
89
|
+
} from "./chunk-WEGZGF3K.js";
|
|
86
90
|
import {
|
|
87
91
|
RUN_ID,
|
|
88
92
|
demoCommand,
|
|
@@ -103,13 +107,15 @@ import {
|
|
|
103
107
|
readRun,
|
|
104
108
|
runIds,
|
|
105
109
|
saveRun
|
|
106
|
-
} from "./chunk-
|
|
110
|
+
} from "./chunk-EQWUCFXK.js";
|
|
107
111
|
import {
|
|
108
112
|
MANAGED_GIT_HOOK_NAMES,
|
|
109
113
|
assertOwnedHookRuntime,
|
|
110
114
|
atomicWrite,
|
|
115
|
+
cloudUserInstallComplete,
|
|
111
116
|
ensureRegistration,
|
|
112
117
|
entryHasCommand,
|
|
118
|
+
hasDeveloperUserInstall,
|
|
113
119
|
hookRuntimePaths,
|
|
114
120
|
inspectFailureProtection,
|
|
115
121
|
inspectGitHookEntrypoint,
|
|
@@ -118,8 +124,10 @@ import {
|
|
|
118
124
|
inspectHookRuntimeResolutions2,
|
|
119
125
|
makeRegistration,
|
|
120
126
|
managedHookBlock,
|
|
127
|
+
performCloudUserInstall,
|
|
121
128
|
performStatus,
|
|
122
129
|
performStatus2,
|
|
130
|
+
planProjectInactiveDeclaration,
|
|
123
131
|
projectRoot,
|
|
124
132
|
readSettings,
|
|
125
133
|
registerClaudeCommands,
|
|
@@ -129,9 +137,10 @@ import {
|
|
|
129
137
|
stableNodePath,
|
|
130
138
|
stageHookRuntime,
|
|
131
139
|
stripCommand
|
|
132
|
-
} from "./chunk-
|
|
133
|
-
import "./chunk-
|
|
140
|
+
} from "./chunk-PRJ7P6J5.js";
|
|
141
|
+
import "./chunk-P4O7L7JZ.js";
|
|
134
142
|
import {
|
|
143
|
+
MAX_SCOPE_GLOB_CHARS,
|
|
135
144
|
bold,
|
|
136
145
|
boundedHealthError,
|
|
137
146
|
color,
|
|
@@ -155,14 +164,18 @@ import {
|
|
|
155
164
|
isGitHubInstallIntentStartResponse,
|
|
156
165
|
isGitHubInstallIntentStatusResponse,
|
|
157
166
|
isReconcileResolutionResponse,
|
|
167
|
+
isScopeDirectoryPrefix,
|
|
168
|
+
isScopeGlobPattern,
|
|
158
169
|
stripAnsi
|
|
159
|
-
} from "./chunk-
|
|
170
|
+
} from "./chunk-NYDM4HSS.js";
|
|
160
171
|
import {
|
|
161
172
|
CliManagementResponseError,
|
|
173
|
+
DEFAULT_API_URL,
|
|
162
174
|
HttpError,
|
|
163
175
|
clearStoredCredentials,
|
|
164
176
|
commitCredentials,
|
|
165
177
|
decisionIdentifier,
|
|
178
|
+
getBearerClient,
|
|
166
179
|
getClient,
|
|
167
180
|
getPinnedClient,
|
|
168
181
|
getPinnedManagementClient,
|
|
@@ -171,13 +184,17 @@ import {
|
|
|
171
184
|
getTokenExpiresAt,
|
|
172
185
|
isSessionEnded,
|
|
173
186
|
refreshToken,
|
|
174
|
-
setStoredToken
|
|
175
|
-
|
|
176
|
-
terminalSafeLine
|
|
177
|
-
} from "./chunk-ZKXNJB6U.js";
|
|
187
|
+
setStoredToken
|
|
188
|
+
} from "./chunk-3KPTVK4N.js";
|
|
178
189
|
import {
|
|
190
|
+
CLOUD_CREDENTIALS_REMEDY,
|
|
191
|
+
CLOUD_GITHUB_CONNECT_REMEDY,
|
|
192
|
+
CLOUD_SETUP_POINTER,
|
|
179
193
|
MachineAuthError,
|
|
180
194
|
REFRESH_TOKEN_PATH,
|
|
195
|
+
SERVER_WAIT_PREFIX,
|
|
196
|
+
SESSION_IDENTITY_VALUE,
|
|
197
|
+
SESSION_IDENTITY_VARIABLE,
|
|
181
198
|
TOKEN_FILE_PATH,
|
|
182
199
|
WorkosConnectProtocolError,
|
|
183
200
|
acquireMachineCredential,
|
|
@@ -185,33 +202,50 @@ import {
|
|
|
185
202
|
binFile,
|
|
186
203
|
canonicalGitRoot,
|
|
187
204
|
canonicalRepositoryPath,
|
|
205
|
+
clearCloudPrepared,
|
|
188
206
|
clearDemoPause,
|
|
207
|
+
clearMachineCooldowns,
|
|
189
208
|
clearMachineCredentials,
|
|
190
209
|
commandMatchesBin,
|
|
191
210
|
compareSemver,
|
|
192
211
|
configureMachine,
|
|
193
212
|
decisionIngestionStatus,
|
|
213
|
+
declaresInactive,
|
|
194
214
|
discoverMachineConfiguration,
|
|
195
215
|
discoverWorkosConnect,
|
|
196
216
|
endDemoPause,
|
|
217
|
+
ensureSessionIdentity,
|
|
197
218
|
environmentCredentials,
|
|
219
|
+
exchangeMachineCredentials,
|
|
220
|
+
explicitlyActive,
|
|
198
221
|
extendDemoPause,
|
|
199
222
|
gitToplevel,
|
|
223
|
+
githubRepositoryFullName,
|
|
200
224
|
hasMachineConfiguration,
|
|
225
|
+
hasProjectPrimInstall,
|
|
201
226
|
healDemoPause,
|
|
202
227
|
hookCommandResolutions,
|
|
228
|
+
insideClaudeCode,
|
|
229
|
+
isClaudeCloudSession,
|
|
230
|
+
isGitIgnored,
|
|
231
|
+
isPreparedCloudSession,
|
|
203
232
|
isRepoActiveForCapture,
|
|
204
233
|
isValidRepoSyncId,
|
|
234
|
+
linkSessionIdentity,
|
|
235
|
+
machineApiUrl,
|
|
205
236
|
machineContext,
|
|
206
237
|
machineRecord,
|
|
207
238
|
machineString,
|
|
208
239
|
mainWorktreeRoot,
|
|
240
|
+
markActivationExplicit,
|
|
241
|
+
markCloudPrepared,
|
|
209
242
|
packageRoot,
|
|
210
243
|
packageVersion,
|
|
211
244
|
pauseCaptureForDemo,
|
|
212
245
|
pinnedNpxArgs,
|
|
213
246
|
pollWorkosDeviceAuthorization,
|
|
214
247
|
prepareMachineMetadataDirectory,
|
|
248
|
+
preparedInSession,
|
|
215
249
|
primConfigDirectory,
|
|
216
250
|
processIsAlive,
|
|
217
251
|
readDemoPause,
|
|
@@ -221,14 +255,20 @@ import {
|
|
|
221
255
|
repositoryBindingState,
|
|
222
256
|
requestWorkosDeviceAuthorization,
|
|
223
257
|
resolveAuthCredential,
|
|
258
|
+
resolveStoredCredential,
|
|
259
|
+
sessionIdentityMessage,
|
|
260
|
+
sessionIdentityMode,
|
|
224
261
|
setRepoActive,
|
|
225
262
|
stableHookCommand,
|
|
263
|
+
stripControlChars,
|
|
226
264
|
syncDirectory,
|
|
265
|
+
terminalSafeLine,
|
|
266
|
+
verifyAcquiredMachineIdentity,
|
|
227
267
|
verifyMachineIdentity,
|
|
228
268
|
withFileLock,
|
|
229
269
|
withFileLockSync,
|
|
230
270
|
writeMachineMetadata
|
|
231
|
-
} from "./chunk-
|
|
271
|
+
} from "./chunk-6QAXVFRJ.js";
|
|
232
272
|
import "./chunk-JSBRDJBE.js";
|
|
233
273
|
|
|
234
274
|
// src/index.ts
|
|
@@ -361,19 +401,6 @@ async function pollGitHubInstallIntent(client, start, options = {}) {
|
|
|
361
401
|
}
|
|
362
402
|
}
|
|
363
403
|
|
|
364
|
-
// src/lib/developer-enrollment.ts
|
|
365
|
-
import {
|
|
366
|
-
constants as constants2,
|
|
367
|
-
createHash as createHash2,
|
|
368
|
-
generateKeyPairSync,
|
|
369
|
-
privateDecrypt,
|
|
370
|
-
randomBytes as randomBytes2,
|
|
371
|
-
randomUUID
|
|
372
|
-
} from "crypto";
|
|
373
|
-
import { readFileSync } from "fs";
|
|
374
|
-
import { hostname } from "os";
|
|
375
|
-
import { join as join3 } from "path";
|
|
376
|
-
|
|
377
404
|
// src/flusher.ts
|
|
378
405
|
import { createReadStream, renameSync as renameSync2, statSync, unlinkSync } from "fs";
|
|
379
406
|
import { dirname as dirname2, join as join2 } from "path";
|
|
@@ -882,6 +909,17 @@ function journalNeedsFlush(now = Date.now()) {
|
|
|
882
909
|
}
|
|
883
910
|
|
|
884
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";
|
|
885
923
|
function installationPath(owner, directory = primConfigDirectory()) {
|
|
886
924
|
return join3(
|
|
887
925
|
directory,
|
|
@@ -912,6 +950,186 @@ async function activatePending(identity) {
|
|
|
912
950
|
return true;
|
|
913
951
|
}
|
|
914
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
|
+
}
|
|
960
|
+
async function exchangeEnrollment(client, request, onStarted) {
|
|
961
|
+
const { publicKey, privateKey } = generateKeyPairSync("rsa", { modulusLength: 2048 });
|
|
962
|
+
const verifier = randomBytes2(32).toString("hex");
|
|
963
|
+
const signal = AbortSignal.timeout(6e4);
|
|
964
|
+
const start = machineRecord(
|
|
965
|
+
await client.post(
|
|
966
|
+
"/api/cli/auth/enrollment/start",
|
|
967
|
+
{
|
|
968
|
+
installationId: request.installationId,
|
|
969
|
+
requestId: randomUUID(),
|
|
970
|
+
displayName: request.displayName,
|
|
971
|
+
publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),
|
|
972
|
+
challenge: createHash2("sha256").update(verifier).digest("hex"),
|
|
973
|
+
...request.environment ? { [ENROLLMENT_KIND_FIELD]: ENVIRONMENT_ENROLLMENT_KIND } : {}
|
|
974
|
+
},
|
|
975
|
+
{ signal }
|
|
976
|
+
)
|
|
977
|
+
);
|
|
978
|
+
if (!isCliEnrollmentStartResponse(start) || !machineString(start.enrollmentId, 128))
|
|
979
|
+
throw new MachineAuthError("invalid_enrollment", "The server returned an invalid enrollment.");
|
|
980
|
+
onStarted?.();
|
|
981
|
+
const response = machineRecord(
|
|
982
|
+
await client.post(
|
|
983
|
+
"/api/cli/auth/enrollment/redeem",
|
|
984
|
+
{ enrollmentId: start.enrollmentId, verifier },
|
|
985
|
+
{ signal }
|
|
986
|
+
)
|
|
987
|
+
);
|
|
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
|
+
)
|
|
995
|
+
throw new MachineAuthError(
|
|
996
|
+
"invalid_enrollment",
|
|
997
|
+
"The server returned an invalid enrollment exchange."
|
|
998
|
+
);
|
|
999
|
+
try {
|
|
1000
|
+
return {
|
|
1001
|
+
enrollmentId: start.enrollmentId,
|
|
1002
|
+
clientId: response.clientId,
|
|
1003
|
+
machineId: response.machineId,
|
|
1004
|
+
secret: privateDecrypt(
|
|
1005
|
+
{ key: privateKey, padding: constants2.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
|
|
1006
|
+
Buffer.from(response.ciphertext, "base64")
|
|
1007
|
+
).toString("utf8")
|
|
1008
|
+
};
|
|
1009
|
+
} catch {
|
|
1010
|
+
throw new MachineAuthError(
|
|
1011
|
+
"invalid_enrollment",
|
|
1012
|
+
"The credential exchange could not be decrypted for this installation."
|
|
1013
|
+
);
|
|
1014
|
+
}
|
|
1015
|
+
}
|
|
1016
|
+
async function enrollmentOwner(client, rejectedSessionHint = "Sign in once with prim auth login to authorize this developer installation.") {
|
|
1017
|
+
let status2;
|
|
1018
|
+
try {
|
|
1019
|
+
status2 = machineRecord(
|
|
1020
|
+
await client.get("/api/cli/auth/enrollment/status", {
|
|
1021
|
+
signal: AbortSignal.timeout(15e3)
|
|
1022
|
+
})
|
|
1023
|
+
);
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
if (error instanceof HttpError && (error.status === 401 || error.status === 403))
|
|
1026
|
+
throw new MachineAuthError("human_sign_in_required", rejectedSessionHint);
|
|
1027
|
+
throw error;
|
|
1028
|
+
}
|
|
1029
|
+
if (!machineString(status2.userId, 128) || !machineString(status2.organizationId, 128))
|
|
1030
|
+
throw new MachineAuthError(
|
|
1031
|
+
"invalid_enrollment",
|
|
1032
|
+
"The server did not verify the enrollment user and organization."
|
|
1033
|
+
);
|
|
1034
|
+
return { authorizedUserId: status2.userId, organizationId: status2.organizationId };
|
|
1035
|
+
}
|
|
1036
|
+
var INSTALLATION_NAME_MAX_LENGTH = 128;
|
|
1037
|
+
var ENV_VALUE = /^[\w.~+/:=-]+$/u;
|
|
1038
|
+
async function prepareEnvironmentEnrollment(displayName) {
|
|
1039
|
+
const name = displayName.trim();
|
|
1040
|
+
if (!machineString(name, INSTALLATION_NAME_MAX_LENGTH))
|
|
1041
|
+
throw new MachineAuthError(
|
|
1042
|
+
"invalid_installation_name",
|
|
1043
|
+
`Name the installation with 1-${INSTALLATION_NAME_MAX_LENGTH} printable characters.`
|
|
1044
|
+
);
|
|
1045
|
+
let siteUrl;
|
|
1046
|
+
try {
|
|
1047
|
+
siteUrl = machineApiUrl(getSiteUrl());
|
|
1048
|
+
} catch {
|
|
1049
|
+
siteUrl = "";
|
|
1050
|
+
}
|
|
1051
|
+
if (!siteUrl || !ENV_VALUE.test(siteUrl))
|
|
1052
|
+
throw new MachineAuthError(
|
|
1053
|
+
"invalid_configuration",
|
|
1054
|
+
"PRIM_API_URL must be an HTTPS origin that can be written as an .env value."
|
|
1055
|
+
);
|
|
1056
|
+
const configuration = await discoverMachineConfiguration(siteUrl);
|
|
1057
|
+
if (!configuration.developerEnrollment)
|
|
1058
|
+
throw new MachineAuthError(
|
|
1059
|
+
"enrollment_unavailable",
|
|
1060
|
+
"Automatic enrollment is not enabled on this server."
|
|
1061
|
+
);
|
|
1062
|
+
return { name, siteUrl, configuration };
|
|
1063
|
+
}
|
|
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) {
|
|
1071
|
+
const client = getBearerClient(humanAccessToken, siteUrl);
|
|
1072
|
+
const owner = await enrollmentOwner(
|
|
1073
|
+
client,
|
|
1074
|
+
"The server did not accept this sign-in for enrollment. Check the organization's enrollment policy, then retry."
|
|
1075
|
+
);
|
|
1076
|
+
let registered = false;
|
|
1077
|
+
try {
|
|
1078
|
+
const { clientId, machineId, secret } = await exchangeEnrollment(
|
|
1079
|
+
client,
|
|
1080
|
+
{
|
|
1081
|
+
installationId: randomUUID(),
|
|
1082
|
+
displayName: name,
|
|
1083
|
+
authorizedUserId: owner.authorizedUserId,
|
|
1084
|
+
environment
|
|
1085
|
+
},
|
|
1086
|
+
() => {
|
|
1087
|
+
registered = true;
|
|
1088
|
+
}
|
|
1089
|
+
);
|
|
1090
|
+
const tokens = await exchangeMachineCredentials(configuration, clientId, secret);
|
|
1091
|
+
const identity = await verifyMachineIdentity(siteUrl, tokens.accessToken, clientId);
|
|
1092
|
+
if (identity.machineId !== machineId || identity.authorizedUserId !== (environment ? void 0 : owner.authorizedUserId) || identity.organizationId !== owner.organizationId)
|
|
1093
|
+
throw new MachineAuthError(
|
|
1094
|
+
"delegation_mismatch",
|
|
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.",
|
|
1096
|
+
true
|
|
1097
|
+
);
|
|
1098
|
+
const lines = installationEnvironment({ clientId, clientSecret: secret }, siteUrl);
|
|
1099
|
+
return {
|
|
1100
|
+
environment: environment ? [...lines, SESSION_IDENTITY_ENVIRONMENT_LINE] : lines,
|
|
1101
|
+
displayName: name,
|
|
1102
|
+
clientId,
|
|
1103
|
+
clientSecret: secret,
|
|
1104
|
+
machineId,
|
|
1105
|
+
authorizedUserId: owner.authorizedUserId,
|
|
1106
|
+
organizationId: owner.organizationId
|
|
1107
|
+
};
|
|
1108
|
+
} catch (error) {
|
|
1109
|
+
const uncertain = !registered && !(error instanceof HttpError && error.status < 500);
|
|
1110
|
+
if (!registered && !uncertain) throw error;
|
|
1111
|
+
const cause = error instanceof MachineAuthError ? error.message : "Enrollment could not finish.";
|
|
1112
|
+
throw new MachineAuthError(
|
|
1113
|
+
error instanceof MachineAuthError ? error.code : "enrollment_failed",
|
|
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.`
|
|
1115
|
+
);
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
function installationEnvironment(installation, siteUrl) {
|
|
1119
|
+
const entries = [
|
|
1120
|
+
["PRIM_M2M_CLIENT_ID", installation.clientId],
|
|
1121
|
+
["PRIM_M2M_CLIENT_SECRET", installation.clientSecret]
|
|
1122
|
+
];
|
|
1123
|
+
if (siteUrl !== DEFAULT_API_URL) entries.push(["PRIM_API_URL", siteUrl]);
|
|
1124
|
+
return entries.map(([key, value]) => {
|
|
1125
|
+
if (!ENV_VALUE.test(value))
|
|
1126
|
+
throw new MachineAuthError(
|
|
1127
|
+
"invalid_credentials",
|
|
1128
|
+
`${key} cannot be written as an .env value.`
|
|
1129
|
+
);
|
|
1130
|
+
return `${key}=${value}`;
|
|
1131
|
+
});
|
|
1132
|
+
}
|
|
915
1133
|
async function enrollDeveloperInstallation(ifSupported = false) {
|
|
916
1134
|
if (hasMachineConfiguration()) {
|
|
917
1135
|
const current = await acquireMachineCredential();
|
|
@@ -959,27 +1177,7 @@ async function enrollDeveloperInstallation(ifSupported = false) {
|
|
|
959
1177
|
};
|
|
960
1178
|
}
|
|
961
1179
|
const client = await getPinnedClient();
|
|
962
|
-
|
|
963
|
-
try {
|
|
964
|
-
status2 = machineRecord(
|
|
965
|
-
await client.get("/api/cli/auth/enrollment/status", {
|
|
966
|
-
signal: AbortSignal.timeout(15e3)
|
|
967
|
-
})
|
|
968
|
-
);
|
|
969
|
-
} catch (error) {
|
|
970
|
-
if (error instanceof HttpError && (error.status === 401 || error.status === 403))
|
|
971
|
-
throw new MachineAuthError(
|
|
972
|
-
"human_sign_in_required",
|
|
973
|
-
"Sign in once with prim auth login to authorize this developer installation."
|
|
974
|
-
);
|
|
975
|
-
throw error;
|
|
976
|
-
}
|
|
977
|
-
if (!machineString(status2.userId, 128) || !machineString(status2.organizationId, 128))
|
|
978
|
-
throw new MachineAuthError(
|
|
979
|
-
"invalid_enrollment",
|
|
980
|
-
"The server did not verify the enrollment user and organization."
|
|
981
|
-
);
|
|
982
|
-
const owner = { authorizedUserId: status2.userId, organizationId: status2.organizationId };
|
|
1180
|
+
const owner = await enrollmentOwner(client);
|
|
983
1181
|
const path = installationPath(owner, directory);
|
|
984
1182
|
let installationId;
|
|
985
1183
|
try {
|
|
@@ -1000,58 +1198,18 @@ async function enrollDeveloperInstallation(ifSupported = false) {
|
|
|
1000
1198
|
await flush();
|
|
1001
1199
|
} catch {
|
|
1002
1200
|
}
|
|
1003
|
-
const {
|
|
1004
|
-
|
|
1005
|
-
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
{
|
|
1010
|
-
installationId,
|
|
1011
|
-
requestId: randomUUID(),
|
|
1012
|
-
displayName: hostname().slice(0, 128),
|
|
1013
|
-
publicKey: publicKey.export({ type: "spki", format: "pem" }).toString(),
|
|
1014
|
-
challenge: createHash2("sha256").update(verifier).digest("hex")
|
|
1015
|
-
},
|
|
1016
|
-
{ signal }
|
|
1017
|
-
)
|
|
1018
|
-
);
|
|
1019
|
-
if (!isCliEnrollmentStartResponse(start) || !machineString(start.enrollmentId, 128))
|
|
1020
|
-
throw new MachineAuthError(
|
|
1021
|
-
"invalid_enrollment",
|
|
1022
|
-
"The server returned an invalid enrollment."
|
|
1023
|
-
);
|
|
1024
|
-
const response = machineRecord(
|
|
1025
|
-
await client.post(
|
|
1026
|
-
"/api/cli/auth/enrollment/redeem",
|
|
1027
|
-
{ enrollmentId: start.enrollmentId, verifier },
|
|
1028
|
-
{ signal }
|
|
1029
|
-
)
|
|
1030
|
-
);
|
|
1031
|
-
if (!isCliEnrollmentRedeemResponse(response) || !machineString(response.clientId, 256) || !machineString(response.ciphertext, 4096) || response.authorizedUserId !== owner.authorizedUserId)
|
|
1032
|
-
throw new MachineAuthError(
|
|
1033
|
-
"invalid_enrollment",
|
|
1034
|
-
"The server returned an invalid enrollment exchange."
|
|
1035
|
-
);
|
|
1036
|
-
let secret;
|
|
1037
|
-
try {
|
|
1038
|
-
secret = privateDecrypt(
|
|
1039
|
-
{ key: privateKey, padding: constants2.RSA_PKCS1_OAEP_PADDING, oaepHash: "sha256" },
|
|
1040
|
-
Buffer.from(response.ciphertext, "base64")
|
|
1041
|
-
).toString("utf8");
|
|
1042
|
-
} catch {
|
|
1043
|
-
throw new MachineAuthError(
|
|
1044
|
-
"invalid_enrollment",
|
|
1045
|
-
"The credential exchange could not be decrypted for this installation."
|
|
1046
|
-
);
|
|
1047
|
-
}
|
|
1048
|
-
const profile = await configureMachine(response.clientId, secret, {
|
|
1201
|
+
const { enrollmentId, clientId, secret } = await exchangeEnrollment(client, {
|
|
1202
|
+
installationId,
|
|
1203
|
+
displayName: hostname().slice(0, 128),
|
|
1204
|
+
authorizedUserId: owner.authorizedUserId
|
|
1205
|
+
});
|
|
1206
|
+
const profile = await configureMachine(clientId, secret, {
|
|
1049
1207
|
expectedAuthorizedUserId: owner.authorizedUserId,
|
|
1050
1208
|
expectedOrganizationId: owner.organizationId
|
|
1051
1209
|
});
|
|
1052
1210
|
writeMachineMetadata(path, {
|
|
1053
1211
|
installationId,
|
|
1054
|
-
pendingEnrollmentId:
|
|
1212
|
+
pendingEnrollmentId: enrollmentId,
|
|
1055
1213
|
pendingMachineId: profile.machineId
|
|
1056
1214
|
});
|
|
1057
1215
|
const activationPending = await activatePending(profile);
|
|
@@ -1658,9 +1816,85 @@ function authStatusResult(status2, reason, source, refreshTokenPresent) {
|
|
|
1658
1816
|
warnings: source === "token_file" && !refreshTokenPresent ? ["no refresh token"] : []
|
|
1659
1817
|
};
|
|
1660
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
|
+
}
|
|
1661
1894
|
async function verifyAuthStatus() {
|
|
1662
1895
|
let machineMetadata = {};
|
|
1663
1896
|
try {
|
|
1897
|
+
if (hasMachineConfiguration() && sessionIdentityMode()) return await verifySessionStatus();
|
|
1664
1898
|
if (hasMachineConfiguration()) {
|
|
1665
1899
|
const context = machineContext();
|
|
1666
1900
|
machineMetadata = {
|
|
@@ -1674,16 +1908,12 @@ async function verifyAuthStatus() {
|
|
|
1674
1908
|
signal: AbortSignal.timeout(AUTH_PROBE_TIMEOUT_MS)
|
|
1675
1909
|
});
|
|
1676
1910
|
if (!machine) throw new Error("missing machine");
|
|
1677
|
-
|
|
1678
|
-
...machineMetadata,
|
|
1911
|
+
const tokenExpiry = machine.tokenInjection ? { accessTokenExpiresInMs: null, accessTokenExpired: false, tokenHeldByProxy: true } : {
|
|
1679
1912
|
accessTokenExpiresInMs: machine.expiresAt - Date.now(),
|
|
1680
1913
|
accessTokenExpired: machine.expiresAt <= Date.now()
|
|
1681
1914
|
};
|
|
1682
|
-
|
|
1683
|
-
|
|
1684
|
-
machine.accessToken,
|
|
1685
|
-
machine.clientId
|
|
1686
|
-
);
|
|
1915
|
+
machineMetadata = { ...machineMetadata, ...tokenExpiry };
|
|
1916
|
+
const identity = await verifyAcquiredMachineIdentity(machine);
|
|
1687
1917
|
return {
|
|
1688
1918
|
...authStatusResult("valid", "verified", "machine", false),
|
|
1689
1919
|
principalKind: "machine",
|
|
@@ -1693,8 +1923,7 @@ async function verifyAuthStatus() {
|
|
|
1693
1923
|
effectiveScopes: identity.scopes,
|
|
1694
1924
|
organizationId: machine.organizationId,
|
|
1695
1925
|
storageBackend: machine.storage,
|
|
1696
|
-
|
|
1697
|
-
accessTokenExpired: machine.expiresAt <= Date.now()
|
|
1926
|
+
...tokenExpiry
|
|
1698
1927
|
};
|
|
1699
1928
|
}
|
|
1700
1929
|
} catch (error) {
|
|
@@ -1713,7 +1942,8 @@ async function verifyAuthStatus() {
|
|
|
1713
1942
|
),
|
|
1714
1943
|
...machineMetadata,
|
|
1715
1944
|
principalKind: "machine",
|
|
1716
|
-
recoveryReason: error instanceof MachineAuthError ? error.code : "verification_unavailable"
|
|
1945
|
+
recoveryReason: error instanceof MachineAuthError ? error.code : "verification_unavailable",
|
|
1946
|
+
...error instanceof MachineAuthError ? { recoveryDetail: error.message } : {}
|
|
1717
1947
|
};
|
|
1718
1948
|
}
|
|
1719
1949
|
const credential = resolveAuthCredential();
|
|
@@ -1797,15 +2027,23 @@ function authStatusExitCode(status2) {
|
|
|
1797
2027
|
return status2 === "invalid" ? EXIT_FAIL : EXIT_UNREACHABLE;
|
|
1798
2028
|
}
|
|
1799
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
|
+
}
|
|
1800
2036
|
if (result.principalKind === "machine") {
|
|
1801
2037
|
console.error(
|
|
1802
|
-
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}. Check the credential store or run prim auth configure-machine with credentials from your administrator
|
|
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."}`
|
|
1803
2039
|
);
|
|
1804
2040
|
return;
|
|
1805
2041
|
}
|
|
1806
2042
|
if (result.status === "invalid") {
|
|
1807
2043
|
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.";
|
|
1808
|
-
console.log(
|
|
2044
|
+
console.log(
|
|
2045
|
+
isClaudeCloudSession() ? `${detail} In a Claude Code cloud session, ${CLOUD_CREDENTIALS_REMEDY}.` : `${detail} Run \`prim auth login\` to authenticate.`
|
|
2046
|
+
);
|
|
1809
2047
|
return;
|
|
1810
2048
|
}
|
|
1811
2049
|
if (result.status === "unreachable") {
|
|
@@ -1842,10 +2080,274 @@ function requiresLegacyAuthentication() {
|
|
|
1842
2080
|
);
|
|
1843
2081
|
return false;
|
|
1844
2082
|
}
|
|
2083
|
+
async function signInInteractively(options) {
|
|
2084
|
+
const siteUrl = getSiteUrl();
|
|
2085
|
+
let discovery;
|
|
2086
|
+
try {
|
|
2087
|
+
discovery = await discoverWorkosConnect(siteUrl);
|
|
2088
|
+
} catch (error) {
|
|
2089
|
+
return {
|
|
2090
|
+
ok: false,
|
|
2091
|
+
error: error instanceof WorkosConnectProtocolError ? error.code : "config_fetch_failed",
|
|
2092
|
+
detail: error instanceof Error ? error.message : "Connect discovery failed"
|
|
2093
|
+
};
|
|
2094
|
+
}
|
|
2095
|
+
if (discovery.state === "available") {
|
|
2096
|
+
try {
|
|
2097
|
+
const authorization = await requestWorkosDeviceAuthorization(discovery.configuration);
|
|
2098
|
+
const verificationUrl = authorization.verificationUriComplete ?? authorization.verificationUri;
|
|
2099
|
+
console.error(`Authenticate at:
|
|
2100
|
+
${verificationUrl}`);
|
|
2101
|
+
console.error(`Verification code: ${authorization.userCode}`);
|
|
2102
|
+
if (options.browser) openBrowser(verificationUrl);
|
|
2103
|
+
const tokens = await pollWorkosDeviceAuthorization(discovery.configuration, authorization);
|
|
2104
|
+
return {
|
|
2105
|
+
ok: true,
|
|
2106
|
+
flow: "device",
|
|
2107
|
+
credentials: {
|
|
2108
|
+
...tokens,
|
|
2109
|
+
metadata: {
|
|
2110
|
+
version: 1,
|
|
2111
|
+
family: "workos_connect",
|
|
2112
|
+
issuer: discovery.configuration.issuer,
|
|
2113
|
+
clientId: discovery.configuration.clientId
|
|
2114
|
+
}
|
|
2115
|
+
}
|
|
2116
|
+
};
|
|
2117
|
+
} catch (error) {
|
|
2118
|
+
return {
|
|
2119
|
+
ok: false,
|
|
2120
|
+
error: error instanceof WorkosConnectProtocolError ? error.code : "device_authorization_failed",
|
|
2121
|
+
detail: error instanceof Error ? error.message : "Device authorization failed"
|
|
2122
|
+
};
|
|
2123
|
+
}
|
|
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
|
+
};
|
|
2131
|
+
let config;
|
|
2132
|
+
try {
|
|
2133
|
+
config = await fetchAuthBrokerConfig(siteUrl);
|
|
2134
|
+
} catch {
|
|
2135
|
+
return {
|
|
2136
|
+
ok: false,
|
|
2137
|
+
error: "config_fetch_failed",
|
|
2138
|
+
detail: "Failed to fetch MCP config. Is the Convex backend running?"
|
|
2139
|
+
};
|
|
2140
|
+
}
|
|
2141
|
+
const { verifier, challenge } = generatePkce();
|
|
2142
|
+
const state = base64url(randomBytes4(16));
|
|
2143
|
+
const redirectUri = `http://${LOCALHOST}:${CALLBACK_PORT}/callback`;
|
|
2144
|
+
let settle;
|
|
2145
|
+
const outcome = new Promise((resolve8) => {
|
|
2146
|
+
settle = resolve8;
|
|
2147
|
+
});
|
|
2148
|
+
const server = createServer((req, res) => {
|
|
2149
|
+
const url = new URL(req.url ?? "/", `http://${LOCALHOST}`);
|
|
2150
|
+
if (url.pathname !== "/callback") {
|
|
2151
|
+
res.writeHead(404);
|
|
2152
|
+
res.end("Not found");
|
|
2153
|
+
return;
|
|
2154
|
+
}
|
|
2155
|
+
const page = resolveCallbackPage(url.searchParams, state);
|
|
2156
|
+
res.writeHead(page.status, HTML_HEADERS);
|
|
2157
|
+
res.end(page.html, () => settle(page.result));
|
|
2158
|
+
});
|
|
2159
|
+
try {
|
|
2160
|
+
await new Promise((resolve8, reject) => {
|
|
2161
|
+
const onError = (err) => reject(err);
|
|
2162
|
+
server.once("error", onError);
|
|
2163
|
+
server.listen(CALLBACK_PORT, LOCALHOST, () => {
|
|
2164
|
+
server.removeListener("error", onError);
|
|
2165
|
+
resolve8();
|
|
2166
|
+
});
|
|
2167
|
+
});
|
|
2168
|
+
} catch (err) {
|
|
2169
|
+
if (err instanceof Error && err.code === "EADDRINUSE") {
|
|
2170
|
+
return {
|
|
2171
|
+
ok: false,
|
|
2172
|
+
error: "callback_port_in_use",
|
|
2173
|
+
detail: `Port ${CALLBACK_PORT} is in use \u2014 another prim sign-in may be running. Close it and retry.`
|
|
2174
|
+
};
|
|
2175
|
+
}
|
|
2176
|
+
return {
|
|
2177
|
+
ok: false,
|
|
2178
|
+
error: "callback_bind_failed",
|
|
2179
|
+
detail: `Could not start the local callback server: ${err instanceof Error ? err.message : String(err)}`
|
|
2180
|
+
};
|
|
2181
|
+
}
|
|
2182
|
+
server.on("error", () => {
|
|
2183
|
+
});
|
|
2184
|
+
const authUrl = new URL(config.authorization_endpoint);
|
|
2185
|
+
authUrl.searchParams.set("client_id", config.client_id);
|
|
2186
|
+
authUrl.searchParams.set("redirect_uri", redirectUri);
|
|
2187
|
+
authUrl.searchParams.set("response_type", "code");
|
|
2188
|
+
authUrl.searchParams.set("provider", "authkit");
|
|
2189
|
+
authUrl.searchParams.set("scope", config.default_scopes.join(" "));
|
|
2190
|
+
authUrl.searchParams.set("state", state);
|
|
2191
|
+
authUrl.searchParams.set("code_challenge", challenge);
|
|
2192
|
+
authUrl.searchParams.set("code_challenge_method", "S256");
|
|
2193
|
+
if (options.browser) {
|
|
2194
|
+
console.error("Opening browser for authentication...");
|
|
2195
|
+
openBrowser(authUrl.toString());
|
|
2196
|
+
}
|
|
2197
|
+
console.error(`If the browser doesn't open, visit:
|
|
2198
|
+
${authUrl.toString()}
|
|
2199
|
+
`);
|
|
2200
|
+
console.error("Waiting for callback...");
|
|
2201
|
+
const timer = setTimeout(() => {
|
|
2202
|
+
settle({ authenticated: false, error: "timeout", detail: "Authentication timed out." });
|
|
2203
|
+
}, CALLBACK_TIMEOUT_MS);
|
|
2204
|
+
timer.unref();
|
|
2205
|
+
const result = await outcome;
|
|
2206
|
+
clearTimeout(timer);
|
|
2207
|
+
server.close();
|
|
2208
|
+
if (!result.authenticated) {
|
|
2209
|
+
return { ok: false, error: result.error, detail: result.detail };
|
|
2210
|
+
}
|
|
2211
|
+
try {
|
|
2212
|
+
const tokens = await exchangeCode(siteUrl, result.code, verifier, redirectUri);
|
|
2213
|
+
return { ok: true, flow: "legacy", credentials: tokens };
|
|
2214
|
+
} catch (err) {
|
|
2215
|
+
return {
|
|
2216
|
+
ok: false,
|
|
2217
|
+
error: "token_exchange_failed",
|
|
2218
|
+
detail: err instanceof Error ? err.message : String(err)
|
|
2219
|
+
};
|
|
2220
|
+
}
|
|
2221
|
+
}
|
|
2222
|
+
function signInHost(issuer) {
|
|
2223
|
+
try {
|
|
2224
|
+
return new URL(issuer).hostname;
|
|
2225
|
+
} catch {
|
|
2226
|
+
return "the sign-in host";
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
function reportEnrollmentFailure(error, detail) {
|
|
2230
|
+
const human = detail ? `${stripControlChars(error)}: ${stripControlChars(detail)}` : stripControlChars(error);
|
|
2231
|
+
console.error(`Enrollment failed: ${human}`);
|
|
2232
|
+
process.exitCode = EXIT_FAIL;
|
|
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
|
+
}
|
|
2280
|
+
async function enrollNewInstallation(options) {
|
|
2281
|
+
if (!options.newInstallation || !options.printEnv || options.ifSupported) {
|
|
2282
|
+
reportEnrollmentFailure(
|
|
2283
|
+
"invalid_arguments",
|
|
2284
|
+
"Use --new-installation <name> together with --print-env (and without --if-supported)."
|
|
2285
|
+
);
|
|
2286
|
+
return;
|
|
2287
|
+
}
|
|
2288
|
+
try {
|
|
2289
|
+
const enrollment = await prepareEnvironmentEnrollment(options.newInstallation);
|
|
2290
|
+
console.error(
|
|
2291
|
+
`Sign in to authorize a new installation named "${stripControlChars(enrollment.name)}". This machine's own credentials are not changed.`
|
|
2292
|
+
);
|
|
2293
|
+
const signIn = await signInInteractively({ browser: options.browser });
|
|
2294
|
+
if (!signIn.ok) {
|
|
2295
|
+
reportEnrollmentFailure(signIn.error, signIn.detail);
|
|
2296
|
+
return;
|
|
2297
|
+
}
|
|
2298
|
+
const installation = await enrollEnvironmentInstallation(
|
|
2299
|
+
enrollment,
|
|
2300
|
+
signIn.credentials.accessToken
|
|
2301
|
+
);
|
|
2302
|
+
process.stdout.write(`${installation.environment.join("\n")}
|
|
2303
|
+
`);
|
|
2304
|
+
console.error(
|
|
2305
|
+
[
|
|
2306
|
+
`Installation "${stripControlChars(installation.displayName)}" is authorized for your account; its Decisions belong to you.`,
|
|
2307
|
+
"The secret is shown only once and is not stored on this machine.",
|
|
2308
|
+
// Anyone who uses a cloud environment can read its variables; its
|
|
2309
|
+
// network secrets cannot be read back, so say that way first.
|
|
2310
|
+
`For a Claude Code cloud environment, keep the secret out of the variables: add a "Username and password" network secret for ${signInHost(enrollment.configuration.issuer)} (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.`,
|
|
2311
|
+
"Or paste every line above into the environment's variables, where anyone who uses the environment can read them.",
|
|
2312
|
+
"An organization admin can revoke the installation in Settings \u2192 Developer installations."
|
|
2313
|
+
].join("\n")
|
|
2314
|
+
);
|
|
2315
|
+
process.exitCode = EXIT_OK;
|
|
2316
|
+
} catch (error) {
|
|
2317
|
+
reportEnrollmentFailure(
|
|
2318
|
+
error instanceof MachineAuthError ? error.code : "enrollment_failed",
|
|
2319
|
+
error instanceof MachineAuthError ? error.message : "Enrollment could not finish. Check the organization's enrollment policy, then retry."
|
|
2320
|
+
);
|
|
2321
|
+
}
|
|
2322
|
+
}
|
|
2323
|
+
function refuseCloudSignIn(report = reportFailure) {
|
|
2324
|
+
if (!isClaudeCloudSession()) return false;
|
|
2325
|
+
report(
|
|
2326
|
+
"cloud_session_sign_in_unavailable",
|
|
2327
|
+
`Interactive sign-in is not used inside a Claude Code cloud session. ${CLOUD_CREDENTIALS_REMEDY.charAt(0).toUpperCase()}${CLOUD_CREDENTIALS_REMEDY.slice(1)}.`
|
|
2328
|
+
);
|
|
2329
|
+
return true;
|
|
2330
|
+
}
|
|
1845
2331
|
function registerAuthCommands(program2) {
|
|
1846
2332
|
const auth = program2.command("auth").description("Manage CLI authentication");
|
|
1847
|
-
auth.command("enroll").description("Authorize this developer installation using your signed-in account").option("--if-supported", "Keep legacy authentication when server enrollment is unavailable").
|
|
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(
|
|
2334
|
+
"--new-installation <name>",
|
|
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)"
|
|
2339
|
+
).option(
|
|
2340
|
+
"--print-env",
|
|
2341
|
+
"Print the new installation's PRIM_M2M_* credentials to STDOUT as .env lines for an environment"
|
|
2342
|
+
).option("--no-browser", "Print the sign-in URL without opening a browser").action(async (options) => {
|
|
2343
|
+
if (options.newInstallation !== void 0 || options.newEnvironment !== void 0 || options.printEnv) {
|
|
2344
|
+
if (refuseCloudSignIn(reportEnrollmentFailure)) return;
|
|
2345
|
+
if (options.newEnvironment !== void 0) await enrollNewEnvironment(options);
|
|
2346
|
+
else await enrollNewInstallation(options);
|
|
2347
|
+
return;
|
|
2348
|
+
}
|
|
1848
2349
|
try {
|
|
2350
|
+
if (isClaudeCloudSession() && !hasMachineConfiguration() && refuseCloudSignIn()) return;
|
|
1849
2351
|
const result = await enrollDeveloperInstallation(options.ifSupported);
|
|
1850
2352
|
if (result.enrolled)
|
|
1851
2353
|
console.error(
|
|
@@ -1924,134 +2426,20 @@ function registerAuthCommands(program2) {
|
|
|
1924
2426
|
});
|
|
1925
2427
|
auth.command("login").description("Authenticate via browser (WorkOS OAuth)").option("--no-browser", "Print the verification URL without opening a browser").action(async (options) => {
|
|
1926
2428
|
if (!requiresLegacyAuthentication()) return;
|
|
1927
|
-
|
|
1928
|
-
|
|
1929
|
-
|
|
1930
|
-
|
|
1931
|
-
} catch (error) {
|
|
1932
|
-
reportFailure(
|
|
1933
|
-
error instanceof WorkosConnectProtocolError ? error.code : "config_fetch_failed",
|
|
1934
|
-
error instanceof Error ? error.message : "Connect discovery failed"
|
|
1935
|
-
);
|
|
2429
|
+
if (refuseCloudSignIn()) return;
|
|
2430
|
+
const signIn = await signInInteractively(options);
|
|
2431
|
+
if (!signIn.ok) {
|
|
2432
|
+
reportFailure(signIn.error, signIn.detail);
|
|
1936
2433
|
return;
|
|
1937
2434
|
}
|
|
1938
|
-
if (discovery.state === "available") {
|
|
1939
|
-
try {
|
|
1940
|
-
const authorization = await requestWorkosDeviceAuthorization(discovery.configuration);
|
|
1941
|
-
const verificationUrl = authorization.verificationUriComplete ?? authorization.verificationUri;
|
|
1942
|
-
console.error(`Authenticate at:
|
|
1943
|
-
${verificationUrl}`);
|
|
1944
|
-
console.error(`Verification code: ${authorization.userCode}`);
|
|
1945
|
-
if (options.browser) openBrowser(verificationUrl);
|
|
1946
|
-
const tokens = await pollWorkosDeviceAuthorization(
|
|
1947
|
-
discovery.configuration,
|
|
1948
|
-
authorization
|
|
1949
|
-
);
|
|
1950
|
-
await commitCredentials({
|
|
1951
|
-
...tokens,
|
|
1952
|
-
metadata: {
|
|
1953
|
-
version: 1,
|
|
1954
|
-
family: "workos_connect",
|
|
1955
|
-
issuer: discovery.configuration.issuer,
|
|
1956
|
-
clientId: discovery.configuration.clientId
|
|
1957
|
-
}
|
|
1958
|
-
});
|
|
1959
|
-
reportSuccess();
|
|
1960
|
-
} catch (error) {
|
|
1961
|
-
reportFailure(
|
|
1962
|
-
error instanceof WorkosConnectProtocolError ? error.code : "device_authorization_failed",
|
|
1963
|
-
error instanceof Error ? error.message : "Device authorization failed"
|
|
1964
|
-
);
|
|
1965
|
-
}
|
|
1966
|
-
return;
|
|
1967
|
-
}
|
|
1968
|
-
let config;
|
|
1969
2435
|
try {
|
|
1970
|
-
|
|
1971
|
-
|
|
2436
|
+
await commitCredentials(signIn.credentials);
|
|
2437
|
+
reportSuccess();
|
|
2438
|
+
} catch (error) {
|
|
1972
2439
|
reportFailure(
|
|
1973
|
-
"
|
|
1974
|
-
|
|
2440
|
+
signIn.flow === "device" ? "device_authorization_failed" : "token_exchange_failed",
|
|
2441
|
+
error instanceof Error ? error.message : signIn.flow === "device" ? "Device authorization failed" : String(error)
|
|
1975
2442
|
);
|
|
1976
|
-
return;
|
|
1977
|
-
}
|
|
1978
|
-
const { verifier, challenge } = generatePkce();
|
|
1979
|
-
const state = base64url(randomBytes4(16));
|
|
1980
|
-
const redirectUri = `http://${LOCALHOST}:${CALLBACK_PORT}/callback`;
|
|
1981
|
-
let settle;
|
|
1982
|
-
const outcome = new Promise((resolve8) => {
|
|
1983
|
-
settle = resolve8;
|
|
1984
|
-
});
|
|
1985
|
-
const server = createServer((req, res) => {
|
|
1986
|
-
const url = new URL(req.url ?? "/", `http://${LOCALHOST}`);
|
|
1987
|
-
if (url.pathname !== "/callback") {
|
|
1988
|
-
res.writeHead(404);
|
|
1989
|
-
res.end("Not found");
|
|
1990
|
-
return;
|
|
1991
|
-
}
|
|
1992
|
-
const page = resolveCallbackPage(url.searchParams, state);
|
|
1993
|
-
res.writeHead(page.status, HTML_HEADERS);
|
|
1994
|
-
res.end(page.html, () => settle(page.result));
|
|
1995
|
-
});
|
|
1996
|
-
try {
|
|
1997
|
-
await new Promise((resolve8, reject) => {
|
|
1998
|
-
const onError = (err) => reject(err);
|
|
1999
|
-
server.once("error", onError);
|
|
2000
|
-
server.listen(CALLBACK_PORT, LOCALHOST, () => {
|
|
2001
|
-
server.removeListener("error", onError);
|
|
2002
|
-
resolve8();
|
|
2003
|
-
});
|
|
2004
|
-
});
|
|
2005
|
-
} catch (err) {
|
|
2006
|
-
if (err instanceof Error && err.code === "EADDRINUSE") {
|
|
2007
|
-
reportFailure(
|
|
2008
|
-
"callback_port_in_use",
|
|
2009
|
-
`Port ${CALLBACK_PORT} is in use \u2014 another 'prim auth login' may be running. Close it and retry.`
|
|
2010
|
-
);
|
|
2011
|
-
} else {
|
|
2012
|
-
reportFailure(
|
|
2013
|
-
"callback_bind_failed",
|
|
2014
|
-
`Could not start the local callback server: ${err instanceof Error ? err.message : String(err)}`
|
|
2015
|
-
);
|
|
2016
|
-
}
|
|
2017
|
-
return;
|
|
2018
|
-
}
|
|
2019
|
-
server.on("error", () => {
|
|
2020
|
-
});
|
|
2021
|
-
const authUrl = new URL(config.authorization_endpoint);
|
|
2022
|
-
authUrl.searchParams.set("client_id", config.client_id);
|
|
2023
|
-
authUrl.searchParams.set("redirect_uri", redirectUri);
|
|
2024
|
-
authUrl.searchParams.set("response_type", "code");
|
|
2025
|
-
authUrl.searchParams.set("provider", "authkit");
|
|
2026
|
-
authUrl.searchParams.set("scope", config.default_scopes.join(" "));
|
|
2027
|
-
authUrl.searchParams.set("state", state);
|
|
2028
|
-
authUrl.searchParams.set("code_challenge", challenge);
|
|
2029
|
-
authUrl.searchParams.set("code_challenge_method", "S256");
|
|
2030
|
-
if (options.browser) {
|
|
2031
|
-
console.error("Opening browser for authentication...");
|
|
2032
|
-
openBrowser(authUrl.toString());
|
|
2033
|
-
}
|
|
2034
|
-
console.error(`If the browser doesn't open, visit:
|
|
2035
|
-
${authUrl.toString()}
|
|
2036
|
-
`);
|
|
2037
|
-
console.error("Waiting for callback...");
|
|
2038
|
-
const timer = setTimeout(() => {
|
|
2039
|
-
settle({ authenticated: false, error: "timeout", detail: "Authentication timed out." });
|
|
2040
|
-
}, CALLBACK_TIMEOUT_MS);
|
|
2041
|
-
timer.unref();
|
|
2042
|
-
const result = await outcome;
|
|
2043
|
-
clearTimeout(timer);
|
|
2044
|
-
server.close();
|
|
2045
|
-
if (!result.authenticated) {
|
|
2046
|
-
reportFailure(result.error, result.detail);
|
|
2047
|
-
return;
|
|
2048
|
-
}
|
|
2049
|
-
try {
|
|
2050
|
-
const tokens = await exchangeCode(siteUrl, result.code, verifier, redirectUri);
|
|
2051
|
-
await commitCredentials(tokens);
|
|
2052
|
-
reportSuccess();
|
|
2053
|
-
} catch (err) {
|
|
2054
|
-
reportFailure("token_exchange_failed", err instanceof Error ? err.message : String(err));
|
|
2055
2443
|
}
|
|
2056
2444
|
});
|
|
2057
2445
|
auth.command("set-token <token>").description("Save a bearer token for authenticated CLI calls").action(async (token) => {
|
|
@@ -2085,18 +2473,140 @@ ${authUrl.toString()}
|
|
|
2085
2473
|
}
|
|
2086
2474
|
}
|
|
2087
2475
|
});
|
|
2088
|
-
if (removed || machineRemoved) {
|
|
2089
|
-
console.log("Local tokens removed.");
|
|
2090
|
-
} else {
|
|
2091
|
-
console.log("No saved tokens found.");
|
|
2092
|
-
}
|
|
2093
|
-
});
|
|
2094
|
-
auth.command("
|
|
2095
|
-
|
|
2096
|
-
|
|
2097
|
-
|
|
2098
|
-
process.
|
|
2099
|
-
|
|
2476
|
+
if (removed || machineRemoved) {
|
|
2477
|
+
console.log("Local tokens removed.");
|
|
2478
|
+
} else {
|
|
2479
|
+
console.log("No saved tokens found.");
|
|
2480
|
+
}
|
|
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
|
+
});
|
|
2497
|
+
auth.command("status").description("Check authentication status and token expiry").option("--json", "Output as JSON").action(async (opts) => {
|
|
2498
|
+
const result = await verifyAuthStatus();
|
|
2499
|
+
if (opts.json) printJson(result);
|
|
2500
|
+
else writeHumanAuthStatus(result);
|
|
2501
|
+
process.exit(authStatusExitCode(result.status));
|
|
2502
|
+
});
|
|
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;
|
|
2100
2610
|
}
|
|
2101
2611
|
async function readMachineSecret(fromStdin) {
|
|
2102
2612
|
if (fromStdin) {
|
|
@@ -2222,6 +2732,7 @@ function reportBinding(binding, installAttempted = false) {
|
|
|
2222
2732
|
}
|
|
2223
2733
|
process.stderr.write(
|
|
2224
2734
|
installAttempted ? `[prim] GitHub repo connection could not be completed for ${binding.repositoryFullName}; the GitHub App was not granted admin access to that repository
|
|
2735
|
+
` : isCloudMachineSession() ? `[prim] GitHub repo connection is required for ${binding.repositoryFullName} and cannot be completed from a Claude Code cloud session: ${CLOUD_GITHUB_CONNECT_REMEDY}
|
|
2225
2736
|
` : `[prim] GitHub repo connection is required for ${binding.repositoryFullName}; it enables repository-specific file attribution, Conflict Gate verification, and commit correlation. Starting GitHub App installation\u2026
|
|
2226
2737
|
`
|
|
2227
2738
|
);
|
|
@@ -2261,6 +2772,8 @@ async function runGithubConnect(dependencies = defaultDependencies2, options = {
|
|
|
2261
2772
|
if (existing.status === "connected") {
|
|
2262
2773
|
return { kind: "connected", binding: existing };
|
|
2263
2774
|
}
|
|
2775
|
+
if (isCloudMachineSession())
|
|
2776
|
+
return { kind: "unbound", binding: existing, installAttempted: false };
|
|
2264
2777
|
const start = await dependencies.createInstallIntent(client, {
|
|
2265
2778
|
signal: AbortSignal.timeout(START_TIMEOUT_MS),
|
|
2266
2779
|
now: dependencies.now
|
|
@@ -2904,7 +3417,10 @@ function registerHooksCommands(program2) {
|
|
|
2904
3417
|
|
|
2905
3418
|
// src/commands/activation.ts
|
|
2906
3419
|
var CONNECT_PROMPT = "[prim] GitHub repo connection is required to enable repository-specific file attribution, Conflict Gate verification, and commit correlation. Start the GitHub App connection now?";
|
|
2907
|
-
var GITHUB_CONNECTION_REQUIRED = "GitHub repo connection is required before using Primitive in this repository. It enables repository-specific file attribution, Conflict Gate verification, and commit correlation.
|
|
3420
|
+
var GITHUB_CONNECTION_REQUIRED = "GitHub repo connection is required before using Primitive in this repository. It enables repository-specific file attribution, Conflict Gate verification, and commit correlation.";
|
|
3421
|
+
function githubConnectionRequired() {
|
|
3422
|
+
return `${GITHUB_CONNECTION_REQUIRED} ${isCloudMachineSession() ? `It cannot be completed from a Claude Code cloud session: ${CLOUD_GITHUB_CONNECT_REMEDY}.` : "Run `prim github connect` to complete it."}`;
|
|
3423
|
+
}
|
|
2908
3424
|
function wireRepositoryHooks(root) {
|
|
2909
3425
|
stageGitHookRuntime();
|
|
2910
3426
|
refreshOwnedGlobalHooks();
|
|
@@ -2949,7 +3465,7 @@ function wireRepositoryHooks(root) {
|
|
|
2949
3465
|
return { paths, changed };
|
|
2950
3466
|
}
|
|
2951
3467
|
async function maybeConnectRepository(root, globals) {
|
|
2952
|
-
if (isNonInteractive(globals)) return void 0;
|
|
3468
|
+
if (isNonInteractive(globals) || isCloudMachineSession()) return void 0;
|
|
2953
3469
|
const approved = Boolean(globals.yes) || await askConfirmation(CONNECT_PROMPT, process.stderr);
|
|
2954
3470
|
if (!approved) return void 0;
|
|
2955
3471
|
const outcome = await runGithubConnect(void 0, { root, browser: true });
|
|
@@ -2974,7 +3490,17 @@ function hookPathFields(paths) {
|
|
|
2974
3490
|
...paths["post-rewrite"] ? { postRewriteHook: paths["post-rewrite"] } : {}
|
|
2975
3491
|
};
|
|
2976
3492
|
}
|
|
3493
|
+
function projectScope(globals, active) {
|
|
3494
|
+
if (globals.scope === void 0) return false;
|
|
3495
|
+
if (globals.scope === "project") return true;
|
|
3496
|
+
process.stderr.write(
|
|
3497
|
+
`[prim] invalid --scope '${String(globals.scope)}': \`prim ${active ? "enable" : "disable"}\` accepts only 'project'
|
|
3498
|
+
`
|
|
3499
|
+
);
|
|
3500
|
+
process.exit(2);
|
|
3501
|
+
}
|
|
2977
3502
|
async function applyActivation(active, globals = {}) {
|
|
3503
|
+
const project = projectScope(globals, active);
|
|
2978
3504
|
const root = gitToplevel();
|
|
2979
3505
|
if (!root) {
|
|
2980
3506
|
process.stderr.write(
|
|
@@ -2983,12 +3509,14 @@ async function applyActivation(active, globals = {}) {
|
|
|
2983
3509
|
);
|
|
2984
3510
|
process.exit(1);
|
|
2985
3511
|
}
|
|
2986
|
-
let phase =
|
|
3512
|
+
let phase = "the repository's committed opt-out";
|
|
2987
3513
|
try {
|
|
2988
3514
|
let binding;
|
|
2989
3515
|
let hookPaths = {};
|
|
2990
3516
|
let hooksChanged = false;
|
|
2991
3517
|
const wasActive = repoActiveFlag(root) === "true";
|
|
3518
|
+
const declaration = project ? planProjectInactiveDeclaration(root, !active) : void 0;
|
|
3519
|
+
phase = active ? "post-commit hook coverage" : "local deactivation";
|
|
2992
3520
|
if (active) {
|
|
2993
3521
|
({ paths: hookPaths, changed: hooksChanged } = wireRepositoryHooks(root));
|
|
2994
3522
|
phase = "GitHub repo connection";
|
|
@@ -2997,11 +3525,12 @@ async function applyActivation(active, globals = {}) {
|
|
|
2997
3525
|
if (active && binding?.status === "unbound") {
|
|
2998
3526
|
const connected = await maybeConnectRepository(root, globals);
|
|
2999
3527
|
if (!connected) {
|
|
3000
|
-
process.stderr.write(`[prim] ${
|
|
3528
|
+
process.stderr.write(`[prim] ${githubConnectionRequired()}
|
|
3001
3529
|
`);
|
|
3002
3530
|
printJson({
|
|
3003
3531
|
active: false,
|
|
3004
3532
|
repo: root,
|
|
3533
|
+
declaredInactive: declaresInactive(root),
|
|
3005
3534
|
bindingStatus: binding.status,
|
|
3006
3535
|
repositoryFullName: binding.repositoryFullName,
|
|
3007
3536
|
...hookPathFields(hookPaths)
|
|
@@ -3020,6 +3549,11 @@ async function applyActivation(active, globals = {}) {
|
|
|
3020
3549
|
phase = "local activation";
|
|
3021
3550
|
clearDemoPause(root);
|
|
3022
3551
|
setRepoActive(root, active);
|
|
3552
|
+
markActivationExplicit(root);
|
|
3553
|
+
if (declaration) {
|
|
3554
|
+
phase = "the repository's committed opt-out";
|
|
3555
|
+
declaration.apply();
|
|
3556
|
+
}
|
|
3023
3557
|
if (!active) clearHooksWired(root);
|
|
3024
3558
|
if (active) {
|
|
3025
3559
|
recordHooksWired(root, { onlyIfAbsent: wasActive && !hooksChanged });
|
|
@@ -3027,9 +3561,32 @@ async function applyActivation(active, globals = {}) {
|
|
|
3027
3561
|
await daemonRequest("statusline_invalidate", {}, { timeoutMs: 250 });
|
|
3028
3562
|
process.stderr.write(`[prim] prim ${active ? "enabled" : "disabled"} in ${root}
|
|
3029
3563
|
`);
|
|
3564
|
+
const declaredInactive = declaresInactive(root);
|
|
3565
|
+
const ignored = Boolean(project && !active && isGitIgnored(root, ".claude/settings.json"));
|
|
3566
|
+
if (declaration?.changed)
|
|
3567
|
+
process.stderr.write(
|
|
3568
|
+
active ? `[prim] removed this repository's opt-out from ${declaration.path}; commit the change so new clones and Claude Code cloud sessions follow it
|
|
3569
|
+
` : `[prim] recorded this repository's opt-out (PRIM_ACTIVE=false) in ${declaration.path}; commit it so prim stays off in every clone and every Claude Code cloud session, until someone runs \`prim enable\` there
|
|
3570
|
+
`
|
|
3571
|
+
);
|
|
3572
|
+
if (ignored)
|
|
3573
|
+
process.stderr.write(
|
|
3574
|
+
"[prim] this repository's .gitignore covers .claude/settings.json, so a plain `git add` skips it: stage it with `git add -f .claude/settings.json`, or the opt-out stays in this clone only\n"
|
|
3575
|
+
);
|
|
3576
|
+
else if (active && declaredInactive)
|
|
3577
|
+
process.stderr.write(
|
|
3578
|
+
"[prim] this repository commits an opt-out (PRIM_ACTIVE=false in .claude/settings.json): enabled for this clone only. `prim enable --scope project` removes the opt-out\n"
|
|
3579
|
+
);
|
|
3580
|
+
else if (!active && !declaredInactive && isPreparedCloudSession())
|
|
3581
|
+
process.stderr.write(
|
|
3582
|
+
"[prim] this lasts for this session's clone only: the next Claude Code cloud session starts from a fresh one. To keep prim off in this repository, run `prim disable --scope project` and commit .claude/settings.json\n"
|
|
3583
|
+
);
|
|
3030
3584
|
printJson({
|
|
3031
3585
|
active,
|
|
3032
3586
|
repo: root,
|
|
3587
|
+
declaredInactive,
|
|
3588
|
+
...declaration?.changed ? { settingsPath: declaration.path } : {},
|
|
3589
|
+
...ignored ? { settingsIgnored: true } : {},
|
|
3033
3590
|
...binding ? {
|
|
3034
3591
|
bindingStatus: binding.status,
|
|
3035
3592
|
repositoryFullName: binding.repositoryFullName,
|
|
@@ -3048,8 +3605,14 @@ async function applyActivation(active, globals = {}) {
|
|
|
3048
3605
|
}
|
|
3049
3606
|
}
|
|
3050
3607
|
function registerActivationCommands(program2) {
|
|
3051
|
-
program2.command("enable").description("Activate prim's hooks in this repo (git config prim.active=true)").
|
|
3052
|
-
|
|
3608
|
+
program2.command("enable").description("Activate prim's hooks in this repo (git config prim.active=true)").option(
|
|
3609
|
+
"--scope <scope>",
|
|
3610
|
+
"project: also remove the repository's committed opt-out from .claude/settings.json"
|
|
3611
|
+
).action((_opts, command) => applyActivation(true, command.optsWithGlobals()));
|
|
3612
|
+
program2.command("disable").description("Mute prim's hooks in this repo (git config prim.active=false)").option(
|
|
3613
|
+
"--scope <scope>",
|
|
3614
|
+
"project: also record the opt-out in .claude/settings.json to commit, so it holds in every clone and Claude Code cloud session"
|
|
3615
|
+
).action(
|
|
3053
3616
|
(_opts, command) => applyActivation(false, command.optsWithGlobals())
|
|
3054
3617
|
);
|
|
3055
3618
|
}
|
|
@@ -3098,14 +3661,14 @@ async function inspectCodexHost(reload = false) {
|
|
|
3098
3661
|
maxPayload: MAX_RESPONSE_BYTES,
|
|
3099
3662
|
perMessageDeflate: false
|
|
3100
3663
|
});
|
|
3101
|
-
const
|
|
3664
|
+
const finish2 = (value) => {
|
|
3102
3665
|
if (finished) return;
|
|
3103
3666
|
finished = true;
|
|
3104
3667
|
clearTimeout(timer);
|
|
3105
3668
|
socket.terminate();
|
|
3106
3669
|
resolve8(value);
|
|
3107
3670
|
};
|
|
3108
|
-
const fail = (reason) =>
|
|
3671
|
+
const fail = (reason) => finish2({ ...unavailable(reason), ...refreshed ? { reload: "refreshed" } : {} });
|
|
3109
3672
|
const timer = setTimeout(() => fail("host-timeout"), TIMEOUT_MS);
|
|
3110
3673
|
const request = (next, params) => {
|
|
3111
3674
|
method = next;
|
|
@@ -3150,7 +3713,7 @@ async function inspectCodexHost(reload = false) {
|
|
|
3150
3713
|
) ? "review-required" : owned.every(
|
|
3151
3714
|
(hook) => ["trusted", "managed"].includes(hook.trustStatus ?? "")
|
|
3152
3715
|
) ? "trusted" : "unknown";
|
|
3153
|
-
|
|
3716
|
+
finish2({
|
|
3154
3717
|
connection: "available",
|
|
3155
3718
|
trust,
|
|
3156
3719
|
reload: refreshed ? "refreshed" : "not-requested"
|
|
@@ -3224,7 +3787,7 @@ function applyUninstall(settings) {
|
|
|
3224
3787
|
hooks[event] = list;
|
|
3225
3788
|
}
|
|
3226
3789
|
}
|
|
3227
|
-
return { ...settings, hooks };
|
|
3790
|
+
return settings.hooks === void 0 ? settings : { ...settings, hooks };
|
|
3228
3791
|
}
|
|
3229
3792
|
function captureInstalled(settings) {
|
|
3230
3793
|
return CODEX_CAPTURE_EVENTS.some(
|
|
@@ -3429,17 +3992,17 @@ async function runPinnedEnsure(options) {
|
|
|
3429
3992
|
}
|
|
3430
3993
|
const timer = setTimeout(() => {
|
|
3431
3994
|
child.kill("SIGTERM");
|
|
3432
|
-
|
|
3995
|
+
finish2(false);
|
|
3433
3996
|
}, options.timeoutMs ?? LATEST_BOOTSTRAP_TIMEOUT_MS);
|
|
3434
|
-
const
|
|
3997
|
+
const finish2 = (result) => {
|
|
3435
3998
|
if (settled) return;
|
|
3436
3999
|
settled = true;
|
|
3437
4000
|
clearTimeout(timer);
|
|
3438
4001
|
resolve8(result);
|
|
3439
4002
|
};
|
|
3440
4003
|
timer.unref();
|
|
3441
|
-
child.once("error", () =>
|
|
3442
|
-
child.once("exit", (code) =>
|
|
4004
|
+
child.once("error", () => finish2(false));
|
|
4005
|
+
child.once("exit", (code) => finish2(code === 0));
|
|
3443
4006
|
});
|
|
3444
4007
|
}
|
|
3445
4008
|
async function runLatestDaemonBootstrap(ensureCurrent, options = {}) {
|
|
@@ -5228,6 +5791,13 @@ async function detachedDaemonStatus() {
|
|
|
5228
5791
|
{ timeoutMs: STATUS_PROBE_TIMEOUT_MS }
|
|
5229
5792
|
) : null;
|
|
5230
5793
|
const { json, exitCode } = classifyStatus(pidAlive, responding, snapshot, pid?.pid);
|
|
5794
|
+
if (!pidAlive && isClaudeCloudSession() && daemonExplicitlyDisabled()) {
|
|
5795
|
+
process.stderr.write(
|
|
5796
|
+
"[prim] daemon not used in Claude Code cloud sessions; capture delivers directly\n"
|
|
5797
|
+
);
|
|
5798
|
+
console.log(JSON.stringify({ ...json, disabled: true, cloudSession: true }, null, 2));
|
|
5799
|
+
return;
|
|
5800
|
+
}
|
|
5231
5801
|
if (!pidAlive) {
|
|
5232
5802
|
process.stderr.write("[prim] \u2717 daemon down\n");
|
|
5233
5803
|
} else if (!responding) {
|
|
@@ -6351,6 +6921,99 @@ function formatRelateJson(result) {
|
|
|
6351
6921
|
return JSON.stringify(result.outcome, null, 2);
|
|
6352
6922
|
}
|
|
6353
6923
|
|
|
6924
|
+
// src/decisions/location-scope.ts
|
|
6925
|
+
var LocationScopeInputError = class extends Error {
|
|
6926
|
+
constructor(message) {
|
|
6927
|
+
super(message);
|
|
6928
|
+
this.name = "LocationScopeInputError";
|
|
6929
|
+
}
|
|
6930
|
+
};
|
|
6931
|
+
var MAX_LOCATION_SCOPE_SELECTORS = 25;
|
|
6932
|
+
var MAX_LOCATION_SCOPE_BRANCHES = 25;
|
|
6933
|
+
var MAX_BRANCH_PATTERN_CHARS = 255;
|
|
6934
|
+
var MAX_SHOWN_VALUE_CHARS = 80;
|
|
6935
|
+
function shown(value) {
|
|
6936
|
+
return JSON.stringify(
|
|
6937
|
+
value.length <= MAX_SHOWN_VALUE_CHARS ? value : `${value.slice(0, MAX_SHOWN_VALUE_CHARS - 1)}\u2026`
|
|
6938
|
+
);
|
|
6939
|
+
}
|
|
6940
|
+
function hasControlCharacter(value) {
|
|
6941
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
6942
|
+
const code = value.charCodeAt(index);
|
|
6943
|
+
if (code <= 31 || code === 127) return true;
|
|
6944
|
+
}
|
|
6945
|
+
return false;
|
|
6946
|
+
}
|
|
6947
|
+
function isScopeBranchPattern(value) {
|
|
6948
|
+
return value.length > 0 && value.length <= MAX_BRANCH_PATTERN_CHARS && !hasControlCharacter(value);
|
|
6949
|
+
}
|
|
6950
|
+
function normalizeScopeDirectory(value) {
|
|
6951
|
+
const start = value.startsWith("./") ? 2 : 0;
|
|
6952
|
+
let end = value.length;
|
|
6953
|
+
while (end > start && value.charCodeAt(end - 1) === 47) end -= 1;
|
|
6954
|
+
return value.slice(start, end);
|
|
6955
|
+
}
|
|
6956
|
+
function scopeDirectories(values) {
|
|
6957
|
+
return values.map((value) => {
|
|
6958
|
+
const directory = normalizeScopeDirectory(value);
|
|
6959
|
+
if (directory === "." || directory === "" && value.startsWith("./")) {
|
|
6960
|
+
throw new LocationScopeInputError(
|
|
6961
|
+
`--scope-dir ${shown(value)} names the repository root; use --scope-repo to govern the whole repository`
|
|
6962
|
+
);
|
|
6963
|
+
}
|
|
6964
|
+
if (!isScopeDirectoryPrefix(directory)) {
|
|
6965
|
+
throw new LocationScopeInputError(
|
|
6966
|
+
`--scope-dir ${shown(value)} is not a repository-relative directory; use a path such as docs/ga: no leading "/", no "\\", no control character, no empty, "." or ".." segment, at most ${MAX_SCOPE_GLOB_CHARS} characters`
|
|
6967
|
+
);
|
|
6968
|
+
}
|
|
6969
|
+
return directory;
|
|
6970
|
+
});
|
|
6971
|
+
}
|
|
6972
|
+
function scopeGlobs(values) {
|
|
6973
|
+
for (const value of values) {
|
|
6974
|
+
if (!isScopeGlobPattern(value)) {
|
|
6975
|
+
throw new LocationScopeInputError(
|
|
6976
|
+
`--scope-glob ${shown(value)} is not an accepted glob; use a repository-relative pattern such as src/**/*.ts: no leading "/", no control character, no empty, "." or ".." segment, none of [ ] { } ! ( ) \\ ~ $ \`, at most ${MAX_SCOPE_GLOB_CHARS} characters`
|
|
6977
|
+
);
|
|
6978
|
+
}
|
|
6979
|
+
}
|
|
6980
|
+
return [...values];
|
|
6981
|
+
}
|
|
6982
|
+
function scopeBranches(values) {
|
|
6983
|
+
for (const value of values) {
|
|
6984
|
+
if (!isScopeBranchPattern(value)) {
|
|
6985
|
+
throw new LocationScopeInputError(
|
|
6986
|
+
`--scope-branch ${shown(value)} is not an accepted branch pattern; use a name or pattern such as main or release/*: not empty, no control character, at most ${MAX_BRANCH_PATTERN_CHARS} characters`
|
|
6987
|
+
);
|
|
6988
|
+
}
|
|
6989
|
+
}
|
|
6990
|
+
return [...values];
|
|
6991
|
+
}
|
|
6992
|
+
function locationScopeFromOptions(options) {
|
|
6993
|
+
const directories = scopeDirectories(options.scopeDir ?? []);
|
|
6994
|
+
const globs = scopeGlobs(options.scopeGlob ?? []);
|
|
6995
|
+
const branches = scopeBranches(options.scopeBranch ?? []);
|
|
6996
|
+
const selectorCount = (options.scopeRepo ? 1 : 0) + new Set(directories).size + new Set(globs).size;
|
|
6997
|
+
if (selectorCount > MAX_LOCATION_SCOPE_SELECTORS) {
|
|
6998
|
+
throw new LocationScopeInputError(
|
|
6999
|
+
`--scope-repo, --scope-dir and --scope-glob name ${selectorCount} distinct selectors; a Decision allows at most ${MAX_LOCATION_SCOPE_SELECTORS}`
|
|
7000
|
+
);
|
|
7001
|
+
}
|
|
7002
|
+
const branchCount = new Set(branches).size;
|
|
7003
|
+
if (branchCount > MAX_LOCATION_SCOPE_BRANCHES) {
|
|
7004
|
+
throw new LocationScopeInputError(
|
|
7005
|
+
`--scope-branch names ${branchCount} distinct branch patterns; a Decision allows at most ${MAX_LOCATION_SCOPE_BRANCHES}`
|
|
7006
|
+
);
|
|
7007
|
+
}
|
|
7008
|
+
const location = {
|
|
7009
|
+
...options.scopeRepo ? { repository: true } : {},
|
|
7010
|
+
...directories.length > 0 ? { directories } : {},
|
|
7011
|
+
...globs.length > 0 ? { globs } : {},
|
|
7012
|
+
...branches.length > 0 ? { branches } : {}
|
|
7013
|
+
};
|
|
7014
|
+
return Object.keys(location).length === 0 ? void 0 : location;
|
|
7015
|
+
}
|
|
7016
|
+
|
|
6354
7017
|
// src/decisions/repairs.ts
|
|
6355
7018
|
var REPAIRS_TIMEOUT_MS = 1e4;
|
|
6356
7019
|
var MAX_REPAIR_LIST_PAGES = 100;
|
|
@@ -6907,7 +7570,7 @@ var DecisionRescopeResponseError = class extends Error {
|
|
|
6907
7570
|
this.name = "DecisionRescopeResponseError";
|
|
6908
7571
|
}
|
|
6909
7572
|
};
|
|
6910
|
-
function
|
|
7573
|
+
function projectScope2(scope) {
|
|
6911
7574
|
return {
|
|
6912
7575
|
...scope.scopeResolution === "unresolved" ? { scopeResolution: "unresolved" } : {},
|
|
6913
7576
|
location: {
|
|
@@ -6924,7 +7587,7 @@ function projectScope(scope) {
|
|
|
6924
7587
|
};
|
|
6925
7588
|
}
|
|
6926
7589
|
function projectSuccess2(response) {
|
|
6927
|
-
const scope =
|
|
7590
|
+
const scope = projectScope2(response.scope);
|
|
6928
7591
|
if (response.outcome === "no_op") {
|
|
6929
7592
|
return {
|
|
6930
7593
|
outcome: "no_op",
|
|
@@ -7346,14 +8009,10 @@ function rejectUserScope(command, error) {
|
|
|
7346
8009
|
console.log(JSON.stringify({ ok: false, error: "invalid_user_scope" }, null, 2));
|
|
7347
8010
|
process.exitCode = EXIT_USAGE;
|
|
7348
8011
|
}
|
|
7349
|
-
function
|
|
7350
|
-
|
|
7351
|
-
|
|
7352
|
-
|
|
7353
|
-
...options.scopeGlob && options.scopeGlob.length > 0 ? { globs: options.scopeGlob } : {},
|
|
7354
|
-
...options.scopeBranch && options.scopeBranch.length > 0 ? { branches: options.scopeBranch } : {}
|
|
7355
|
-
};
|
|
7356
|
-
return Object.keys(location).length === 0 ? void 0 : location;
|
|
8012
|
+
function rejectLocationScope(command, error) {
|
|
8013
|
+
console.error(terminalSafeLine(`[prim] ${command} rejected: ${error.message}.`));
|
|
8014
|
+
console.log(JSON.stringify({ ok: false, error: "invalid_location_scope" }, null, 2));
|
|
8015
|
+
process.exitCode = EXIT_USAGE;
|
|
7357
8016
|
}
|
|
7358
8017
|
function registerDecisionsCommands(program2) {
|
|
7359
8018
|
const decisions = program2.command("decisions").description("Inspect the project Decision Graph");
|
|
@@ -7606,7 +8265,16 @@ function registerDecisionsCommands(program2) {
|
|
|
7606
8265
|
throw error;
|
|
7607
8266
|
}
|
|
7608
8267
|
const requestedFiles = opts.files ?? [];
|
|
7609
|
-
|
|
8268
|
+
let location;
|
|
8269
|
+
try {
|
|
8270
|
+
location = locationScopeFromOptions(opts);
|
|
8271
|
+
} catch (error) {
|
|
8272
|
+
if (error instanceof LocationScopeInputError) {
|
|
8273
|
+
rejectLocationScope("create", error);
|
|
8274
|
+
return;
|
|
8275
|
+
}
|
|
8276
|
+
throw error;
|
|
8277
|
+
}
|
|
7610
8278
|
let explicitScope = {};
|
|
7611
8279
|
if (requestedFiles.length > 0 || location !== void 0) {
|
|
7612
8280
|
const binding = repoSyncId(process.cwd());
|
|
@@ -7739,7 +8407,16 @@ function registerDecisionsCommands(program2) {
|
|
|
7739
8407
|
}
|
|
7740
8408
|
throw error;
|
|
7741
8409
|
}
|
|
7742
|
-
|
|
8410
|
+
let location;
|
|
8411
|
+
try {
|
|
8412
|
+
location = locationScopeFromOptions(opts);
|
|
8413
|
+
} catch (error) {
|
|
8414
|
+
if (error instanceof LocationScopeInputError) {
|
|
8415
|
+
rejectLocationScope("rescope", error);
|
|
8416
|
+
return;
|
|
8417
|
+
}
|
|
8418
|
+
throw error;
|
|
8419
|
+
}
|
|
7743
8420
|
const hasLocationSelector = location !== void 0;
|
|
7744
8421
|
const hasNonLocationScope = time !== void 0 || users !== void 0;
|
|
7745
8422
|
process.exitCode = await rescopeDecision({
|
|
@@ -9118,7 +9795,12 @@ function classifyDoctor(checks) {
|
|
|
9118
9795
|
}
|
|
9119
9796
|
function classifyAuthCredential(credential, expiresAt, hasRefresh) {
|
|
9120
9797
|
if (!credential) {
|
|
9121
|
-
return {
|
|
9798
|
+
return {
|
|
9799
|
+
name: "auth",
|
|
9800
|
+
status: "fail",
|
|
9801
|
+
// `prim auth login` is refused in a cloud session; name what works there.
|
|
9802
|
+
detail: isClaudeCloudSession() ? `no credentials \u2014 ${CLOUD_CREDENTIALS_REMEDY}` : "no token \u2014 run `prim auth login`"
|
|
9803
|
+
};
|
|
9122
9804
|
}
|
|
9123
9805
|
if (credential.source !== "token_file") {
|
|
9124
9806
|
return { name: "auth", status: "ok", detail: "valid fixed bearer credential" };
|
|
@@ -9136,14 +9818,28 @@ function classifyAuthCredential(credential, expiresAt, hasRefresh) {
|
|
|
9136
9818
|
const detail = expiresAt !== void 0 ? `valid (${String(Math.round((expiresAt - Date.now()) / MS_PER_SECOND))}s left)` : "valid";
|
|
9137
9819
|
return { name: "auth", status: "ok", detail };
|
|
9138
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
|
+
}
|
|
9139
9834
|
async function checkAuth() {
|
|
9140
9835
|
try {
|
|
9141
9836
|
if (hasMachineConfiguration()) {
|
|
9142
9837
|
const status2 = await verifyAuthStatus();
|
|
9838
|
+
if (status2.principalKind === "session") return classifySessionAuth(status2);
|
|
9143
9839
|
return {
|
|
9144
9840
|
name: "auth",
|
|
9145
9841
|
status: status2.authenticated ? "ok" : "fail",
|
|
9146
|
-
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}
|
|
9842
|
+
detail: status2.authenticated ? `machine ${status2.displayName ?? status2.machineId} \xB7 ${status2.storageBackend} \xB7 ${status2.tokenHeldByProxy ? "token held by the environment's proxy" : `expires in ${Math.round((status2.accessTokenExpiresInMs ?? 0) / 1e3)}s`}` : `machine authentication: ${status2.recoveryReason}. ${status2.recoveryDetail ? stripControlChars(status2.recoveryDetail) : "Unlock the credential store or run prim auth configure-machine."}`
|
|
9147
9843
|
};
|
|
9148
9844
|
}
|
|
9149
9845
|
} catch {
|
|
@@ -9163,6 +9859,12 @@ async function checkAuth() {
|
|
|
9163
9859
|
}
|
|
9164
9860
|
function classifyDaemonHealth(snapshot, options = {}) {
|
|
9165
9861
|
if (options.disabled) {
|
|
9862
|
+
if (isClaudeCloudSession())
|
|
9863
|
+
return {
|
|
9864
|
+
name: "daemon",
|
|
9865
|
+
status: "ok",
|
|
9866
|
+
detail: "not used in Claude Code cloud sessions; capture delivers directly"
|
|
9867
|
+
};
|
|
9166
9868
|
return {
|
|
9167
9869
|
name: "daemon",
|
|
9168
9870
|
status: "fail",
|
|
@@ -9410,19 +10112,20 @@ async function checkJournalOrganization() {
|
|
|
9410
10112
|
}
|
|
9411
10113
|
function classifyRepositoryBinding(value, current, active) {
|
|
9412
10114
|
const connectionCapabilities = "It enables repository-specific file attribution, Conflict Gate verification, and commit correlation.";
|
|
10115
|
+
const cloud = isCloudMachineSession();
|
|
9413
10116
|
if (current.status === "unbound") {
|
|
9414
10117
|
if (!active) {
|
|
9415
10118
|
return {
|
|
9416
10119
|
name: "github-repo-connection",
|
|
9417
10120
|
status: "fail",
|
|
9418
|
-
detail: `GitHub repo connection is required before using Primitive in this repository. ${connectionCapabilities} Run
|
|
10121
|
+
detail: `GitHub repo connection is required before using Primitive in this repository. ${connectionCapabilities} ${cloud ? `To complete it, ${CLOUD_GITHUB_CONNECT_REMEDY}.` : "Run `prim github connect`, then `prim enable`."}`
|
|
9419
10122
|
};
|
|
9420
10123
|
}
|
|
9421
10124
|
const localDetail = value === void 0 ? "GitHub repo connection is not complete" : isValidRepoSyncId(value) ? "server reports GitHub repo connection is not complete; the last connection state is retained locally for recovery" : "server reports GitHub repo connection is not complete; the local cached connection state is invalid";
|
|
9422
10125
|
return {
|
|
9423
10126
|
name: "github-repo-connection",
|
|
9424
10127
|
status: "warn",
|
|
9425
|
-
detail: `${localDetail} \u2014 GitHub repo connection is required before using Primitive in this repository. ${connectionCapabilities} Run
|
|
10128
|
+
detail: `${localDetail} \u2014 GitHub repo connection is required before using Primitive in this repository. ${connectionCapabilities} ${cloud ? `To complete it, ${CLOUD_GITHUB_CONNECT_REMEDY}.` : "Run `prim github connect` to complete it."}`
|
|
9426
10129
|
};
|
|
9427
10130
|
}
|
|
9428
10131
|
if (!isValidRepoSyncId(value)) {
|
|
@@ -10485,6 +11188,21 @@ var HTTP_SERVER_ERROR_MIN = 500;
|
|
|
10485
11188
|
function isDomainRejection(err) {
|
|
10486
11189
|
return err instanceof HttpError && err.status >= HTTP_CLIENT_ERROR_MIN && err.status < HTTP_SERVER_ERROR_MIN;
|
|
10487
11190
|
}
|
|
11191
|
+
var MAX_REFUSAL_FIELD_CHARS = 500;
|
|
11192
|
+
function capped(value) {
|
|
11193
|
+
return value.length <= MAX_REFUSAL_FIELD_CHARS ? value : `${value.slice(0, MAX_REFUSAL_FIELD_CHARS - 1)}\u2026`;
|
|
11194
|
+
}
|
|
11195
|
+
function serverRefusal(error) {
|
|
11196
|
+
if (!(error instanceof HttpError) || !isCliErrorResponse(error.body)) return {};
|
|
11197
|
+
const { error: code, message } = error.body;
|
|
11198
|
+
return {
|
|
11199
|
+
error: capped(code),
|
|
11200
|
+
...typeof message === "string" ? { message: capped(message) } : {}
|
|
11201
|
+
};
|
|
11202
|
+
}
|
|
11203
|
+
function machineScopeRemedy() {
|
|
11204
|
+
return isCloudMachineSession() ? "This Claude Code cloud session's credential is not permitted to record a resolution. Recording an outcome does not bypass the gate or change a Decision; continue without the record." : "This credential is not permitted to record a resolution.";
|
|
11205
|
+
}
|
|
10488
11206
|
async function performReconcile(idOrShortId, opts = {}) {
|
|
10489
11207
|
if (opts.check !== void 0 || opts.outcome !== void 0) {
|
|
10490
11208
|
await performResolution(idOrShortId, opts);
|
|
@@ -10529,9 +11247,17 @@ async function performResolution(idOrShortId, opts) {
|
|
|
10529
11247
|
`);
|
|
10530
11248
|
} catch (error) {
|
|
10531
11249
|
const status2 = error instanceof HttpError ? error.status : void 0;
|
|
10532
|
-
|
|
11250
|
+
const refusal = serverRefusal(error);
|
|
11251
|
+
const detail = [refusal.error, refusal.message].map((value) => boundedHealthError(value)).filter(Boolean).join(": ");
|
|
11252
|
+
process.stderr.write(
|
|
11253
|
+
`[prim] resolution failed${status2 ? ` (${status2})` : ""}${detail ? `: ${detail}` : ""}
|
|
11254
|
+
`
|
|
11255
|
+
);
|
|
11256
|
+
if (status2 === 403 && refusal.error === "machine_scope_required") {
|
|
11257
|
+
process.stderr.write(`[prim] ${machineScopeRemedy()}
|
|
10533
11258
|
`);
|
|
10534
|
-
|
|
11259
|
+
}
|
|
11260
|
+
console.log(JSON.stringify({ ok: false, status: status2, ...refusal }));
|
|
10535
11261
|
process.exitCode = isDomainRejection(error) ? EXIT_USAGE2 : EXIT_SERVER;
|
|
10536
11262
|
}
|
|
10537
11263
|
}
|
|
@@ -10607,14 +11333,341 @@ function registerSessionCommands(program2) {
|
|
|
10607
11333
|
});
|
|
10608
11334
|
}
|
|
10609
11335
|
|
|
11336
|
+
// src/commands/setup-cloud.ts
|
|
11337
|
+
var EXIT_INCOMPLETE = 1;
|
|
11338
|
+
var EXIT_USAGE3 = 2;
|
|
11339
|
+
function refuseOutsideCloud(deps, mode) {
|
|
11340
|
+
const env = deps.env ?? process.env;
|
|
11341
|
+
if (isClaudeCloudSession(env)) return false;
|
|
11342
|
+
if (mode === "prepare" && (deps.platform ?? process.platform) === "linux") return false;
|
|
11343
|
+
refuse(
|
|
11344
|
+
deps,
|
|
11345
|
+
mode,
|
|
11346
|
+
mode === "prepare" ? "cloud \xB7 refusing: --prepare is for a Claude Code cloud environment's setup script (a Linux VM); on this machine it would disable the daemon" : "cloud \xB7 refusing: this is not a Claude Code cloud session (CLAUDE_CODE_REMOTE is not true); on this machine it would disable the daemon. Run `prim setup` instead"
|
|
11347
|
+
);
|
|
11348
|
+
return true;
|
|
11349
|
+
}
|
|
11350
|
+
function refuse(deps, mode, reason) {
|
|
11351
|
+
deps.note(reason);
|
|
11352
|
+
printJson({
|
|
11353
|
+
ok: false,
|
|
11354
|
+
cloud: mode,
|
|
11355
|
+
results: { cloud: "missing" },
|
|
11356
|
+
failed: ["cloud"],
|
|
11357
|
+
remedies: [reason],
|
|
11358
|
+
instructions: "Cloud setup does not apply on this machine. Tell the user why in one sentence."
|
|
11359
|
+
});
|
|
11360
|
+
deps.exit(EXIT_USAGE3);
|
|
11361
|
+
}
|
|
11362
|
+
function prepareCloudImage(deps) {
|
|
11363
|
+
if (refuseOutsideCloud(deps, "prepare")) return;
|
|
11364
|
+
const env = deps.env ?? process.env;
|
|
11365
|
+
if (!isClaudeCloudSession(env) && (deps.developerInstall ?? hasDeveloperUserInstall)()) {
|
|
11366
|
+
refuse(
|
|
11367
|
+
deps,
|
|
11368
|
+
"prepare",
|
|
11369
|
+
"cloud \xB7 refusing: this machine has its own user-scope prim install; --prepare is for a Claude Code cloud environment's setup script"
|
|
11370
|
+
);
|
|
11371
|
+
return;
|
|
11372
|
+
}
|
|
11373
|
+
const results = {};
|
|
11374
|
+
const remedies = [];
|
|
11375
|
+
const origin = prepareOrigin(deps);
|
|
11376
|
+
prepareSteps(deps, results, remedies, origin);
|
|
11377
|
+
if (origin === "session" && results.prepared === "ok") {
|
|
11378
|
+
const reason = "image \xB7 not prepared by this run: it ran inside a running Claude Code session, so only this VM is wired. Claude Code loads the hooks when it next starts here, and new sessions start from the environment's image. If the environment's setup script does not run `prim setup --cloud --prepare` yet, add it there; sessions started after that load the hooks";
|
|
11379
|
+
deps.note(reason);
|
|
11380
|
+
remedies.push(reason);
|
|
11381
|
+
results.image = "missing";
|
|
11382
|
+
}
|
|
11383
|
+
finish(deps, "prepare", results, remedies);
|
|
11384
|
+
}
|
|
11385
|
+
function prepareOrigin(deps) {
|
|
11386
|
+
const env = deps.env ?? process.env;
|
|
11387
|
+
if (!insideClaudeCode(env)) return "image";
|
|
11388
|
+
const live = isPreparedCloudSession(env) && !preparedInSession(env) && (deps.userHooksComplete ?? cloudUserInstallComplete)();
|
|
11389
|
+
return live ? "image" : "session";
|
|
11390
|
+
}
|
|
11391
|
+
function setupCloudSession(deps) {
|
|
11392
|
+
if (refuseOutsideCloud(deps, "session")) return;
|
|
11393
|
+
const results = {};
|
|
11394
|
+
const remedies = [];
|
|
11395
|
+
const outcome = {};
|
|
11396
|
+
sessionSteps(deps, results, remedies, {}, outcome);
|
|
11397
|
+
finish(deps, "session", results, remedies, outcome.optedOut);
|
|
11398
|
+
}
|
|
11399
|
+
function setupDetectedCloudSession(deps) {
|
|
11400
|
+
const env = deps.env ?? process.env;
|
|
11401
|
+
deps.note("cloud \xB7 Claude Code cloud session detected; running cloud setup");
|
|
11402
|
+
const results = {};
|
|
11403
|
+
const remedies = [];
|
|
11404
|
+
const root = gitToplevel(deps.cwd);
|
|
11405
|
+
let preparedNow = false;
|
|
11406
|
+
if (!isPreparedCloudSession(env) && !(root && hasProjectPrimInstall(root)) && !(root && optsOut(root))) {
|
|
11407
|
+
prepareSteps(deps, results, remedies, "session");
|
|
11408
|
+
preparedNow = results.prepared === "ok";
|
|
11409
|
+
}
|
|
11410
|
+
const outcome = {};
|
|
11411
|
+
sessionSteps(deps, results, remedies, { preparedNow }, outcome);
|
|
11412
|
+
finish(deps, "session", results, remedies, outcome.optedOut);
|
|
11413
|
+
}
|
|
11414
|
+
function optsOut(root) {
|
|
11415
|
+
return declaresInactive(root) && !explicitlyActive(root);
|
|
11416
|
+
}
|
|
11417
|
+
function prepareSteps(deps, results, remedies, origin = "image") {
|
|
11418
|
+
const env = deps.env ?? process.env;
|
|
11419
|
+
clearCloudPrepared(env);
|
|
11420
|
+
const attempt = (key, label2, action) => {
|
|
11421
|
+
deps.note(`${label2} \xB7 installing\u2026`);
|
|
11422
|
+
try {
|
|
11423
|
+
action();
|
|
11424
|
+
results[key] = "ok";
|
|
11425
|
+
} catch (error) {
|
|
11426
|
+
const reason = `${label2} \xB7 ${error instanceof Error ? error.message : String(error)}`;
|
|
11427
|
+
deps.note(reason);
|
|
11428
|
+
remedies.push(reason);
|
|
11429
|
+
results[key] = "failed";
|
|
11430
|
+
}
|
|
11431
|
+
};
|
|
11432
|
+
attempt("runtime", "hook runtime", deps.stage ?? stageHookRuntime);
|
|
11433
|
+
attempt(
|
|
11434
|
+
"userHooks",
|
|
11435
|
+
"Claude Code hooks (user scope)",
|
|
11436
|
+
deps.installUserHooks ?? (() => {
|
|
11437
|
+
performCloudUserInstall();
|
|
11438
|
+
})
|
|
11439
|
+
);
|
|
11440
|
+
const step = (key, label2, args) => {
|
|
11441
|
+
deps.note(`${label2}\u2026`);
|
|
11442
|
+
results[key] = deps.run(args).code === 0 ? "ok" : "failed";
|
|
11443
|
+
if (results[key] === "failed")
|
|
11444
|
+
remedies.push(`${key} \xB7 failed; run \`prim ${args.join(" ")}\` to see why`);
|
|
11445
|
+
};
|
|
11446
|
+
step("preauth", "pre-authorize \xB7 writing prim allow-rule (user scope)", [
|
|
11447
|
+
"claude",
|
|
11448
|
+
"preauth",
|
|
11449
|
+
"--scope",
|
|
11450
|
+
"user"
|
|
11451
|
+
]);
|
|
11452
|
+
step("skill", "agent skill \xB7 installing", [
|
|
11453
|
+
"skill",
|
|
11454
|
+
"install",
|
|
11455
|
+
"--agent",
|
|
11456
|
+
"claude",
|
|
11457
|
+
"--scope",
|
|
11458
|
+
"user"
|
|
11459
|
+
]);
|
|
11460
|
+
step("daemon", "daemon \xB7 recording the opt-out", ["daemon", "stop"]);
|
|
11461
|
+
if (results.runtime === "ok" && results.userHooks === "ok")
|
|
11462
|
+
attempt(
|
|
11463
|
+
"prepared",
|
|
11464
|
+
"cloud activation",
|
|
11465
|
+
() => (deps.markPrepared ?? ((from) => markCloudPrepared(env, from)))(origin)
|
|
11466
|
+
);
|
|
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
|
+
}
|
|
11508
|
+
function credentialsReady({ deps, results, remedy, env }) {
|
|
11509
|
+
let machine;
|
|
11510
|
+
try {
|
|
11511
|
+
machine = hasMachineConfiguration({ env });
|
|
11512
|
+
} catch (error) {
|
|
11513
|
+
remedy(`credentials \xB7 ${error instanceof MachineAuthError ? error.message : String(error)}`);
|
|
11514
|
+
results.credentials = "failed";
|
|
11515
|
+
return false;
|
|
11516
|
+
}
|
|
11517
|
+
if (!machine && !resolveStoredCredential(env)) {
|
|
11518
|
+
remedy(
|
|
11519
|
+
`credentials \xB7 missing: ${CLOUD_CREDENTIALS_REMEDY}; the environment must also allow ${cloudAllowedDomains(void 0, void 0, env).join(" and ")} under Allowed domains (blocked by default)`
|
|
11520
|
+
);
|
|
11521
|
+
results.credentials = "missing";
|
|
11522
|
+
return false;
|
|
11523
|
+
}
|
|
11524
|
+
clearMachineCooldowns(primConfigDirectory({ env }));
|
|
11525
|
+
const status2 = deps.run(["auth", "status", "--json"], true);
|
|
11526
|
+
const auth = deps.parseAuthStatus(status2);
|
|
11527
|
+
if (auth !== "valid") {
|
|
11528
|
+
const detail = authFailureDetail(status2.stdout);
|
|
11529
|
+
remedy(
|
|
11530
|
+
auth === "unreachable" ? unreachableRemedy(detail, env) : machine ? `credentials \xB7 ${detail ?? "rejected"}${// Guidance that already names the replacement needs no second copy.
|
|
11531
|
+
detail?.includes("prim auth enroll") ? "" : "; if the credential itself was revoked, mint a replacement with `prim auth enroll --new-installation` and revoke the old installation in Settings \u2192 Developer installations"}` : (
|
|
11532
|
+
// A fixed token or stored sign-in has no installation to revoke.
|
|
11533
|
+
`credentials \xB7 the sign-in was rejected: ${CLOUD_CREDENTIALS_REMEDY}`
|
|
11534
|
+
)
|
|
11535
|
+
);
|
|
11536
|
+
results.credentials = "failed";
|
|
11537
|
+
return false;
|
|
11538
|
+
}
|
|
11539
|
+
if (enrollmentRequired(status2.stdout)) {
|
|
11540
|
+
remedy(
|
|
11541
|
+
`credentials \xB7 this sign-in can only enroll an installation, which a cloud session cannot do: ${CLOUD_CREDENTIALS_REMEDY}`
|
|
11542
|
+
);
|
|
11543
|
+
results.credentials = "failed";
|
|
11544
|
+
return false;
|
|
11545
|
+
}
|
|
11546
|
+
results.credentials = "ok";
|
|
11547
|
+
return true;
|
|
11548
|
+
}
|
|
11549
|
+
function repositoryRoot({ deps, results, remedy }, outcome) {
|
|
11550
|
+
const root = gitToplevel(deps.cwd);
|
|
11551
|
+
if (!root) {
|
|
11552
|
+
remedy("repository \xB7 not a git repository; run from the cloned repository");
|
|
11553
|
+
results.repository = "missing";
|
|
11554
|
+
return void 0;
|
|
11555
|
+
}
|
|
11556
|
+
if (optsOut(root)) {
|
|
11557
|
+
deps.note(
|
|
11558
|
+
"repository \xB7 opted out: its .claude/settings.json declares PRIM_ACTIVE=false, so prim stays off here. `prim enable` turns it on for this session's clone; `prim enable --scope project` removes the opt-out"
|
|
11559
|
+
);
|
|
11560
|
+
results.repository = "ok";
|
|
11561
|
+
outcome.optedOut = true;
|
|
11562
|
+
return void 0;
|
|
11563
|
+
}
|
|
11564
|
+
if (!githubRepositoryFullName(root)) {
|
|
11565
|
+
remedy(`repository \xB7 ${repositoryIdentityRemedy(root)}`);
|
|
11566
|
+
results.repository = "missing";
|
|
11567
|
+
return void 0;
|
|
11568
|
+
}
|
|
11569
|
+
return root;
|
|
11570
|
+
}
|
|
11571
|
+
function sessionHooks({ deps, results, remedy, env }, root, options) {
|
|
11572
|
+
const pendingHooks = options.preparedNow === true || preparedInSession(env);
|
|
11573
|
+
if (root !== void 0 && hasProjectPrimInstall(root) || !pendingHooks && isPreparedCloudSession(env) && (deps.userHooksComplete ?? cloudUserInstallComplete)()) {
|
|
11574
|
+
results.session = "ok";
|
|
11575
|
+
} else if (pendingHooks) {
|
|
11576
|
+
remedy(
|
|
11577
|
+
"session hooks \xB7 wired in this VM, but Claude Code loads them only when it next starts here, and new sessions start from the environment's image: add `prim setup --cloud --prepare` to the environment's setup script"
|
|
11578
|
+
);
|
|
11579
|
+
results.session = "missing";
|
|
11580
|
+
} else {
|
|
11581
|
+
remedy(
|
|
11582
|
+
`session hooks \xB7 none: run \`prim setup --cloud --prepare\` in the environment's setup script${// Outside a repository there is nothing to commit an install to.
|
|
11583
|
+
root === void 0 ? "" : ", or commit `prim claude install --scope project` in this repository"}`
|
|
11584
|
+
);
|
|
11585
|
+
results.session = "missing";
|
|
11586
|
+
}
|
|
11587
|
+
}
|
|
11588
|
+
function sessionSteps(deps, results, remedies, options = {}, outcome = {}) {
|
|
11589
|
+
const remedy = (message) => {
|
|
11590
|
+
deps.note(message);
|
|
11591
|
+
remedies.push(message);
|
|
11592
|
+
};
|
|
11593
|
+
const check = { deps, results, remedy, env: deps.env ?? process.env };
|
|
11594
|
+
const credentials = identityReady(check) && credentialsReady(check);
|
|
11595
|
+
const root = repositoryRoot(check, outcome);
|
|
11596
|
+
if (!outcome.optedOut) sessionHooks(check, root ?? gitToplevel(deps.cwd) ?? void 0, options);
|
|
11597
|
+
if (!credentials || !root) return;
|
|
11598
|
+
const step = (key, label2, args) => {
|
|
11599
|
+
if (label2) deps.note(`${label2} \xB7 installing\u2026`);
|
|
11600
|
+
results[key] = deps.run(args).code === 0 ? "ok" : "failed";
|
|
11601
|
+
if (results[key] === "failed")
|
|
11602
|
+
remedy(`${label2 || key} \xB7 failed; run \`prim ${args.join(" ")}\` to see why`);
|
|
11603
|
+
};
|
|
11604
|
+
if (results.daemon === void 0) step("daemon", "", ["daemon", "stop"]);
|
|
11605
|
+
step("hooks", "git hooks", ["hooks", "install"]);
|
|
11606
|
+
deps.note("activate this repo \xB7 installing\u2026");
|
|
11607
|
+
const enabled = deps.run(["enable", "--non-interactive"]);
|
|
11608
|
+
results.enable = enabled.code === 0 ? "ok" : "failed";
|
|
11609
|
+
if (results.enable === "failed") {
|
|
11610
|
+
const unconnected = unconnectedRepository(enabled.stdout);
|
|
11611
|
+
remedy(
|
|
11612
|
+
unconnected ? `repository \xB7 ${unconnected} is not connected to Primitive: ${isCloudMachineSession(deps.env ?? process.env) ? CLOUD_GITHUB_CONNECT_REMEDY : "run `prim github connect --no-browser` and open the link it prints"}` : "activate this repo \xB7 failed; run `prim enable --non-interactive` to see why"
|
|
11613
|
+
);
|
|
11614
|
+
}
|
|
11615
|
+
}
|
|
11616
|
+
function unreachableRemedy(detail, env) {
|
|
11617
|
+
if (detail?.startsWith(SERVER_WAIT_PREFIX)) return `credentials \xB7 ${detail}`;
|
|
11618
|
+
if (detail?.includes("Allowed domains"))
|
|
11619
|
+
return `credentials \xB7 ${detail}; prim needs ${cloudAllowedDomains(void 0, void 0, env).join(" and ")} allowed`;
|
|
11620
|
+
return `credentials \xB7 Primitive is unreachable from this environment: ${cloudEgressRemedy()}${detail ? ` (${detail})` : ""}`;
|
|
11621
|
+
}
|
|
11622
|
+
function unconnectedRepository(stdout) {
|
|
11623
|
+
try {
|
|
11624
|
+
const parsed = JSON.parse(stdout || "{}");
|
|
11625
|
+
return parsed.bindingStatus === "unbound" && typeof parsed.repositoryFullName === "string" ? stripControlChars(parsed.repositoryFullName) : void 0;
|
|
11626
|
+
} catch {
|
|
11627
|
+
return void 0;
|
|
11628
|
+
}
|
|
11629
|
+
}
|
|
11630
|
+
function enrollmentRequired(stdout) {
|
|
11631
|
+
try {
|
|
11632
|
+
return JSON.parse(stdout || "{}").enrollmentRequired === true;
|
|
11633
|
+
} catch {
|
|
11634
|
+
return false;
|
|
11635
|
+
}
|
|
11636
|
+
}
|
|
11637
|
+
function authFailureDetail(stdout) {
|
|
11638
|
+
try {
|
|
11639
|
+
const parsed = JSON.parse(stdout || "{}");
|
|
11640
|
+
return typeof parsed.recoveryDetail === "string" ? stripControlChars(parsed.recoveryDetail).replace(CLOUD_SETUP_POINTER, "").replace(/\.$/u, "") : void 0;
|
|
11641
|
+
} catch {
|
|
11642
|
+
return void 0;
|
|
11643
|
+
}
|
|
11644
|
+
}
|
|
11645
|
+
function finish(deps, mode, results, remedies, optedOut = false) {
|
|
11646
|
+
const failed = Object.keys(results).filter((key) => results[key] !== "ok");
|
|
11647
|
+
deps.note(
|
|
11648
|
+
failed.length === 0 ? `cloud ${mode} complete` : `cloud ${mode} incomplete (${failed.join(", ")})`
|
|
11649
|
+
);
|
|
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.";
|
|
11651
|
+
printJson({
|
|
11652
|
+
ok: failed.length === 0,
|
|
11653
|
+
cloud: mode,
|
|
11654
|
+
results,
|
|
11655
|
+
failed,
|
|
11656
|
+
remedies,
|
|
11657
|
+
instructions,
|
|
11658
|
+
...optedOut ? { optedOut: true } : {}
|
|
11659
|
+
});
|
|
11660
|
+
if (failed.length) deps.exit(EXIT_INCOMPLETE);
|
|
11661
|
+
}
|
|
11662
|
+
|
|
10610
11663
|
// src/commands/setup.ts
|
|
10611
11664
|
import { spawnSync as spawnSync2 } from "child_process";
|
|
10612
11665
|
import { existsSync as existsSync12, readFileSync as readFileSync10 } from "fs";
|
|
10613
11666
|
import { homedir as homedir7 } from "os";
|
|
10614
11667
|
import { join as join16, resolve as resolve5, sep } from "path";
|
|
10615
|
-
var
|
|
11668
|
+
var EXIT_INCOMPLETE2 = 1;
|
|
10616
11669
|
var GITHUB_CONNECT_TIMEOUT_MS = 9e4;
|
|
10617
|
-
var
|
|
11670
|
+
var EXIT_USAGE4 = 2;
|
|
10618
11671
|
var SETUP_ORCHESTRATOR_ENV = "PRIM_SETUP_ORCHESTRATOR";
|
|
10619
11672
|
var SETUP_DAEMON_DRAINS_ENV = "PRIM_SETUP_DAEMON_DRAINS";
|
|
10620
11673
|
function setupStepSpawnOptions(capture, env = process.env, options = {}) {
|
|
@@ -10788,7 +11841,7 @@ function parseSetupAuthStatus(result) {
|
|
|
10788
11841
|
if (parsed.status === "invalid") return "invalid";
|
|
10789
11842
|
} catch {
|
|
10790
11843
|
}
|
|
10791
|
-
return result.code ===
|
|
11844
|
+
return result.code === EXIT_USAGE4 ? "unreachable" : "invalid";
|
|
10792
11845
|
}
|
|
10793
11846
|
function registerSetupCommand(program2, dependencies = {}) {
|
|
10794
11847
|
program2.command("setup").description(
|
|
@@ -10803,7 +11856,13 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10803
11856
|
).option(
|
|
10804
11857
|
"--migrate",
|
|
10805
11858
|
"with the default user scope, remove any project-scoped prim config in this repo (else just warn)"
|
|
10806
|
-
).option("--no-daemon", "stop and disable the companion daemon").option("--details", "show full human installation diagnostics on STDERR").option("--skip-demo", "skip the optional author story and remember that choice").
|
|
11859
|
+
).option("--no-daemon", "stop and disable the companion daemon").option("--details", "show full human installation diagnostics on STDERR").option("--skip-demo", "skip the optional author story and remember that choice").option(
|
|
11860
|
+
"--cloud",
|
|
11861
|
+
"set up a Claude Code cloud session with machine credentials: git hooks and activation only, no daemon or onboarding"
|
|
11862
|
+
).option(
|
|
11863
|
+
"--prepare",
|
|
11864
|
+
"with --cloud, prepare the environment's image from its setup script: hook runtime, user-scope Claude hooks, activation (no credentials or network)"
|
|
11865
|
+
).action((opts, command) => {
|
|
10807
11866
|
const setupAt = Date.now();
|
|
10808
11867
|
const { agent: agentInput, detected } = resolveAgent(opts.agent, process.env);
|
|
10809
11868
|
if (agentInput !== "claude" && agentInput !== "codex" && agentInput !== "cursor" && agentInput !== "hermes") {
|
|
@@ -10811,18 +11870,38 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10811
11870
|
`[prim] unknown --agent "${agentInput}" (expected claude, codex, cursor, or hermes)
|
|
10812
11871
|
`
|
|
10813
11872
|
);
|
|
10814
|
-
(dependencies.exit ?? process.exit)(
|
|
11873
|
+
(dependencies.exit ?? process.exit)(EXIT_USAGE4);
|
|
10815
11874
|
return;
|
|
10816
11875
|
}
|
|
10817
11876
|
if (opts.scope !== "project" && opts.scope !== "user") {
|
|
10818
11877
|
process.stderr.write(`[prim] unknown --scope "${opts.scope}" (expected project or user)
|
|
10819
11878
|
`);
|
|
10820
|
-
(dependencies.exit ?? process.exit)(
|
|
11879
|
+
(dependencies.exit ?? process.exit)(EXIT_USAGE4);
|
|
11880
|
+
return;
|
|
11881
|
+
}
|
|
11882
|
+
const cloudSetup = opts.cloud === true || isClaudeCloudSession();
|
|
11883
|
+
if (opts.prepare && !opts.cloud) {
|
|
11884
|
+
process.stderr.write("[prim] --prepare applies only with --cloud\n");
|
|
11885
|
+
(dependencies.exit ?? process.exit)(EXIT_USAGE4);
|
|
11886
|
+
return;
|
|
11887
|
+
}
|
|
11888
|
+
const cloudConflicts = cloudSetup ? [
|
|
11889
|
+
opts.agent !== void 0 && agentInput !== "claude" ? "--agent" : void 0,
|
|
11890
|
+
command.getOptionValueSource("scope") === "cli" ? "--scope" : void 0,
|
|
11891
|
+
opts.globalHooksPath ? "--global-hooks-path" : void 0,
|
|
11892
|
+
opts.migrate ? "--migrate" : void 0
|
|
11893
|
+
].filter((flag) => flag !== void 0) : [];
|
|
11894
|
+
if (cloudConflicts.length) {
|
|
11895
|
+
process.stderr.write(
|
|
11896
|
+
`[prim] ${opts.cloud ? "--cloud" : "setup in a Claude Code cloud session"} does not combine with ${cloudConflicts.join(", ")}
|
|
11897
|
+
`
|
|
11898
|
+
);
|
|
11899
|
+
(dependencies.exit ?? process.exit)(EXIT_USAGE4);
|
|
10821
11900
|
return;
|
|
10822
11901
|
}
|
|
10823
11902
|
if (opts.globalHooksPath && opts.scope !== "user") {
|
|
10824
11903
|
process.stderr.write("[prim] --global-hooks-path applies only with --scope user\n");
|
|
10825
|
-
(dependencies.exit ?? process.exit)(
|
|
11904
|
+
(dependencies.exit ?? process.exit)(EXIT_USAGE4);
|
|
10826
11905
|
return;
|
|
10827
11906
|
}
|
|
10828
11907
|
const agent = agentInput;
|
|
@@ -10833,7 +11912,8 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10833
11912
|
const childArgs = opts.details ? args.filter((arg) => arg !== "--compact") : args;
|
|
10834
11913
|
const r = spawnSync2(process.execPath, [self, ...childArgs], {
|
|
10835
11914
|
...setupStepSpawnOptions(capture, process.env, {
|
|
10836
|
-
|
|
11915
|
+
// Cloud setup stops the daemon, so its steps drain for themselves.
|
|
11916
|
+
startsDaemon: opts.daemon && !cloudSetup,
|
|
10837
11917
|
compact: true
|
|
10838
11918
|
}),
|
|
10839
11919
|
timeout: timeoutMs2
|
|
@@ -10852,6 +11932,13 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10852
11932
|
`);
|
|
10853
11933
|
});
|
|
10854
11934
|
const exit = dependencies.exit ?? process.exit;
|
|
11935
|
+
if (cloudSetup) {
|
|
11936
|
+
const cloud = { run, note, exit, parseAuthStatus: parseSetupAuthStatus };
|
|
11937
|
+
if (opts.prepare) prepareCloudImage(cloud);
|
|
11938
|
+
else if (opts.cloud) setupCloudSession(cloud);
|
|
11939
|
+
else setupDetectedCloudSession(cloud);
|
|
11940
|
+
return;
|
|
11941
|
+
}
|
|
10855
11942
|
if (detected && agent !== "claude") {
|
|
10856
11943
|
note(`agent \xB7 detected ${agent} session (override with --agent <agent>)`);
|
|
10857
11944
|
}
|
|
@@ -10860,14 +11947,14 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10860
11947
|
let authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
|
|
10861
11948
|
if (authStatus === "unreachable") {
|
|
10862
11949
|
note("auth \xB7 verification unavailable; no setup changes were made");
|
|
10863
|
-
exit(
|
|
11950
|
+
exit(EXIT_USAGE4);
|
|
10864
11951
|
return;
|
|
10865
11952
|
}
|
|
10866
11953
|
if (authStatus === "invalid" && machine) {
|
|
10867
11954
|
note(
|
|
10868
11955
|
"auth \xB7 machine credentials need attention; run prim auth status, then configure-machine with administrator-issued credentials"
|
|
10869
11956
|
);
|
|
10870
|
-
exit(
|
|
11957
|
+
exit(EXIT_INCOMPLETE2);
|
|
10871
11958
|
return;
|
|
10872
11959
|
}
|
|
10873
11960
|
if (authStatus === "invalid") {
|
|
@@ -10875,7 +11962,7 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10875
11962
|
const login = run(["auth", "login"]);
|
|
10876
11963
|
if (login.code !== 0) {
|
|
10877
11964
|
note("auth \xB7 login failed; no integration changes were made");
|
|
10878
|
-
exit(
|
|
11965
|
+
exit(EXIT_INCOMPLETE2);
|
|
10879
11966
|
return;
|
|
10880
11967
|
}
|
|
10881
11968
|
authStatus = parseSetupAuthStatus(run(["auth", "status", "--json"], true));
|
|
@@ -10883,7 +11970,7 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10883
11970
|
note(
|
|
10884
11971
|
authStatus === "unreachable" ? "auth \xB7 login completed but verification is unavailable; no integration changes were made" : "auth \xB7 login did not produce valid credentials; no integration changes were made"
|
|
10885
11972
|
);
|
|
10886
|
-
exit(authStatus === "unreachable" ?
|
|
11973
|
+
exit(authStatus === "unreachable" ? EXIT_USAGE4 : EXIT_INCOMPLETE2);
|
|
10887
11974
|
return;
|
|
10888
11975
|
}
|
|
10889
11976
|
} else {
|
|
@@ -10900,7 +11987,7 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10900
11987
|
note(
|
|
10901
11988
|
"auth \xB7 installation enrollment failed; existing credentials and captured activity were preserved. Run prim auth enroll for details."
|
|
10902
11989
|
);
|
|
10903
|
-
exit(
|
|
11990
|
+
exit(EXIT_INCOMPLETE2);
|
|
10904
11991
|
return;
|
|
10905
11992
|
}
|
|
10906
11993
|
const payload = setupChildPayload(enrollment.stdout);
|
|
@@ -10982,7 +12069,7 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
10982
12069
|
failed: failed2,
|
|
10983
12070
|
health
|
|
10984
12071
|
});
|
|
10985
|
-
if (failed2.length) exit(
|
|
12072
|
+
if (failed2.length) exit(EXIT_INCOMPLETE2);
|
|
10986
12073
|
return;
|
|
10987
12074
|
}
|
|
10988
12075
|
if (welcomeHandoff) {
|
|
@@ -11021,7 +12108,7 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
11021
12108
|
instructions: "Read the file at welcomeSkill and follow it."
|
|
11022
12109
|
}
|
|
11023
12110
|
});
|
|
11024
|
-
exit(failed2.length === 0 ? 0 :
|
|
12111
|
+
exit(failed2.length === 0 ? 0 : EXIT_INCOMPLETE2);
|
|
11025
12112
|
return;
|
|
11026
12113
|
}
|
|
11027
12114
|
const installationSucceeded = !Object.values(results).includes("failed");
|
|
@@ -11091,7 +12178,7 @@ function registerSetupCommand(program2, dependencies = {}) {
|
|
|
11091
12178
|
welcome: setupChildPayload(welcomeResult.stdout),
|
|
11092
12179
|
...onboarding ? { onboarding, nextAction: onboarding.nextAction } : {}
|
|
11093
12180
|
});
|
|
11094
|
-
exit(failed.length === 0 ? 0 :
|
|
12181
|
+
exit(failed.length === 0 ? 0 : EXIT_INCOMPLETE2);
|
|
11095
12182
|
});
|
|
11096
12183
|
}
|
|
11097
12184
|
function primCommand(argv = process.argv, version = packageVersion()) {
|
|
@@ -11177,7 +12264,7 @@ function registerStatuslineCommands(program2) {
|
|
|
11177
12264
|
|
|
11178
12265
|
// src/commands/uninstall.ts
|
|
11179
12266
|
import { spawnSync as spawnSync3 } from "child_process";
|
|
11180
|
-
var
|
|
12267
|
+
var EXIT_INCOMPLETE3 = 1;
|
|
11181
12268
|
var CHILD_TIMEOUT_MS = 3e4;
|
|
11182
12269
|
var UNINSTALL_ORCHESTRATOR_ENV = "PRIM_UNINSTALL_ORCHESTRATOR";
|
|
11183
12270
|
function planUninstallSteps(inRepository) {
|
|
@@ -11305,7 +12392,7 @@ function registerUninstallCommand(program2, dependencies = {}) {
|
|
|
11305
12392
|
});
|
|
11306
12393
|
const detail = result2.error?.message ?? result2.stderr ?? "";
|
|
11307
12394
|
return {
|
|
11308
|
-
code: result2.status ??
|
|
12395
|
+
code: result2.status ?? EXIT_INCOMPLETE3,
|
|
11309
12396
|
stdout: result2.stdout ?? "",
|
|
11310
12397
|
stderr: detail
|
|
11311
12398
|
};
|
|
@@ -11380,7 +12467,7 @@ function registerUninstallCommand(program2, dependencies = {}) {
|
|
|
11380
12467
|
note(
|
|
11381
12468
|
complete ? "uninstall complete \xB7 credentials and pending journals preserved" : `uninstall incomplete \xB7 failed: ${failed.join(", ")}`
|
|
11382
12469
|
);
|
|
11383
|
-
exit(complete ? 0 :
|
|
12470
|
+
exit(complete ? 0 : EXIT_INCOMPLETE3);
|
|
11384
12471
|
});
|
|
11385
12472
|
}
|
|
11386
12473
|
|
|
@@ -11814,7 +12901,7 @@ function runStartupBackgroundWork(argv, env, work) {
|
|
|
11814
12901
|
const uninstall2 = command === "uninstall" || env[UNINSTALL_ORCHESTRATOR_ENV] === "1";
|
|
11815
12902
|
if (uninstall2 || command === "demo") return;
|
|
11816
12903
|
work.notify();
|
|
11817
|
-
const setupDaemonDrains = command === "setup" && !args.includes("--no-daemon") || env[SETUP_DAEMON_DRAINS_ENV] === "1";
|
|
12904
|
+
const setupDaemonDrains = command === "setup" && !args.includes("--no-daemon") && !args.includes("--cloud") && !isClaudeCloudSession(env) || env[SETUP_DAEMON_DRAINS_ENV] === "1";
|
|
11818
12905
|
if (!setupDaemonDrains && (command !== "moves" || subcommand !== "flush")) work.flush();
|
|
11819
12906
|
if (mayHealDaemon(argv, env)) work.healDaemon();
|
|
11820
12907
|
}
|