@primitive.ai/prim 0.1.0-alpha.127 → 0.1.0-alpha.128
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +76 -5
- package/dist/{chunk-NVDPKW7Z.js → chunk-3KPTVK4N.js} +3 -51
- package/dist/{chunk-URYZDQFH.js → chunk-4DYEBYKM.js} +3 -5
- package/dist/{chunk-HZI5PBN4.js → chunk-6QAXVFRJ.js} +1129 -39
- package/dist/{chunk-A5VTE43F.js → chunk-ANMNGGTN.js} +2 -2
- package/dist/{chunk-TNWI3JWK.js → chunk-B3ICJZXV.js} +4 -2
- package/dist/{chunk-RV3JFSMX.js → chunk-C357P37M.js} +4 -4
- package/dist/{chunk-KFRGVHGB.js → chunk-E57UVUJL.js} +6 -6
- package/dist/{chunk-MGKSZSTV.js → chunk-EQWUCFXK.js} +3 -3
- package/dist/{chunk-72NIZMZN.js → chunk-M6KIDB5R.js} +8 -3
- package/dist/{chunk-O65UVJZH.js → chunk-N6PZE7HX.js} +2 -2
- package/dist/{chunk-WGTUNUIS.js → chunk-NYDM4HSS.js} +5 -5
- package/dist/{chunk-R4EYLEIK.js → chunk-P4O7L7JZ.js} +2 -2
- package/dist/{chunk-UUQT5GMO.js → chunk-PRJ7P6J5.js} +1 -1
- package/dist/{chunk-H74RDXKP.js → chunk-PTZ6BWSU.js} +2 -2
- package/dist/{chunk-F3FDVHR7.js → chunk-QQ3G5SXX.js} +1 -1
- package/dist/{chunk-VVFVENU4.js → chunk-RDT2IV2Z.js} +6 -6
- package/dist/{chunk-L6IL4N6Y.js → chunk-VLT2KGPE.js} +34 -34
- package/dist/{chunk-H6X52UVF.js → chunk-WEGZGF3K.js} +1 -1
- package/dist/{chunk-C4QNBSWB.js → chunk-XINFTNA2.js} +8 -8
- package/dist/{chunk-JCKOW45X.js → chunk-ZCT23NBS.js} +2 -2
- package/dist/daemon/server.js +1311 -364
- package/dist/hook-runtime/daemon/server.js +1311 -364
- package/dist/hook-runtime/hooks/post-commit.js +395 -242
- package/dist/hook-runtime/hooks/post-rewrite.js +391 -238
- package/dist/hook-runtime/hooks/post-tool-use.js +1442 -498
- package/dist/hook-runtime/hooks/pre-commit.js +1293 -349
- package/dist/hook-runtime/hooks/pre-tool-use-worker.js +1087 -143
- package/dist/hook-runtime/hooks/prim-hook.js +1457 -513
- package/dist/hook-runtime/hooks/session-end.js +369 -216
- package/dist/hook-runtime/hooks/session-start.js +1209 -219
- package/dist/hook-runtime/index.js +2406 -1036
- package/dist/hook-runtime/statusline-main.js +360 -207
- 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 +9 -9
- package/dist/hooks/prim-hook.js +16 -16
- package/dist/hooks/session-end.js +4 -4
- package/dist/hooks/session-start.js +63 -20
- package/dist/index.js +387 -43
- package/dist/statusline-main.js +360 -207
- package/package.json +1 -1
|
@@ -742,6 +742,8 @@ function isClaudeCloudSession(env = process.env) {
|
|
|
742
742
|
}
|
|
743
743
|
var CLOUD_CREDENTIALS_REMEDY = 'give the cloud environment PRIM_M2M_CLIENT_ID and PRIM_M2M_CLIENT_SECRET, as variables or with the secret held as a network secret; mint them on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`, which says where each value goes';
|
|
744
744
|
var CLOUD_REJECTED_CREDENTIALS_REMEDY = 'correct the credentials in the cloud environment\'s settings, or if the installation was revoked mint a replacement on your own machine with `prim auth enroll --new-installation "Claude Code cloud" --print-env`; then start a new cloud session';
|
|
745
|
+
var CLOUD_REJECTED_CREDENTIALS_NOTICE = `Primitive is not connected in this Claude Code cloud session: its credentials were rejected. To fix it, ${CLOUD_REJECTED_CREDENTIALS_REMEDY}.`;
|
|
746
|
+
var CLOUD_GITHUB_CONNECT_REMEDY = "run `prim github connect` in a clone of it on your own machine, then start a new cloud session";
|
|
745
747
|
function cloudSetupPointer(message, env = process.env) {
|
|
746
748
|
return isClaudeCloudSession(env) ? `${message.replace(/[.;\s]+$/u, "")}${CLOUD_SETUP_POINTER}` : message;
|
|
747
749
|
}
|
|
@@ -831,13 +833,20 @@ var GIT_TIMEOUT_MS2 = 1e3;
|
|
|
831
833
|
var MAX_SETTINGS_BYTES = 1024 * 1024;
|
|
832
834
|
var GITHUB_OWNER_PATTERN = /^(?![A-Za-z0-9-]*--)[A-Za-z0-9](?:[A-Za-z0-9-]{0,37}[A-Za-z0-9])?$/u;
|
|
833
835
|
var GITHUB_REPOSITORY_PATTERN = /^(?!\.{1,2}$)[A-Za-z0-9._-]{1,100}$/u;
|
|
836
|
+
var CREDENTIAL_VARIABLE = /^(?:PRIM_TOKEN|PRIM_M2M_\w+)$/u;
|
|
837
|
+
function gitChildEnvironment(env = process.env) {
|
|
838
|
+
return Object.fromEntries(
|
|
839
|
+
Object.entries(env).filter(([name]) => !CREDENTIAL_VARIABLE.test(name))
|
|
840
|
+
);
|
|
841
|
+
}
|
|
834
842
|
function gitToplevel(cwd) {
|
|
835
843
|
try {
|
|
836
844
|
return execFileSync3("git", ["rev-parse", "--show-toplevel"], {
|
|
837
845
|
cwd,
|
|
838
846
|
encoding: "utf-8",
|
|
839
847
|
stdio: ["ignore", "pipe", "ignore"],
|
|
840
|
-
timeout: GIT_TIMEOUT_MS2
|
|
848
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
849
|
+
env: gitChildEnvironment()
|
|
841
850
|
}).trim();
|
|
842
851
|
} catch {
|
|
843
852
|
return null;
|
|
@@ -849,13 +858,17 @@ function gitValue(cwd, args) {
|
|
|
849
858
|
cwd,
|
|
850
859
|
encoding: "utf-8",
|
|
851
860
|
stdio: ["ignore", "pipe", "ignore"],
|
|
852
|
-
timeout: GIT_TIMEOUT_MS2
|
|
861
|
+
timeout: GIT_TIMEOUT_MS2,
|
|
862
|
+
env: gitChildEnvironment()
|
|
853
863
|
}).trim();
|
|
854
864
|
return value || void 0;
|
|
855
865
|
} catch {
|
|
856
866
|
return void 0;
|
|
857
867
|
}
|
|
858
868
|
}
|
|
869
|
+
function currentBranch(cwd) {
|
|
870
|
+
return gitValue(cwd, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
871
|
+
}
|
|
859
872
|
function parseGithubRepositoryName(path) {
|
|
860
873
|
const parts = path.replace(/^\/+|\/+$/g, "").replace(/\.git$/i, "").split("/");
|
|
861
874
|
if (parts.length !== 2 || !GITHUB_OWNER_PATTERN.test(parts[0] ?? "") || !GITHUB_REPOSITORY_PATTERN.test(parts[1] ?? "")) {
|
|
@@ -1522,18 +1535,18 @@ function publicDecisionResponse(value) {
|
|
|
1522
1535
|
}
|
|
1523
1536
|
|
|
1524
1537
|
// src/client.ts
|
|
1525
|
-
import { createHash as
|
|
1526
|
-
import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as
|
|
1538
|
+
import { createHash as createHash8 } from "crypto";
|
|
1539
|
+
import { chmodSync as chmodSync4, existsSync as existsSync10, mkdirSync as mkdirSync6, readFileSync as readFileSync14, rmSync as rmSync9 } from "fs";
|
|
1527
1540
|
import { dirname as dirname9 } from "path";
|
|
1528
1541
|
|
|
1529
1542
|
// src/lib/credentials.ts
|
|
1530
|
-
import { createHash as
|
|
1543
|
+
import { createHash as createHash7 } from "crypto";
|
|
1531
1544
|
import { readFileSync as readFileSync12 } from "fs";
|
|
1532
|
-
import { join as
|
|
1545
|
+
import { join as join15 } from "path";
|
|
1533
1546
|
|
|
1534
1547
|
// src/lib/machine-credentials.ts
|
|
1535
1548
|
import { execFileSync as execFileSync5 } from "child_process";
|
|
1536
|
-
import { createHash as
|
|
1549
|
+
import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID2 } from "crypto";
|
|
1537
1550
|
import {
|
|
1538
1551
|
chmodSync as chmodSync2,
|
|
1539
1552
|
existsSync as existsSync9,
|
|
@@ -1541,11 +1554,11 @@ import {
|
|
|
1541
1554
|
lstatSync as lstatSync6,
|
|
1542
1555
|
mkdirSync as mkdirSync5,
|
|
1543
1556
|
readFileSync as readFileSync11,
|
|
1544
|
-
rmSync as
|
|
1557
|
+
rmSync as rmSync8,
|
|
1545
1558
|
writeFileSync as writeFileSync5
|
|
1546
1559
|
} from "fs";
|
|
1547
1560
|
import { createRequire as createRequire2 } from "module";
|
|
1548
|
-
import { dirname as dirname8, join as
|
|
1561
|
+
import { dirname as dirname8, join as join14 } from "path";
|
|
1549
1562
|
import { fileURLToPath as fileURLToPath4 } from "url";
|
|
1550
1563
|
|
|
1551
1564
|
// src/lib/machine-broker.ts
|
|
@@ -1722,10 +1735,10 @@ function parseWorkosConnectTokens(value, options = {}) {
|
|
|
1722
1735
|
"access_token",
|
|
1723
1736
|
WORKOS_CONNECT_RESPONSE_MAX_BYTES
|
|
1724
1737
|
);
|
|
1725
|
-
const
|
|
1738
|
+
const refreshToken3 = record.refresh_token === void 0 && options.fallbackRefreshToken !== void 0 ? options.fallbackRefreshToken : exactString(record.refresh_token, "refresh_token", WORKOS_CONNECT_RESPONSE_MAX_BYTES);
|
|
1726
1739
|
return {
|
|
1727
1740
|
accessToken,
|
|
1728
|
-
refreshToken:
|
|
1741
|
+
refreshToken: refreshToken3,
|
|
1729
1742
|
expiresIn: record.expires_in === void 0 ? void 0 : safeInteger(record.expires_in, "expires_in", 1, MAX_TOKEN_LIFETIME_SECONDS)
|
|
1730
1743
|
};
|
|
1731
1744
|
}
|
|
@@ -2300,32 +2313,999 @@ async function withMachineCooldown(directory, apiUrl, clientId, signal, request3
|
|
|
2300
2313
|
}
|
|
2301
2314
|
}
|
|
2302
2315
|
|
|
2316
|
+
// src/lib/session-identity.ts
|
|
2317
|
+
import { execFile } from "child_process";
|
|
2318
|
+
import { createHash as createHash5 } from "crypto";
|
|
2319
|
+
import { rmSync as rmSync7 } from "fs";
|
|
2320
|
+
import { join as join13 } from "path";
|
|
2321
|
+
import { promisify } from "util";
|
|
2322
|
+
|
|
2323
|
+
// src/lib/terminal-safe.ts
|
|
2324
|
+
function replaceIsolatedSurrogates(value) {
|
|
2325
|
+
let out = "";
|
|
2326
|
+
for (let index = 0; index < value.length; index += 1) {
|
|
2327
|
+
const unit = value.charCodeAt(index);
|
|
2328
|
+
if (unit >= 55296 && unit <= 56319) {
|
|
2329
|
+
const next = value.charCodeAt(index + 1);
|
|
2330
|
+
if (next >= 56320 && next <= 57343) {
|
|
2331
|
+
out += value[index] + value[index + 1];
|
|
2332
|
+
index += 1;
|
|
2333
|
+
} else {
|
|
2334
|
+
out += "\uFFFD";
|
|
2335
|
+
}
|
|
2336
|
+
} else if (unit >= 56320 && unit <= 57343) {
|
|
2337
|
+
out += "\uFFFD";
|
|
2338
|
+
} else {
|
|
2339
|
+
out += value[index];
|
|
2340
|
+
}
|
|
2341
|
+
}
|
|
2342
|
+
return out;
|
|
2343
|
+
}
|
|
2344
|
+
function isUnsafeTerminalCodePoint(point) {
|
|
2345
|
+
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
2346
|
+
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
2347
|
+
point === 1564 || // Arabic letter mark
|
|
2348
|
+
point === 6158 || // Mongolian vowel separator
|
|
2349
|
+
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
2350
|
+
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
2351
|
+
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
2352
|
+
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
2353
|
+
point === 65279 || // zero-width no-break space / BOM
|
|
2354
|
+
point >= 917504 && point <= 917631;
|
|
2355
|
+
return c0OrC1 || bidiOrZeroWidth;
|
|
2356
|
+
}
|
|
2357
|
+
function terminalSafeText(value) {
|
|
2358
|
+
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
2359
|
+
}
|
|
2360
|
+
function terminalSafeLine(value) {
|
|
2361
|
+
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
2362
|
+
}
|
|
2363
|
+
function isTerminalSafeText(value) {
|
|
2364
|
+
return terminalSafeText(value) === value;
|
|
2365
|
+
}
|
|
2366
|
+
var stripControlChars = terminalSafeText;
|
|
2367
|
+
|
|
2368
|
+
// src/lib/session-identity.ts
|
|
2369
|
+
var SESSION_IDENTITY_VARIABLE = "PRIM_CLOUD_IDENTITY";
|
|
2370
|
+
var SESSION_IDENTITY_VALUE = "session";
|
|
2371
|
+
var SESSION_ID_VARIABLE = "CLAUDE_CODE_REMOTE_SESSION_ID";
|
|
2372
|
+
var USER_EMAIL_VARIABLE = "CLAUDE_CODE_USER_EMAIL";
|
|
2373
|
+
var SESSION_TOKEN_PREFIX = "prim_sess_";
|
|
2374
|
+
var SESSION_BRANCH = /^claude\/[A-Za-z0-9][A-Za-z0-9._/-]{0,199}$/u;
|
|
2375
|
+
var SHA = /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u;
|
|
2376
|
+
var SESSION_ID = /^[A-Za-z0-9._:-]{1,200}$/u;
|
|
2377
|
+
var EMAIL_HINT = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9-]*\.)+[A-Za-z]{2,}$/u;
|
|
2378
|
+
var CHALLENGE_REUSE_MARGIN_MS = 3e4;
|
|
2379
|
+
var SESSION_IDENTITY_ROUTES = {
|
|
2380
|
+
challenge: "/api/cli/session-identity/challenge",
|
|
2381
|
+
token: "/api/cli/session-identity/token",
|
|
2382
|
+
refresh: "/api/cli/session-identity/token/refresh",
|
|
2383
|
+
link: "/api/cli/session-identity/link"
|
|
2384
|
+
};
|
|
2385
|
+
var DEFAULT_API_URL = "https://api.getprimitive.ai";
|
|
2386
|
+
var RENEW_BEFORE_MS = 6e4;
|
|
2387
|
+
var GIT_TIMEOUT_MS4 = 1e4;
|
|
2388
|
+
var POLL_BUDGET_MS = 15e3;
|
|
2389
|
+
var POLL_FIRST_DELAY_MS = 500;
|
|
2390
|
+
var POLL_MAX_DELAY_MS = 3e3;
|
|
2391
|
+
var BACKGROUND_RETRY_MS = 5 * 6e4;
|
|
2392
|
+
var LOCK_TIMEOUT_MS = 6e4;
|
|
2393
|
+
var RESPONSE_MAX_BYTES = 64 * 1024;
|
|
2394
|
+
function sessionIdentityRequested(env = process.env) {
|
|
2395
|
+
return isClaudeCloudSession(env) && env[SESSION_IDENTITY_VARIABLE]?.trim() === SESSION_IDENTITY_VALUE;
|
|
2396
|
+
}
|
|
2397
|
+
function sessionIdentityMode(deps = {}) {
|
|
2398
|
+
const env = deps.env ?? process.env;
|
|
2399
|
+
return sessionIdentityRequested(env) && (env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0);
|
|
2400
|
+
}
|
|
2401
|
+
function failure(code, cause, remedy) {
|
|
2402
|
+
return { status: "failed", code, cause, remedy };
|
|
2403
|
+
}
|
|
2404
|
+
var RETRY_REMEDY = "run `prim setup --cloud` to try again";
|
|
2405
|
+
var NEW_SESSION_REMEDY = "start a new cloud session";
|
|
2406
|
+
var ENVIRONMENT_CREDENTIAL_REMEDY = 'ask the organization admin who set up the environment to check its credential, or to mint a replacement with `prim auth enroll --new-environment "<name>" --print-env`; then start a new cloud session';
|
|
2407
|
+
var SESSION_REVOKED = failure(
|
|
2408
|
+
"session_revoked",
|
|
2409
|
+
"Primitive no longer accepts this session's member token: an organization admin revoked the session or the member's GitHub link, the member left the organization, or the token was renewed elsewhere",
|
|
2410
|
+
`${NEW_SESSION_REMEDY}, which identifies you again through GitHub (if your GitHub link was removed, run \`prim auth link\` there when it asks)`
|
|
2411
|
+
);
|
|
2412
|
+
var CHALLENGE_WINDOW_PASSED = failure(
|
|
2413
|
+
"challenge_expired",
|
|
2414
|
+
"this session's identity check expired before it was exchanged for a token (a verified check stays usable, including for linking a GitHub account, for 30 minutes)",
|
|
2415
|
+
`${NEW_SESSION_REMEDY}, and if it asks you to link your GitHub account, run \`prim auth link\` there right away`
|
|
2416
|
+
);
|
|
2417
|
+
var CHALLENGE_GONE = failure(
|
|
2418
|
+
"challenge_not_found",
|
|
2419
|
+
"Primitive no longer knows this session's identity check (the environment credential may have been replaced since)",
|
|
2420
|
+
NEW_SESSION_REMEDY
|
|
2421
|
+
);
|
|
2422
|
+
var FINAL_CODES = /* @__PURE__ */ new Set(["session_revoked", "environment_credential_rejected"]);
|
|
2423
|
+
function rejectionFailure(reason, repository) {
|
|
2424
|
+
switch (reason) {
|
|
2425
|
+
case "identity_mismatch":
|
|
2426
|
+
return failure(
|
|
2427
|
+
"identity_mismatch",
|
|
2428
|
+
"the session branch was created by a GitHub account linked to a different Primitive member than the one signed in to Claude, so Primitive attributes this session to no one",
|
|
2429
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check members' GitHub links`
|
|
2430
|
+
);
|
|
2431
|
+
case "push_after_expiry":
|
|
2432
|
+
return failure(
|
|
2433
|
+
"push_after_expiry",
|
|
2434
|
+
`GitHub's notice of the identity push to ${repository} reached Primitive after the identity check had expired`,
|
|
2435
|
+
`${NEW_SESSION_REMEDY}; if it happens again, check that Primitive's GitHub App on ${repository} delivers its notices`
|
|
2436
|
+
);
|
|
2437
|
+
case "repository_mismatch":
|
|
2438
|
+
return failure(
|
|
2439
|
+
"repository_mismatch",
|
|
2440
|
+
`Primitive received the identity push from a different repository than ${repository}`,
|
|
2441
|
+
`check that this checkout's origin is ${repository} on GitHub, then ${NEW_SESSION_REMEDY}`
|
|
2442
|
+
);
|
|
2443
|
+
case "conflicting_push":
|
|
2444
|
+
return failure(
|
|
2445
|
+
"conflicting_push",
|
|
2446
|
+
`more than one GitHub account created the session branch on ${repository}, so Primitive cannot tell who started this session`,
|
|
2447
|
+
NEW_SESSION_REMEDY
|
|
2448
|
+
);
|
|
2449
|
+
case "unsupported_sender":
|
|
2450
|
+
return failure(
|
|
2451
|
+
"unsupported_sender",
|
|
2452
|
+
`the session branch on ${repository} was created by a GitHub App or bot, not by a person's GitHub account`,
|
|
2453
|
+
`check that the cloud environment pushes to GitHub as the person who started the session, then ${NEW_SESSION_REMEDY}`
|
|
2454
|
+
);
|
|
2455
|
+
default:
|
|
2456
|
+
return failure(
|
|
2457
|
+
"challenge_rejected",
|
|
2458
|
+
`Primitive rejected the identity push to ${repository}${typeof reason === "string" ? ` (${terminalSafeLine(reason).slice(0, 120)})` : ""}`,
|
|
2459
|
+
`${NEW_SESSION_REMEDY}; if it happens again, ask an organization admin to check Primitive's GitHub App on ${repository}`
|
|
2460
|
+
);
|
|
2461
|
+
}
|
|
2462
|
+
}
|
|
2463
|
+
function sessionIdentityMessage(outcome) {
|
|
2464
|
+
if (outcome.status === "link_required")
|
|
2465
|
+
return `GitHub account @${outcome.githubLogin} started this Claude Code cloud session but is not linked to a Primitive account yet. To link it once, run \`prim auth link\` and sign in at the URL it prints with the code it shows; later sessions then identify you automatically.`;
|
|
2466
|
+
return `Primitive could not identify who started this Claude Code cloud session: ${outcome.cause}. To fix it, ${outcome.remedy}.`;
|
|
2467
|
+
}
|
|
2468
|
+
function hash(value) {
|
|
2469
|
+
return createHash5("sha256").update(value).digest("hex");
|
|
2470
|
+
}
|
|
2471
|
+
function sessionContext(deps) {
|
|
2472
|
+
const env = deps.env ?? process.env;
|
|
2473
|
+
const environment = environmentCredentials(deps);
|
|
2474
|
+
if (!environment)
|
|
2475
|
+
return failure(
|
|
2476
|
+
"environment_credential_missing",
|
|
2477
|
+
"the cloud environment has no environment credential",
|
|
2478
|
+
'ask an organization admin to create one with `prim auth enroll --new-environment "<name>" --print-env` and add it to the environment, then start a new cloud session'
|
|
2479
|
+
);
|
|
2480
|
+
const sessionId = env[SESSION_ID_VARIABLE]?.trim();
|
|
2481
|
+
if (!sessionId || !SESSION_ID.test(sessionId))
|
|
2482
|
+
return failure(
|
|
2483
|
+
"session_id_missing",
|
|
2484
|
+
`this Claude Code cloud session does not report a session ID Primitive accepts (${SESSION_ID_VARIABLE})`,
|
|
2485
|
+
NEW_SESSION_REMEDY
|
|
2486
|
+
);
|
|
2487
|
+
const apiUrl = machineApiUrl(env.PRIM_API_URL?.trim() || DEFAULT_API_URL);
|
|
2488
|
+
const directory = deps.directory ?? primConfigDirectory({ env });
|
|
2489
|
+
const key = hash(`${apiUrl}\0${environment.clientId}\0${sessionId}`);
|
|
2490
|
+
return {
|
|
2491
|
+
directory,
|
|
2492
|
+
apiUrl,
|
|
2493
|
+
clientId: environment.clientId,
|
|
2494
|
+
generation: environment.generation,
|
|
2495
|
+
sessionId,
|
|
2496
|
+
tokenPath: join13(directory, `session_identity_${key}.json`),
|
|
2497
|
+
statePath: join13(directory, `session_identity_${key}.state.json`),
|
|
2498
|
+
lockPath: join13(directory, "session-identity.lock")
|
|
2499
|
+
};
|
|
2500
|
+
}
|
|
2501
|
+
function readRecord(path) {
|
|
2502
|
+
try {
|
|
2503
|
+
const value = readMachineMetadata(path);
|
|
2504
|
+
return value === void 0 ? void 0 : machineRecord(value);
|
|
2505
|
+
} catch {
|
|
2506
|
+
return void 0;
|
|
2507
|
+
}
|
|
2508
|
+
}
|
|
2509
|
+
function finiteNumber(value) {
|
|
2510
|
+
return typeof value === "number" && Number.isFinite(value);
|
|
2511
|
+
}
|
|
2512
|
+
function readToken(context) {
|
|
2513
|
+
const data = readRecord(context.tokenPath);
|
|
2514
|
+
if (!data || data.version !== 1 || data.apiUrl !== context.apiUrl || data.clientId !== context.clientId || data.generation !== context.generation || data.sessionId !== context.sessionId || !machineString(data.accessToken, 8192) || !data.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !finiteNumber(data.expiresAt) || !finiteNumber(data.refreshAfter) || !machineString(data.userId, 256) || !machineString(data.displayName, 256) || !machineString(data.organizationId, 256) || !machineString(data.issuer, 2048) || !machineString(data.audience, 256))
|
|
2515
|
+
return void 0;
|
|
2516
|
+
const identity = data.identity;
|
|
2517
|
+
if (!identity || identity.clientId !== context.clientId || identity.authorizedUserId !== data.userId || identity.organizationId !== data.organizationId)
|
|
2518
|
+
return void 0;
|
|
2519
|
+
return data;
|
|
2520
|
+
}
|
|
2521
|
+
function readState(context) {
|
|
2522
|
+
const data = readRecord(context.statePath);
|
|
2523
|
+
if (!data || data.version !== 1 || data.sessionId !== context.sessionId || data.status !== "link_required" && data.status !== "failed" || typeof data.code !== "string" || !finiteNumber(data.at))
|
|
2524
|
+
return void 0;
|
|
2525
|
+
return data;
|
|
2526
|
+
}
|
|
2527
|
+
function writeToken(context, record) {
|
|
2528
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
2529
|
+
writeMachineMetadata(context.tokenPath, record);
|
|
2530
|
+
rmSync7(context.statePath, { force: true });
|
|
2531
|
+
}
|
|
2532
|
+
function writeState(context, state) {
|
|
2533
|
+
try {
|
|
2534
|
+
prepareMachineMetadataDirectory(context.directory);
|
|
2535
|
+
writeMachineMetadata(context.statePath, { version: 1, ...state });
|
|
2536
|
+
} catch {
|
|
2537
|
+
}
|
|
2538
|
+
}
|
|
2539
|
+
function tokenValid(record, now = Date.now()) {
|
|
2540
|
+
return now < record.expiresAt - RENEW_BEFORE_MS;
|
|
2541
|
+
}
|
|
2542
|
+
function tokenFresh(record, now = Date.now()) {
|
|
2543
|
+
return tokenValid(record, now) && now < record.refreshAfter;
|
|
2544
|
+
}
|
|
2545
|
+
function toCredential(record) {
|
|
2546
|
+
return {
|
|
2547
|
+
issuer: record.issuer,
|
|
2548
|
+
audience: record.audience,
|
|
2549
|
+
...record.identity,
|
|
2550
|
+
accessToken: record.accessToken,
|
|
2551
|
+
expiresAt: record.expiresAt,
|
|
2552
|
+
apiUrl: record.apiUrl,
|
|
2553
|
+
generation: record.generation,
|
|
2554
|
+
storage: "environment",
|
|
2555
|
+
session: {
|
|
2556
|
+
userId: record.userId,
|
|
2557
|
+
displayName: record.displayName,
|
|
2558
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
2559
|
+
refreshAfter: record.refreshAfter
|
|
2560
|
+
}
|
|
2561
|
+
};
|
|
2562
|
+
}
|
|
2563
|
+
function identified(record, reused) {
|
|
2564
|
+
return {
|
|
2565
|
+
status: "ok",
|
|
2566
|
+
credential: toCredential(record),
|
|
2567
|
+
displayName: record.displayName,
|
|
2568
|
+
...record.githubLogin ? { githubLogin: record.githubLogin } : {},
|
|
2569
|
+
reused
|
|
2570
|
+
};
|
|
2571
|
+
}
|
|
2572
|
+
function cachedSessionCredential(deps = {}) {
|
|
2573
|
+
if (!sessionIdentityMode(deps)) return void 0;
|
|
2574
|
+
let context;
|
|
2575
|
+
try {
|
|
2576
|
+
context = sessionContext(deps);
|
|
2577
|
+
} catch {
|
|
2578
|
+
return void 0;
|
|
2579
|
+
}
|
|
2580
|
+
if ("status" in context) return void 0;
|
|
2581
|
+
const record = readToken(context);
|
|
2582
|
+
return record && tokenValid(record) ? toCredential(record) : void 0;
|
|
2583
|
+
}
|
|
2584
|
+
function outcomeFromState(state) {
|
|
2585
|
+
if (state.status === "link_required" && state.githubLogin && state.challengeId)
|
|
2586
|
+
return {
|
|
2587
|
+
status: "link_required",
|
|
2588
|
+
githubLogin: state.githubLogin,
|
|
2589
|
+
challengeId: state.challengeId,
|
|
2590
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0
|
|
2591
|
+
};
|
|
2592
|
+
return failure(
|
|
2593
|
+
state.code,
|
|
2594
|
+
state.cause ?? "the last identity check failed",
|
|
2595
|
+
state.remedy ?? RETRY_REMEDY
|
|
2596
|
+
);
|
|
2597
|
+
}
|
|
2598
|
+
function parseInstant(value) {
|
|
2599
|
+
if (finiteNumber(value) && value > 0) return value < 1e12 ? value * 1e3 : value;
|
|
2600
|
+
if (typeof value === "string" && value.length <= 64) {
|
|
2601
|
+
const parsed = Date.parse(value);
|
|
2602
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
2603
|
+
}
|
|
2604
|
+
return void 0;
|
|
2605
|
+
}
|
|
2606
|
+
async function sendJson(url, init, fetchImpl) {
|
|
2607
|
+
const response = await fetchImpl(url, { ...init, redirect: "error" });
|
|
2608
|
+
let value;
|
|
2609
|
+
try {
|
|
2610
|
+
const parsed = await readBoundedJson(response, RESPONSE_MAX_BYTES);
|
|
2611
|
+
value = parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0;
|
|
2612
|
+
} catch {
|
|
2613
|
+
value = void 0;
|
|
2614
|
+
}
|
|
2615
|
+
return { status: response.status, value };
|
|
2616
|
+
}
|
|
2617
|
+
function environmentOnly(deps) {
|
|
2618
|
+
return { ...deps, environmentOnly: true };
|
|
2619
|
+
}
|
|
2620
|
+
async function environmentRequest(method, path, body, deps, signal) {
|
|
2621
|
+
const send = async (credential2) => {
|
|
2622
|
+
const headers = { "Content-Type": "application/json" };
|
|
2623
|
+
const text = body === void 0 ? void 0 : JSON.stringify(body);
|
|
2624
|
+
if (credential2.tokenInjection) {
|
|
2625
|
+
const response = await forwardMachineRequest(
|
|
2626
|
+
{ method, path, headers, ...text === void 0 ? {} : { body: text } },
|
|
2627
|
+
signal,
|
|
2628
|
+
environmentOnly(deps)
|
|
2629
|
+
);
|
|
2630
|
+
const parsed = await response.json().catch(() => void 0);
|
|
2631
|
+
return {
|
|
2632
|
+
status: response.status,
|
|
2633
|
+
value: parsed && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : void 0
|
|
2634
|
+
};
|
|
2635
|
+
}
|
|
2636
|
+
return sendJson(
|
|
2637
|
+
`${credential2.apiUrl}${path}`,
|
|
2638
|
+
{
|
|
2639
|
+
method,
|
|
2640
|
+
headers: { ...headers, Authorization: `Bearer ${credential2.accessToken}` },
|
|
2641
|
+
...text === void 0 ? {} : { body: text },
|
|
2642
|
+
signal: signal ?? AbortSignal.timeout(GIT_TIMEOUT_MS4)
|
|
2643
|
+
},
|
|
2644
|
+
deps.fetch ?? fetch
|
|
2645
|
+
);
|
|
2646
|
+
};
|
|
2647
|
+
let credential = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
2648
|
+
if (!credential) throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
2649
|
+
let answer = await send(credential);
|
|
2650
|
+
if (answer.status === 401) {
|
|
2651
|
+
credential = await acquireMachineCredential({ force: true, signal }, environmentOnly(deps));
|
|
2652
|
+
if (!credential)
|
|
2653
|
+
throw new MachineAuthError("identity_unavailable", "No environment credential.");
|
|
2654
|
+
answer = await send(credential);
|
|
2655
|
+
}
|
|
2656
|
+
return answer;
|
|
2657
|
+
}
|
|
2658
|
+
function environmentFailure(error, apiUrl) {
|
|
2659
|
+
if (error instanceof MachineAuthError && error.terminal)
|
|
2660
|
+
return failure(
|
|
2661
|
+
"environment_credential_rejected",
|
|
2662
|
+
"Primitive rejected the cloud environment's credential",
|
|
2663
|
+
ENVIRONMENT_CREDENTIAL_REMEDY
|
|
2664
|
+
);
|
|
2665
|
+
const host = (() => {
|
|
2666
|
+
try {
|
|
2667
|
+
return new URL(apiUrl).hostname;
|
|
2668
|
+
} catch {
|
|
2669
|
+
return "Primitive";
|
|
2670
|
+
}
|
|
2671
|
+
})();
|
|
2672
|
+
return failure(
|
|
2673
|
+
"identity_unavailable",
|
|
2674
|
+
`Primitive could not be reached for the identity check${error instanceof MachineAuthError ? ` (${terminalSafeLine(error.message).slice(0, 200)})` : ""}`,
|
|
2675
|
+
`check that ${host} is under the cloud environment's Allowed domains, then ${RETRY_REMEDY}`
|
|
2676
|
+
);
|
|
2677
|
+
}
|
|
2678
|
+
function answerError(answer) {
|
|
2679
|
+
return typeof answer.value?.error === "string" ? answer.value.error : void 0;
|
|
2680
|
+
}
|
|
2681
|
+
async function git2(root, args, signal) {
|
|
2682
|
+
try {
|
|
2683
|
+
const { stdout, stderr } = await promisify(execFile)("git", args, {
|
|
2684
|
+
cwd: root,
|
|
2685
|
+
encoding: "utf8",
|
|
2686
|
+
timeout: GIT_TIMEOUT_MS4,
|
|
2687
|
+
signal,
|
|
2688
|
+
env: { ...gitChildEnvironment(), GIT_TERMINAL_PROMPT: "0" },
|
|
2689
|
+
maxBuffer: 1024 * 1024
|
|
2690
|
+
});
|
|
2691
|
+
return { ok: true, code: 0, stdout, stderr, timedOut: false };
|
|
2692
|
+
} catch (error) {
|
|
2693
|
+
const failed = error;
|
|
2694
|
+
return {
|
|
2695
|
+
ok: false,
|
|
2696
|
+
code: typeof failed.code === "number" ? failed.code : void 0,
|
|
2697
|
+
stdout: failed.stdout ?? "",
|
|
2698
|
+
stderr: failed.stderr ?? "",
|
|
2699
|
+
timedOut: failed.killed === true || failed.signal === "SIGTERM"
|
|
2700
|
+
};
|
|
2701
|
+
}
|
|
2702
|
+
}
|
|
2703
|
+
function gitDetail(stderr) {
|
|
2704
|
+
const lines = stderr.split("\n").map((line) => terminalSafeLine(line.replace(/\/\/[^/\s@]+@/gu, "//"))).filter(Boolean);
|
|
2705
|
+
return (lines.find((line) => /error|denied|refused|forbidden|403|fatal/iu.test(line)) ?? lines.at(-1) ?? "no detail").slice(0, 200);
|
|
2706
|
+
}
|
|
2707
|
+
async function defaultSleep2(milliseconds, signal) {
|
|
2708
|
+
await new Promise((resolve10, reject) => {
|
|
2709
|
+
const timer = setTimeout(resolve10, milliseconds);
|
|
2710
|
+
signal?.addEventListener(
|
|
2711
|
+
"abort",
|
|
2712
|
+
() => {
|
|
2713
|
+
clearTimeout(timer);
|
|
2714
|
+
reject(signal.reason);
|
|
2715
|
+
},
|
|
2716
|
+
{ once: true }
|
|
2717
|
+
);
|
|
2718
|
+
});
|
|
2719
|
+
}
|
|
2720
|
+
async function pollChallenge(apiUrl, challengeId, repository, deps, signal) {
|
|
2721
|
+
const sleep = deps.sleep ?? defaultSleep2;
|
|
2722
|
+
const deadline = Date.now() + (deps.pollBudgetMs ?? POLL_BUDGET_MS);
|
|
2723
|
+
let delay = POLL_FIRST_DELAY_MS;
|
|
2724
|
+
let unreachable2;
|
|
2725
|
+
for (; ; ) {
|
|
2726
|
+
const remaining = deadline - Date.now();
|
|
2727
|
+
if (remaining <= 0) break;
|
|
2728
|
+
await sleep(Math.min(delay, remaining), signal);
|
|
2729
|
+
delay = Math.min(POLL_MAX_DELAY_MS, Math.round(delay * 1.5));
|
|
2730
|
+
let answer;
|
|
2731
|
+
try {
|
|
2732
|
+
answer = await environmentRequest(
|
|
2733
|
+
"GET",
|
|
2734
|
+
`${SESSION_IDENTITY_ROUTES.challenge}/${encodeURIComponent(challengeId)}`,
|
|
2735
|
+
void 0,
|
|
2736
|
+
deps,
|
|
2737
|
+
signal
|
|
2738
|
+
);
|
|
2739
|
+
} catch (error) {
|
|
2740
|
+
signal?.throwIfAborted();
|
|
2741
|
+
unreachable2 = error;
|
|
2742
|
+
continue;
|
|
2743
|
+
}
|
|
2744
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2745
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2746
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), apiUrl);
|
|
2747
|
+
if (answer.status < 200 || answer.status > 299) {
|
|
2748
|
+
unreachable2 = new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`);
|
|
2749
|
+
continue;
|
|
2750
|
+
}
|
|
2751
|
+
unreachable2 = void 0;
|
|
2752
|
+
const status = answer.value;
|
|
2753
|
+
if (status?.status === "verified")
|
|
2754
|
+
return {
|
|
2755
|
+
...machineString(status.githubLogin, 64) ? { githubLogin: status.githubLogin } : {}
|
|
2756
|
+
};
|
|
2757
|
+
if (status?.status === "expired")
|
|
2758
|
+
return failure(
|
|
2759
|
+
"challenge_expired",
|
|
2760
|
+
`the identity check expired before Primitive received GitHub's notice of the push to ${repository}`,
|
|
2761
|
+
NEW_SESSION_REMEDY
|
|
2762
|
+
);
|
|
2763
|
+
if (status?.status === "rejected")
|
|
2764
|
+
return rejectionFailure(status.reason, repository);
|
|
2765
|
+
}
|
|
2766
|
+
if (unreachable2) return environmentFailure(unreachable2, apiUrl);
|
|
2767
|
+
return failure(
|
|
2768
|
+
"webhook_timeout",
|
|
2769
|
+
`GitHub's notice of the identity push to ${repository} did not reach Primitive within ${Math.round((deps.pollBudgetMs ?? POLL_BUDGET_MS) / 1e3)} s`,
|
|
2770
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2771
|
+
);
|
|
2772
|
+
}
|
|
2773
|
+
function parseTokenAnswer(value) {
|
|
2774
|
+
if (!value) return void 0;
|
|
2775
|
+
const user = value.user;
|
|
2776
|
+
const expiresAt = parseInstant(value.expiresAt);
|
|
2777
|
+
const refreshAfter = parseInstant(value.refreshAfter) ?? expiresAt;
|
|
2778
|
+
if (!machineString(value.accessToken, 8192) || !value.accessToken.startsWith(SESSION_TOKEN_PREFIX) || !expiresAt || !refreshAfter || !user || !machineString(user.id, 256) || !machineString(user.displayName, 256) || !machineString(value.organizationId, 256))
|
|
2779
|
+
return void 0;
|
|
2780
|
+
return {
|
|
2781
|
+
accessToken: value.accessToken,
|
|
2782
|
+
expiresAt,
|
|
2783
|
+
refreshAfter: Math.min(refreshAfter, expiresAt),
|
|
2784
|
+
userId: user.id,
|
|
2785
|
+
displayName: user.displayName,
|
|
2786
|
+
organizationId: value.organizationId
|
|
2787
|
+
};
|
|
2788
|
+
}
|
|
2789
|
+
var SERVER_CONTRACT_FAILURE = failure(
|
|
2790
|
+
"server_contract",
|
|
2791
|
+
"Primitive's answer did not identify the linked member",
|
|
2792
|
+
"update prim (`npx --yes @primitive.ai/prim@latest`) and run `prim setup --cloud`; if it persists, report it to Primitive"
|
|
2793
|
+
);
|
|
2794
|
+
async function recordFor(context, answer, extra, deps, signal) {
|
|
2795
|
+
let identity;
|
|
2796
|
+
let environment;
|
|
2797
|
+
try {
|
|
2798
|
+
environment = await acquireMachineCredential({ signal }, environmentOnly(deps));
|
|
2799
|
+
identity = await verifyMachineIdentity(
|
|
2800
|
+
context.apiUrl,
|
|
2801
|
+
answer.accessToken,
|
|
2802
|
+
context.clientId,
|
|
2803
|
+
signal,
|
|
2804
|
+
deps.fetch
|
|
2805
|
+
);
|
|
2806
|
+
} catch (error) {
|
|
2807
|
+
if (error instanceof MachineAuthError && error.code === "machine_identity_rejected")
|
|
2808
|
+
return SERVER_CONTRACT_FAILURE;
|
|
2809
|
+
return environmentFailure(error, context.apiUrl);
|
|
2810
|
+
}
|
|
2811
|
+
if (!environment || identity.authorizedUserId !== answer.userId || identity.organizationId !== answer.organizationId)
|
|
2812
|
+
return SERVER_CONTRACT_FAILURE;
|
|
2813
|
+
return {
|
|
2814
|
+
version: 1,
|
|
2815
|
+
apiUrl: context.apiUrl,
|
|
2816
|
+
clientId: context.clientId,
|
|
2817
|
+
generation: context.generation,
|
|
2818
|
+
sessionId: context.sessionId,
|
|
2819
|
+
issuer: environment.issuer,
|
|
2820
|
+
audience: environment.audience,
|
|
2821
|
+
accessToken: answer.accessToken,
|
|
2822
|
+
expiresAt: answer.expiresAt,
|
|
2823
|
+
refreshAfter: answer.refreshAfter,
|
|
2824
|
+
userId: answer.userId,
|
|
2825
|
+
displayName: answer.displayName,
|
|
2826
|
+
organizationId: answer.organizationId,
|
|
2827
|
+
...extra.githubLogin ? { githubLogin: extra.githubLogin } : {},
|
|
2828
|
+
identity,
|
|
2829
|
+
...extra.repositoryRoot ? { repositoryRoot: extra.repositoryRoot } : {}
|
|
2830
|
+
};
|
|
2831
|
+
}
|
|
2832
|
+
async function refreshToken(context, record, deps, signal) {
|
|
2833
|
+
let answer;
|
|
2834
|
+
try {
|
|
2835
|
+
answer = await environmentRequest(
|
|
2836
|
+
"POST",
|
|
2837
|
+
SESSION_IDENTITY_ROUTES.refresh,
|
|
2838
|
+
{ accessToken: record.accessToken },
|
|
2839
|
+
deps,
|
|
2840
|
+
signal
|
|
2841
|
+
);
|
|
2842
|
+
} catch (error) {
|
|
2843
|
+
signal?.throwIfAborted();
|
|
2844
|
+
return error instanceof MachineAuthError && error.terminal ? { status: "refused", failure: environmentFailure(error, context.apiUrl) } : { status: "unavailable" };
|
|
2845
|
+
}
|
|
2846
|
+
const code = answerError(answer);
|
|
2847
|
+
if (answer.status === 401 && (code === "session_revoked" || code === "invalid_session_token"))
|
|
2848
|
+
return { status: "refused", failure: SESSION_REVOKED };
|
|
2849
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2850
|
+
return {
|
|
2851
|
+
status: "refused",
|
|
2852
|
+
failure: environmentFailure(
|
|
2853
|
+
new MachineAuthError("rejected", "rejected", true),
|
|
2854
|
+
context.apiUrl
|
|
2855
|
+
)
|
|
2856
|
+
};
|
|
2857
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2858
|
+
if (!token || token.userId !== record.userId || token.organizationId !== record.organizationId)
|
|
2859
|
+
return { status: "unavailable" };
|
|
2860
|
+
return {
|
|
2861
|
+
status: "ok",
|
|
2862
|
+
record: {
|
|
2863
|
+
...record,
|
|
2864
|
+
accessToken: token.accessToken,
|
|
2865
|
+
expiresAt: token.expiresAt,
|
|
2866
|
+
refreshAfter: token.refreshAfter,
|
|
2867
|
+
displayName: token.displayName
|
|
2868
|
+
}
|
|
2869
|
+
};
|
|
2870
|
+
}
|
|
2871
|
+
function exchangeRefusal(answer, repository) {
|
|
2872
|
+
if (answer.status === 404) return CHALLENGE_GONE;
|
|
2873
|
+
if (answer.status !== 409) return void 0;
|
|
2874
|
+
switch (answerError(answer)) {
|
|
2875
|
+
case "identity_mismatch":
|
|
2876
|
+
return rejectionFailure("identity_mismatch", repository);
|
|
2877
|
+
case "challenge_rejected":
|
|
2878
|
+
return rejectionFailure(answer.value?.reason, repository);
|
|
2879
|
+
case "challenge_expired":
|
|
2880
|
+
return CHALLENGE_WINDOW_PASSED;
|
|
2881
|
+
case "challenge_already_exchanged":
|
|
2882
|
+
return failure(
|
|
2883
|
+
"challenge_already_exchanged",
|
|
2884
|
+
"this session's identity check was already exchanged for a token this VM does not hold",
|
|
2885
|
+
NEW_SESSION_REMEDY
|
|
2886
|
+
);
|
|
2887
|
+
case "challenge_pending":
|
|
2888
|
+
return failure(
|
|
2889
|
+
"webhook_timeout",
|
|
2890
|
+
`GitHub's notice of the identity push to ${repository} has not reached Primitive yet`,
|
|
2891
|
+
`check that Primitive's GitHub App is installed with access to ${repository}, then ${RETRY_REMEDY}`
|
|
2892
|
+
);
|
|
2893
|
+
default:
|
|
2894
|
+
return void 0;
|
|
2895
|
+
}
|
|
2896
|
+
}
|
|
2897
|
+
async function exchangeChallenge(context, challenge, repositoryRoot, deps, signal) {
|
|
2898
|
+
let answer;
|
|
2899
|
+
try {
|
|
2900
|
+
answer = await environmentRequest(
|
|
2901
|
+
"POST",
|
|
2902
|
+
SESSION_IDENTITY_ROUTES.token,
|
|
2903
|
+
{ challengeId: challenge.challengeId },
|
|
2904
|
+
deps,
|
|
2905
|
+
signal
|
|
2906
|
+
);
|
|
2907
|
+
} catch (error) {
|
|
2908
|
+
signal?.throwIfAborted();
|
|
2909
|
+
return environmentFailure(error, context.apiUrl);
|
|
2910
|
+
}
|
|
2911
|
+
if (answer.status === 409 && answerError(answer) === "github_account_not_linked") {
|
|
2912
|
+
const login = answer.value?.githubLogin;
|
|
2913
|
+
return {
|
|
2914
|
+
status: "link_required",
|
|
2915
|
+
githubLogin: machineString(login, 64) ? login : challenge.githubLogin ?? "unknown",
|
|
2916
|
+
challengeId: challenge.challengeId,
|
|
2917
|
+
challengeExpiresAt: challenge.challengeExpiresAt
|
|
2918
|
+
};
|
|
2919
|
+
}
|
|
2920
|
+
const refused = exchangeRefusal(
|
|
2921
|
+
answer,
|
|
2922
|
+
repositoryRoot && githubRepositoryFullName(repositoryRoot) || "the repository"
|
|
2923
|
+
);
|
|
2924
|
+
if (refused) return refused;
|
|
2925
|
+
const token = answer.status === 200 ? parseTokenAnswer(answer.value) : void 0;
|
|
2926
|
+
if (!token) {
|
|
2927
|
+
if (answer.status === 401 || answer.status === 403)
|
|
2928
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
2929
|
+
return answer.status >= 500 ? environmentFailure(
|
|
2930
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
2931
|
+
context.apiUrl
|
|
2932
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
2933
|
+
}
|
|
2934
|
+
return recordFor(
|
|
2935
|
+
context,
|
|
2936
|
+
token,
|
|
2937
|
+
{ githubLogin: challenge.githubLogin, repositoryRoot },
|
|
2938
|
+
deps,
|
|
2939
|
+
signal
|
|
2940
|
+
);
|
|
2941
|
+
}
|
|
2942
|
+
async function challengeAndPush(context, root, previous, deps, attempt, signal) {
|
|
2943
|
+
const env = deps.env ?? process.env;
|
|
2944
|
+
const repository = githubRepositoryFullName(root);
|
|
2945
|
+
if (!repository)
|
|
2946
|
+
return failure(
|
|
2947
|
+
"repository_unidentified",
|
|
2948
|
+
"this checkout does not name its GitHub repository",
|
|
2949
|
+
"run it in the repository the session cloned; for a checkout with no GitHub origin, commit its repository declaration with `prim claude install --scope project` from a clone whose origin is on GitHub"
|
|
2950
|
+
);
|
|
2951
|
+
const branch = currentBranch(root);
|
|
2952
|
+
if (!branch || !SESSION_BRANCH.test(branch) || branch.includes("..") || branch.endsWith(".lock"))
|
|
2953
|
+
return failure(
|
|
2954
|
+
"not_session_branch",
|
|
2955
|
+
`this checkout is on ${branch ? `branch ${terminalSafeLine(branch).slice(0, 120)}` : "a detached HEAD"}, not the session's own claude/\u2026 branch, so prim cannot prove who started the session and pushed nothing`,
|
|
2956
|
+
`${NEW_SESSION_REMEDY} and let it identify you before switching branches`
|
|
2957
|
+
);
|
|
2958
|
+
attempt.branch = branch;
|
|
2959
|
+
let baseSha = previous?.branch === branch && previous.baseSha ? previous.baseSha : void 0;
|
|
2960
|
+
if (!baseSha) {
|
|
2961
|
+
const head = await git2(root, ["rev-parse", "--verify", "HEAD^{commit}"], signal);
|
|
2962
|
+
baseSha = head.stdout.trim();
|
|
2963
|
+
if (!head.ok || !SHA.test(baseSha))
|
|
2964
|
+
return failure(
|
|
2965
|
+
"no_commit",
|
|
2966
|
+
"this checkout has no commit to create the session branch at",
|
|
2967
|
+
NEW_SESSION_REMEDY
|
|
2968
|
+
);
|
|
2969
|
+
}
|
|
2970
|
+
const published = await git2(
|
|
2971
|
+
root,
|
|
2972
|
+
[
|
|
2973
|
+
"for-each-ref",
|
|
2974
|
+
"--count=1",
|
|
2975
|
+
"--format=%(refname)",
|
|
2976
|
+
"--contains",
|
|
2977
|
+
baseSha,
|
|
2978
|
+
"refs/remotes/origin/"
|
|
2979
|
+
],
|
|
2980
|
+
signal
|
|
2981
|
+
);
|
|
2982
|
+
if (!published.ok || published.stdout.trim() === "")
|
|
2983
|
+
return failure(
|
|
2984
|
+
"unpublished_commits",
|
|
2985
|
+
`this checkout's commit ${baseSha.slice(0, 12)} is not on GitHub yet, and creating the session branch at it would publish it, so prim pushed nothing`,
|
|
2986
|
+
`${NEW_SESSION_REMEDY} and let it identify you before committing`
|
|
2987
|
+
);
|
|
2988
|
+
attempt.baseSha = baseSha;
|
|
2989
|
+
const remote = await git2(
|
|
2990
|
+
root,
|
|
2991
|
+
["ls-remote", "--exit-code", "origin", `refs/heads/${branch}`],
|
|
2992
|
+
signal
|
|
2993
|
+
);
|
|
2994
|
+
const recorded = previous?.branch === branch && previous.challengeId ? { challengeId: previous.challengeId, challengeExpiresAt: previous.challengeExpiresAt ?? 0 } : void 0;
|
|
2995
|
+
if (remote.ok && recorded) {
|
|
2996
|
+
Object.assign(attempt, recorded);
|
|
2997
|
+
return { ...recorded, repository };
|
|
2998
|
+
}
|
|
2999
|
+
if (remote.ok)
|
|
3000
|
+
return failure(
|
|
3001
|
+
"branch_exists",
|
|
3002
|
+
`the session branch ${branch} already exists on GitHub, so this session cannot prove who started it`,
|
|
3003
|
+
NEW_SESSION_REMEDY
|
|
3004
|
+
);
|
|
3005
|
+
if (remote.code !== 2)
|
|
3006
|
+
return failure(
|
|
3007
|
+
remote.timedOut ? "push_timeout" : "remote_unavailable",
|
|
3008
|
+
`prim could not check ${repository} for the session branch (${remote.timedOut ? "timed out" : gitDetail(remote.stderr)})`,
|
|
3009
|
+
`check the session's access to ${repository} on GitHub, then ${RETRY_REMEDY}`
|
|
3010
|
+
);
|
|
3011
|
+
if (recorded && previous?.baseSha === baseSha && recorded.challengeExpiresAt > Date.now() + CHALLENGE_REUSE_MARGIN_MS) {
|
|
3012
|
+
Object.assign(attempt, recorded);
|
|
3013
|
+
return pushSessionBranch(root, repository, branch, baseSha, recorded, signal);
|
|
3014
|
+
}
|
|
3015
|
+
let answer;
|
|
3016
|
+
try {
|
|
3017
|
+
const email = env[USER_EMAIL_VARIABLE]?.trim();
|
|
3018
|
+
answer = await environmentRequest(
|
|
3019
|
+
"POST",
|
|
3020
|
+
SESSION_IDENTITY_ROUTES.challenge,
|
|
3021
|
+
{
|
|
3022
|
+
repositoryFullName: repository,
|
|
3023
|
+
claudeSessionId: context.sessionId,
|
|
3024
|
+
branch,
|
|
3025
|
+
baseSha,
|
|
3026
|
+
// Only a cross-check: one Primitive would refuse is left out, not sent.
|
|
3027
|
+
...email && email.length <= 320 && EMAIL_HINT.test(email) ? { userEmailHint: email } : {}
|
|
3028
|
+
},
|
|
3029
|
+
deps,
|
|
3030
|
+
signal
|
|
3031
|
+
);
|
|
3032
|
+
} catch (error) {
|
|
3033
|
+
signal?.throwIfAborted();
|
|
3034
|
+
return environmentFailure(error, context.apiUrl);
|
|
3035
|
+
}
|
|
3036
|
+
if (answer.status === 404 && answerError(answer) === "repository_not_connected")
|
|
3037
|
+
return failure(
|
|
3038
|
+
"repository_not_connected",
|
|
3039
|
+
`${repository} is not connected to Primitive`,
|
|
3040
|
+
CLOUD_GITHUB_CONNECT_REMEDY
|
|
3041
|
+
);
|
|
3042
|
+
if (answer.status === 401 || answer.status === 403)
|
|
3043
|
+
return environmentFailure(new MachineAuthError("rejected", "rejected", true), context.apiUrl);
|
|
3044
|
+
if (answer.status === 409 && answerError(answer) === "challenge_already_open")
|
|
3045
|
+
return failure(
|
|
3046
|
+
"challenge_open",
|
|
3047
|
+
`an identity check for ${branch} on ${repository} is still open from an earlier attempt that this VM did not record`,
|
|
3048
|
+
`wait five minutes, then ${RETRY_REMEDY}`
|
|
3049
|
+
);
|
|
3050
|
+
if (answer.status === 429)
|
|
3051
|
+
return failure(
|
|
3052
|
+
"too_many_challenges",
|
|
3053
|
+
"too many sessions of this cloud environment are being identified at once",
|
|
3054
|
+
`wait a few minutes, then ${RETRY_REMEDY}`
|
|
3055
|
+
);
|
|
3056
|
+
const challengeId = answer.value?.challengeId;
|
|
3057
|
+
const challengeExpiresAt = parseInstant(answer.value?.expiresAt);
|
|
3058
|
+
if (answer.status !== 200 || !machineString(challengeId, 256) || !challengeExpiresAt)
|
|
3059
|
+
return answer.status >= 500 ? environmentFailure(
|
|
3060
|
+
new MachineAuthError("identity_unavailable", `HTTP ${answer.status}`),
|
|
3061
|
+
context.apiUrl
|
|
3062
|
+
) : SERVER_CONTRACT_FAILURE;
|
|
3063
|
+
if (answer.value?.ref !== `refs/heads/${branch}`) return SERVER_CONTRACT_FAILURE;
|
|
3064
|
+
attempt.challengeId = challengeId;
|
|
3065
|
+
attempt.challengeExpiresAt = challengeExpiresAt;
|
|
3066
|
+
return pushSessionBranch(
|
|
3067
|
+
root,
|
|
3068
|
+
repository,
|
|
3069
|
+
branch,
|
|
3070
|
+
baseSha,
|
|
3071
|
+
{ challengeId, challengeExpiresAt },
|
|
3072
|
+
signal
|
|
3073
|
+
);
|
|
3074
|
+
}
|
|
3075
|
+
async function pushSessionBranch(root, repository, branch, baseSha, challenge, signal) {
|
|
3076
|
+
const push = await git2(
|
|
3077
|
+
root,
|
|
3078
|
+
[
|
|
3079
|
+
"-c",
|
|
3080
|
+
"core.hooksPath=/dev/null",
|
|
3081
|
+
"-c",
|
|
3082
|
+
"push.followTags=false",
|
|
3083
|
+
"-c",
|
|
3084
|
+
"push.recurseSubmodules=no",
|
|
3085
|
+
"-c",
|
|
3086
|
+
"push.gpgSign=false",
|
|
3087
|
+
"-c",
|
|
3088
|
+
"push.pushOption=",
|
|
3089
|
+
"push",
|
|
3090
|
+
"--no-verify",
|
|
3091
|
+
"--no-follow-tags",
|
|
3092
|
+
"--no-recurse-submodules",
|
|
3093
|
+
"--no-signed",
|
|
3094
|
+
"--quiet",
|
|
3095
|
+
"origin",
|
|
3096
|
+
`${baseSha}:refs/heads/${branch}`
|
|
3097
|
+
],
|
|
3098
|
+
signal
|
|
3099
|
+
);
|
|
3100
|
+
if (!push.ok)
|
|
3101
|
+
return push.timedOut ? failure(
|
|
3102
|
+
"push_timeout",
|
|
3103
|
+
`creating the session branch ${branch} on ${repository} did not finish in ${GIT_TIMEOUT_MS4 / 1e3} s`,
|
|
3104
|
+
`check the session's network access to GitHub, then ${RETRY_REMEDY}`
|
|
3105
|
+
) : failure(
|
|
3106
|
+
"push_refused",
|
|
3107
|
+
`creating the session branch ${branch} on ${repository} was refused (${gitDetail(push.stderr)})`,
|
|
3108
|
+
`check that the GitHub account that started this session can push to ${repository} and that the cloud environment lets the session push, then ${NEW_SESSION_REMEDY}`
|
|
3109
|
+
);
|
|
3110
|
+
return { ...challenge, repository };
|
|
3111
|
+
}
|
|
3112
|
+
async function ensureSessionIdentity(options = {}, deps = {}) {
|
|
3113
|
+
let context;
|
|
3114
|
+
try {
|
|
3115
|
+
context = sessionContext(deps);
|
|
3116
|
+
} catch (error) {
|
|
3117
|
+
return failure(
|
|
3118
|
+
"environment_credential_invalid",
|
|
3119
|
+
error instanceof MachineAuthError ? terminalSafeLine(error.message).replace(/\.$/u, "") : "the environment credential is misconfigured",
|
|
3120
|
+
"correct the cloud environment's PRIM_M2M_* variables, then start a new cloud session"
|
|
3121
|
+
);
|
|
3122
|
+
}
|
|
3123
|
+
if ("status" in context) return context;
|
|
3124
|
+
const ctx = context;
|
|
3125
|
+
const startedAt = Date.now();
|
|
3126
|
+
prepareMachineMetadataDirectory(ctx.directory);
|
|
3127
|
+
return withFileLock(
|
|
3128
|
+
ctx.lockPath,
|
|
3129
|
+
async () => {
|
|
3130
|
+
const record = readToken(ctx);
|
|
3131
|
+
const forced = options.force === true && (!options.observedToken || options.observedToken === record?.accessToken);
|
|
3132
|
+
if (record && !forced && tokenFresh(record)) return identified(record, true);
|
|
3133
|
+
if (record) {
|
|
3134
|
+
const refreshed = await refreshToken(ctx, record, deps, options.signal);
|
|
3135
|
+
if (refreshed.status === "ok") {
|
|
3136
|
+
writeToken(ctx, refreshed.record);
|
|
3137
|
+
return identified(refreshed.record, true);
|
|
3138
|
+
}
|
|
3139
|
+
if (refreshed.status === "refused") {
|
|
3140
|
+
rmSync7(ctx.tokenPath, { force: true });
|
|
3141
|
+
writeState(ctx, {
|
|
3142
|
+
sessionId: ctx.sessionId,
|
|
3143
|
+
status: "failed",
|
|
3144
|
+
code: refreshed.failure.code,
|
|
3145
|
+
cause: refreshed.failure.cause,
|
|
3146
|
+
remedy: refreshed.failure.remedy,
|
|
3147
|
+
...record.repositoryRoot ? { repositoryRoot: record.repositoryRoot } : {},
|
|
3148
|
+
at: Date.now()
|
|
3149
|
+
});
|
|
3150
|
+
return refreshed.failure;
|
|
3151
|
+
}
|
|
3152
|
+
if (!forced && tokenValid(record)) return identified(record, true);
|
|
3153
|
+
}
|
|
3154
|
+
const state = readState(ctx);
|
|
3155
|
+
if (!record && state && FINAL_CODES.has(state.code)) return outcomeFromState(state);
|
|
3156
|
+
const root = (options.cwd ? gitToplevel(options.cwd) : null) ?? record?.repositoryRoot ?? state?.repositoryRoot;
|
|
3157
|
+
if (!options.explicit) {
|
|
3158
|
+
if (!root || !(record || state))
|
|
3159
|
+
return failure(
|
|
3160
|
+
"not_identified",
|
|
3161
|
+
"this session has not identified who started it yet",
|
|
3162
|
+
RETRY_REMEDY
|
|
3163
|
+
);
|
|
3164
|
+
if (state && state.at > Date.now() - BACKGROUND_RETRY_MS) return outcomeFromState(state);
|
|
3165
|
+
} else if (state && state.at >= startedAt) {
|
|
3166
|
+
return outcomeFromState(state);
|
|
3167
|
+
}
|
|
3168
|
+
if (!root)
|
|
3169
|
+
return failure(
|
|
3170
|
+
"repository_missing",
|
|
3171
|
+
"this is not a git repository",
|
|
3172
|
+
"run it in the repository the session cloned"
|
|
3173
|
+
);
|
|
3174
|
+
const attempt = { root };
|
|
3175
|
+
const remember = (outcome) => {
|
|
3176
|
+
writeState(ctx, {
|
|
3177
|
+
sessionId: ctx.sessionId,
|
|
3178
|
+
status: outcome.status,
|
|
3179
|
+
code: outcome.status === "failed" ? outcome.code : "github_account_not_linked",
|
|
3180
|
+
...outcome.status === "failed" ? { cause: outcome.cause, remedy: outcome.remedy } : {
|
|
3181
|
+
githubLogin: outcome.githubLogin
|
|
3182
|
+
},
|
|
3183
|
+
challengeId: outcome.status === "link_required" ? outcome.challengeId : attempt.challengeId,
|
|
3184
|
+
challengeExpiresAt: outcome.status === "link_required" ? outcome.challengeExpiresAt : attempt.challengeExpiresAt,
|
|
3185
|
+
repositoryRoot: root,
|
|
3186
|
+
branch: attempt.branch ?? state?.branch,
|
|
3187
|
+
baseSha: attempt.baseSha ?? state?.baseSha,
|
|
3188
|
+
at: Date.now()
|
|
3189
|
+
});
|
|
3190
|
+
return outcome;
|
|
3191
|
+
};
|
|
3192
|
+
let challenge;
|
|
3193
|
+
if (state?.code === "webhook_timeout" && state.challengeId && (state.challengeExpiresAt ?? 0) > Date.now()) {
|
|
3194
|
+
attempt.challengeId = state.challengeId;
|
|
3195
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
3196
|
+
attempt.branch = state.branch;
|
|
3197
|
+
attempt.baseSha = state.baseSha;
|
|
3198
|
+
challenge = {
|
|
3199
|
+
challengeId: state.challengeId,
|
|
3200
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
3201
|
+
repository: githubRepositoryFullName(root) ?? "the repository"
|
|
3202
|
+
};
|
|
3203
|
+
} else if (state?.status === "link_required" && state.challengeId) {
|
|
3204
|
+
attempt.challengeId = state.challengeId;
|
|
3205
|
+
attempt.challengeExpiresAt = state.challengeExpiresAt;
|
|
3206
|
+
const exchanged2 = await exchangeChallenge(
|
|
3207
|
+
ctx,
|
|
3208
|
+
{
|
|
3209
|
+
challengeId: state.challengeId,
|
|
3210
|
+
challengeExpiresAt: state.challengeExpiresAt ?? 0,
|
|
3211
|
+
githubLogin: state.githubLogin
|
|
3212
|
+
},
|
|
3213
|
+
root,
|
|
3214
|
+
deps,
|
|
3215
|
+
options.signal
|
|
3216
|
+
);
|
|
3217
|
+
if ("status" in exchanged2) return remember(exchanged2);
|
|
3218
|
+
writeToken(ctx, exchanged2);
|
|
3219
|
+
return identified(exchanged2, false);
|
|
3220
|
+
} else if (!options.explicit) {
|
|
3221
|
+
return state ? outcomeFromState(state) : failure(
|
|
3222
|
+
"not_identified",
|
|
3223
|
+
"this session has not identified who started it yet",
|
|
3224
|
+
RETRY_REMEDY
|
|
3225
|
+
);
|
|
3226
|
+
} else {
|
|
3227
|
+
const pushed = await challengeAndPush(ctx, root, state, deps, attempt, options.signal);
|
|
3228
|
+
if ("status" in pushed) return remember(pushed);
|
|
3229
|
+
challenge = pushed;
|
|
3230
|
+
}
|
|
3231
|
+
const verified = await pollChallenge(
|
|
3232
|
+
ctx.apiUrl,
|
|
3233
|
+
challenge.challengeId,
|
|
3234
|
+
challenge.repository,
|
|
3235
|
+
// A hook process waits only briefly for a late notice.
|
|
3236
|
+
options.explicit ? deps : { ...deps, pollBudgetMs: Math.min(deps.pollBudgetMs ?? POLL_BUDGET_MS, 3e3) },
|
|
3237
|
+
options.signal
|
|
3238
|
+
);
|
|
3239
|
+
if ("status" in verified) return remember(verified);
|
|
3240
|
+
const exchanged = await exchangeChallenge(
|
|
3241
|
+
ctx,
|
|
3242
|
+
{ ...challenge, githubLogin: verified.githubLogin },
|
|
3243
|
+
root,
|
|
3244
|
+
deps,
|
|
3245
|
+
options.signal
|
|
3246
|
+
);
|
|
3247
|
+
if ("status" in exchanged) return remember(exchanged);
|
|
3248
|
+
writeToken(ctx, exchanged);
|
|
3249
|
+
return identified(exchanged, false);
|
|
3250
|
+
},
|
|
3251
|
+
{ signal: options.signal, timeoutMs: LOCK_TIMEOUT_MS }
|
|
3252
|
+
);
|
|
3253
|
+
}
|
|
3254
|
+
async function acquireSessionCredential(options = {}, deps = {}) {
|
|
3255
|
+
const cached2 = cachedSessionCredential(deps);
|
|
3256
|
+
const fresh = cached2?.session !== void 0 && Date.now() < cached2.session.refreshAfter;
|
|
3257
|
+
if (cached2 && fresh && !options.force) return cached2;
|
|
3258
|
+
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
3259
|
+
let outcome;
|
|
3260
|
+
try {
|
|
3261
|
+
outcome = await ensureSessionIdentity(
|
|
3262
|
+
{ force: options.force, observedToken: cached2?.accessToken, signal },
|
|
3263
|
+
deps
|
|
3264
|
+
);
|
|
3265
|
+
} catch (error) {
|
|
3266
|
+
options.signal?.throwIfAborted();
|
|
3267
|
+
if (error instanceof MachineAuthError) throw error;
|
|
3268
|
+
throw new MachineAuthError(
|
|
3269
|
+
"identity_unavailable",
|
|
3270
|
+
"Identifying who started this cloud session is still in progress; retry shortly."
|
|
3271
|
+
);
|
|
3272
|
+
}
|
|
3273
|
+
if (outcome.status === "ok") return outcome.credential;
|
|
3274
|
+
throw new MachineAuthError(
|
|
3275
|
+
outcome.status === "link_required" ? "github_account_not_linked" : outcome.code,
|
|
3276
|
+
sessionIdentityMessage(outcome)
|
|
3277
|
+
);
|
|
3278
|
+
}
|
|
3279
|
+
|
|
2303
3280
|
// src/lib/machine-credentials.ts
|
|
3281
|
+
function sessionScoped(deps) {
|
|
3282
|
+
return !deps.localEnvironment && !deps.environmentOnly && sessionIdentityMode(deps);
|
|
3283
|
+
}
|
|
2304
3284
|
var require3 = createRequire2(import.meta.url);
|
|
2305
3285
|
var SERVICE = "ai.primitive.prim.machine";
|
|
2306
|
-
var
|
|
3286
|
+
var DEFAULT_API_URL2 = "https://api.getprimitive.ai";
|
|
2307
3287
|
var PROFILE_FILE = "machine_profile.json";
|
|
2308
|
-
var
|
|
3288
|
+
var RENEW_BEFORE_MS2 = 6e4;
|
|
2309
3289
|
var cached;
|
|
2310
3290
|
function configurationDirectory(deps) {
|
|
2311
3291
|
return deps.directory ?? primConfigDirectory({ env: deps.env });
|
|
2312
3292
|
}
|
|
2313
3293
|
function apiUrlFor(deps) {
|
|
2314
|
-
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() ||
|
|
3294
|
+
return machineApiUrl((deps.env ?? process.env).PRIM_API_URL?.trim() || DEFAULT_API_URL2);
|
|
2315
3295
|
}
|
|
2316
|
-
function
|
|
2317
|
-
return
|
|
3296
|
+
function hash2(value) {
|
|
3297
|
+
return createHash6("sha256").update(value).digest("hex");
|
|
2318
3298
|
}
|
|
2319
3299
|
function recordPath(directory, generation) {
|
|
2320
|
-
return
|
|
3300
|
+
return join14(directory, `machine_${generation}.json`);
|
|
2321
3301
|
}
|
|
2322
3302
|
function storageKey(directory, generation) {
|
|
2323
|
-
return `${
|
|
3303
|
+
return `${hash2(directory)}:${generation}`;
|
|
2324
3304
|
}
|
|
2325
3305
|
function environmentContextPath(deps, clientId) {
|
|
2326
|
-
return
|
|
3306
|
+
return join14(
|
|
2327
3307
|
configurationDirectory(deps),
|
|
2328
|
-
`machine_context_${
|
|
3308
|
+
`machine_context_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.json`
|
|
2329
3309
|
);
|
|
2330
3310
|
}
|
|
2331
3311
|
function writeEnvironmentContext(credential, deps) {
|
|
@@ -2386,7 +3366,7 @@ function readEnvironmentContext(environment, deps) {
|
|
|
2386
3366
|
function keyringEntry(key) {
|
|
2387
3367
|
let directory = dirname8(fileURLToPath4(import.meta.url));
|
|
2388
3368
|
for (let depth = 0; depth < 5; depth++) {
|
|
2389
|
-
const loader =
|
|
3369
|
+
const loader = join14(directory, "native", "keyring.cjs");
|
|
2390
3370
|
if (existsSync9(loader)) {
|
|
2391
3371
|
const module2 = require3(loader);
|
|
2392
3372
|
return new module2.AsyncEntry(SERVICE, key, { linux: { store: "secret-service" } });
|
|
@@ -2428,6 +3408,9 @@ function writePrivate(path, value) {
|
|
|
2428
3408
|
`, { mode: 384 });
|
|
2429
3409
|
protectPath(path, false);
|
|
2430
3410
|
}
|
|
3411
|
+
function readMachineMetadata(path) {
|
|
3412
|
+
return readPrivate(path);
|
|
3413
|
+
}
|
|
2431
3414
|
function readPrivate(path) {
|
|
2432
3415
|
let raw;
|
|
2433
3416
|
try {
|
|
@@ -2483,7 +3466,7 @@ function parseProfile(value) {
|
|
|
2483
3466
|
};
|
|
2484
3467
|
}
|
|
2485
3468
|
function readMachineProfile(deps = {}) {
|
|
2486
|
-
const value = readPrivate(
|
|
3469
|
+
const value = readPrivate(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
2487
3470
|
return value === void 0 ? void 0 : parseProfile(value);
|
|
2488
3471
|
}
|
|
2489
3472
|
var NETWORK_SECRET_AUTH = "network-secret";
|
|
@@ -2492,7 +3475,7 @@ var INJECTED_IDENTITY_TTL_MS = 60 * 6e4;
|
|
|
2492
3475
|
var brokerKeys = /* @__PURE__ */ new Map();
|
|
2493
3476
|
function networkSecretBrokerKey(deps, clientId) {
|
|
2494
3477
|
const directory = configurationDirectory(deps);
|
|
2495
|
-
const path =
|
|
3478
|
+
const path = join14(directory, `machine_network_${hash2(`${apiUrlFor(deps)}\0${clientId}`)}.key`);
|
|
2496
3479
|
const known = brokerKeys.get(path);
|
|
2497
3480
|
if (known) return known;
|
|
2498
3481
|
ensureDirectory(directory);
|
|
@@ -2533,7 +3516,7 @@ function networkSecretBrokerKey(deps, clientId) {
|
|
|
2533
3516
|
} catch (error) {
|
|
2534
3517
|
if (error.code !== "EEXIST") throw error;
|
|
2535
3518
|
} finally {
|
|
2536
|
-
|
|
3519
|
+
rmSync8(staged, { force: true });
|
|
2537
3520
|
}
|
|
2538
3521
|
}
|
|
2539
3522
|
const key = read()?.key;
|
|
@@ -2566,7 +3549,7 @@ function environmentCredentials(deps) {
|
|
|
2566
3549
|
"conflicting_credentials",
|
|
2567
3550
|
`Unset PRIM_M2M_CLIENT_SECRET: with PRIM_M2M_CLIENT_AUTH=${auth} the environment's network secret supplies it.`
|
|
2568
3551
|
);
|
|
2569
|
-
const generation =
|
|
3552
|
+
const generation = hash2(`${apiUrlFor(deps)}\0${clientId}\0${auth}\0broker-proxy`);
|
|
2570
3553
|
const credentials = {
|
|
2571
3554
|
clientId,
|
|
2572
3555
|
generation,
|
|
@@ -2587,12 +3570,12 @@ function environmentCredentials(deps) {
|
|
|
2587
3570
|
return {
|
|
2588
3571
|
clientId,
|
|
2589
3572
|
clientSecret,
|
|
2590
|
-
generation:
|
|
3573
|
+
generation: hash2(`${apiUrlFor(deps)}\0${clientId}\0${clientSecret}`)
|
|
2591
3574
|
};
|
|
2592
3575
|
}
|
|
2593
3576
|
function hasMachineConfiguration(deps = {}) {
|
|
2594
3577
|
const env = deps.env ?? process.env;
|
|
2595
|
-
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync9(
|
|
3578
|
+
const configured = env.PRIM_M2M_CLIENT_ID !== void 0 || env.PRIM_M2M_CLIENT_SECRET !== void 0 || env.PRIM_M2M_CLIENT_AUTH !== void 0 || existsSync9(join14(configurationDirectory(deps), PROFILE_FILE));
|
|
2596
3579
|
if (configured && env.PRIM_TOKEN?.trim()) {
|
|
2597
3580
|
throw new MachineAuthError(
|
|
2598
3581
|
"conflicting_credentials",
|
|
@@ -2604,6 +3587,7 @@ function hasMachineConfiguration(deps = {}) {
|
|
|
2604
3587
|
}
|
|
2605
3588
|
function machineContext(deps = {}) {
|
|
2606
3589
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3590
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
2607
3591
|
const environment = environmentCredentials(deps);
|
|
2608
3592
|
if (environment) {
|
|
2609
3593
|
if (environmentTerminal === environment.generation) return void 0;
|
|
@@ -2618,6 +3602,7 @@ function machineContext(deps = {}) {
|
|
|
2618
3602
|
return profile;
|
|
2619
3603
|
}
|
|
2620
3604
|
function cachedMachineCredential(deps = {}) {
|
|
3605
|
+
if (sessionScoped(deps)) return cachedSessionCredential(deps);
|
|
2621
3606
|
const context = machineContext(deps);
|
|
2622
3607
|
return context && cached?.generation === context.generation && cached.apiUrl === context.apiUrl ? cached : void 0;
|
|
2623
3608
|
}
|
|
@@ -2626,7 +3611,7 @@ function machineSessionEnded(deps = {}) {
|
|
|
2626
3611
|
const generation = environmentCredentials(deps)?.generation ?? readMachineProfile(deps)?.generation;
|
|
2627
3612
|
if (!generation) return false;
|
|
2628
3613
|
if (environmentCredentials(deps)) return environmentTerminal === generation;
|
|
2629
|
-
return readPrivate(
|
|
3614
|
+
return readPrivate(join14(configurationDirectory(deps), "machine_terminal.json")) === generation;
|
|
2630
3615
|
}
|
|
2631
3616
|
var environmentTerminal;
|
|
2632
3617
|
var NETWORK_REJECTION_PAUSE_MS = 3e4;
|
|
@@ -2690,6 +3675,7 @@ async function persistRecord(record, deps, signal) {
|
|
|
2690
3675
|
}
|
|
2691
3676
|
async function acquireMachineCredential(options = {}, deps = {}) {
|
|
2692
3677
|
if (!hasMachineConfiguration(deps)) return void 0;
|
|
3678
|
+
if (sessionScoped(deps)) return acquireSessionCredential(options, deps);
|
|
2693
3679
|
const signal = options.signal ? AbortSignal.any([options.signal, AbortSignal.timeout(1e4)]) : AbortSignal.timeout(1e4);
|
|
2694
3680
|
const apiUrl = apiUrlFor(deps);
|
|
2695
3681
|
const environment = environmentCredentials(deps);
|
|
@@ -2718,7 +3704,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2718
3704
|
}
|
|
2719
3705
|
}
|
|
2720
3706
|
return withFileLock(
|
|
2721
|
-
|
|
3707
|
+
join14(directory2, "credentials.lock"),
|
|
2722
3708
|
async () => {
|
|
2723
3709
|
if (machineSessionEnded(deps))
|
|
2724
3710
|
throw new MachineAuthError(
|
|
@@ -2726,7 +3712,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2726
3712
|
rejectedCredentialsMessage("Rotate the injected machine credentials.", deps.env),
|
|
2727
3713
|
true
|
|
2728
3714
|
);
|
|
2729
|
-
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() +
|
|
3715
|
+
if ((!options.force || observedToken2 && cached?.accessToken !== observedToken2) && cached?.generation === environment.generation && cached.expiresAt > Date.now() + RENEW_BEFORE_MS2)
|
|
2730
3716
|
return cached;
|
|
2731
3717
|
if (networkManaged && networkRejection?.generation === environment.generation && networkRejection.until > Date.now())
|
|
2732
3718
|
throw networkRejection.error;
|
|
@@ -2800,7 +3786,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2800
3786
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2801
3787
|
try {
|
|
2802
3788
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2803
|
-
|
|
3789
|
+
rmSync8(contextPath, { force: true });
|
|
2804
3790
|
} catch {
|
|
2805
3791
|
}
|
|
2806
3792
|
throw error;
|
|
@@ -2810,7 +3796,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2810
3796
|
const contextPath = environmentContextPath(deps, environment.clientId);
|
|
2811
3797
|
try {
|
|
2812
3798
|
if (machineRecord(readPrivate(contextPath)).generation === environment.generation)
|
|
2813
|
-
|
|
3799
|
+
rmSync8(contextPath, { force: true });
|
|
2814
3800
|
} catch {
|
|
2815
3801
|
}
|
|
2816
3802
|
}
|
|
@@ -2824,7 +3810,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2824
3810
|
const expected = machineContext(deps);
|
|
2825
3811
|
const directory = configurationDirectory(deps);
|
|
2826
3812
|
return withFileLock(
|
|
2827
|
-
|
|
3813
|
+
join14(directory, "credentials.lock"),
|
|
2828
3814
|
async () => {
|
|
2829
3815
|
const profile = readMachineProfile(deps);
|
|
2830
3816
|
if (!profile || profile.generation !== expected?.generation || profile.apiUrl !== apiUrl)
|
|
@@ -2839,7 +3825,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2839
3825
|
true
|
|
2840
3826
|
);
|
|
2841
3827
|
let record = await loadRecord(profile, deps, signal);
|
|
2842
|
-
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() +
|
|
3828
|
+
if (options.force && (!observedToken || observedToken === record.accessToken) || record.expiresAt <= Date.now() + RENEW_BEFORE_MS2) {
|
|
2843
3829
|
try {
|
|
2844
3830
|
const { tokens, identity } = await withMachineCooldown(
|
|
2845
3831
|
directory,
|
|
@@ -2874,7 +3860,7 @@ async function acquireMachineCredential(options = {}, deps = {}) {
|
|
|
2874
3860
|
await persistRecord(record, deps, signal);
|
|
2875
3861
|
} catch (error) {
|
|
2876
3862
|
if (error instanceof MachineAuthError && error.terminal)
|
|
2877
|
-
writePrivate(
|
|
3863
|
+
writePrivate(join14(directory, "machine_terminal.json"), profile.generation);
|
|
2878
3864
|
throw error;
|
|
2879
3865
|
}
|
|
2880
3866
|
}
|
|
@@ -2903,17 +3889,23 @@ async function forwardMachineRequest(request3, signal, deps = {}) {
|
|
|
2903
3889
|
signal: signal ? AbortSignal.any([signal, AbortSignal.timeout(3e4)]) : AbortSignal.timeout(3e4)
|
|
2904
3890
|
});
|
|
2905
3891
|
}
|
|
3892
|
+
function prepareMachineMetadataDirectory(directory) {
|
|
3893
|
+
ensureDirectory(directory);
|
|
3894
|
+
}
|
|
3895
|
+
function writeMachineMetadata(path, value) {
|
|
3896
|
+
writePrivate(path, value);
|
|
3897
|
+
}
|
|
2906
3898
|
|
|
2907
3899
|
// src/lib/credentials.ts
|
|
2908
3900
|
var CONFIG_DIRECTORY = primConfigDirectory();
|
|
2909
|
-
var TOKEN_FILE_PATH =
|
|
2910
|
-
var REFRESH_TOKEN_PATH =
|
|
2911
|
-
var TOKEN_EXPIRES_PATH =
|
|
2912
|
-
var TERMINAL_REFRESH_PATH =
|
|
2913
|
-
var CREDENTIAL_METADATA_PATH =
|
|
2914
|
-
var CREDENTIAL_FAMILY_PATH =
|
|
2915
|
-
var CREDENTIAL_MIGRATION_PATH =
|
|
2916
|
-
var CREDENTIAL_LOCK_PATH =
|
|
3901
|
+
var TOKEN_FILE_PATH = join15(CONFIG_DIRECTORY, "token");
|
|
3902
|
+
var REFRESH_TOKEN_PATH = join15(CONFIG_DIRECTORY, "refresh_token");
|
|
3903
|
+
var TOKEN_EXPIRES_PATH = join15(CONFIG_DIRECTORY, "token_expires_at");
|
|
3904
|
+
var TERMINAL_REFRESH_PATH = join15(CONFIG_DIRECTORY, "refresh_terminal");
|
|
3905
|
+
var CREDENTIAL_METADATA_PATH = join15(CONFIG_DIRECTORY, "credential_metadata.json");
|
|
3906
|
+
var CREDENTIAL_FAMILY_PATH = join15(CONFIG_DIRECTORY, "credential_family.json");
|
|
3907
|
+
var CREDENTIAL_MIGRATION_PATH = join15(CONFIG_DIRECTORY, "credential_migration.json");
|
|
3908
|
+
var CREDENTIAL_LOCK_PATH = join15(CONFIG_DIRECTORY, "credentials.lock");
|
|
2917
3909
|
var MAX_CREDENTIAL_METADATA_BYTES = 4096;
|
|
2918
3910
|
var CREDENTIAL_MIGRATION_VERSION = 1;
|
|
2919
3911
|
var CREDENTIAL_MIGRATION_STATE = "family_bound";
|
|
@@ -2941,16 +3933,16 @@ function resolveAuthCredential(options = {}) {
|
|
|
2941
3933
|
);
|
|
2942
3934
|
if (metadata.state === "legacy_broker") {
|
|
2943
3935
|
if (metadata.metadata) {
|
|
2944
|
-
const
|
|
2945
|
-
if (!
|
|
3936
|
+
const refreshToken4 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3937
|
+
if (!refreshToken4 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken4)) {
|
|
2946
3938
|
return void 0;
|
|
2947
3939
|
}
|
|
2948
3940
|
}
|
|
2949
3941
|
return { token: stored, source: "token_file" };
|
|
2950
3942
|
}
|
|
2951
3943
|
if (metadata.state === "invalid") return void 0;
|
|
2952
|
-
const
|
|
2953
|
-
if (!
|
|
3944
|
+
const refreshToken3 = readTrimmed(options.refreshTokenPath ?? REFRESH_TOKEN_PATH);
|
|
3945
|
+
if (!refreshToken3 || metadata.metadata.accessTokenHash !== credentialFingerprint(stored) || metadata.metadata.refreshTokenHash !== credentialFingerprint(refreshToken3)) {
|
|
2954
3946
|
return void 0;
|
|
2955
3947
|
}
|
|
2956
3948
|
return { token: stored, source: "token_file" };
|
|
@@ -2959,15 +3951,15 @@ function resolveStoredCredential(env = process.env) {
|
|
|
2959
3951
|
const directory = primConfigDirectory({ env });
|
|
2960
3952
|
return resolveAuthCredential({
|
|
2961
3953
|
env,
|
|
2962
|
-
tokenFilePath:
|
|
2963
|
-
refreshTokenPath:
|
|
2964
|
-
metadataPath:
|
|
2965
|
-
familyPath:
|
|
2966
|
-
migrationPath:
|
|
3954
|
+
tokenFilePath: join15(directory, "token"),
|
|
3955
|
+
refreshTokenPath: join15(directory, "refresh_token"),
|
|
3956
|
+
metadataPath: join15(directory, "credential_metadata.json"),
|
|
3957
|
+
familyPath: join15(directory, "credential_family.json"),
|
|
3958
|
+
migrationPath: join15(directory, "credential_migration.json")
|
|
2967
3959
|
});
|
|
2968
3960
|
}
|
|
2969
3961
|
function credentialFingerprint(value) {
|
|
2970
|
-
return
|
|
3962
|
+
return createHash7("sha256").update(value).digest("hex");
|
|
2971
3963
|
}
|
|
2972
3964
|
function parseLegacyBrokerCredentialMetadata(value) {
|
|
2973
3965
|
if (value === null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -3061,7 +4053,7 @@ function jwtExpiresAt(token) {
|
|
|
3061
4053
|
// src/daemon/client-instance-id.ts
|
|
3062
4054
|
import { randomBytes as randomBytes5 } from "crypto";
|
|
3063
4055
|
import { chmodSync as chmodSync3, lstatSync as lstatSync7, readFileSync as readFileSync13 } from "fs";
|
|
3064
|
-
import { join as
|
|
4056
|
+
import { join as join16 } from "path";
|
|
3065
4057
|
var CONFIG_DIRECTORY_MODE = 448;
|
|
3066
4058
|
var INSTANCE_FILE_MODE = 384;
|
|
3067
4059
|
var INSTANCE_ENTROPY_BYTES = 32;
|
|
@@ -3112,8 +4104,8 @@ function atomicWrite(path, value) {
|
|
|
3112
4104
|
}
|
|
3113
4105
|
async function getOrCreateClientInstanceId(options) {
|
|
3114
4106
|
const configDir = options.configDir;
|
|
3115
|
-
const path =
|
|
3116
|
-
const lockPath =
|
|
4107
|
+
const path = join16(configDir, "client_instance_id");
|
|
4108
|
+
const lockPath = join16(configDir, "client-instance.lock");
|
|
3117
4109
|
ensurePrivateConfigDirectory(configDir);
|
|
3118
4110
|
return withFileLock(
|
|
3119
4111
|
lockPath,
|
|
@@ -3157,56 +4149,11 @@ async function ingestUploaderHeaders() {
|
|
|
3157
4149
|
return headers;
|
|
3158
4150
|
}
|
|
3159
4151
|
|
|
3160
|
-
// src/lib/terminal-safe.ts
|
|
3161
|
-
function replaceIsolatedSurrogates(value) {
|
|
3162
|
-
let out = "";
|
|
3163
|
-
for (let index = 0; index < value.length; index += 1) {
|
|
3164
|
-
const unit = value.charCodeAt(index);
|
|
3165
|
-
if (unit >= 55296 && unit <= 56319) {
|
|
3166
|
-
const next = value.charCodeAt(index + 1);
|
|
3167
|
-
if (next >= 56320 && next <= 57343) {
|
|
3168
|
-
out += value[index] + value[index + 1];
|
|
3169
|
-
index += 1;
|
|
3170
|
-
} else {
|
|
3171
|
-
out += "\uFFFD";
|
|
3172
|
-
}
|
|
3173
|
-
} else if (unit >= 56320 && unit <= 57343) {
|
|
3174
|
-
out += "\uFFFD";
|
|
3175
|
-
} else {
|
|
3176
|
-
out += value[index];
|
|
3177
|
-
}
|
|
3178
|
-
}
|
|
3179
|
-
return out;
|
|
3180
|
-
}
|
|
3181
|
-
function isUnsafeTerminalCodePoint(point) {
|
|
3182
|
-
const c0OrC1 = point <= 31 || point >= 127 && point <= 159;
|
|
3183
|
-
const bidiOrZeroWidth = point === 173 || // soft hyphen
|
|
3184
|
-
point === 1564 || // Arabic letter mark
|
|
3185
|
-
point === 6158 || // Mongolian vowel separator
|
|
3186
|
-
point >= 8203 && point <= 8207 || // zero-width + directional marks
|
|
3187
|
-
point >= 8234 && point <= 8238 || // bidi embeddings/overrides
|
|
3188
|
-
point >= 8288 && point <= 8303 || // word joiner + bidi isolates/controls
|
|
3189
|
-
point >= 65529 && point <= 65531 || // interlinear annotation controls
|
|
3190
|
-
point === 65279 || // zero-width no-break space / BOM
|
|
3191
|
-
point >= 917504 && point <= 917631;
|
|
3192
|
-
return c0OrC1 || bidiOrZeroWidth;
|
|
3193
|
-
}
|
|
3194
|
-
function terminalSafeText(value) {
|
|
3195
|
-
return Array.from(replaceIsolatedSurrogates(value)).filter((character) => !isUnsafeTerminalCodePoint(character.codePointAt(0) ?? 0)).join("");
|
|
3196
|
-
}
|
|
3197
|
-
function terminalSafeLine(value) {
|
|
3198
|
-
return terminalSafeText(value.replace(/\s+/gu, " ")).replace(/\s+/gu, " ").trim();
|
|
3199
|
-
}
|
|
3200
|
-
function isTerminalSafeText(value) {
|
|
3201
|
-
return terminalSafeText(value) === value;
|
|
3202
|
-
}
|
|
3203
|
-
var stripControlChars = terminalSafeText;
|
|
3204
|
-
|
|
3205
4152
|
// src/client.ts
|
|
3206
4153
|
var CONFIG_DIR_MODE = 448;
|
|
3207
4154
|
var CREDENTIAL_FILE_MODE = 384;
|
|
3208
4155
|
var REFRESH_THRESHOLD_MS = 6e4;
|
|
3209
|
-
var
|
|
4156
|
+
var DEFAULT_API_URL3 = "https://api.getprimitive.ai";
|
|
3210
4157
|
var AUTH_EXPIRED_MESSAGE = "Authentication expired. Run `prim auth login` to re-authenticate.";
|
|
3211
4158
|
function authExpiredMessage() {
|
|
3212
4159
|
return isClaudeCloudSession() ? `Primitive credentials are missing or rejected in this Claude Code cloud session: ${CLOUD_CREDENTIALS_REMEDY}.` : AUTH_EXPIRED_MESSAGE;
|
|
@@ -3223,7 +4170,7 @@ function getSiteUrl() {
|
|
|
3223
4170
|
return getSiteUrlForEnvironment(process.env.PRIM_API_URL);
|
|
3224
4171
|
}
|
|
3225
4172
|
function getSiteUrlForEnvironment(primApiUrl) {
|
|
3226
|
-
return primApiUrl?.trim() ||
|
|
4173
|
+
return primApiUrl?.trim() || DEFAULT_API_URL3;
|
|
3227
4174
|
}
|
|
3228
4175
|
function expiresAtFor(token, expiresIn) {
|
|
3229
4176
|
return expiresIn === void 0 ? jwtExpiresAt(token) : Date.now() + expiresIn * 1e3;
|
|
@@ -3239,7 +4186,7 @@ function atomicWrite2(path, content) {
|
|
|
3239
4186
|
}
|
|
3240
4187
|
function removeCredentialFile(path) {
|
|
3241
4188
|
if (!existsSync10(path)) return false;
|
|
3242
|
-
|
|
4189
|
+
rmSync9(path, { force: true });
|
|
3243
4190
|
return true;
|
|
3244
4191
|
}
|
|
3245
4192
|
function getTokenExpiresAt() {
|
|
@@ -3254,23 +4201,23 @@ function isTokenExpiringSoon(credential) {
|
|
|
3254
4201
|
const expiresAt = getTokenExpiresAt();
|
|
3255
4202
|
return expiresAt !== void 0 && Date.now() >= expiresAt - REFRESH_THRESHOLD_MS;
|
|
3256
4203
|
}
|
|
3257
|
-
function refreshFingerprint(
|
|
3258
|
-
return
|
|
4204
|
+
function refreshFingerprint(refreshToken3) {
|
|
4205
|
+
return createHash8("sha256").update(refreshToken3).digest("hex");
|
|
3259
4206
|
}
|
|
3260
|
-
function legacyBrokerCredentialMetadata(accessToken,
|
|
4207
|
+
function legacyBrokerCredentialMetadata(accessToken, refreshToken3) {
|
|
3261
4208
|
return {
|
|
3262
4209
|
version: 1,
|
|
3263
4210
|
family: "legacy_broker",
|
|
3264
4211
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
3265
|
-
refreshTokenHash: refreshFingerprint(
|
|
4212
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
3266
4213
|
};
|
|
3267
4214
|
}
|
|
3268
|
-
function credentialFamilyMetadata(accessToken,
|
|
4215
|
+
function credentialFamilyMetadata(accessToken, refreshToken3, metadata) {
|
|
3269
4216
|
const hashes = {
|
|
3270
4217
|
accessTokenHash: refreshFingerprint(accessToken),
|
|
3271
|
-
refreshTokenHash: refreshFingerprint(
|
|
4218
|
+
refreshTokenHash: refreshFingerprint(refreshToken3)
|
|
3272
4219
|
};
|
|
3273
|
-
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken,
|
|
4220
|
+
return metadata === void 0 ? legacyBrokerCredentialMetadata(accessToken, refreshToken3) : { ...metadata, ...hashes };
|
|
3274
4221
|
}
|
|
3275
4222
|
function writeCredentialMigrationSentinel() {
|
|
3276
4223
|
atomicWrite2(
|
|
@@ -3282,11 +4229,11 @@ function writeCredentialMigrationSentinel() {
|
|
|
3282
4229
|
`
|
|
3283
4230
|
);
|
|
3284
4231
|
}
|
|
3285
|
-
function bindLegacyBrokerGeneration(accessToken,
|
|
3286
|
-
if (metadata.state !== "legacy_broker" || !accessToken || !
|
|
4232
|
+
function bindLegacyBrokerGeneration(accessToken, refreshToken3, metadata) {
|
|
4233
|
+
if (metadata.state !== "legacy_broker" || !accessToken || !refreshToken3) {
|
|
3287
4234
|
return { state: "invalid" };
|
|
3288
4235
|
}
|
|
3289
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
4236
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
3290
4237
|
if (metadata.metadata !== void 0 && (metadata.metadata.accessTokenHash !== familyMetadata.accessTokenHash || metadata.metadata.refreshTokenHash !== familyMetadata.refreshTokenHash)) {
|
|
3291
4238
|
return { state: "invalid" };
|
|
3292
4239
|
}
|
|
@@ -3303,17 +4250,17 @@ function preserveMarkerlessLegacyGeneration() {
|
|
|
3303
4250
|
const metadata = readStoredCredentialMetadata();
|
|
3304
4251
|
if (metadata.state !== "legacy_broker" || metadata.metadata !== void 0) return;
|
|
3305
4252
|
const accessToken = readTrimmed2(TOKEN_FILE_PATH);
|
|
3306
|
-
const
|
|
3307
|
-
if (!(accessToken &&
|
|
3308
|
-
const familyMetadata = legacyBrokerCredentialMetadata(accessToken,
|
|
4253
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
4254
|
+
if (!(accessToken && refreshToken3)) return;
|
|
4255
|
+
const familyMetadata = legacyBrokerCredentialMetadata(accessToken, refreshToken3);
|
|
3309
4256
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
3310
4257
|
`);
|
|
3311
4258
|
}
|
|
3312
4259
|
function terminalFingerprint() {
|
|
3313
4260
|
return readTrimmed2(TERMINAL_REFRESH_PATH);
|
|
3314
4261
|
}
|
|
3315
|
-
function writeTerminalFingerprint(
|
|
3316
|
-
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(
|
|
4262
|
+
function writeTerminalFingerprint(refreshToken3) {
|
|
4263
|
+
atomicWrite2(TERMINAL_REFRESH_PATH, `${refreshFingerprint(refreshToken3)}
|
|
3317
4264
|
`);
|
|
3318
4265
|
}
|
|
3319
4266
|
function clearTerminalFingerprint() {
|
|
@@ -3322,20 +4269,20 @@ function clearTerminalFingerprint() {
|
|
|
3322
4269
|
function isSessionEnded() {
|
|
3323
4270
|
if (hasMachineConfiguration()) return machineSessionEnded();
|
|
3324
4271
|
if (resolveAuthCredential()?.source !== "token_file") return false;
|
|
3325
|
-
const
|
|
4272
|
+
const refreshToken3 = readTrimmed2(REFRESH_TOKEN_PATH);
|
|
3326
4273
|
const ended = terminalFingerprint();
|
|
3327
|
-
return Boolean(
|
|
4274
|
+
return Boolean(refreshToken3 && ended && refreshFingerprint(refreshToken3) === ended);
|
|
3328
4275
|
}
|
|
3329
4276
|
function withCredentialLock(operation, options = {}) {
|
|
3330
4277
|
return withFileLock(CREDENTIAL_LOCK_PATH, operation, options);
|
|
3331
4278
|
}
|
|
3332
4279
|
function commitCredentialsUnlocked(credentials) {
|
|
3333
4280
|
const accessToken = credentials.accessToken.trim();
|
|
3334
|
-
const
|
|
3335
|
-
if (!accessToken || !
|
|
4281
|
+
const refreshToken3 = credentials.refreshToken.trim();
|
|
4282
|
+
if (!accessToken || !refreshToken3) {
|
|
3336
4283
|
throw new Error("OAuth credentials require both access and refresh tokens");
|
|
3337
4284
|
}
|
|
3338
|
-
const familyMetadata = credentialFamilyMetadata(accessToken,
|
|
4285
|
+
const familyMetadata = credentialFamilyMetadata(accessToken, refreshToken3, credentials.metadata);
|
|
3339
4286
|
if (credentials.metadata !== void 0) {
|
|
3340
4287
|
preserveMarkerlessLegacyGeneration();
|
|
3341
4288
|
writeCredentialMigrationSentinel();
|
|
@@ -3343,10 +4290,10 @@ function commitCredentialsUnlocked(credentials) {
|
|
|
3343
4290
|
`);
|
|
3344
4291
|
atomicWrite2(CREDENTIAL_METADATA_PATH, `${JSON.stringify(familyMetadata)}
|
|
3345
4292
|
`);
|
|
3346
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
4293
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
3347
4294
|
`);
|
|
3348
4295
|
} else {
|
|
3349
|
-
atomicWrite2(REFRESH_TOKEN_PATH, `${
|
|
4296
|
+
atomicWrite2(REFRESH_TOKEN_PATH, `${refreshToken3}
|
|
3350
4297
|
`);
|
|
3351
4298
|
atomicWrite2(CREDENTIAL_FAMILY_PATH, `${JSON.stringify(familyMetadata)}
|
|
3352
4299
|
`);
|
|
@@ -3383,15 +4330,15 @@ function refreshDiagnostic(response, detail, quiet, provider) {
|
|
|
3383
4330
|
`
|
|
3384
4331
|
);
|
|
3385
4332
|
}
|
|
3386
|
-
function metadataMatchesCredentialGeneration(expected, accessToken,
|
|
4333
|
+
function metadataMatchesCredentialGeneration(expected, accessToken, refreshToken3) {
|
|
3387
4334
|
const current = readStoredCredentialMetadata();
|
|
3388
4335
|
if (expected.state === "legacy_broker") {
|
|
3389
4336
|
if (current.state !== "legacy_broker") return false;
|
|
3390
4337
|
if (!expected.metadata) return current.metadata === void 0;
|
|
3391
|
-
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
4338
|
+
return current.metadata !== void 0 && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
3392
4339
|
}
|
|
3393
4340
|
if (expected.state !== "workos_connect" || current.state !== "workos_connect") return false;
|
|
3394
|
-
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(
|
|
4341
|
+
return current.metadata.issuer === expected.metadata.issuer && current.metadata.clientId === expected.metadata.clientId && current.metadata.accessTokenHash === refreshFingerprint(accessToken) && current.metadata.accessTokenHash === expected.metadata.accessTokenHash && current.metadata.refreshTokenHash === refreshFingerprint(refreshToken3) && current.metadata.refreshTokenHash === expected.metadata.refreshTokenHash;
|
|
3395
4342
|
}
|
|
3396
4343
|
function uncoordinatedLegacyWinnerAccessToken(expected, currentGeneration) {
|
|
3397
4344
|
if (!expected || readCredentialMigrationState() !== "valid") return void 0;
|
|
@@ -3560,7 +4507,7 @@ async function performTokenRefresh(options = {}) {
|
|
|
3560
4507
|
);
|
|
3561
4508
|
}
|
|
3562
4509
|
var _refreshInFlight;
|
|
3563
|
-
function
|
|
4510
|
+
function refreshToken2(options = {}) {
|
|
3564
4511
|
if (hasMachineConfiguration())
|
|
3565
4512
|
return acquireMachineCredential(options).then((credential) => credential?.accessToken);
|
|
3566
4513
|
if (_refreshInFlight) return _refreshInFlight;
|
|
@@ -3698,7 +4645,7 @@ async function machineClient(options = {}, management = false) {
|
|
|
3698
4645
|
if (response.status === 401)
|
|
3699
4646
|
throw new HttpError(
|
|
3700
4647
|
401,
|
|
3701
|
-
selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
4648
|
+
selected.session ? "Primitive rejected this cloud session's token after renewing it. To fix it, start a new cloud session, which identifies you again through GitHub." : selected.tokenInjection ? "Machine access was rejected. Check the cloud environment's OAuth 2.0 client credentials network secret, or mint a replacement credential if this one was revoked." : rejectedCredentialsMessage(
|
|
3702
4649
|
"Machine access was rejected. Ask your administrator to check or rotate its credentials."
|
|
3703
4650
|
)
|
|
3704
4651
|
);
|
|
@@ -3719,7 +4666,7 @@ async function request2(method, path, body, options) {
|
|
|
3719
4666
|
let refreshAttempted = false;
|
|
3720
4667
|
if (credential && isTokenExpiringSoon(credential)) {
|
|
3721
4668
|
refreshAttempted = true;
|
|
3722
|
-
const token = await
|
|
4669
|
+
const token = await refreshToken2({
|
|
3723
4670
|
signal: options?.signal,
|
|
3724
4671
|
quiet: options?.quietRefresh
|
|
3725
4672
|
});
|
|
@@ -3738,7 +4685,7 @@ async function request2(method, path, body, options) {
|
|
|
3738
4685
|
let retryToken = latest?.token !== tokenUsed ? latest?.token : void 0;
|
|
3739
4686
|
if (!retryToken && latest?.source === "token_file" && !refreshAttempted) {
|
|
3740
4687
|
refreshAttempted = true;
|
|
3741
|
-
retryToken = await
|
|
4688
|
+
retryToken = await refreshToken2({ signal: options?.signal, quiet: options?.quietRefresh });
|
|
3742
4689
|
}
|
|
3743
4690
|
if (retryToken) {
|
|
3744
4691
|
_cachedCredential = {
|
|
@@ -3758,7 +4705,7 @@ function getClient() {
|
|
|
3758
4705
|
}
|
|
3759
4706
|
|
|
3760
4707
|
// src/commands/claude-plugin.ts
|
|
3761
|
-
import { createHash as
|
|
4708
|
+
import { createHash as createHash11 } from "crypto";
|
|
3762
4709
|
import {
|
|
3763
4710
|
constants as constants4,
|
|
3764
4711
|
closeSync as closeSync3,
|
|
@@ -3771,11 +4718,11 @@ import {
|
|
|
3771
4718
|
readSync as readSync2,
|
|
3772
4719
|
readdirSync as readdirSync5,
|
|
3773
4720
|
realpathSync as realpathSync3,
|
|
3774
|
-
rmSync as
|
|
4721
|
+
rmSync as rmSync10,
|
|
3775
4722
|
rmdirSync as rmdirSync3
|
|
3776
4723
|
} from "fs";
|
|
3777
4724
|
import { homedir as homedir7 } from "os";
|
|
3778
|
-
import { dirname as dirname12, isAbsolute as isAbsolute6, join as
|
|
4725
|
+
import { dirname as dirname12, isAbsolute as isAbsolute6, join as join21, relative as relative2, resolve as resolve5, sep as sep2 } from "path";
|
|
3779
4726
|
import { fileURLToPath as fileURLToPath6 } from "url";
|
|
3780
4727
|
|
|
3781
4728
|
// node_modules/.pnpm/yaml@2.9.0/node_modules/yaml/browser/dist/nodes/identity.js
|
|
@@ -10046,7 +10993,7 @@ function parse(src, reviver, options) {
|
|
|
10046
10993
|
}
|
|
10047
10994
|
|
|
10048
10995
|
// src/commands/skill.ts
|
|
10049
|
-
import { createHash as
|
|
10996
|
+
import { createHash as createHash10 } from "crypto";
|
|
10050
10997
|
import {
|
|
10051
10998
|
constants as constants3,
|
|
10052
10999
|
closeSync as closeSync2,
|
|
@@ -10061,7 +11008,7 @@ import {
|
|
|
10061
11008
|
unlinkSync as unlinkSync2
|
|
10062
11009
|
} from "fs";
|
|
10063
11010
|
import { homedir as homedir6 } from "os";
|
|
10064
|
-
import { dirname as dirname11, join as
|
|
11011
|
+
import { dirname as dirname11, join as join20, resolve as resolve4 } from "path";
|
|
10065
11012
|
import { fileURLToPath as fileURLToPath5 } from "url";
|
|
10066
11013
|
|
|
10067
11014
|
// node_modules/.pnpm/diff@5.2.2/node_modules/diff/lib/index.mjs
|
|
@@ -10231,7 +11178,7 @@ Diff.prototype = {
|
|
|
10231
11178
|
tokenize: function tokenize(value) {
|
|
10232
11179
|
return value.split("");
|
|
10233
11180
|
},
|
|
10234
|
-
join: function
|
|
11181
|
+
join: function join18(chars) {
|
|
10235
11182
|
return chars.join("");
|
|
10236
11183
|
}
|
|
10237
11184
|
};
|
|
@@ -10416,11 +11363,11 @@ arrayDiff.join = arrayDiff.removeEmpty = function(value) {
|
|
|
10416
11363
|
};
|
|
10417
11364
|
|
|
10418
11365
|
// src/commands/welcome-skill.ts
|
|
10419
|
-
import { createHash as
|
|
11366
|
+
import { createHash as createHash9 } from "crypto";
|
|
10420
11367
|
import { existsSync as existsSync11, lstatSync as lstatSync8, readFileSync as readFileSync15, readdirSync as readdirSync3, rmdirSync, unlinkSync } from "fs";
|
|
10421
11368
|
import { homedir as homedir5 } from "os";
|
|
10422
|
-
import { dirname as dirname10, join as
|
|
10423
|
-
var WELCOME_SKILL_SOURCE =
|
|
11369
|
+
import { dirname as dirname10, join as join19 } from "path";
|
|
11370
|
+
var WELCOME_SKILL_SOURCE = join19("skills", "prim-welcome", "SKILL.md");
|
|
10424
11371
|
|
|
10425
11372
|
// src/commands/skill.ts
|
|
10426
11373
|
var __dirname = dirname11(fileURLToPath5(import.meta.url));
|
|
@@ -10455,10 +11402,10 @@ function readCodexGuidance(path) {
|
|
|
10455
11402
|
}
|
|
10456
11403
|
}
|
|
10457
11404
|
function effectiveCodexGuidance(scope) {
|
|
10458
|
-
const override = readCodexGuidance(
|
|
11405
|
+
const override = readCodexGuidance(join20(scope, "AGENTS.override.md"));
|
|
10459
11406
|
if (override === null) return null;
|
|
10460
11407
|
if (override !== void 0 && override.toString("utf8").trim().length > 0) return override;
|
|
10461
|
-
const base = readCodexGuidance(
|
|
11408
|
+
const base = readCodexGuidance(join20(scope, "AGENTS.md"));
|
|
10462
11409
|
return base ?? null;
|
|
10463
11410
|
}
|
|
10464
11411
|
function hasUsablePrimBlock(content, visibleBytes) {
|
|
@@ -10481,7 +11428,7 @@ function hasUsablePrimBlock(content, visibleBytes) {
|
|
|
10481
11428
|
}
|
|
10482
11429
|
function hasUsableCodexGuidance(projectRoot2) {
|
|
10483
11430
|
try {
|
|
10484
|
-
const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) :
|
|
11431
|
+
const codexHome = process.env.CODEX_HOME?.trim() ? resolve4(process.env.CODEX_HOME) : join20(homedir6(), ".codex");
|
|
10485
11432
|
const scopes = [
|
|
10486
11433
|
{ path: codexHome, visibleBytes: CODEX_GUIDANCE_LIMIT_BYTES },
|
|
10487
11434
|
{ path: projectRoot2, visibleBytes: CODEX_DEFAULT_PROJECT_GUIDANCE_BYTES }
|
|
@@ -10497,18 +11444,18 @@ function hasUsableCodexGuidance(projectRoot2) {
|
|
|
10497
11444
|
var CURSOR_SKILL_OWNER = "@primitive.ai/prim";
|
|
10498
11445
|
var CURSOR_SKILL_MANIFEST = ".prim-owned.json";
|
|
10499
11446
|
function sha256(content) {
|
|
10500
|
-
return
|
|
11447
|
+
return createHash10("sha256").update(content).digest("hex");
|
|
10501
11448
|
}
|
|
10502
11449
|
function cursorSkillDirectory(cwd, scope) {
|
|
10503
11450
|
const base = scope === "user" ? cursorConfigDirectory() : gitToplevel(cwd) ?? cwd;
|
|
10504
|
-
return
|
|
11451
|
+
return join20(base, scope === "user" ? "skills" : ".cursor/skills", "prim");
|
|
10505
11452
|
}
|
|
10506
11453
|
function cursorSkillPaths(cwd, scope) {
|
|
10507
11454
|
const directory = cursorSkillDirectory(cwd, scope);
|
|
10508
11455
|
return {
|
|
10509
11456
|
directory,
|
|
10510
|
-
skill:
|
|
10511
|
-
manifest:
|
|
11457
|
+
skill: join20(directory, "SKILL.md"),
|
|
11458
|
+
manifest: join20(directory, CURSOR_SKILL_MANIFEST)
|
|
10512
11459
|
};
|
|
10513
11460
|
}
|
|
10514
11461
|
function readCursorSkillManifest(path) {
|
|
@@ -10561,8 +11508,8 @@ var MAX_SKILL_BYTES = 1024 * 1024;
|
|
|
10561
11508
|
var REFRESH_LOCK_TIMEOUT_MS = 150;
|
|
10562
11509
|
var REFRESH_LOCK_POLL_MS = 10;
|
|
10563
11510
|
function pluginDirFor(cwd, scope) {
|
|
10564
|
-
const base = scope === "user" ?
|
|
10565
|
-
return
|
|
11511
|
+
const base = scope === "user" ? join21(homedir7(), ".claude") : join21(gitToplevel(cwd) ?? cwd, ".claude");
|
|
11512
|
+
return join21(base, "skills", "prim");
|
|
10566
11513
|
}
|
|
10567
11514
|
function packageVersion2() {
|
|
10568
11515
|
let dir = __dirname2;
|
|
@@ -10584,8 +11531,8 @@ function renderClaudePlugin() {
|
|
|
10584
11531
|
}
|
|
10585
11532
|
function pluginPaths(dir) {
|
|
10586
11533
|
return {
|
|
10587
|
-
manifestPath:
|
|
10588
|
-
skillPath:
|
|
11534
|
+
manifestPath: join21(dir, ".claude-plugin", "plugin.json"),
|
|
11535
|
+
skillPath: join21(dir, "SKILL.md")
|
|
10589
11536
|
};
|
|
10590
11537
|
}
|
|
10591
11538
|
function pathIsInside(root, path) {
|
|
@@ -10650,9 +11597,9 @@ function inspectRecognizedInstallation(paths, projectRoot2) {
|
|
|
10650
11597
|
};
|
|
10651
11598
|
}
|
|
10652
11599
|
function refreshLockDir(physicalPluginDir) {
|
|
10653
|
-
const cacheRoot = process.env.XDG_CACHE_HOME ||
|
|
10654
|
-
const identity =
|
|
10655
|
-
return
|
|
11600
|
+
const cacheRoot = process.env.XDG_CACHE_HOME || join21(homedir7(), ".cache");
|
|
11601
|
+
const identity = createHash11("sha256").update(physicalPluginDir).digest("hex");
|
|
11602
|
+
return join21(cacheRoot, "prim", "skill-refresh-locks", `${identity}.lock`);
|
|
10656
11603
|
}
|
|
10657
11604
|
async function refreshClaudePlugins(cwd, options = {}) {
|
|
10658
11605
|
const result = { installed: 0, refreshed: 0 };
|
|
@@ -10660,7 +11607,7 @@ async function refreshClaudePlugins(cwd, options = {}) {
|
|
|
10660
11607
|
if (options.includeProject !== false) {
|
|
10661
11608
|
const projectRoot2 = options.projectRoot ?? gitToplevel(cwd);
|
|
10662
11609
|
if (projectRoot2 !== null && isAbsolute6(projectRoot2)) {
|
|
10663
|
-
candidates.push({ dir:
|
|
11610
|
+
candidates.push({ dir: join21(projectRoot2, ".claude", "skills", "prim"), projectRoot: projectRoot2 });
|
|
10664
11611
|
}
|
|
10665
11612
|
}
|
|
10666
11613
|
candidates.push({ dir: pluginDirFor(cwd, "user") });
|
|
@@ -10723,13 +11670,13 @@ async function refreshClaudePlugins(cwd, options = {}) {
|
|
|
10723
11670
|
}
|
|
10724
11671
|
|
|
10725
11672
|
// src/daemon/principal.ts
|
|
10726
|
-
import { createHash as
|
|
11673
|
+
import { createHash as createHash12 } from "crypto";
|
|
10727
11674
|
var PRINCIPAL_COMPONENT_MAX_LENGTH = 512;
|
|
10728
11675
|
function boundedClaim(value) {
|
|
10729
11676
|
return typeof value === "string" && value.length > 0 && value.length <= PRINCIPAL_COMPONENT_MAX_LENGTH ? value : void 0;
|
|
10730
11677
|
}
|
|
10731
11678
|
function sha2562(value) {
|
|
10732
|
-
return
|
|
11679
|
+
return createHash12("sha256").update(value).digest("hex");
|
|
10733
11680
|
}
|
|
10734
11681
|
function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
|
|
10735
11682
|
if (hasMachineConfiguration()) {
|
|
@@ -10783,8 +11730,8 @@ function parseDaemonResponseEnvelope(value) {
|
|
|
10783
11730
|
|
|
10784
11731
|
// src/daemon/client.ts
|
|
10785
11732
|
import { createConnection } from "net";
|
|
10786
|
-
import { join as
|
|
10787
|
-
var SOCK_PATH =
|
|
11733
|
+
import { join as join22 } from "path";
|
|
11734
|
+
var SOCK_PATH = join22(primConfigDirectory(), "sock");
|
|
10788
11735
|
var DEFAULT_TIMEOUT_MS2 = 250;
|
|
10789
11736
|
var nextRequestId = 1;
|
|
10790
11737
|
function daemonRequest(method, params = {}, opts = {}) {
|
|
@@ -11093,13 +12040,13 @@ async function acknowledgeDecisionFeedback(input, dependencies = {}) {
|
|
|
11093
12040
|
// src/lib/bin-cache.ts
|
|
11094
12041
|
import { chmodSync as chmodSync5, mkdirSync as mkdirSync8 } from "fs";
|
|
11095
12042
|
import { homedir as homedir8 } from "os";
|
|
11096
|
-
import { join as
|
|
12043
|
+
import { join as join23 } from "path";
|
|
11097
12044
|
var GIT_HOOK_CACHE_SHELL_DIR = "${XDG_CACHE_HOME:-$HOME/.cache}/prim/bin";
|
|
11098
12045
|
var GIT_HOOK_CACHE_TTL_MINUTES = 1440;
|
|
11099
12046
|
var GIT_HOOK_CACHED_BINS = ["prim-post-commit", "prim-post-rewrite"];
|
|
11100
12047
|
function binCacheDir() {
|
|
11101
|
-
const base = process.env.XDG_CACHE_HOME ||
|
|
11102
|
-
return
|
|
12048
|
+
const base = process.env.XDG_CACHE_HOME || join23(homedir8(), ".cache");
|
|
12049
|
+
return join23(base, "prim", "bin");
|
|
11103
12050
|
}
|
|
11104
12051
|
function writeAtomic(path, content) {
|
|
11105
12052
|
atomicWriteFile(path, content, { mode: 384 });
|
|
@@ -11112,11 +12059,11 @@ function warmBinCache() {
|
|
|
11112
12059
|
const dir = binCacheDir();
|
|
11113
12060
|
mkdirSync8(dir, { recursive: true, mode: 448 });
|
|
11114
12061
|
chmodSync5(dir, 448);
|
|
11115
|
-
writeAtomic(
|
|
12062
|
+
writeAtomic(join23(dir, "node"), process.execPath);
|
|
11116
12063
|
for (const bin of GIT_HOOK_CACHED_BINS) {
|
|
11117
12064
|
const file = binFile(bin);
|
|
11118
12065
|
if (file) {
|
|
11119
|
-
writeAtomic(
|
|
12066
|
+
writeAtomic(join23(dir, bin), file);
|
|
11120
12067
|
}
|
|
11121
12068
|
}
|
|
11122
12069
|
} catch {
|
|
@@ -11164,11 +12111,14 @@ async function probe(url, fetchImpl) {
|
|
|
11164
12111
|
return { ok: false, failure: probeFailure(error) };
|
|
11165
12112
|
}
|
|
11166
12113
|
}
|
|
11167
|
-
function unreachable(what,
|
|
11168
|
-
if (
|
|
11169
|
-
if (
|
|
12114
|
+
function unreachable(what, failure2, remedy) {
|
|
12115
|
+
if (failure2 === "blocked") return `this environment cannot reach ${what}. To fix it, ${remedy}.`;
|
|
12116
|
+
if (failure2 === "timeout")
|
|
11170
12117
|
return `${what} did not answer in time. If this persists, check that you ${remedy.replace(/^add /u, "added ")}.`;
|
|
11171
|
-
return `${what} could not be reached (${
|
|
12118
|
+
return `${what} could not be reached (${failure2}). Check the environment's network access: ${remedy}.`;
|
|
12119
|
+
}
|
|
12120
|
+
function credentialRejected(error) {
|
|
12121
|
+
return error instanceof HttpError && error.status === 401;
|
|
11172
12122
|
}
|
|
11173
12123
|
async function diagnoseCloudSession(options = {}) {
|
|
11174
12124
|
const env = options.env ?? process.env;
|
|
@@ -11184,6 +12134,7 @@ async function diagnoseCloudSession(options = {}) {
|
|
|
11184
12134
|
}
|
|
11185
12135
|
if (!machine && !resolveStoredCredential(env))
|
|
11186
12136
|
return `${prefix}: it has no credentials. To fix it, ${CLOUD_CREDENTIALS_REMEDY}.`;
|
|
12137
|
+
if (machine && credentialRejected(options.bindFailure)) return CLOUD_REJECTED_CREDENTIALS_NOTICE;
|
|
11187
12138
|
if (options.cwd !== void 0 && !githubRepositoryFullName(options.cwd))
|
|
11188
12139
|
return `${prefix}: ${repositoryIdentityRemedy(options.cwd)}.`;
|
|
11189
12140
|
const fetchImpl = options.fetch ?? fetch;
|
|
@@ -38022,19 +38973,19 @@ async function fetchAndCacheCollectScope(cwd, dependencies = defaultDependencies
|
|
|
38022
38973
|
// src/lib/commit-heartbeat.ts
|
|
38023
38974
|
import { execFileSync as execFileSync6 } from "child_process";
|
|
38024
38975
|
import { mkdirSync as mkdirSync9, readFileSync as readFileSync18, readdirSync as readdirSync6, unlinkSync as unlinkSync3 } from "fs";
|
|
38025
|
-
import { dirname as dirname13, join as
|
|
38976
|
+
import { dirname as dirname13, join as join24, resolve as resolve6 } from "path";
|
|
38026
38977
|
var WIRED_PATH = "prim/git-hooks-wired";
|
|
38027
|
-
var
|
|
38978
|
+
var GIT_TIMEOUT_MS5 = 1e3;
|
|
38028
38979
|
var MAX_STAMP_BYTES = 1024;
|
|
38029
38980
|
function commonPath(cwd, relative4) {
|
|
38030
38981
|
const value = execFileSync6("git", ["rev-parse", "--git-common-dir"], {
|
|
38031
38982
|
cwd,
|
|
38032
38983
|
encoding: "utf8",
|
|
38033
38984
|
stdio: ["ignore", "pipe", "ignore"],
|
|
38034
|
-
timeout:
|
|
38985
|
+
timeout: GIT_TIMEOUT_MS5
|
|
38035
38986
|
}).replace(/\r?\n$/u, "");
|
|
38036
38987
|
if (value === "" || /[\0\r\n]/u.test(value)) throw new Error("Git returned an unsafe path");
|
|
38037
|
-
return
|
|
38988
|
+
return join24(resolve6(cwd, value), relative4);
|
|
38038
38989
|
}
|
|
38039
38990
|
function ensurePrivateParent(path) {
|
|
38040
38991
|
mkdirSync9(dirname13(dirname13(path)), { recursive: true, mode: 448 });
|
|
@@ -38072,7 +39023,7 @@ function clearHooksWired(cwd) {
|
|
|
38072
39023
|
|
|
38073
39024
|
// src/lib/git-hooks.ts
|
|
38074
39025
|
import { execFileSync as execFileSync7 } from "child_process";
|
|
38075
|
-
import { createHash as
|
|
39026
|
+
import { createHash as createHash13, randomUUID as randomUUID3 } from "crypto";
|
|
38076
39027
|
import {
|
|
38077
39028
|
constants as constants5,
|
|
38078
39029
|
closeSync as closeSync4,
|
|
@@ -38088,7 +39039,7 @@ import {
|
|
|
38088
39039
|
unlinkSync as unlinkSync4,
|
|
38089
39040
|
writeFileSync as writeFileSync6
|
|
38090
39041
|
} from "fs";
|
|
38091
|
-
import { basename as basename3, dirname as dirname14, isAbsolute as isAbsolute8, join as
|
|
39042
|
+
import { basename as basename3, dirname as dirname14, isAbsolute as isAbsolute8, join as join25, relative as relative3, resolve as resolve7, sep as sep3 } from "path";
|
|
38092
39043
|
|
|
38093
39044
|
// src/lib/git-hook-legacy.ts
|
|
38094
39045
|
import { isAbsolute as isAbsolute7 } from "path";
|
|
@@ -38267,7 +39218,7 @@ var LEGACY_PRIM_CREATED_MARK = "prim-created-hook";
|
|
|
38267
39218
|
var LEGACY_PRIM_OWNED_HEADER = "# prim post-commit hook \u2014 installed by: prim hooks install (prim-managed-hook)";
|
|
38268
39219
|
var LEGACY_GLOBAL_OWNED_HEADER = "# prim global post-commit hook (core.hooksPath) \u2014 managed by prim; do not edit.";
|
|
38269
39220
|
var MAX_HOOK_BYTES = 1048576;
|
|
38270
|
-
var
|
|
39221
|
+
var GIT_TIMEOUT_MS6 = 1e3;
|
|
38271
39222
|
var SUPPORTED_SHEBANGS = /* @__PURE__ */ new Set([
|
|
38272
39223
|
"#!/bin/sh",
|
|
38273
39224
|
"#!/usr/bin/env sh",
|
|
@@ -38317,7 +39268,7 @@ function gitHooksMode(options = {}) {
|
|
|
38317
39268
|
cwd: options.cwd,
|
|
38318
39269
|
encoding: "utf8",
|
|
38319
39270
|
stdio: ["ignore", "pipe", "ignore"],
|
|
38320
|
-
timeout:
|
|
39271
|
+
timeout: GIT_TIMEOUT_MS6
|
|
38321
39272
|
}
|
|
38322
39273
|
).trim();
|
|
38323
39274
|
return value === "manual" ? "manual" : "auto";
|
|
@@ -38397,7 +39348,7 @@ function realpathLoose(path) {
|
|
|
38397
39348
|
let current = resolve7(path);
|
|
38398
39349
|
for (; ; ) {
|
|
38399
39350
|
try {
|
|
38400
|
-
return
|
|
39351
|
+
return join25(realpathSync4.native(current), ...missing);
|
|
38401
39352
|
} catch {
|
|
38402
39353
|
const parent = dirname14(current);
|
|
38403
39354
|
if (parent === current) return resolve7(path);
|
|
@@ -38412,7 +39363,7 @@ function isWithin(path, directory) {
|
|
|
38412
39363
|
}
|
|
38413
39364
|
function primGitHooksDirectory() {
|
|
38414
39365
|
try {
|
|
38415
|
-
return
|
|
39366
|
+
return join25(primConfigDirectory(), "git-hooks");
|
|
38416
39367
|
} catch {
|
|
38417
39368
|
return void 0;
|
|
38418
39369
|
}
|
|
@@ -38424,7 +39375,7 @@ function otherWorktreeRoots(gitRoot) {
|
|
|
38424
39375
|
cwd: gitRoot,
|
|
38425
39376
|
encoding: "utf8",
|
|
38426
39377
|
stdio: ["ignore", "pipe", "ignore"],
|
|
38427
|
-
timeout:
|
|
39378
|
+
timeout: GIT_TIMEOUT_MS6
|
|
38428
39379
|
}).split("\n").flatMap((line) => line.startsWith("worktree ") ? [realpathLoose(line.slice(9))] : []).filter((root) => root !== self);
|
|
38429
39380
|
} catch {
|
|
38430
39381
|
return [];
|
|
@@ -38458,7 +39409,7 @@ function resolveEffectiveGitHook(hookName, cwd = process.cwd()) {
|
|
|
38458
39409
|
cwd: gitRoot,
|
|
38459
39410
|
encoding: "utf8",
|
|
38460
39411
|
stdio: ["ignore", "pipe", "ignore"],
|
|
38461
|
-
timeout:
|
|
39412
|
+
timeout: GIT_TIMEOUT_MS6
|
|
38462
39413
|
}
|
|
38463
39414
|
).replace(/\r?\n$/u, "").split(/\r?\n/u);
|
|
38464
39415
|
if (lines.length !== 3) throw new Error("Git returned unexpected repository paths");
|
|
@@ -38515,7 +39466,7 @@ function assertUsableHuskyDispatcher(target, spec) {
|
|
|
38515
39466
|
const huskyRuntime = resolve7(dirname14(target.dispatcherPath), "h");
|
|
38516
39467
|
const runtimeStat = assertSafeFile(huskyRuntime, spec);
|
|
38517
39468
|
const runtime = runtimeStat ? readHookFile(huskyRuntime) : void 0;
|
|
38518
|
-
const runtimeHash = runtime ?
|
|
39469
|
+
const runtimeHash = runtime ? createHash13("sha256").update(runtime).digest("hex") : void 0;
|
|
38519
39470
|
if (!runtimeHash || !HUSKY_V9_RUNTIME_HASHES.has(runtimeHash)) {
|
|
38520
39471
|
throw new Error(`unrecognized Husky v9 hook runtime: ${huskyRuntime}`);
|
|
38521
39472
|
}
|
|
@@ -38593,7 +39544,7 @@ function blockInsertionPoint(content, spec, huskyV8) {
|
|
|
38593
39544
|
var HUSKY_SPEC_MAJOR_RE = /^\s*[~^]?=?\s*v?([0-9]+)(?:\.(?:[0-9]+|[xX*])){0,2}(?:-[0-9A-Za-z.-]+)?\s*$/u;
|
|
38594
39545
|
function declaredHuskyMajor(dir) {
|
|
38595
39546
|
for (let current = resolve7(dir); ; ) {
|
|
38596
|
-
const manifest =
|
|
39547
|
+
const manifest = join25(current, "package.json");
|
|
38597
39548
|
if (existsSync14(manifest)) {
|
|
38598
39549
|
try {
|
|
38599
39550
|
if (lstatSync11(manifest).size > MAX_HOOK_BYTES) return void 0;
|
|
@@ -38606,12 +39557,12 @@ function declaredHuskyMajor(dir) {
|
|
|
38606
39557
|
}
|
|
38607
39558
|
}
|
|
38608
39559
|
const parent = dirname14(current);
|
|
38609
|
-
if (parent === current || existsSync14(
|
|
39560
|
+
if (parent === current || existsSync14(join25(current, ".git"))) return void 0;
|
|
38610
39561
|
current = parent;
|
|
38611
39562
|
}
|
|
38612
39563
|
}
|
|
38613
39564
|
function isHuskyV8Hook(hookPath) {
|
|
38614
|
-
const runtime =
|
|
39565
|
+
const runtime = join25(dirname14(hookPath), "_", "husky.sh");
|
|
38615
39566
|
try {
|
|
38616
39567
|
const stat = lstatSync11(runtime);
|
|
38617
39568
|
return stat.isFile() && stat.size <= MAX_HOOK_BYTES && readFileSync19(runtime, "utf8").includes("husky_skip_init");
|
|
@@ -38939,8 +39890,8 @@ import {
|
|
|
38939
39890
|
unlinkSync as unlinkSync5,
|
|
38940
39891
|
writeFileSync as writeFileSync7
|
|
38941
39892
|
} from "fs";
|
|
38942
|
-
import { dirname as dirname15, isAbsolute as isAbsolute9, join as
|
|
38943
|
-
var WORKSPACE_ID_RELATIVE_PATH =
|
|
39893
|
+
import { dirname as dirname15, isAbsolute as isAbsolute9, join as join26, resolve as resolve8 } from "path";
|
|
39894
|
+
var WORKSPACE_ID_RELATIVE_PATH = join26("prim", "workspace-id");
|
|
38944
39895
|
var MAX_ANCESTORS = 64;
|
|
38945
39896
|
var MAX_GIT_FILE_BYTES = 4096;
|
|
38946
39897
|
var MAX_ID_FILE_BYTES = 128;
|
|
@@ -38999,11 +39950,11 @@ function resolveWorkspaceIdPath(cwd) {
|
|
|
38999
39950
|
function resolveFromFilesystem(cwd) {
|
|
39000
39951
|
let current = resolve8(cwd);
|
|
39001
39952
|
for (let depth = 0; depth < MAX_ANCESTORS; depth += 1) {
|
|
39002
|
-
const dotGit =
|
|
39953
|
+
const dotGit = join26(current, ".git");
|
|
39003
39954
|
try {
|
|
39004
39955
|
const stat = lstatSync12(dotGit);
|
|
39005
39956
|
if (stat.isDirectory() && isGitDirectory(dotGit)) {
|
|
39006
|
-
return
|
|
39957
|
+
return join26(dotGit, WORKSPACE_ID_RELATIVE_PATH);
|
|
39007
39958
|
}
|
|
39008
39959
|
if (stat.isFile() && stat.size <= MAX_GIT_FILE_BYTES) {
|
|
39009
39960
|
const contents = readFileSync20(dotGit, "utf8");
|
|
@@ -39011,7 +39962,7 @@ function resolveFromFilesystem(cwd) {
|
|
|
39011
39962
|
if (match?.[1]) {
|
|
39012
39963
|
const gitDirectory = isAbsolute9(match[1]) ? resolve8(match[1]) : resolve8(current, match[1]);
|
|
39013
39964
|
if (isGitDirectory(gitDirectory)) {
|
|
39014
|
-
return
|
|
39965
|
+
return join26(gitDirectory, WORKSPACE_ID_RELATIVE_PATH);
|
|
39015
39966
|
}
|
|
39016
39967
|
}
|
|
39017
39968
|
}
|
|
@@ -39030,7 +39981,7 @@ function resolveFromFilesystem(cwd) {
|
|
|
39030
39981
|
}
|
|
39031
39982
|
function isGitDirectory(path) {
|
|
39032
39983
|
try {
|
|
39033
|
-
return statSync3(
|
|
39984
|
+
return statSync3(join26(path, "HEAD")).isFile();
|
|
39034
39985
|
} catch {
|
|
39035
39986
|
return false;
|
|
39036
39987
|
}
|
|
@@ -39068,7 +40019,7 @@ function inspectPath(path) {
|
|
|
39068
40019
|
function createWorkspaceId(path) {
|
|
39069
40020
|
const parent = dirname15(path);
|
|
39070
40021
|
const workspaceId = randomUUID4();
|
|
39071
|
-
const temporaryPath =
|
|
40022
|
+
const temporaryPath = join26(parent, `.workspace-id-${process.pid}-${randomUUID4()}.tmp`);
|
|
39072
40023
|
let temporaryCreated = false;
|
|
39073
40024
|
let publishing = false;
|
|
39074
40025
|
try {
|
|
@@ -39128,7 +40079,7 @@ function errorCode2(error) {
|
|
|
39128
40079
|
}
|
|
39129
40080
|
|
|
39130
40081
|
// src/hooks/codex-context.ts
|
|
39131
|
-
import { createHash as
|
|
40082
|
+
import { createHash as createHash14, randomBytes as randomBytes7 } from "crypto";
|
|
39132
40083
|
import {
|
|
39133
40084
|
chmodSync as chmodSync7,
|
|
39134
40085
|
existsSync as existsSync15,
|
|
@@ -39136,12 +40087,12 @@ import {
|
|
|
39136
40087
|
readFileSync as readFileSync21,
|
|
39137
40088
|
readdirSync as readdirSync7,
|
|
39138
40089
|
renameSync as renameSync4,
|
|
39139
|
-
rmSync as
|
|
40090
|
+
rmSync as rmSync11,
|
|
39140
40091
|
statSync as statSync4,
|
|
39141
40092
|
unlinkSync as unlinkSync6,
|
|
39142
40093
|
writeFileSync as writeFileSync8
|
|
39143
40094
|
} from "fs";
|
|
39144
|
-
import { join as
|
|
40095
|
+
import { join as join27 } from "path";
|
|
39145
40096
|
|
|
39146
40097
|
// src/daemon/decision-digest-cache.ts
|
|
39147
40098
|
import { randomBytes as randomBytes6 } from "crypto";
|
|
@@ -39294,10 +40245,10 @@ var STATE_VERSION = 1;
|
|
|
39294
40245
|
var DRAFT_STATE_VERSION = 2;
|
|
39295
40246
|
var NO_CURSOR = -1;
|
|
39296
40247
|
function stateRoot(namespace) {
|
|
39297
|
-
return
|
|
40248
|
+
return join27(primConfigDirectory(), namespace, "decision-digests");
|
|
39298
40249
|
}
|
|
39299
40250
|
function draftStateRoot(namespace) {
|
|
39300
|
-
return
|
|
40251
|
+
return join27(primConfigDirectory(), namespace, "decision-draft-deliveries");
|
|
39301
40252
|
}
|
|
39302
40253
|
function workspaceFor(cwd) {
|
|
39303
40254
|
try {
|
|
@@ -39308,13 +40259,13 @@ function workspaceFor(cwd) {
|
|
|
39308
40259
|
}
|
|
39309
40260
|
function statePath(args) {
|
|
39310
40261
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
|
|
39311
|
-
const key =
|
|
39312
|
-
return
|
|
40262
|
+
const key = createHash14("sha256").update(identity).digest("hex");
|
|
40263
|
+
return join27(stateRoot(args.namespace), `${key}.json`);
|
|
39313
40264
|
}
|
|
39314
40265
|
function draftStatePath(args) {
|
|
39315
40266
|
const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
|
|
39316
|
-
const key =
|
|
39317
|
-
return
|
|
40267
|
+
const key = createHash14("sha256").update(identity).digest("hex");
|
|
40268
|
+
return join27(draftStateRoot(args.namespace), `${key}.json`);
|
|
39318
40269
|
}
|
|
39319
40270
|
function parseState(value) {
|
|
39320
40271
|
if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
|
|
@@ -39352,7 +40303,7 @@ function parseDraftState(value) {
|
|
|
39352
40303
|
updatedAt: record.updatedAt
|
|
39353
40304
|
};
|
|
39354
40305
|
}
|
|
39355
|
-
function
|
|
40306
|
+
function readState2(path) {
|
|
39356
40307
|
if (!existsSync15(path)) return void 0;
|
|
39357
40308
|
try {
|
|
39358
40309
|
return parseState(JSON.parse(readFileSync21(path, "utf8")));
|
|
@@ -39371,7 +40322,7 @@ function readDraftState(path) {
|
|
|
39371
40322
|
function writeStateFile(path, directory, state) {
|
|
39372
40323
|
mkdirSync12(directory, { recursive: true, mode: 448 });
|
|
39373
40324
|
chmodSync7(directory, 448);
|
|
39374
|
-
const temporary =
|
|
40325
|
+
const temporary = join27(
|
|
39375
40326
|
directory,
|
|
39376
40327
|
`.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes7(8).toString("hex")}`
|
|
39377
40328
|
);
|
|
@@ -39402,7 +40353,7 @@ function cleanupStateFiles(directory, now) {
|
|
|
39402
40353
|
const files = [];
|
|
39403
40354
|
const residue = [];
|
|
39404
40355
|
for (const name of names) {
|
|
39405
|
-
const path =
|
|
40356
|
+
const path = join27(directory, name);
|
|
39406
40357
|
try {
|
|
39407
40358
|
const mtimeMs = statSync4(path).mtimeMs;
|
|
39408
40359
|
if (name.endsWith(".json")) {
|
|
@@ -39424,7 +40375,7 @@ function cleanupStateFiles(directory, now) {
|
|
|
39424
40375
|
for (const path of residue) {
|
|
39425
40376
|
try {
|
|
39426
40377
|
if (now - statSync4(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
|
|
39427
|
-
|
|
40378
|
+
rmSync11(path, { recursive: true, force: true });
|
|
39428
40379
|
}
|
|
39429
40380
|
} catch {
|
|
39430
40381
|
}
|
|
@@ -39510,7 +40461,7 @@ async function commitState(path, args, namespace) {
|
|
|
39510
40461
|
await withFileLock(
|
|
39511
40462
|
`${path}.lock`,
|
|
39512
40463
|
() => {
|
|
39513
|
-
const latest =
|
|
40464
|
+
const latest = readState2(path);
|
|
39514
40465
|
writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
|
|
39515
40466
|
cleanupStateFiles(stateRoot(namespace), args.now);
|
|
39516
40467
|
},
|
|
@@ -39557,7 +40508,7 @@ async function prepareCodexContext(options) {
|
|
|
39557
40508
|
const siteUrl = getSiteUrl();
|
|
39558
40509
|
const workspace = workspaceFor(options.cwd);
|
|
39559
40510
|
const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
|
|
39560
|
-
const previous =
|
|
40511
|
+
const previous = readState2(path);
|
|
39561
40512
|
const principal = resolveDaemonPrincipal();
|
|
39562
40513
|
const privatePath = principal ? draftStatePath({
|
|
39563
40514
|
cwd: options.cwd,
|
|
@@ -39707,7 +40658,7 @@ async function prepareCodexContext(options) {
|
|
|
39707
40658
|
}
|
|
39708
40659
|
|
|
39709
40660
|
// src/hooks/normalize.ts
|
|
39710
|
-
import { createHash as
|
|
40661
|
+
import { createHash as createHash15 } from "crypto";
|
|
39711
40662
|
import { realpathSync as realpathSync5 } from "fs";
|
|
39712
40663
|
import { isAbsolute as isAbsolute10, resolve as resolve9 } from "path";
|
|
39713
40664
|
var HERMES_EVENT_MAP = {
|
|
@@ -39752,7 +40703,7 @@ function requiredId(value, field) {
|
|
|
39752
40703
|
}
|
|
39753
40704
|
function cursorToolUseId(value) {
|
|
39754
40705
|
if (SAFE_CORRELATION_ID_RE.test(value)) return value;
|
|
39755
|
-
return `cursor:tool:v1:${
|
|
40706
|
+
return `cursor:tool:v1:${createHash15("sha256").update(value).digest("hex")}`;
|
|
39756
40707
|
}
|
|
39757
40708
|
function workspaceCandidates(value) {
|
|
39758
40709
|
if (!Array.isArray(value)) return [];
|
|
@@ -39849,7 +40800,7 @@ function normalizeEnvelope(parsed, agent) {
|
|
|
39849
40800
|
]);
|
|
39850
40801
|
return {
|
|
39851
40802
|
...parsed,
|
|
39852
|
-
tool_use_id: `codex:fallback:v1:${
|
|
40803
|
+
tool_use_id: `codex:fallback:v1:${createHash15("sha256").update(stableToolIdentity).digest("hex")}`
|
|
39853
40804
|
};
|
|
39854
40805
|
}
|
|
39855
40806
|
return parsed;
|
|
@@ -39865,11 +40816,18 @@ function normalizeEnvelope(parsed, agent) {
|
|
|
39865
40816
|
}
|
|
39866
40817
|
|
|
39867
40818
|
// src/hooks/reauth-notice.ts
|
|
40819
|
+
function sharedEnvironment() {
|
|
40820
|
+
try {
|
|
40821
|
+
return sessionIdentityMode();
|
|
40822
|
+
} catch {
|
|
40823
|
+
return false;
|
|
40824
|
+
}
|
|
40825
|
+
}
|
|
39868
40826
|
var REAUTH_NOTICE = "[prim] authentication ended \u2014 run `prim auth login` to resume decision capture";
|
|
39869
40827
|
function reauthNoticeFields(agent) {
|
|
39870
40828
|
if (agent === "claude_code") {
|
|
39871
40829
|
if (isClaudeCloudSession()) {
|
|
39872
|
-
const notice = `Primitive is not connected in this Claude Code cloud session:
|
|
40830
|
+
const notice = !hasMachineConfiguration() ? `Primitive is not connected in this Claude Code cloud session: its sign-in ended. To fix it, ${CLOUD_CREDENTIALS_REMEDY}.` : sharedEnvironment() ? `Primitive is not connected in this Claude Code cloud session: its environment credential was rejected. To fix it, ${ENVIRONMENT_CREDENTIAL_REMEDY}.` : CLOUD_REJECTED_CREDENTIALS_NOTICE;
|
|
39873
40831
|
return {
|
|
39874
40832
|
systemMessage: notice,
|
|
39875
40833
|
additionalContext: `${notice} Tell the user this in one sentence before starting their task.`
|
|
@@ -39886,6 +40844,18 @@ function reauthNoticeFields(agent) {
|
|
|
39886
40844
|
var DAEMON_TIMEOUT_MS = 250;
|
|
39887
40845
|
var REPOSITORY_BIND_TIMEOUT_MS = 1e3;
|
|
39888
40846
|
var CLOUD_REPOSITORY_BIND_TIMEOUT_MS = 1e4;
|
|
40847
|
+
var SESSION_IDENTITY_TIMEOUT_MS = 35e3;
|
|
40848
|
+
function sessionIdentityNotice(outcome) {
|
|
40849
|
+
if (!outcome || outcome.status === "ok") return void 0;
|
|
40850
|
+
const notice = `${sessionIdentityMessage(outcome)} Until then, nothing this session captures is sent to Primitive.`;
|
|
40851
|
+
return outcome.status === "link_required" ? {
|
|
40852
|
+
notice,
|
|
40853
|
+
instruction: `${notice} Before starting their task, tell the user this in one sentence. When they agree, run \`prim auth link\` as a background command (it waits until they finish signing in), and give them the sign-in URL and code it prints as soon as they appear.`
|
|
40854
|
+
} : {
|
|
40855
|
+
notice,
|
|
40856
|
+
instruction: `${notice} Tell the user this in one sentence before starting their task.`
|
|
40857
|
+
};
|
|
40858
|
+
}
|
|
39889
40859
|
var PRIM_TRIGGER = "When this task chooses between plausible approaches or establishes or changes a lasting goal, priority, constraint, invariant, default, commitment, tradeoff, exception, or shared instruction";
|
|
39890
40860
|
var PRIM_EXCLUSIONS = "Never invoke `prim` for routine implementation that merely follows an existing decision made before this task or for temporary tactics; they never qualify, including for evaluation.";
|
|
39891
40861
|
function primReminder(action, rationaleAction) {
|
|
@@ -39938,9 +40908,9 @@ async function activeProjectRoot(cwd) {
|
|
|
39938
40908
|
} catch {
|
|
39939
40909
|
}
|
|
39940
40910
|
return { root, binding };
|
|
39941
|
-
} catch {
|
|
40911
|
+
} catch (error) {
|
|
40912
|
+
return { root, bindFailure: error };
|
|
39942
40913
|
}
|
|
39943
|
-
return { root };
|
|
39944
40914
|
} catch {
|
|
39945
40915
|
return null;
|
|
39946
40916
|
}
|
|
@@ -39987,11 +40957,31 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
39987
40957
|
let active = false;
|
|
39988
40958
|
let skillState = { installed: 0, refreshed: 0 };
|
|
39989
40959
|
let claudeBinding;
|
|
40960
|
+
let bindFailure;
|
|
40961
|
+
let identityNotice;
|
|
39990
40962
|
if (agent === "claude_code") {
|
|
40963
|
+
let identityMode = false;
|
|
40964
|
+
try {
|
|
40965
|
+
identityMode = sessionIdentityMode();
|
|
40966
|
+
} catch {
|
|
40967
|
+
}
|
|
40968
|
+
if (identityMode) {
|
|
40969
|
+
try {
|
|
40970
|
+
identityNotice = sessionIdentityNotice(
|
|
40971
|
+
await ensureSessionIdentity({
|
|
40972
|
+
cwd,
|
|
40973
|
+
explicit: true,
|
|
40974
|
+
signal: AbortSignal.timeout(SESSION_IDENTITY_TIMEOUT_MS)
|
|
40975
|
+
})
|
|
40976
|
+
);
|
|
40977
|
+
} catch {
|
|
40978
|
+
}
|
|
40979
|
+
}
|
|
39991
40980
|
const activeProject = await activeProjectRoot(cwd);
|
|
39992
40981
|
projectRoot2 = activeProject?.root ?? null;
|
|
39993
40982
|
active = projectRoot2 !== null;
|
|
39994
40983
|
claudeBinding = activeProject?.binding;
|
|
40984
|
+
bindFailure = activeProject?.bindFailure;
|
|
39995
40985
|
try {
|
|
39996
40986
|
skillState = await refreshClaudePlugins(
|
|
39997
40987
|
cwd,
|
|
@@ -40000,7 +40990,7 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
40000
40990
|
} catch {
|
|
40001
40991
|
}
|
|
40002
40992
|
}
|
|
40003
|
-
if (isSessionEnded() && agent !== "codex" && agent !== "cursor") {
|
|
40993
|
+
if (isSessionEnded() && agent !== "codex" && agent !== "cursor" && !identityNotice) {
|
|
40004
40994
|
const notice = reauthNoticeFields(agent);
|
|
40005
40995
|
if (notice) {
|
|
40006
40996
|
return {
|
|
@@ -40063,15 +41053,15 @@ async function processSessionStart(raw, agent, feedbackSignal) {
|
|
|
40063
41053
|
};
|
|
40064
41054
|
}
|
|
40065
41055
|
if (agent === "claude_code") {
|
|
40066
|
-
let cloudNotice;
|
|
40067
|
-
if (active && !claudeBinding && isClaudeCloudSession()) {
|
|
41056
|
+
let cloudNotice = identityNotice?.notice;
|
|
41057
|
+
if (active && !claudeBinding && isClaudeCloudSession() && !identityNotice) {
|
|
40068
41058
|
try {
|
|
40069
|
-
cloudNotice = await diagnoseCloudSession({ cwd: projectRoot2 ?? cwd });
|
|
41059
|
+
cloudNotice = await diagnoseCloudSession({ cwd: projectRoot2 ?? cwd, bindFailure });
|
|
40070
41060
|
} catch {
|
|
40071
41061
|
}
|
|
40072
41062
|
}
|
|
40073
41063
|
const additionalContext = [
|
|
40074
|
-
cloudNotice ? `${cloudNotice} Tell the user this in one sentence before starting their task.` : void 0,
|
|
41064
|
+
identityNotice ? identityNotice.instruction : cloudNotice ? `${cloudNotice} Tell the user this in one sentence before starting their task.` : void 0,
|
|
40075
41065
|
claudeBinding ? claudeBindingReminder(claudeBinding, isClaudeCloudSession()) : void 0,
|
|
40076
41066
|
active && skillState.installed > 0 ? PRIM_SKILL_REMINDER : void 0
|
|
40077
41067
|
].filter((value) => value !== void 0).join("\n\n");
|