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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +90 -0
  2. package/dist/{chunk-RUEIVZ6T.js → chunk-2BEUR3DU.js} +2 -2
  3. package/dist/{chunk-5ME3WD3P.js → chunk-6KXQQ7CQ.js} +6 -3
  4. package/dist/{chunk-CWV5ZQR6.js → chunk-6OPSSJHO.js} +5 -5
  5. package/dist/{chunk-4NUGCUQC.js → chunk-74DQDWLW.js} +2 -2
  6. package/dist/{chunk-WN7OURQ3.js → chunk-BFYJLI7V.js} +1 -1
  7. package/dist/{chunk-T2T45KF6.js → chunk-DT7E3SD5.js} +4 -4
  8. package/dist/{chunk-DQ4I3FLF.js → chunk-EZXIKEMA.js} +3 -3
  9. package/dist/{chunk-4M23K2KZ.js → chunk-FYYHBOOM.js} +2 -2
  10. package/dist/{chunk-3WQ7SBOZ.js → chunk-HPA7RGSZ.js} +3 -3
  11. package/dist/{chunk-NL5VU7EU.js → chunk-JFWJN2ME.js} +3 -3
  12. package/dist/{chunk-GOMEWFMG.js → chunk-L32WYFJT.js} +143 -61
  13. package/dist/{chunk-OXW6PSPT.js → chunk-NBNQI3YJ.js} +15 -3
  14. package/dist/{chunk-LOFMI3D4.js → chunk-ND6TYHNI.js} +2 -2
  15. package/dist/{chunk-4GYJHN26.js → chunk-NJBN3WXF.js} +1607 -549
  16. package/dist/{chunk-HLMC7VS4.js → chunk-O73J3KQQ.js} +5702 -2860
  17. package/dist/{chunk-JZC2LHS6.js → chunk-PPZ56EVJ.js} +1 -1
  18. package/dist/{chunk-FXXMDO7D.js → chunk-R35M4RCY.js} +4 -4
  19. package/dist/chunk-TI37ME2D.js +210 -0
  20. package/dist/{chunk-NMZSCSMY.js → chunk-YP4OXKNX.js} +13 -1
  21. package/dist/{chunk-S3ZIMGXV.js → chunk-ZKXNJB6U.js} +76 -2
  22. package/dist/daemon/server.js +12321 -8354
  23. package/dist/hook-runtime/daemon/server.js +12321 -8354
  24. package/dist/hook-runtime/hooks/post-commit.js +6743 -3634
  25. package/dist/hook-runtime/hooks/post-rewrite.js +6776 -3668
  26. package/dist/hook-runtime/hooks/post-tool-use.js +7108 -3140
  27. package/dist/hook-runtime/hooks/pre-commit.js +1263 -280
  28. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +15115 -11297
  29. package/dist/hook-runtime/hooks/prim-hook.js +10879 -7024
  30. package/dist/hook-runtime/hooks/session-end.js +399 -139
  31. package/dist/hook-runtime/hooks/session-start.js +13277 -9454
  32. package/dist/hook-runtime/index.js +17575 -13050
  33. package/dist/hook-runtime/statusline-main.js +375 -122
  34. package/dist/hooks/post-commit.js +7 -7
  35. package/dist/hooks/post-rewrite.js +6 -6
  36. package/dist/hooks/post-tool-use.js +31 -21
  37. package/dist/hooks/pre-commit.js +4 -4
  38. package/dist/hooks/pre-tool-use-worker.js +9 -9
  39. package/dist/hooks/prim-hook.js +16 -16
  40. package/dist/hooks/session-end.js +4 -4
  41. package/dist/hooks/session-start.js +16 -12
  42. package/dist/index.js +9124 -8763
  43. package/dist/statusline-main.js +375 -122
  44. package/package.json +3 -1
  45. package/dist/chunk-RRAC76LJ.js +0 -36
@@ -3,7 +3,7 @@ import {
3
3
  isTerminalSafeText,
4
4
  terminalSafeLine,
5
5
  terminalSafeText
6
- } from "./chunk-S3ZIMGXV.js";
6
+ } from "./chunk-ZKXNJB6U.js";
7
7
 
8
8
  // src/decisions/feedback.ts
9
9
  var FEEDBACK_PROTOCOL_VERSION = 2;
@@ -4,20 +4,20 @@ import {
4
4
  import {
5
5
  analyzeShellTargets,
6
6
  extractFileTargets
7
- } from "./chunk-3WQ7SBOZ.js";
7
+ } from "./chunk-HPA7RGSZ.js";
8
8
  import {
9
9
  scrubEnvironmentPaths
10
- } from "./chunk-4NUGCUQC.js";
10
+ } from "./chunk-74DQDWLW.js";
11
11
  import {
12
12
  cachedCollectScopeAdmits
13
- } from "./chunk-HLMC7VS4.js";
13
+ } from "./chunk-O73J3KQQ.js";
14
14
  import {
15
15
  canonicalRepositoryPath,
16
16
  currentBranch,
17
17
  isRepoActiveForCapture,
18
18
  relatedWorktreeTarget,
19
19
  repoSyncId
20
- } from "./chunk-4GYJHN26.js";
20
+ } from "./chunk-NJBN3WXF.js";
21
21
 
22
22
  // src/hooks/file-refs.ts
23
23
  var MAX_PREFLIGHT_FILE_TARGETS = 25;
@@ -0,0 +1,210 @@
1
+ import {
2
+ isMoveIngestRequest,
3
+ scheduleCollectScopeRefresh
4
+ } from "./chunk-O73J3KQQ.js";
5
+ import {
6
+ getPinnedClient,
7
+ getSiteUrl
8
+ } from "./chunk-ZKXNJB6U.js";
9
+ import {
10
+ machineApiUrl,
11
+ machineJournalBucket,
12
+ parseMachineIdentity
13
+ } from "./chunk-NJBN3WXF.js";
14
+
15
+ // src/protocol/decision-lifecycle.ts
16
+ var DECISION_LIFECYCLE_PROTOCOL_VERSION = 2;
17
+
18
+ // src/journal-organization.ts
19
+ var ORGANIZATION_BINDING_VERSION = 1;
20
+ var ORGANIZATION_ID_RE = /^[A-Za-z0-9_-]{1,128}$/;
21
+ var UNBOUND_BUCKET = "_unbound";
22
+ var InvalidJournalEnvelopeError = class extends Error {
23
+ constructor() {
24
+ super("Invalid locally journaled move");
25
+ this.name = "InvalidJournalEnvelopeError";
26
+ }
27
+ };
28
+ function safeOrganizationId(value) {
29
+ return typeof value === "string" && ORGANIZATION_ID_RE.test(value);
30
+ }
31
+ function isCaptureAuthorityKind(value) {
32
+ return value === "workos" || value === "service_token";
33
+ }
34
+ function parseOrganizationBinding(value) {
35
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
36
+ return { state: "server_contract_unavailable" };
37
+ }
38
+ const record = value;
39
+ if (record.organizationBindingVersion === 2 || record.organizationBindingVersion === 3) {
40
+ try {
41
+ const principal = record.principal;
42
+ const identity = parseMachineIdentity(record, String(principal.clientId));
43
+ return { state: "current", binding: { captureAuthorityKind: "workos_m2m", ...identity } };
44
+ } catch {
45
+ return { state: "server_contract_unavailable" };
46
+ }
47
+ }
48
+ if (record.authenticated !== true || record.organizationBindingVersion !== ORGANIZATION_BINDING_VERSION || !isCaptureAuthorityKind(record.captureAuthorityKind)) {
49
+ return { state: "server_contract_unavailable" };
50
+ }
51
+ if (record.organizationId === null && record.workosOrganizationId === null) {
52
+ return { state: "no_current_organization" };
53
+ }
54
+ if (safeOrganizationId(record.organizationId) && record.workosOrganizationId === null) {
55
+ return { state: "organization_identity_unreconciled" };
56
+ }
57
+ if (!safeOrganizationId(record.organizationId) || !safeOrganizationId(record.workosOrganizationId)) {
58
+ return { state: "server_contract_unavailable" };
59
+ }
60
+ return {
61
+ state: "current",
62
+ binding: {
63
+ captureAuthorityKind: record.captureAuthorityKind,
64
+ organizationId: record.organizationId,
65
+ workosOrganizationId: record.workosOrganizationId
66
+ }
67
+ };
68
+ }
69
+ function summarizeRetainedBuckets(retained) {
70
+ const counts = /* @__PURE__ */ new Map();
71
+ for (const item of retained) {
72
+ counts.set(item.reason, (counts.get(item.reason) ?? 0) + 1);
73
+ }
74
+ return [...counts].sort(([left], [right]) => left.localeCompare(right)).map(([reason, count]) => `${reason}:${String(count)}`).join(", ");
75
+ }
76
+ function classifyJournalBuckets(buckets, binding) {
77
+ const deliverableBuckets = /* @__PURE__ */ new Set();
78
+ const retainedBuckets = [];
79
+ for (const bucket of [...new Set(buckets)].sort()) {
80
+ if (bucket === UNBOUND_BUCKET) {
81
+ retainedBuckets.push({ bucket, reason: "unbound" });
82
+ continue;
83
+ }
84
+ if (typeof binding === "string") {
85
+ retainedBuckets.push({ bucket, reason: binding });
86
+ continue;
87
+ }
88
+ if (binding.captureAuthorityKind === "workos_m2m") {
89
+ if (binding.clientId && bucket === machineJournalBucket({
90
+ apiUrl: machineApiUrl(getSiteUrl()),
91
+ clientId: binding.clientId,
92
+ authorizedUserId: binding.authorizedUserId
93
+ }))
94
+ deliverableBuckets.add(bucket);
95
+ else
96
+ retainedBuckets.push({
97
+ bucket,
98
+ reason: bucket.startsWith("_machine_") ? "machine_identity_mismatch" : "legacy_authority_retained"
99
+ });
100
+ continue;
101
+ }
102
+ if (bucket.startsWith("_machine_")) {
103
+ retainedBuckets.push({ bucket, reason: "machine_identity_mismatch" });
104
+ continue;
105
+ }
106
+ if (bucket === binding.organizationId || bucket === binding.workosOrganizationId) {
107
+ deliverableBuckets.add(bucket);
108
+ } else {
109
+ retainedBuckets.push({ bucket, reason: "organization_mismatch" });
110
+ }
111
+ }
112
+ return { deliverableBuckets, retainedBuckets };
113
+ }
114
+ function buildOrganizationBoundMoveRequest(batch, binding) {
115
+ const capturedOrganizationId = binding.captureAuthorityKind === "workos" ? binding.workosOrganizationId : binding.organizationId;
116
+ const request = {
117
+ batch: batch.map((move) => {
118
+ if (typeof move !== "object" || move === null || Array.isArray(move)) {
119
+ return move;
120
+ }
121
+ const { captureActor, ...wireMove } = move;
122
+ if (binding.captureAuthorityKind === "workos_m2m") {
123
+ if (!captureActor || captureActor.clientId !== binding.clientId || captureActor.authorizedUserId !== binding.authorizedUserId || captureActor.apiUrl !== machineApiUrl(getSiteUrl()) || captureActor.machineId && captureActor.machineId !== binding.machineId || captureActor.organizationId && captureActor.organizationId !== binding.organizationId)
124
+ throw new InvalidJournalEnvelopeError();
125
+ } else if (captureActor) throw new InvalidJournalEnvelopeError();
126
+ return {
127
+ ...wireMove,
128
+ envelopeVersion: binding.captureAuthorityKind === "workos_m2m" ? binding.authorizedUserId ? 6 : 5 : 4,
129
+ ...binding.captureAuthorityKind === "workos_m2m" ? {
130
+ capturedMachineId: binding.machineId,
131
+ ...binding.authorizedUserId ? { capturedUserId: binding.authorizedUserId } : {}
132
+ } : {},
133
+ capturedOrganizationId,
134
+ captureAuthorityKind: binding.captureAuthorityKind,
135
+ decisionLifecycleProtocolVersion: DECISION_LIFECYCLE_PROTOCOL_VERSION
136
+ };
137
+ })
138
+ };
139
+ if (!isMoveIngestRequest(request)) {
140
+ throw new InvalidJournalEnvelopeError();
141
+ }
142
+ return request;
143
+ }
144
+ async function inspectJournalDelivery(buckets, options = {}) {
145
+ const bucketList = [...new Set(buckets)];
146
+ let client;
147
+ try {
148
+ client = options.client ?? await (options.createClient ?? (() => getPinnedClient()))();
149
+ } catch {
150
+ return classifyJournalBuckets(bucketList, "identity_unavailable");
151
+ }
152
+ let parsed;
153
+ try {
154
+ parsed = parseOrganizationBinding(
155
+ await client.get("/api/cli/auth/status", {
156
+ signal: AbortSignal.timeout(1e4),
157
+ quietRefresh: true
158
+ })
159
+ );
160
+ } catch {
161
+ return classifyJournalBuckets(bucketList, "identity_unavailable");
162
+ }
163
+ if (parsed.state !== "current") {
164
+ return classifyJournalBuckets(bucketList, parsed.state);
165
+ }
166
+ return {
167
+ client,
168
+ binding: parsed.binding,
169
+ ...classifyJournalBuckets(bucketList, parsed.binding)
170
+ };
171
+ }
172
+
173
+ // src/ingest-response.ts
174
+ var IngestAcknowledgementError = class extends Error {
175
+ constructor(message) {
176
+ super(message);
177
+ this.name = "IngestAcknowledgementError";
178
+ }
179
+ };
180
+ function requireDurableIngestAcknowledgement(value, expected, cwd = process.cwd()) {
181
+ if (typeof value !== "object" || value === null) {
182
+ throw new IngestAcknowledgementError("ingest response was not an object");
183
+ }
184
+ const response = value;
185
+ if (response.disposition !== "persisted") {
186
+ throw new IngestAcknowledgementError("ingest response did not confirm persistence");
187
+ }
188
+ if (response.acknowledged !== expected) {
189
+ throw new IngestAcknowledgementError(
190
+ `ingest acknowledged ${String(response.acknowledged)} of ${String(expected)} moves`
191
+ );
192
+ }
193
+ if (typeof response.collectScopeVersion === "number" && Number.isSafeInteger(response.collectScopeVersion) && response.collectScopeVersion >= 0) {
194
+ const roots = typeof cwd === "string" ? [cwd] : cwd;
195
+ for (const root of new Set(roots)) {
196
+ scheduleCollectScopeRefresh(root, response.collectScopeVersion);
197
+ }
198
+ }
199
+ return value;
200
+ }
201
+
202
+ export {
203
+ InvalidJournalEnvelopeError,
204
+ parseOrganizationBinding,
205
+ summarizeRetainedBuckets,
206
+ classifyJournalBuckets,
207
+ buildOrganizationBoundMoveRequest,
208
+ inspectJournalDelivery,
209
+ requireDurableIngestAcknowledgement
210
+ };
@@ -1,8 +1,10 @@
1
1
  import {
2
2
  decodeJwtPayload,
3
+ hasMachineConfiguration,
4
+ machineContext,
3
5
  primConfigDirectory,
4
6
  resolveAuthCredential
5
- } from "./chunk-4GYJHN26.js";
7
+ } from "./chunk-NJBN3WXF.js";
6
8
 
7
9
  // src/daemon/principal.ts
8
10
  import { createHash } from "crypto";
@@ -14,6 +16,16 @@ function sha256(value) {
14
16
  return createHash("sha256").update(value).digest("hex");
15
17
  }
16
18
  function resolveDaemonPrincipal(token = resolveAuthCredential()?.token) {
19
+ if (hasMachineConfiguration()) {
20
+ const machine = machineContext();
21
+ return machine ? {
22
+ principalId: sha256(
23
+ `${machine.issuer}\0${machine.clientId}${machine.authorizedUserId ? `\0${machine.authorizedUserId}` : ""}`
24
+ ),
25
+ organizationId: machine.workosOrganizationId,
26
+ credentialFingerprint: sha256(machine.generation)
27
+ } : void 0;
28
+ }
17
29
  if (!token) return void 0;
18
30
  const payload = decodeJwtPayload(token);
19
31
  const subject = boundedClaim(payload?.sub);
@@ -5,14 +5,20 @@ import {
5
5
  CREDENTIAL_MIGRATION_PATH,
6
6
  CREDENTIAL_MIGRATION_STATE,
7
7
  CREDENTIAL_MIGRATION_VERSION,
8
+ MachineAuthError,
8
9
  REFRESH_TOKEN_PATH,
9
10
  TERMINAL_REFRESH_PATH,
10
11
  TOKEN_EXPIRES_PATH,
11
12
  TOKEN_FILE_PATH,
12
13
  WORKOS_CONNECT_RESPONSE_MAX_BYTES,
14
+ acquireMachineCredential,
13
15
  atomicWriteFile,
16
+ cachedMachineCredential,
14
17
  ensureDurableDirectory,
18
+ hasMachineConfiguration,
15
19
  jwtExpiresAt,
20
+ machineContext,
21
+ machineSessionEnded,
16
22
  packageVersion,
17
23
  parseWorkosConnectTokens,
18
24
  primConfigDirectory,
@@ -23,7 +29,7 @@ import {
23
29
  syncDirectory,
24
30
  withFileLock,
25
31
  workosConnectTokenEndpoint
26
- } from "./chunk-4GYJHN26.js";
32
+ } from "./chunk-NJBN3WXF.js";
27
33
 
28
34
  // src/decisions/identity.ts
29
35
  var PUBLIC_ID = /^dec_[0-9a-f]{8}$/u;
@@ -289,6 +295,7 @@ function removeCredentialFile(path) {
289
295
  return true;
290
296
  }
291
297
  function getTokenExpiresAt() {
298
+ if (hasMachineConfiguration()) return cachedMachineCredential()?.expiresAt;
292
299
  const stored = readTrimmed(TOKEN_EXPIRES_PATH);
293
300
  if (stored === void 0) return void 0;
294
301
  const value = Number(stored);
@@ -365,6 +372,7 @@ function clearTerminalFingerprint() {
365
372
  removeCredentialFile(TERMINAL_REFRESH_PATH);
366
373
  }
367
374
  function isSessionEnded() {
375
+ if (hasMachineConfiguration()) return machineSessionEnded();
368
376
  if (resolveAuthCredential()?.source !== "token_file") return false;
369
377
  const refreshToken2 = readTrimmed(REFRESH_TOKEN_PATH);
370
378
  const ended = terminalFingerprint();
@@ -660,6 +668,8 @@ async function performTokenRefresh(options = {}) {
660
668
  }
661
669
  var _refreshInFlight;
662
670
  function refreshToken(options = {}) {
671
+ if (hasMachineConfiguration())
672
+ return acquireMachineCredential(options).then((credential) => credential?.accessToken);
663
673
  if (_refreshInFlight) return _refreshInFlight;
664
674
  const attempt = performTokenRefresh(options).then((token) => {
665
675
  if (token) _cachedCredential = { token, source: "token_file" };
@@ -720,7 +730,8 @@ async function fetchWithToken(method, path, body, options, token, siteUrl) {
720
730
  ...method === "POST" && path === "/api/cli/moves/ingest" ? await ingestUploaderHeaders() : {}
721
731
  },
722
732
  body: body === void 0 ? void 0 : JSON.stringify(body),
723
- signal: options?.signal
733
+ signal: options?.signal,
734
+ redirect: options?.redirect
724
735
  });
725
736
  }
726
737
  async function responseValue(response) {
@@ -735,7 +746,66 @@ async function responseValue(response) {
735
746
  }
736
747
  return publicDecisionResponse(await response.json());
737
748
  }
749
+ async function machineClient(options = {}, management = false) {
750
+ let credential;
751
+ try {
752
+ credential = await acquireMachineCredential(options);
753
+ } catch (error) {
754
+ if (!(error instanceof MachineAuthError)) throw error;
755
+ throw new HttpError(error.terminal ? 401 : 503, error.message, { error: error.code });
756
+ }
757
+ if (!credential) return void 0;
758
+ const selected = credential;
759
+ const parse = management ? managementResponseValue : responseValue;
760
+ const send = async (method, path, body, requestOptions = {}) => {
761
+ if (machineContext()?.generation !== selected.generation) {
762
+ throw new HttpError(409, "Machine identity changed; restart the operation.");
763
+ }
764
+ const current = await acquireMachineCredential({ signal: requestOptions.signal });
765
+ if (!current || current.generation !== selected.generation || current.machineId !== selected.machineId || current.authorizedUserId !== selected.authorizedUserId || current.organizationId !== selected.organizationId)
766
+ throw new HttpError(409, "Machine identity changed; restart the operation.");
767
+ let response = await fetchWithToken(
768
+ method,
769
+ path,
770
+ body,
771
+ { ...requestOptions, redirect: "error" },
772
+ current.accessToken,
773
+ selected.apiUrl
774
+ );
775
+ if (response.status === 401) {
776
+ const renewed = await acquireMachineCredential({
777
+ force: true,
778
+ signal: requestOptions.signal
779
+ });
780
+ if (!renewed || renewed.generation !== selected.generation || renewed.machineId !== selected.machineId || renewed.authorizedUserId !== selected.authorizedUserId || renewed.organizationId !== selected.organizationId) {
781
+ throw new HttpError(409, "Machine identity changed; restart the operation.");
782
+ }
783
+ response = await fetchWithToken(
784
+ method,
785
+ path,
786
+ body,
787
+ { ...requestOptions, redirect: "error" },
788
+ renewed.accessToken,
789
+ renewed.apiUrl
790
+ );
791
+ }
792
+ if (response.status === 401)
793
+ throw new HttpError(
794
+ 401,
795
+ "Machine access was rejected. Ask your administrator to check or rotate its credentials."
796
+ );
797
+ return parse(response);
798
+ };
799
+ return {
800
+ get: (path, opts) => send("GET", path, void 0, opts),
801
+ post: (path, body, opts) => send("POST", path, body, opts),
802
+ delete: (path, body, opts) => send("DELETE", path, body, opts)
803
+ };
804
+ }
738
805
  async function request(method, path, body, options) {
806
+ const machine = await machineClient(options);
807
+ if (machine)
808
+ return method === "GET" ? machine.get(path, options) : machine.post(path, body, options);
739
809
  const siteUrl = getSiteUrl();
740
810
  let credential = selectedCredential();
741
811
  let refreshAttempted = false;
@@ -779,6 +849,8 @@ function getClient() {
779
849
  };
780
850
  }
781
851
  async function getPinnedClient(options = {}) {
852
+ const machine = await machineClient(options);
853
+ if (machine) return machine;
782
854
  const siteUrl = getSiteUrl();
783
855
  let credential = selectedCredential();
784
856
  if (credential && isTokenExpiringSoon(credential)) {
@@ -799,6 +871,8 @@ async function getPinnedClient(options = {}) {
799
871
  };
800
872
  }
801
873
  async function getPinnedManagementClient(options = {}) {
874
+ const machine = await machineClient(options, true);
875
+ if (machine) return machine;
802
876
  const siteUrl = getSiteUrl();
803
877
  let credential = selectedCredential();
804
878
  if (credential && isTokenExpiringSoon(credential)) {