@primitive.ai/prim 0.1.0-alpha.1 → 0.1.0-alpha.100

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 (47) hide show
  1. package/README.md +413 -37
  2. package/SKILL.md +272 -0
  3. package/dist/chunk-2IRLFOEL.js +766 -0
  4. package/dist/chunk-2Q3OGSTV.js +164 -0
  5. package/dist/chunk-4GLVJLEQ.js +55 -0
  6. package/dist/chunk-5HFTJEA6.js +168 -0
  7. package/dist/chunk-5LRKJTLA.js +155 -0
  8. package/dist/chunk-6C3CCVDI.js +264 -0
  9. package/dist/chunk-7VIMU2HR.js +209 -0
  10. package/dist/chunk-C4D2LMTS.js +511 -0
  11. package/dist/chunk-EZXEWFDG.js +210 -0
  12. package/dist/chunk-GSBHBU7N.js +18982 -0
  13. package/dist/chunk-H6JAQVW4.js +258 -0
  14. package/dist/chunk-IDMLJ4TM.js +36 -0
  15. package/dist/chunk-JJI7FU24.js +439 -0
  16. package/dist/chunk-K4JWJ6OM.js +1496 -0
  17. package/dist/chunk-KGBMU76T.js +175 -0
  18. package/dist/chunk-MXVCP33E.js +847 -0
  19. package/dist/chunk-MZEVEPL3.js +262 -0
  20. package/dist/chunk-O2WV5SQZ.js +1876 -0
  21. package/dist/chunk-OYHYCK4K.js +13 -0
  22. package/dist/chunk-QIHXTYRD.js +135 -0
  23. package/dist/chunk-XG7S3LIL.js +1372 -0
  24. package/dist/daemon/server.js +22644 -0
  25. package/dist/hook-runtime/daemon/server.js +22644 -0
  26. package/dist/hook-runtime/hooks/post-commit.js +20133 -0
  27. package/dist/hook-runtime/hooks/post-rewrite.js +20032 -0
  28. package/dist/hook-runtime/hooks/post-tool-use.js +27307 -0
  29. package/dist/hook-runtime/hooks/pre-commit.js +1657 -0
  30. package/dist/hook-runtime/hooks/pre-tool-use.js +26714 -0
  31. package/dist/hook-runtime/hooks/prim-hook.js +27367 -0
  32. package/dist/hook-runtime/hooks/session-end.js +1176 -0
  33. package/dist/hook-runtime/hooks/session-start.js +30167 -0
  34. package/dist/hook-runtime/index.js +53486 -0
  35. package/dist/hook-runtime/statusline-main.js +886 -0
  36. package/dist/hooks/post-commit.js +196 -0
  37. package/dist/hooks/post-rewrite.js +205 -0
  38. package/dist/hooks/post-tool-use.js +285 -0
  39. package/dist/hooks/pre-commit.js +21 -74
  40. package/dist/hooks/pre-tool-use.js +387 -0
  41. package/dist/hooks/prim-hook.js +235 -0
  42. package/dist/hooks/session-end.js +64 -0
  43. package/dist/hooks/session-start.js +309 -0
  44. package/dist/index.js +9721 -423
  45. package/dist/statusline-main.js +886 -0
  46. package/package.json +46 -23
  47. package/dist/chunk-3APLWTLB.js +0 -165
@@ -0,0 +1,511 @@
1
+ import {
2
+ formatStatusline
3
+ } from "./chunk-5HFTJEA6.js";
4
+ import {
5
+ getSiteUrl,
6
+ isSessionEnded,
7
+ terminalSafeText
8
+ } from "./chunk-2IRLFOEL.js";
9
+ import {
10
+ daemonPrincipalsMatch,
11
+ daemonRequest,
12
+ resolveDaemonPrincipal
13
+ } from "./chunk-5LRKJTLA.js";
14
+ import {
15
+ decisionIngestionStatus,
16
+ gitToplevel,
17
+ packageVersion,
18
+ primConfigDirectory,
19
+ repositoryBindingState,
20
+ withFileLock
21
+ } from "./chunk-XG7S3LIL.js";
22
+
23
+ // src/hooks/codex-context.ts
24
+ import { createHash, randomBytes as randomBytes2 } from "crypto";
25
+ import {
26
+ chmodSync,
27
+ existsSync,
28
+ mkdirSync,
29
+ readFileSync,
30
+ readdirSync,
31
+ renameSync,
32
+ rmSync,
33
+ statSync,
34
+ unlinkSync,
35
+ writeFileSync
36
+ } from "fs";
37
+ import { join } from "path";
38
+
39
+ // src/daemon/decision-digest-cache.ts
40
+ import { randomBytes } from "crypto";
41
+ var DECISION_DIGEST_CACHE_LIMIT = 100;
42
+ var DECISION_DIGEST_CACHE_WINDOW = "24h";
43
+ var DECISION_DIGEST_CACHE_PATH = `/api/cli/decisions/recent?limit=${String(DECISION_DIGEST_CACHE_LIMIT)}&since=${DECISION_DIGEST_CACHE_WINDOW}`;
44
+ var DECISION_DRAFT_DIGEST_CACHE_PATH = `${DECISION_DIGEST_CACHE_PATH}&drafts=true`;
45
+ var SAFE_PRIVATE_DRAFT_ID = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/u;
46
+ function isActionablePrivateDraft(row) {
47
+ if (typeof row !== "object" || row === null || Array.isArray(row)) return false;
48
+ const candidate = row;
49
+ return typeof candidate.id === "string" && SAFE_PRIVATE_DRAFT_ID.test(candidate.id) && typeof candidate.intent === "string" && candidate.authorIsSelf === true && candidate.stage === "draft" && (candidate.intentKind === void 0 || candidate.intentKind === "change");
50
+ }
51
+
52
+ // src/hooks/codex-context.ts
53
+ var CODEX_CONTEXT_TIMEOUT_MS = 250;
54
+ var CODEX_DIGEST_LIMIT = DECISION_DIGEST_CACHE_LIMIT;
55
+ var CODEX_DIGEST_VISIBLE_CAP = 3;
56
+ var CODEX_DIGEST_OVERLAP_MS = 6e4;
57
+ var CODEX_DIGEST_MAX_SEEN_IDS = 128;
58
+ var CODEX_DRAFT_DIGEST_MAX_SEEN_IDS = 4096;
59
+ var CODEX_DIGEST_STATE_RETENTION_MS = 7 * 24 * 60 * 60 * 1e3;
60
+ var CODEX_DIGEST_STATE_MAX_FILES = 256;
61
+ var STATE_VERSION = 1;
62
+ var DRAFT_STATE_VERSION = 2;
63
+ var NO_CURSOR = -1;
64
+ function hasVisibleCodexMessage(output) {
65
+ if (typeof output !== "object" || output === null || Array.isArray(output)) return false;
66
+ const candidate = output;
67
+ return Boolean(
68
+ candidate.systemMessage?.trim() || candidate.hookSpecificOutput?.permissionDecisionReason?.trim() || candidate.hookSpecificOutput?.additionalContext?.trim()
69
+ );
70
+ }
71
+ function appendContext(existing, context) {
72
+ return existing ? `${existing}
73
+
74
+ ${context}` : context;
75
+ }
76
+ function appendCodexContext(output, context) {
77
+ if (!context) return output;
78
+ const candidate = output;
79
+ const next = { ...output };
80
+ if (candidate.systemMessage) {
81
+ next.systemMessage = appendContext(candidate.systemMessage, context);
82
+ } else if (candidate.hookSpecificOutput?.permissionDecisionReason) {
83
+ next.systemMessage = context;
84
+ } else if (candidate.hookSpecificOutput?.additionalContext) {
85
+ next.hookSpecificOutput = {
86
+ ...candidate.hookSpecificOutput,
87
+ additionalContext: appendContext(candidate.hookSpecificOutput.additionalContext, context)
88
+ };
89
+ } else {
90
+ next.systemMessage = context;
91
+ }
92
+ return next;
93
+ }
94
+ function stateRoot(namespace) {
95
+ return join(primConfigDirectory(), namespace, "decision-digests");
96
+ }
97
+ function draftStateRoot(namespace) {
98
+ return join(primConfigDirectory(), namespace, "decision-draft-deliveries");
99
+ }
100
+ function workspaceFor(cwd) {
101
+ try {
102
+ return gitToplevel(cwd) ?? cwd;
103
+ } catch {
104
+ return cwd;
105
+ }
106
+ }
107
+ function statePath(args) {
108
+ const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}`;
109
+ const key = createHash("sha256").update(identity).digest("hex");
110
+ return join(stateRoot(args.namespace), `${key}.json`);
111
+ }
112
+ function draftStatePath(args) {
113
+ const identity = `${args.siteUrl}\0${workspaceFor(args.cwd)}\0${args.sessionId}\0${args.principalId}\0${args.organizationId}\0${args.credentialFingerprint}`;
114
+ const key = createHash("sha256").update(identity).digest("hex");
115
+ return join(draftStateRoot(args.namespace), `${key}.json`);
116
+ }
117
+ function parseState(value) {
118
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
119
+ const record = value;
120
+ if (record.version !== STATE_VERSION || typeof record.sessionId !== "string" || typeof record.siteUrl !== "string" || typeof record.workspace !== "string" || typeof record.startedAt !== "number" || typeof record.watermarkMs !== "number" || !Array.isArray(record.seenIds) || !record.seenIds.every((id) => typeof id === "string") || typeof record.updatedAt !== "number") {
121
+ return void 0;
122
+ }
123
+ return {
124
+ version: STATE_VERSION,
125
+ sessionId: record.sessionId,
126
+ siteUrl: record.siteUrl,
127
+ workspace: record.workspace,
128
+ startedAt: record.startedAt,
129
+ watermarkMs: record.watermarkMs,
130
+ seenIds: record.seenIds.slice(-CODEX_DIGEST_MAX_SEEN_IDS),
131
+ lastReport: typeof record.lastReport === "string" ? record.lastReport : void 0,
132
+ updatedAt: record.updatedAt
133
+ };
134
+ }
135
+ function parseDraftState(value) {
136
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return void 0;
137
+ const record = value;
138
+ if (record.version !== DRAFT_STATE_VERSION || typeof record.sessionId !== "string" || typeof record.siteUrl !== "string" || typeof record.workspace !== "string" || typeof record.principalId !== "string" || typeof record.organizationId !== "string" || typeof record.credentialFingerprint !== "string" || !Array.isArray(record.seenDraftIds) || !record.seenDraftIds.every((id) => typeof id === "string") || typeof record.updatedAt !== "number") {
139
+ return void 0;
140
+ }
141
+ return {
142
+ version: DRAFT_STATE_VERSION,
143
+ sessionId: record.sessionId,
144
+ siteUrl: record.siteUrl,
145
+ workspace: record.workspace,
146
+ principalId: record.principalId,
147
+ organizationId: record.organizationId,
148
+ credentialFingerprint: record.credentialFingerprint,
149
+ seenDraftIds: record.seenDraftIds.slice(-CODEX_DRAFT_DIGEST_MAX_SEEN_IDS),
150
+ updatedAt: record.updatedAt
151
+ };
152
+ }
153
+ function readState(path) {
154
+ if (!existsSync(path)) return void 0;
155
+ try {
156
+ return parseState(JSON.parse(readFileSync(path, "utf8")));
157
+ } catch {
158
+ return void 0;
159
+ }
160
+ }
161
+ function readDraftState(path) {
162
+ if (!existsSync(path)) return void 0;
163
+ try {
164
+ return parseDraftState(JSON.parse(readFileSync(path, "utf8")));
165
+ } catch {
166
+ return void 0;
167
+ }
168
+ }
169
+ function writeStateFile(path, directory, state) {
170
+ mkdirSync(directory, { recursive: true, mode: 448 });
171
+ chmodSync(directory, 448);
172
+ const temporary = join(
173
+ directory,
174
+ `.${path.slice(directory.length + 1)}.tmp-${process.pid}-${randomBytes2(8).toString("hex")}`
175
+ );
176
+ try {
177
+ writeFileSync(temporary, `${JSON.stringify(state)}
178
+ `, {
179
+ encoding: "utf8",
180
+ mode: 384,
181
+ flag: "wx"
182
+ });
183
+ chmodSync(temporary, 384);
184
+ renameSync(temporary, path);
185
+ } finally {
186
+ try {
187
+ unlinkSync(temporary);
188
+ } catch {
189
+ }
190
+ }
191
+ }
192
+ function cleanupStateFiles(directory, now) {
193
+ if (!existsSync(directory)) return;
194
+ let names;
195
+ try {
196
+ names = readdirSync(directory);
197
+ } catch {
198
+ return;
199
+ }
200
+ const files = [];
201
+ const residue = [];
202
+ for (const name of names) {
203
+ const path = join(directory, name);
204
+ try {
205
+ const mtimeMs = statSync(path).mtimeMs;
206
+ if (name.endsWith(".json")) {
207
+ files.push({ path, mtimeMs });
208
+ } else if ((name.includes(".json.tmp-") || name.endsWith(".json.lock")) && now - mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
209
+ residue.push(path);
210
+ }
211
+ } catch {
212
+ }
213
+ }
214
+ const stale = files.filter((file) => now - file.mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS);
215
+ const excess = files.filter((file) => !stale.some((candidate) => candidate.path === file.path)).sort((a, b) => a.mtimeMs - b.mtimeMs).slice(0, Math.max(0, files.length - CODEX_DIGEST_STATE_MAX_FILES));
216
+ for (const file of [...stale, ...excess]) {
217
+ try {
218
+ unlinkSync(file.path);
219
+ } catch {
220
+ }
221
+ }
222
+ for (const path of residue) {
223
+ try {
224
+ if (now - statSync(path).mtimeMs > CODEX_DIGEST_STATE_RETENTION_MS) {
225
+ rmSync(path, { recursive: true, force: true });
226
+ }
227
+ } catch {
228
+ }
229
+ }
230
+ }
231
+ function isChangeDecision(row) {
232
+ return row.intentKind === void 0 || row.intentKind === "change";
233
+ }
234
+ function safeInline(value, fallback) {
235
+ const clean = terminalSafeText(value ?? "").replace(/\s+/gu, " ").trim();
236
+ if (!clean) return fallback;
237
+ return clean.length <= 240 ? clean : `${clean.slice(0, 239)}\u2026`;
238
+ }
239
+ function renderDecisionDigest(rows, options = {}) {
240
+ if (rows.length === 0) return void 0;
241
+ const visible = rows.slice(0, CODEX_DIGEST_VISIBLE_CAP).map((row) => {
242
+ const author = safeInline(row.authorName, "(unknown)").replace(/[;;;‒-―−]/gu, "-");
243
+ const intent = safeInline(row.intent, "(untitled Decision)").replace(/[`“-‟″‶〝〞]/gu, "'");
244
+ return `${author} \u2014 \u201C${intent}\u201D`;
245
+ });
246
+ const overflow = rows.length > CODEX_DIGEST_VISIBLE_CAP ? ` +${String(rows.length - CODEX_DIGEST_VISIBLE_CAP)}${options.pageTruncated === true ? "+" : ""}` : "";
247
+ return `[prim] Decisions captured since last message: ${visible.join("; ")}${overflow}`;
248
+ }
249
+ function actionablePrivateDrafts(rows) {
250
+ const seen = /* @__PURE__ */ new Set();
251
+ const actionable = [];
252
+ for (const row of rows) {
253
+ if (!isActionablePrivateDraft(row) || seen.has(row.id)) continue;
254
+ seen.add(row.id);
255
+ actionable.push(row);
256
+ }
257
+ return actionable;
258
+ }
259
+ function renderDecisionDraftDigest(rows, options = {}) {
260
+ const eligible = actionablePrivateDrafts(rows);
261
+ if (eligible.length === 0) return void 0;
262
+ const visible = eligible.slice(0, CODEX_DIGEST_VISIBLE_CAP);
263
+ const lines = visible.flatMap((row) => {
264
+ const intent = safeInline(row.intent, "(untitled Decision)").replace(/[“-‟″‶〝〞]/gu, "'");
265
+ return [
266
+ `[prim] private Decision ${row.id} \xB7 stage: draft \xB7 \u201C${intent}\u201D`,
267
+ `[prim] Run \`prim decisions publish ${row.id}\` to share it with your team.`
268
+ ];
269
+ });
270
+ if (eligible.length > visible.length) {
271
+ const suffix = options.pageTruncated === true ? "+" : "";
272
+ lines.push(
273
+ `[prim] +${String(eligible.length - visible.length)}${suffix} private Decision drafts remain for later messages.`
274
+ );
275
+ }
276
+ return { message: lines.join("\n"), deliveredIds: visible.map((row) => row.id) };
277
+ }
278
+ function reauthSnapshot(sessionId) {
279
+ return {
280
+ pid: 0,
281
+ uptimeMs: 0,
282
+ sessionId,
283
+ healthy: false,
284
+ needsReauth: true
285
+ };
286
+ }
287
+ function mergeState(latest, args) {
288
+ const seen = new Set(latest?.seenIds ?? []);
289
+ for (const id of args.seenIds) seen.add(id);
290
+ return {
291
+ version: STATE_VERSION,
292
+ sessionId: args.sessionId,
293
+ siteUrl: args.siteUrl,
294
+ workspace: args.workspace,
295
+ startedAt: latest?.startedAt ?? args.startedAt,
296
+ // Advance only on an observed page (server classifiedAt time), never the
297
+ // client clock; an unavailable feed keeps the previous cursor — or the
298
+ // NO_CURSOR sentinel, so the startup backlog survives until the first
299
+ // successful fetch.
300
+ watermarkMs: args.feedAvailable ? Math.max(latest?.watermarkMs ?? NO_CURSOR, args.watermarkMs) : latest?.watermarkMs ?? NO_CURSOR,
301
+ seenIds: [...seen].slice(-CODEX_DIGEST_MAX_SEEN_IDS),
302
+ lastReport: args.report,
303
+ updatedAt: args.now
304
+ };
305
+ }
306
+ async function commitState(path, args, namespace) {
307
+ try {
308
+ await withFileLock(
309
+ `${path}.lock`,
310
+ () => {
311
+ const latest = readState(path);
312
+ writeStateFile(path, stateRoot(namespace), mergeState(latest, args));
313
+ cleanupStateFiles(stateRoot(namespace), args.now);
314
+ },
315
+ { timeoutMs: 50, pollMs: 10 }
316
+ );
317
+ } catch {
318
+ }
319
+ }
320
+ function mergeDraftState(latest, args) {
321
+ const seen = new Set(latest?.seenDraftIds ?? []);
322
+ for (const id of args.deliveredIds) seen.add(id);
323
+ return {
324
+ version: DRAFT_STATE_VERSION,
325
+ sessionId: args.sessionId,
326
+ siteUrl: args.siteUrl,
327
+ workspace: args.workspace,
328
+ principalId: args.principalId,
329
+ organizationId: args.organizationId,
330
+ credentialFingerprint: args.credentialFingerprint,
331
+ seenDraftIds: [...seen].slice(-CODEX_DRAFT_DIGEST_MAX_SEEN_IDS),
332
+ updatedAt: args.now
333
+ };
334
+ }
335
+ async function commitDraftState(path, args, namespace) {
336
+ try {
337
+ let next;
338
+ await withFileLock(
339
+ `${path}.lock`,
340
+ () => {
341
+ const latest = readDraftState(path);
342
+ next = mergeDraftState(latest, args);
343
+ writeStateFile(path, draftStateRoot(namespace), next);
344
+ cleanupStateFiles(draftStateRoot(namespace), args.now);
345
+ },
346
+ { timeoutMs: 50, pollMs: 10 }
347
+ );
348
+ return next;
349
+ } catch {
350
+ return void 0;
351
+ }
352
+ }
353
+ async function prepareCodexContext(options) {
354
+ const namespace = options.namespace ?? "codex";
355
+ const siteUrl = getSiteUrl();
356
+ const workspace = workspaceFor(options.cwd);
357
+ const path = statePath({ cwd: options.cwd, sessionId: options.sessionId, siteUrl, namespace });
358
+ const previous = readState(path);
359
+ const principal = resolveDaemonPrincipal();
360
+ const privatePath = principal ? draftStatePath({
361
+ cwd: options.cwd,
362
+ sessionId: options.sessionId,
363
+ siteUrl,
364
+ principalId: principal.principalId,
365
+ organizationId: principal.organizationId,
366
+ credentialFingerprint: principal.credentialFingerprint,
367
+ namespace
368
+ }) : void 0;
369
+ const previousDraft = privatePath ? readDraftState(privatePath) : void 0;
370
+ const startup = options.startup === true;
371
+ const includeDigest = options.includeDigest !== false;
372
+ const startedAt = previous?.startedAt ?? Date.now();
373
+ const terminalAuth = isSessionEnded();
374
+ let snapshot = null;
375
+ let recent = null;
376
+ let recentDrafts = null;
377
+ if (terminalAuth) {
378
+ snapshot = reauthSnapshot(options.sessionId);
379
+ } else {
380
+ [snapshot, recent, recentDrafts] = await Promise.all([
381
+ daemonRequest(
382
+ "status_snapshot",
383
+ { callerEnv: siteUrl },
384
+ { timeoutMs: CODEX_CONTEXT_TIMEOUT_MS }
385
+ ),
386
+ includeDigest ? daemonRequest(
387
+ "decision_digest_snapshot",
388
+ { callerEnv: siteUrl },
389
+ { timeoutMs: CODEX_CONTEXT_TIMEOUT_MS }
390
+ ) : Promise.resolve(null),
391
+ includeDigest && principal !== void 0 ? daemonRequest(
392
+ "decision_draft_digest_snapshot",
393
+ { callerEnv: siteUrl },
394
+ { timeoutMs: CODEX_CONTEXT_TIMEOUT_MS }
395
+ ) : Promise.resolve(null)
396
+ ]);
397
+ if (principal !== void 0 && !daemonPrincipalsMatch(principal, resolveDaemonPrincipal())) {
398
+ snapshot = null;
399
+ recent = null;
400
+ recentDrafts = null;
401
+ }
402
+ }
403
+ let ingestionStatus;
404
+ const resolveIngestionStatus = () => {
405
+ ingestionStatus ??= decisionIngestionStatus(options.cwd);
406
+ return ingestionStatus;
407
+ };
408
+ const report = formatStatusline(packageVersion() ?? "0.0.0", snapshot, resolveIngestionStatus, {
409
+ includeIngestionWhenUnavailable: true,
410
+ plainLinks: true,
411
+ resolveRepositoryBindingState: () => resolveIngestionStatus() === "enabled" ? repositoryBindingState(options.cwd) : void 0
412
+ });
413
+ const reportChanged = startup || previous?.lastReport !== report;
414
+ let feedAvailable = false;
415
+ let freshRows = [];
416
+ let pageTruncated = false;
417
+ let pageWatermark = NO_CURSOR;
418
+ if (!terminalAuth && includeDigest && recent !== null) {
419
+ feedAvailable = recent.unavailable === void 0 && Array.isArray(recent.decisions);
420
+ if (feedAvailable) {
421
+ const seen = new Set(previous?.seenIds ?? []);
422
+ const lowerBound = previous !== void 0 && previous.watermarkMs >= 0 ? Math.max(0, previous.watermarkMs - CODEX_DIGEST_OVERLAP_MS) : 0;
423
+ freshRows = recent.decisions.filter(
424
+ (row) => isChangeDecision(row) && !seen.has(row.id) && typeof row.classifiedAt === "number" && row.classifiedAt >= lowerBound
425
+ );
426
+ pageTruncated = recent.decisions.length >= CODEX_DIGEST_LIMIT;
427
+ pageWatermark = recent.decisions.reduce(
428
+ (max, row) => typeof row.classifiedAt === "number" && row.classifiedAt > max ? row.classifiedAt : max,
429
+ NO_CURSOR
430
+ );
431
+ }
432
+ }
433
+ const digest = renderDecisionDigest(freshRows, { pageTruncated });
434
+ let draftDigest;
435
+ let draftPageToken;
436
+ let draftPageActionableIds = [];
437
+ if (!terminalAuth && includeDigest && privatePath !== void 0 && recentDrafts !== null && recentDrafts.unavailable === void 0 && Array.isArray(recentDrafts.decisions)) {
438
+ const allActionableDrafts = actionablePrivateDrafts(recentDrafts.decisions);
439
+ const seenDrafts = new Set(previousDraft?.seenDraftIds ?? []);
440
+ const freshDrafts = allActionableDrafts.filter((row) => !seenDrafts.has(row.id));
441
+ draftDigest = renderDecisionDraftDigest(freshDrafts, {
442
+ pageTruncated: recentDrafts.pageDone === false
443
+ });
444
+ draftPageToken = typeof recentDrafts.pageToken === "string" ? recentDrafts.pageToken : void 0;
445
+ draftPageActionableIds = allActionableDrafts.map((row) => row.id);
446
+ }
447
+ const combinedDigest = [digest, draftDigest?.message].filter((value) => value !== void 0).join("\n\n");
448
+ const context = [reportChanged ? report : void 0, combinedDigest || void 0].filter((value) => value !== void 0).join("\n\n") || void 0;
449
+ let acknowledged = false;
450
+ return {
451
+ context,
452
+ decisionDigest: combinedDigest || void 0,
453
+ feedAvailable,
454
+ acknowledge: async (handedOff) => {
455
+ if (!handedOff || acknowledged) return;
456
+ acknowledged = true;
457
+ await commitState(
458
+ path,
459
+ {
460
+ sessionId: options.sessionId,
461
+ siteUrl,
462
+ workspace,
463
+ startedAt,
464
+ watermarkMs: pageWatermark,
465
+ seenIds: freshRows.map((row) => row.id),
466
+ report,
467
+ feedAvailable,
468
+ now: Date.now()
469
+ },
470
+ namespace
471
+ );
472
+ if (privatePath === void 0 || principal === void 0 || draftPageToken === void 0) {
473
+ return;
474
+ }
475
+ let persistedDraft = previousDraft;
476
+ if (draftDigest?.deliveredIds.length) {
477
+ persistedDraft = await commitDraftState(
478
+ privatePath,
479
+ {
480
+ sessionId: options.sessionId,
481
+ siteUrl,
482
+ workspace,
483
+ principalId: principal.principalId,
484
+ organizationId: principal.organizationId,
485
+ credentialFingerprint: principal.credentialFingerprint,
486
+ deliveredIds: draftDigest.deliveredIds,
487
+ now: Date.now()
488
+ },
489
+ namespace
490
+ );
491
+ }
492
+ const seenDrafts = new Set(persistedDraft?.seenDraftIds ?? []);
493
+ const deliveredOnThisPage = draftPageActionableIds.filter((id) => seenDrafts.has(id));
494
+ await daemonRequest(
495
+ "decision_draft_digest_acknowledge",
496
+ {
497
+ callerEnv: siteUrl,
498
+ pageToken: draftPageToken,
499
+ deliveredIds: deliveredOnThisPage
500
+ },
501
+ { timeoutMs: CODEX_CONTEXT_TIMEOUT_MS }
502
+ );
503
+ }
504
+ };
505
+ }
506
+
507
+ export {
508
+ hasVisibleCodexMessage,
509
+ appendCodexContext,
510
+ prepareCodexContext
511
+ };