@primitive.ai/prim 0.1.0-alpha.12 → 0.1.0-alpha.120

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 (56) hide show
  1. package/README.md +540 -38
  2. package/SKILL.md +315 -75
  3. package/assets/primitive-gameplan/SKILL.md +134 -0
  4. package/assets/primitive-gameplan/claude-hooks.json +28 -0
  5. package/assets/primitive-gameplan/scripts/activate.mjs +37 -0
  6. package/dist/chunk-2AKDX4RU.js +209 -0
  7. package/dist/chunk-4GLVJLEQ.js +55 -0
  8. package/dist/chunk-5BQ2NEMP.js +22695 -0
  9. package/dist/chunk-A6M2M5A2.js +36 -0
  10. package/dist/chunk-CCGFRNAA.js +1871 -0
  11. package/dist/chunk-D235RJNO.js +164 -0
  12. package/dist/chunk-EYBE724K.js +135 -0
  13. package/dist/chunk-EZXEWFDG.js +210 -0
  14. package/dist/chunk-GYQOZGGF.js +168 -0
  15. package/dist/chunk-HXICZG5J.js +503 -0
  16. package/dist/chunk-JSBRDJBE.js +30 -0
  17. package/dist/chunk-KZB4ABIB.js +13 -0
  18. package/dist/chunk-L52OD62C.js +1444 -0
  19. package/dist/chunk-LBCPRHNG.js +175 -0
  20. package/dist/chunk-LTTF4MBE.js +439 -0
  21. package/dist/chunk-MWNRXAEB.js +1572 -0
  22. package/dist/chunk-NQFRQ56V.js +262 -0
  23. package/dist/chunk-OYHYCK4K.js +13 -0
  24. package/dist/chunk-P2O7NLVN.js +1341 -0
  25. package/dist/chunk-R2NUH4B7.js +96 -0
  26. package/dist/chunk-SLDZJD6Q.js +157 -0
  27. package/dist/chunk-TC4FTRYO.js +253 -0
  28. package/dist/chunk-U67RBNIZ.js +844 -0
  29. package/dist/chunk-VOC4KOOP.js +258 -0
  30. package/dist/chunk-YTF6OCF3.js +459 -0
  31. package/dist/daemon/server.js +26444 -0
  32. package/dist/hook-runtime/daemon/server.js +26445 -0
  33. package/dist/hook-runtime/hooks/post-commit.js +23836 -0
  34. package/dist/hook-runtime/hooks/post-rewrite.js +23735 -0
  35. package/dist/hook-runtime/hooks/post-tool-use.js +36151 -0
  36. package/dist/hook-runtime/hooks/pre-commit.js +1737 -0
  37. package/dist/hook-runtime/hooks/pre-tool-use-worker.js +35067 -0
  38. package/dist/hook-runtime/hooks/pre-tool-use.js +96 -0
  39. package/dist/hook-runtime/hooks/prim-hook.js +36211 -0
  40. package/dist/hook-runtime/hooks/session-end.js +1188 -0
  41. package/dist/hook-runtime/hooks/session-start.js +33950 -0
  42. package/dist/hook-runtime/index.js +71245 -0
  43. package/dist/hook-runtime/statusline-main.js +892 -0
  44. package/dist/hooks/post-commit.js +197 -0
  45. package/dist/hooks/post-rewrite.js +206 -0
  46. package/dist/hooks/post-tool-use.js +295 -0
  47. package/dist/hooks/pre-commit.js +16 -108
  48. package/dist/hooks/pre-tool-use-worker.js +238 -0
  49. package/dist/hooks/pre-tool-use.js +87 -0
  50. package/dist/hooks/prim-hook.js +245 -0
  51. package/dist/hooks/session-end.js +67 -0
  52. package/dist/hooks/session-start.js +312 -0
  53. package/dist/index.js +10998 -572
  54. package/dist/statusline-main.js +891 -0
  55. package/package.json +49 -16
  56. package/dist/chunk-3APLWTLB.js +0 -165
@@ -0,0 +1,459 @@
1
+ import {
2
+ analyzeShellTargets,
3
+ extractFileTargets
4
+ } from "./chunk-L52OD62C.js";
5
+ import {
6
+ DEFAULT_RULES,
7
+ scrub
8
+ } from "./chunk-NQFRQ56V.js";
9
+ import {
10
+ boundedHealthError,
11
+ isPreflightResponseV4
12
+ } from "./chunk-5BQ2NEMP.js";
13
+ import {
14
+ getClient,
15
+ terminalSafeLine
16
+ } from "./chunk-U67RBNIZ.js";
17
+ import {
18
+ canonicalGitRoot,
19
+ canonicalRepositoryPath
20
+ } from "./chunk-P2O7NLVN.js";
21
+
22
+ // src/hooks/approval-copy.ts
23
+ var MAX_EXCERPT_CHARS = 80;
24
+ var MAX_TITLE_CHARS = 140;
25
+ var MAX_PATH_CHARS = 120;
26
+ var MAX_VISIBLE_CONFLICTS = 3;
27
+ function displayText(value, maxChars) {
28
+ const redacted = scrub(value, DEFAULT_RULES);
29
+ const clean = terminalSafeLine(typeof redacted === "string" ? redacted : "");
30
+ const characters = Array.from(clean);
31
+ return characters.length > maxChars ? `${characters.slice(0, maxChars - 1).join("")}\u2026` : clean;
32
+ }
33
+ function targetLabel(paths) {
34
+ const shown = paths.slice(0, 2).map((path) => `\u201C${displayText(path, MAX_PATH_CHARS)}\u201D`);
35
+ if (shown.length === 0) return "the requested change";
36
+ const remaining = paths.length - shown.length;
37
+ return `${shown.join(" and ")}${remaining > 0 ? ` and ${remaining} more file(s)` : ""}`;
38
+ }
39
+ function editPreview(toolName, toolInput, paths) {
40
+ const input = toolInput && typeof toolInput === "object" ? toolInput : {};
41
+ const targets = targetLabel(paths);
42
+ if (toolName === "Edit") {
43
+ const before = typeof input.old_string === "string" ? displayText(input.old_string, MAX_EXCERPT_CHARS) : "";
44
+ const after = typeof input.new_string === "string" ? displayText(input.new_string, MAX_EXCERPT_CHARS) : "";
45
+ return before && after ? `Edit ${targets}:
46
+ Current text: \u201C${before}\u201D
47
+ Proposed replacement: \u201C${after}\u201D` : `Edit ${targets}.`;
48
+ }
49
+ if (toolName === "Write" || toolName === "NotebookEdit") return `Write ${targets}.`;
50
+ if (toolName === "Bash" || toolName === "Shell") return `Run a command affecting ${targets}.`;
51
+ return `Change ${targets}.`;
52
+ }
53
+ function decisionLabel(conflict) {
54
+ const id = typeof conflict.shortId === "string" && /^[0-9a-f]{8}$/u.test(conflict.shortId) ? `dec_${conflict.shortId}` : typeof conflict.decisionId === "string" && /^dec_[0-9a-f]{8}$/u.test(conflict.decisionId) ? conflict.decisionId : "unknown";
55
+ const title = typeof conflict.title === "string" ? displayText(conflict.title, MAX_TITLE_CHARS) : "";
56
+ return title ? `Decision ${id}: \u201C${title}\u201D.` : `Decision ${id}: details unavailable; inspect it before approving.`;
57
+ }
58
+ function incomplete(evidence) {
59
+ const coverage = evidence.evaluationCoverage;
60
+ return Array.isArray(coverage?.selectionOmissions) && coverage.selectionOmissions.length > 0 || Array.isArray(coverage?.evidenceOmissions) && coverage.evidenceOmissions.length > 0 || coverage?.status !== void 0 && coverage.status !== "completed" || ["candidate_set_truncated", "evidence_incomplete", "coverage_unverified"].includes(
61
+ evidence.reasonCode
62
+ );
63
+ }
64
+ function approvalSummary(evidence, preview) {
65
+ const lines = [preview];
66
+ if (evidence.conflicts.length > 0) {
67
+ lines.push("Primitive found a conflict with an existing decision.");
68
+ lines.push(...evidence.conflicts.slice(0, MAX_VISIBLE_CONFLICTS).map(decisionLabel));
69
+ const remaining = evidence.conflicts.length - MAX_VISIBLE_CONFLICTS;
70
+ if (remaining > 0) lines.push(`${remaining} more conflicting decision(s) need inspection.`);
71
+ } else {
72
+ lines.push(
73
+ displayText(evidence.message || "Primitive requires review before this change.", 180)
74
+ );
75
+ }
76
+ if (incomplete(evidence)) {
77
+ lines.push("Some potentially applicable decisions were not fully checked.");
78
+ }
79
+ return lines.filter(Boolean).join("\n");
80
+ }
81
+
82
+ // src/hooks/preflight-v3.ts
83
+ import { Buffer } from "buffer";
84
+ var PREFLIGHT_PROTOCOL_VERSION = 3;
85
+ var MAX_PREFLIGHT_PATHS = 32;
86
+ var MAX_PROPOSAL_BYTES = 6144;
87
+ var MAX_CLIENT_VERSION_CHARS = 32;
88
+ var CLIENT_VERSION_RE = /^[A-Za-z0-9][A-Za-z0-9._+-]*$/;
89
+ var MAX_DECISION_DISCLOSURES = 16;
90
+ var DISCLOSED_DECISION_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;
91
+ var DISCLOSED_DECISION_SHORT_ID_RE = /^[0-9a-f]{8}$/u;
92
+ function boundedClientVersion(raw) {
93
+ return typeof raw === "string" && raw.length <= MAX_CLIENT_VERSION_CHARS && CLIENT_VERSION_RE.test(raw) ? raw : "unknown";
94
+ }
95
+ function resolvePreflightTargets(args) {
96
+ let rawPaths;
97
+ let coverage = "complete";
98
+ let mutation = "present";
99
+ let definite = false;
100
+ const shellTool = (args.agent === "claude_code" || args.agent === "codex") && args.toolName === "Bash" || args.agent === "cursor" && args.toolName === "Shell";
101
+ if (shellTool) {
102
+ const command = typeof args.toolInput === "string" ? args.toolInput : args.toolInput && typeof args.toolInput === "object" ? args.toolInput.command : void 0;
103
+ if (typeof command !== "string") {
104
+ return { paths: [], coverage: "unverified", mutation: "present" };
105
+ }
106
+ const shell = analyzeShellTargets(command, args.cwd);
107
+ rawPaths = shell.paths;
108
+ coverage = shell.coverage;
109
+ mutation = shell.mutation;
110
+ definite = shell.definiteEdit === true;
111
+ } else {
112
+ const extracted = extractFileTargets(args.toolName, args.toolInput, args.agent);
113
+ if (!extracted) return { paths: [], coverage: "complete", mutation: "none" };
114
+ rawPaths = extracted.paths;
115
+ if (!extracted.complete) coverage = "unverified";
116
+ definite = true;
117
+ }
118
+ const root = canonicalGitRoot(args.cwd);
119
+ const paths = /* @__PURE__ */ new Set();
120
+ for (const rawPath of rawPaths) {
121
+ const canonical = canonicalRepositoryPath(rawPath, args.cwd, root);
122
+ if (canonical) paths.add(canonical);
123
+ else coverage = "unverified";
124
+ }
125
+ const bounded = [...paths];
126
+ if (bounded.length > MAX_PREFLIGHT_PATHS) coverage = "unverified";
127
+ const resolved = bounded.slice(0, MAX_PREFLIGHT_PATHS);
128
+ if (definite && resolved.length === 0 && mutation === "present") {
129
+ return { paths: resolved, coverage: "unverified", mutation, definite: true };
130
+ }
131
+ return { paths: resolved, coverage, mutation };
132
+ }
133
+ function truncateUtf8(value, maxBytes) {
134
+ const encoded = Buffer.from(value);
135
+ if (encoded.byteLength <= maxBytes) return value;
136
+ return encoded.subarray(0, maxBytes).toString("utf8").replace(/\uFFFD$/u, "");
137
+ }
138
+ function proposalFor(toolInput) {
139
+ const redacted = scrub(toolInput, DEFAULT_RULES);
140
+ return truncateUtf8(JSON.stringify(redacted) ?? "", MAX_PROPOSAL_BYTES);
141
+ }
142
+ function proposalIsTruncated(toolInput) {
143
+ return Buffer.byteLength(JSON.stringify(scrub(toolInput, DEFAULT_RULES)) ?? "") > MAX_PROPOSAL_BYTES;
144
+ }
145
+ function parsePreflightResponse(value) {
146
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
147
+ const response = value;
148
+ const verdicts = /* @__PURE__ */ new Set(["allow", "warn", "ask", "block", "unavailable"]);
149
+ if (response.protocolVersion !== PREFLIGHT_PROTOCOL_VERSION || typeof response.verdict !== "string" || !verdicts.has(response.verdict) || typeof response.reasonCode !== "string" || typeof response.message !== "string" || !Array.isArray(response.conflicts) || !Array.isArray(response.bypassed)) {
150
+ return null;
151
+ }
152
+ if (response.checkId !== void 0 && (typeof response.checkId !== "string" || !DISCLOSED_DECISION_ID_RE.test(response.checkId)))
153
+ return null;
154
+ const disclosures = response.decisionDisclosures;
155
+ if (disclosures !== void 0) {
156
+ if (!Array.isArray(disclosures) || disclosures.length === 0 || disclosures.length > MAX_DECISION_DISCLOSURES) {
157
+ return null;
158
+ }
159
+ const seen = /* @__PURE__ */ new Set();
160
+ for (const value2 of disclosures) {
161
+ if (!value2 || typeof value2 !== "object" || Array.isArray(value2)) return null;
162
+ const disclosure = value2;
163
+ if (Object.keys(disclosure).length !== 3 || !Object.hasOwn(disclosure, "decisionId") || !Object.hasOwn(disclosure, "shortId") || !Object.hasOwn(disclosure, "participation") || typeof disclosure.decisionId !== "string" || !DISCLOSED_DECISION_ID_RE.test(disclosure.decisionId) || typeof disclosure.shortId !== "string" || !DISCLOSED_DECISION_SHORT_ID_RE.test(disclosure.shortId) || disclosure.participation !== "candidate" && disclosure.participation !== "reconcile_bypass" || seen.has(disclosure.decisionId)) {
164
+ return null;
165
+ }
166
+ seen.add(disclosure.decisionId);
167
+ }
168
+ }
169
+ return response;
170
+ }
171
+ function decisionDisclosureContext(response) {
172
+ return response.decisionDisclosures?.map(({ decisionId }) => `[primitive] hidden Decision: prim decisions show ${decisionId}`).join("\n") ?? "";
173
+ }
174
+ function proposedChangeExcerpt(proposal) {
175
+ try {
176
+ const input = JSON.parse(proposal);
177
+ if (input && typeof input === "object") {
178
+ for (const key of ["new_string", "new_str", "content", "command"]) {
179
+ if (typeof input[key] === "string") return boundedHealthError(input[key]);
180
+ }
181
+ }
182
+ } catch {
183
+ }
184
+ return boundedHealthError(proposal);
185
+ }
186
+ function resultForPreflight(response, preview = "Review the requested change.", invocation, proposalTruncated = false) {
187
+ const verdict = response.verdict === "block" ? "deny" : response.verdict;
188
+ const message = boundedHealthError(response.message) ?? "";
189
+ const unavailable = message || boundedHealthError(response.reasonCode);
190
+ const safe = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
191
+ const directives = response.conflicts.flatMap((value) => {
192
+ if (!value || typeof value !== "object") return [];
193
+ const { decisionId, shortId, title } = value;
194
+ const id = typeof shortId === "string" && /^[0-9a-f]{8}$/u.test(shortId) ? `dec_${shortId}` : typeof decisionId === "string" && /^dec_[0-9a-f]{8}$/u.test(decisionId) ? decisionId : void 0;
195
+ if (!id) return [];
196
+ return [
197
+ `Governing Decision ${id}${typeof title === "string" && boundedHealthError(title) ? `: ${boundedHealthError(title)}` : ""}.`,
198
+ ...response.checkId && safe.test(response.checkId) ? [
199
+ `Check: ${response.checkId}. After resolving, record the confirmed outcome: prim reconcile ${id} --check ${response.checkId} --outcome followed (retained Decision), or --outcome superseded (after replacing it). Recording a resolution does not authorize an override.`
200
+ ] : []
201
+ ];
202
+ });
203
+ const blocked = response.verdict === "ask" || response.verdict === "block";
204
+ const proposal = invocation ? proposedChangeExcerpt(invocation.proposal) : void 0;
205
+ const editContext = blocked && invocation ? [
206
+ `Proposed edit to: ${invocation.paths.map((path) => boundedHealthError(path)).join(", ")}.`,
207
+ ...proposal ? [`Proposed change (excerpt): ${proposal}`] : []
208
+ ] : [];
209
+ const approvalContext = blocked ? [
210
+ "Overriding these Decisions requires explicit human approval naming each Decision and the proposed conflicting edit.",
211
+ "Reconcile bypasses are disabled: this host integration cannot provide verifiable human approval for a bypass. Keep the edit blocked and choose a compatible change.",
212
+ "Sandbox escalation, automatic review, prefix permissions, --yes, and an agent's assertion of approval do not authorize an override."
213
+ ] : [];
214
+ const guidance = [message, ...editContext, ...new Set(directives), ...approvalContext].filter(Boolean).join("\n");
215
+ const reason = response.conflicts.length > 0 || response.verdict === "ask" || response.verdict === "block" ? approvalSummary(
216
+ {
217
+ conflicts: response.conflicts,
218
+ message,
219
+ reasonCode: response.reasonCode,
220
+ evaluationCoverage: response.evaluationCoverage
221
+ },
222
+ preview
223
+ ) : message;
224
+ const disclosureContext = decisionDisclosureContext(response);
225
+ const truncationNote = proposalTruncated ? "[primitive] shell proposal was truncated; the complete change was not verified" : "";
226
+ return {
227
+ verdict,
228
+ conflicts: response.conflicts,
229
+ reason: [reason, truncationNote].filter(Boolean).join("\n"),
230
+ additionalContext: [
231
+ disclosureContext,
232
+ truncationNote,
233
+ ["warn", "ask", "block"].includes(response.verdict) ? guidance : ""
234
+ ].filter(Boolean).join("\n"),
235
+ truncated: false,
236
+ unavailable: response.verdict === "unavailable" ? unavailable : void 0
237
+ };
238
+ }
239
+
240
+ // src/hooks/preflight-v4.ts
241
+ import { createHash } from "crypto";
242
+ import { setTimeout as delay } from "timers/promises";
243
+ var PREFLIGHT_PROTOCOL_VERSION2 = 4;
244
+ var PREFLIGHT_WAIT_MS = 24e4;
245
+ var PREFLIGHT_REQUEST_MS = 1e4;
246
+ var ENDPOINT = "/api/cli/decisions/conflict-check";
247
+ var SAFE_ID = /^[A-Za-z0-9]{1,64}$/u;
248
+ var STATES = /* @__PURE__ */ new Set(["processing", "completed", "paused", "expired"]);
249
+ var COVERAGE_STATUSES = /* @__PURE__ */ new Set(["completed", "partial", "unavailable", "not_run", "unknown"]);
250
+ function toolInputDigest(toolName, input) {
251
+ function canonical(value, depth = 0) {
252
+ if (depth > 100) throw new Error("Tool input exceeds the identity nesting limit");
253
+ if (value === null || typeof value === "string" || typeof value === "boolean") {
254
+ return JSON.stringify(value);
255
+ }
256
+ if (typeof value === "number" && Number.isFinite(value)) return JSON.stringify(value);
257
+ if (Array.isArray(value))
258
+ return `[${value.map((item) => canonical(item, depth + 1)).join(",")}]`;
259
+ if (typeof value === "object" && value !== null) {
260
+ return `{${Object.entries(value).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0).map(([key, item]) => `${JSON.stringify(key)}:${canonical(item, depth + 1)}`).join(",")}}`;
261
+ }
262
+ throw new Error("Tool input has no stable JSON identity");
263
+ }
264
+ return createHash("sha256").update(canonical({ toolName, input: input ?? null })).digest("hex");
265
+ }
266
+ function isUnidentifiedPause(response) {
267
+ return response.state === "paused" && (response.verdict === "block" || response.verdict === "unavailable") && response.checkId === void 0 && response.evaluationId === void 0;
268
+ }
269
+ function parsePreflightResponse2(value) {
270
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
271
+ const response = value;
272
+ if (!isPreflightResponseV4(response)) return null;
273
+ if (response.protocolVersion !== 4 || !parsePreflightResponse({ ...response, protocolVersion: 3 }))
274
+ return null;
275
+ if (typeof response.state !== "string" || !STATES.has(response.state)) return null;
276
+ for (const key of ["checkId", "evaluationId"]) {
277
+ if (response[key] !== void 0 && (typeof response[key] !== "string" || !SAFE_ID.test(response[key])))
278
+ return null;
279
+ }
280
+ if (!isUnidentifiedPause(response) && !(response.state === "completed" && (response.reasonCode === "enforcement_disabled" || response.reasonCode === "no_targets_skipped")) && (!response.checkId || !response.evaluationId))
281
+ return null;
282
+ if (response.retryAfterMs !== void 0 && (!Number.isSafeInteger(response.retryAfterMs) || response.retryAfterMs < 0))
283
+ return null;
284
+ const coverage = response.evaluationCoverage;
285
+ if (!coverage || typeof coverage !== "object" || Array.isArray(coverage)) return null;
286
+ const counts = coverage;
287
+ for (const key of [
288
+ "candidateCount",
289
+ "submittedCount",
290
+ "evaluatedCount",
291
+ "bypassedCount",
292
+ "semanticBatchCount",
293
+ "completedSemanticBatchCount"
294
+ ]) {
295
+ if (!Number.isSafeInteger(counts[key]) || counts[key] < 0) return null;
296
+ }
297
+ if (typeof counts.discoveryComplete !== "boolean" || typeof counts.status !== "string" || !COVERAGE_STATUSES.has(counts.status))
298
+ return null;
299
+ if (counts.evaluatedCount > counts.submittedCount || counts.completedSemanticBatchCount > counts.semanticBatchCount)
300
+ return null;
301
+ return response;
302
+ }
303
+ function hasCompleteCoverage(response) {
304
+ if (response.state !== "completed" || response.verdict === "unavailable") return false;
305
+ const coverage = response.evaluationCoverage;
306
+ if (response.reasonCode === "enforcement_disabled") {
307
+ return response.verdict === "allow" && coverage.status === "not_run" && coverage.candidateCount === 0 && coverage.submittedCount === 0 && coverage.evaluatedCount === 0 && coverage.bypassedCount === 0 && coverage.semanticBatchCount === 0 && coverage.completedSemanticBatchCount === 0;
308
+ }
309
+ return coverage.status === "completed" && coverage.discoveryComplete && coverage.candidateCount === coverage.evaluatedCount + coverage.bypassedCount && coverage.submittedCount === coverage.evaluatedCount && coverage.semanticBatchCount === coverage.completedSemanticBatchCount;
310
+ }
311
+ function hasConfirmedConflict(response) {
312
+ const coverage = response.evaluationCoverage;
313
+ return (response.state === "completed" || response.state === "processing" || response.state === "paused") && response.conflicts.length > 0 && coverage.discoveryComplete && (response.state !== "completed" || hasCompleteCoverage(response)) && coverage.evaluatedCount <= coverage.candidateCount && coverage.evaluatedCount > 0 && coverage.completedSemanticBatchCount > 0 && (coverage.status === "partial" || coverage.status === "completed") && ["ask", "block", "warn"].includes(response.verdict) && [
314
+ "high_confidence_contradiction",
315
+ "aged_high_confidence_contradiction",
316
+ "provisional_or_uncertain_contradiction"
317
+ ].includes(response.reasonCode);
318
+ }
319
+ function isNoTargetsSkip(response) {
320
+ const coverage = response.evaluationCoverage;
321
+ return response.state === "completed" && response.verdict === "allow" && response.reasonCode === "no_targets_skipped" && response.checkId === void 0 && response.evaluationId === void 0 && response.conflicts.length === 0 && response.bypassed.length === 0 && coverage.status === "completed" && coverage.discoveryComplete && coverage.candidateCount === 0 && coverage.submittedCount === 0 && coverage.evaluatedCount === 0 && coverage.bypassedCount === 0 && coverage.semanticBatchCount === 0 && coverage.completedSemanticBatchCount === 0;
322
+ }
323
+ var PreflightPausedError = class extends Error {
324
+ constructor(message, checkId) {
325
+ super(message);
326
+ this.checkId = checkId;
327
+ }
328
+ };
329
+ function pausedResult(message, checkId) {
330
+ const detail = boundedHealthError(message) ?? "Decision evaluation is incomplete";
331
+ const recovery = checkId && SAFE_ID.test(checkId) ? `Run: prim decisions preflight resume ${checkId}; then retry the tool call.` : "Retry the tool call after restoring the Decision enforcement service.";
332
+ const reason = `[primitive] Operation paused: ${detail}. ${recovery}`;
333
+ return { verdict: "deny", conflicts: [], reason, additionalContext: reason, truncated: false };
334
+ }
335
+ function resultForPreflight2(response, preview, invocation, proposalTruncated = false) {
336
+ if (!hasCompleteCoverage(response) && !hasConfirmedConflict(response))
337
+ return pausedResult(response.message || response.reasonCode, response.checkId);
338
+ return resultForPreflight(
339
+ {
340
+ protocolVersion: 3,
341
+ verdict: response.verdict,
342
+ reasonCode: response.reasonCode,
343
+ message: response.message,
344
+ conflicts: response.conflicts,
345
+ bypassed: response.bypassed,
346
+ checkId: response.checkId,
347
+ decisionDisclosures: response.decisionDisclosures,
348
+ evaluationCoverage: {
349
+ ...response.evaluationCoverage,
350
+ selectionOmissions: [],
351
+ evidenceOmissions: []
352
+ }
353
+ },
354
+ preview,
355
+ invocation,
356
+ proposalTruncated
357
+ );
358
+ }
359
+ async function requestPreflight(operation, deadline = performance.now() + PREFLIGHT_WAIT_MS) {
360
+ if (operation.operation !== "start" && !SAFE_ID.test(operation.checkId))
361
+ throw new PreflightPausedError("Invalid check identity");
362
+ const remaining = deadline - performance.now();
363
+ if (remaining <= 0)
364
+ throw new PreflightPausedError(
365
+ "The check deadline expired",
366
+ operation.operation === "start" ? void 0 : operation.checkId
367
+ );
368
+ const value = await getClient().post(ENDPOINT, operation, {
369
+ signal: AbortSignal.timeout(Math.max(1, Math.ceil(Math.min(PREFLIGHT_REQUEST_MS, remaining)))),
370
+ quietRefresh: true
371
+ });
372
+ if (performance.now() >= deadline)
373
+ throw new PreflightPausedError(
374
+ "The check deadline expired",
375
+ operation.operation === "start" ? void 0 : operation.checkId
376
+ );
377
+ const response = parsePreflightResponse2(value);
378
+ if (!response)
379
+ throw new PreflightPausedError(
380
+ "The enforcement service returned an incompatible V4 response",
381
+ operation.operation === "start" ? void 0 : operation.checkId
382
+ );
383
+ if (response.reasonCode === "no_targets_skipped" && !(operation.operation === "start" && !operation.shellCheck && operation.paths.length === 0 && operation.coverage === "unverified" && isNoTargetsSkip(response))) {
384
+ throw new PreflightPausedError(
385
+ "The enforcement service returned an invalid target-policy exemption",
386
+ operation.operation === "start" ? void 0 : operation.checkId
387
+ );
388
+ }
389
+ if (operation.operation !== "start" && response.checkId !== operation.checkId && !isUnidentifiedPause(response) && !(response.reasonCode === "enforcement_disabled" && hasCompleteCoverage(response)))
390
+ throw new PreflightPausedError(
391
+ "The enforcement service returned a different check identity",
392
+ operation.checkId
393
+ );
394
+ return response;
395
+ }
396
+ async function waitForPreflight(operation, options = {}) {
397
+ const deadline = options.deadline ?? performance.now() + PREFLIGHT_WAIT_MS;
398
+ let next = operation;
399
+ const shellCheck = operation.operation === "start" ? operation.shellCheck : void 0;
400
+ let evaluationId;
401
+ let lastProgress;
402
+ let checkId = operation.operation === "start" ? void 0 : operation.checkId;
403
+ while (true) {
404
+ let response;
405
+ try {
406
+ response = await requestPreflight(next, deadline);
407
+ } catch (error) {
408
+ if (error instanceof PreflightPausedError) throw error;
409
+ if (performance.now() >= deadline)
410
+ throw new PreflightPausedError("The check deadline expired", checkId);
411
+ if (checkId)
412
+ throw new PreflightPausedError(
413
+ "The enforcement service could not finish this check",
414
+ checkId
415
+ );
416
+ throw error;
417
+ }
418
+ if (shellCheck && response.shellCheck?.targetMode !== shellCheck.targetMode && !(response.reasonCode === "enforcement_disabled" && hasCompleteCoverage(response))) {
419
+ throw new PreflightPausedError("The backend did not confirm shell-check support", checkId);
420
+ }
421
+ if (isUnidentifiedPause(response)) {
422
+ if (checkId) throw new PreflightPausedError(response.message || response.reasonCode, checkId);
423
+ return response;
424
+ }
425
+ if (evaluationId && response.evaluationId !== evaluationId && !(response.reasonCode === "enforcement_disabled" && hasCompleteCoverage(response)))
426
+ throw new PreflightPausedError(
427
+ "The enforcement service changed evaluation identity",
428
+ checkId
429
+ );
430
+ checkId = response.checkId;
431
+ evaluationId = response.evaluationId;
432
+ if (response.state !== "processing" || options.stopOnConflict && hasConfirmedConflict(response))
433
+ return response;
434
+ const progress = JSON.stringify(response.evaluationCoverage);
435
+ if (progress !== lastProgress) options.onProgress?.(response);
436
+ lastProgress = progress;
437
+ const remaining = deadline - performance.now();
438
+ if (remaining <= 0) throw new PreflightPausedError("The check deadline expired", checkId);
439
+ await delay(
440
+ Math.min(remaining, Math.max(100, Math.min(5e3, response.retryAfterMs ?? 1e3)))
441
+ );
442
+ next = { protocolVersion: 4, operation: "status", checkId };
443
+ }
444
+ }
445
+
446
+ export {
447
+ editPreview,
448
+ boundedClientVersion,
449
+ resolvePreflightTargets,
450
+ proposalFor,
451
+ proposalIsTruncated,
452
+ PREFLIGHT_PROTOCOL_VERSION2 as PREFLIGHT_PROTOCOL_VERSION,
453
+ toolInputDigest,
454
+ hasCompleteCoverage,
455
+ hasConfirmedConflict,
456
+ resultForPreflight2 as resultForPreflight,
457
+ requestPreflight,
458
+ waitForPreflight
459
+ };