negotium 0.1.12 → 0.1.13

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 (137) hide show
  1. package/dist/canonical-mcp-bridge.js +2 -3
  2. package/dist/canonical-mcp-bridge.js.map +1 -1
  3. package/dist/chunk-a9y2rwxf.js.map +1 -1
  4. package/dist/{chunk-j0kjscb7.js → chunk-s2gez3wg.js} +20 -2
  5. package/dist/{chunk-j0kjscb7.js.map → chunk-s2gez3wg.js.map} +2 -2
  6. package/dist/cron.js +49 -25
  7. package/dist/cron.js.map +15 -14
  8. package/dist/hosted-agent.js +3012 -17
  9. package/dist/hosted-agent.js.map +30 -3
  10. package/dist/main.js +31323 -36
  11. package/dist/main.js.map +198 -3
  12. package/dist/prompts.js +11 -8
  13. package/dist/prompts.js.map +4 -4
  14. package/dist/runtime/src/application/submit-user-message.ts +3 -0
  15. package/dist/runtime/src/index.ts +7 -0
  16. package/dist/runtime/src/mcp/runtime-spec.ts +3 -0
  17. package/dist/runtime/src/mcp/session-comm/server.ts +1 -1
  18. package/dist/runtime/src/platform/mcp-config.ts +13 -0
  19. package/dist/runtime/src/prompts/builders.ts +20 -6
  20. package/dist/runtime/src/query/active-rooms.ts +2 -0
  21. package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
  22. package/dist/runtime/src/runtime/errors.ts +12 -12
  23. package/dist/runtime/src/runtime/turn-runner.ts +12 -0
  24. package/dist/runtime/src/storage/runtime-turn-requests.ts +1 -0
  25. package/dist/runtime/src/types/api.ts +2 -0
  26. package/dist/runtime/src/types.ts +2 -0
  27. package/dist/runtime/src/version.ts +1 -1
  28. package/dist/runtime-helpers.js.map +1 -1
  29. package/dist/storage.js.map +1 -1
  30. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +2 -0
  31. package/dist/types/packages/core/src/platform/mcp-config.d.ts +4 -0
  32. package/dist/types/packages/core/src/prompts/builders.d.ts +2 -0
  33. package/dist/types/packages/core/src/types/api.d.ts +2 -0
  34. package/dist/types/packages/core/src/types.d.ts +2 -0
  35. package/dist/types/packages/core/src/version.d.ts +1 -1
  36. package/dist/vault.js.map +1 -1
  37. package/package.json +1 -1
  38. package/dist/chunk-00q25k7p.js +0 -2387
  39. package/dist/chunk-00q25k7p.js.map +0 -26
  40. package/dist/chunk-03kv7mvj.js +0 -2152
  41. package/dist/chunk-03kv7mvj.js.map +0 -15
  42. package/dist/chunk-05pm51dh.js +0 -589
  43. package/dist/chunk-05pm51dh.js.map +0 -11
  44. package/dist/chunk-0eh16bk1.js +0 -2936
  45. package/dist/chunk-0eh16bk1.js.map +0 -20
  46. package/dist/chunk-0yfqyv88.js +0 -108
  47. package/dist/chunk-0yfqyv88.js.map +0 -10
  48. package/dist/chunk-1k7t7bnx.js +0 -97
  49. package/dist/chunk-1k7t7bnx.js.map +0 -10
  50. package/dist/chunk-3gkfr9vb.js +0 -431
  51. package/dist/chunk-3gkfr9vb.js.map +0 -11
  52. package/dist/chunk-5akd1gbj.js +0 -281
  53. package/dist/chunk-5akd1gbj.js.map +0 -10
  54. package/dist/chunk-7k19pcg8.js +0 -577
  55. package/dist/chunk-7k19pcg8.js.map +0 -14
  56. package/dist/chunk-81tbfbmt.js +0 -10
  57. package/dist/chunk-81tbfbmt.js.map +0 -10
  58. package/dist/chunk-82qhv1mq.js +0 -512
  59. package/dist/chunk-82qhv1mq.js.map +0 -13
  60. package/dist/chunk-8dy7e2a9.js +0 -103
  61. package/dist/chunk-8dy7e2a9.js.map +0 -10
  62. package/dist/chunk-8f2sqmrj.js +0 -1712
  63. package/dist/chunk-8f2sqmrj.js.map +0 -18
  64. package/dist/chunk-9hjeemfz.js +0 -372
  65. package/dist/chunk-9hjeemfz.js.map +0 -10
  66. package/dist/chunk-a4aa2ccv.js +0 -141
  67. package/dist/chunk-a4aa2ccv.js.map +0 -10
  68. package/dist/chunk-bsg215q3.js +0 -3536
  69. package/dist/chunk-bsg215q3.js.map +0 -20
  70. package/dist/chunk-bxnfsc7w.js +0 -58
  71. package/dist/chunk-bxnfsc7w.js.map +0 -10
  72. package/dist/chunk-c500xe9z.js +0 -33
  73. package/dist/chunk-c500xe9z.js.map +0 -10
  74. package/dist/chunk-cngrf7ab.js +0 -149
  75. package/dist/chunk-cngrf7ab.js.map +0 -10
  76. package/dist/chunk-d7tprf06.js +0 -53
  77. package/dist/chunk-d7tprf06.js.map +0 -10
  78. package/dist/chunk-ddnrmkrv.js +0 -61
  79. package/dist/chunk-ddnrmkrv.js.map +0 -10
  80. package/dist/chunk-edb07sjp.js +0 -567
  81. package/dist/chunk-edb07sjp.js.map +0 -14
  82. package/dist/chunk-ejcm6zx8.js +0 -591
  83. package/dist/chunk-ejcm6zx8.js.map +0 -11
  84. package/dist/chunk-ezs352qs.js +0 -237
  85. package/dist/chunk-ezs352qs.js.map +0 -11
  86. package/dist/chunk-f5xgprg1.js +0 -59
  87. package/dist/chunk-f5xgprg1.js.map +0 -10
  88. package/dist/chunk-fbtb3v0s.js +0 -1339
  89. package/dist/chunk-fbtb3v0s.js.map +0 -16
  90. package/dist/chunk-ffefbd3r.js +0 -17
  91. package/dist/chunk-ffefbd3r.js.map +0 -10
  92. package/dist/chunk-gaknyw04.js +0 -708
  93. package/dist/chunk-gaknyw04.js.map +0 -14
  94. package/dist/chunk-gxmny6tq.js +0 -1637
  95. package/dist/chunk-gxmny6tq.js.map +0 -15
  96. package/dist/chunk-h7bj5zwb.js +0 -3069
  97. package/dist/chunk-h7bj5zwb.js.map +0 -32
  98. package/dist/chunk-hp4g7wx7.js +0 -46
  99. package/dist/chunk-hp4g7wx7.js.map +0 -10
  100. package/dist/chunk-hwy3n31w.js +0 -21
  101. package/dist/chunk-hwy3n31w.js.map +0 -9
  102. package/dist/chunk-jzz91jwh.js +0 -70
  103. package/dist/chunk-jzz91jwh.js.map +0 -10
  104. package/dist/chunk-k778y16p.js +0 -153
  105. package/dist/chunk-k778y16p.js.map +0 -11
  106. package/dist/chunk-mh5mexsf.js +0 -147
  107. package/dist/chunk-mh5mexsf.js.map +0 -11
  108. package/dist/chunk-mnwaext5.js +0 -318
  109. package/dist/chunk-mnwaext5.js.map +0 -10
  110. package/dist/chunk-nkgs40ch.js +0 -23
  111. package/dist/chunk-nkgs40ch.js.map +0 -10
  112. package/dist/chunk-pz57vwsm.js +0 -250
  113. package/dist/chunk-pz57vwsm.js.map +0 -11
  114. package/dist/chunk-r6kdp7gn.js +0 -252
  115. package/dist/chunk-r6kdp7gn.js.map +0 -10
  116. package/dist/chunk-rkvrkcgx.js +0 -117
  117. package/dist/chunk-rkvrkcgx.js.map +0 -10
  118. package/dist/chunk-s74rdyqe.js +0 -117
  119. package/dist/chunk-s74rdyqe.js.map +0 -12
  120. package/dist/chunk-sa874j5c.js +0 -9
  121. package/dist/chunk-sa874j5c.js.map +0 -10
  122. package/dist/chunk-sffqdkvq.js +0 -122
  123. package/dist/chunk-sffqdkvq.js.map +0 -10
  124. package/dist/chunk-tcs9qjps.js +0 -64
  125. package/dist/chunk-tcs9qjps.js.map +0 -10
  126. package/dist/chunk-wx83ep8e.js +0 -131
  127. package/dist/chunk-wx83ep8e.js.map +0 -10
  128. package/dist/chunk-xag86ng3.js +0 -122
  129. package/dist/chunk-xag86ng3.js.map +0 -10
  130. package/dist/chunk-xfdkep71.js +0 -371
  131. package/dist/chunk-xfdkep71.js.map +0 -11
  132. package/dist/chunk-xhm1rfpt.js +0 -2907
  133. package/dist/chunk-xhm1rfpt.js.map +0 -24
  134. package/dist/chunk-xpcps28p.js +0 -2138
  135. package/dist/chunk-xpcps28p.js.map +0 -29
  136. package/dist/chunk-yb4rbev9.js +0 -214
  137. package/dist/chunk-yb4rbev9.js.map +0 -10
@@ -1,708 +0,0 @@
1
- import {
2
- parseJsonlText,
3
- writeJsonlFile
4
- } from "./chunk-mh5mexsf.js";
5
- import {
6
- CLAUDE_EFFORT_VALUES,
7
- DM_WORKSPACE_DIR,
8
- MODEL_FABLE,
9
- MODEL_OPUS,
10
- MODEL_SONNET,
11
- TOPIC_WORKSPACE_DIR,
12
- WORKSPACE_DIR
13
- } from "./chunk-ezs352qs.js";
14
- import {
15
- logger
16
- } from "./chunk-ffefbd3r.js";
17
- import {
18
- __require,
19
- __toESM
20
- } from "./chunk-hwy3n31w.js";
21
-
22
- // ../../packages/core/src/platform/maestro-bootstrap-env.ts
23
- process.env.MAESTRO_SDK_SILENT_BOOTSTRAP ??= "1";
24
-
25
- // ../../packages/core/src/agents/claude-registry.ts
26
- import { existsSync as existsSync2, mkdirSync as mkdirSync2, readdirSync, renameSync, unlinkSync } from "fs";
27
- import { homedir as homedir2 } from "os";
28
- import { join as join3 } from "path";
29
-
30
- // ../../packages/core/src/agents/rollout/claude.ts
31
- import { randomUUID } from "crypto";
32
- import { existsSync, readFileSync, writeFileSync } from "fs";
33
- import { homedir } from "os";
34
- import { join as join2 } from "path";
35
-
36
- // ../../packages/core/src/agents/rollout/shared.ts
37
- import { mkdirSync } from "fs";
38
- import { dirname, join, resolve } from "path";
39
- import { fileURLToPath } from "url";
40
- var __dirname2 = dirname(fileURLToPath(import.meta.url));
41
- var trustedWorkspaceRoots = [WORKSPACE_DIR, DM_WORKSPACE_DIR, TOPIC_WORKSPACE_DIR].map((root) => resolve(root));
42
- var FIXTURES_DIR = join(__dirname2, "..", "fixtures");
43
- function clone(obj) {
44
- return structuredClone(obj);
45
- }
46
- var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
47
- function assertUuidLike(label, value) {
48
- if (!UUID_RE.test(value)) {
49
- throw new Error(`rollout: ${label} is not a UUID-shaped string: ${value}`);
50
- }
51
- }
52
- function assertCwdInWorkspace(cwd) {
53
- const abs = resolve(cwd);
54
- const ok = trustedWorkspaceRoots.some((root) => abs === root || abs.startsWith(`${root}/`));
55
- if (!ok) {
56
- throw new Error(`rollout: cwd outside trusted workspace roots: ${cwd} (resolved=${abs})`);
57
- }
58
- }
59
- function ensureCwdExists(cwd) {
60
- assertCwdInWorkspace(cwd);
61
- try {
62
- mkdirSync(cwd, { recursive: true });
63
- } catch (err) {
64
- logger.warn({ err, cwd }, "rollout: ensureCwdExists failed \u2014 caller should pre-create cwd");
65
- }
66
- }
67
- function truncate(text, n) {
68
- const cps = Array.from(text);
69
- return cps.length > n ? `${cps.slice(0, n).join("")}\u2026` : text;
70
- }
71
- function extractChatPairs(entries, opts = { includeToolAnnotations: true }) {
72
- const pairs = [];
73
- let pendingUser = null;
74
- let pendingAssistantParts = [];
75
- let toolBuffer = [];
76
- const flushAssistant = () => {
77
- if (pendingUser === null)
78
- return;
79
- const tools = opts.includeToolAnnotations && toolBuffer.length > 0 ? `
80
-
81
- ${toolBuffer.join(`
82
- `)}` : "";
83
- const assistantText = pendingAssistantParts.join("").trim() + tools;
84
- if (assistantText.trim()) {
85
- pairs.push({ userText: pendingUser, assistantText });
86
- }
87
- pendingUser = null;
88
- pendingAssistantParts = [];
89
- toolBuffer = [];
90
- };
91
- for (const entry of entries) {
92
- const ev = entry.event;
93
- switch (ev.type) {
94
- case "user_message": {
95
- flushAssistant();
96
- pendingUser = ev.content;
97
- break;
98
- }
99
- case "session":
100
- if (pendingAssistantParts.length > 0 || toolBuffer.length > 0) {
101
- flushAssistant();
102
- }
103
- break;
104
- case "text": {
105
- if (pendingUser === null) {
106
- pendingUser = "(continued)";
107
- }
108
- pendingAssistantParts.push(ev.content);
109
- break;
110
- }
111
- case "result": {
112
- if (pendingUser === null) {
113
- pendingUser = "(continued)";
114
- }
115
- pendingAssistantParts = [ev.content];
116
- flushAssistant();
117
- break;
118
- }
119
- case "text_delta":
120
- break;
121
- case "tool_use": {
122
- const u = ev;
123
- toolBuffer.push(`<!-- Tool: ${u.name} ${truncate(JSON.stringify(u.input), 200)} -->`);
124
- break;
125
- }
126
- case "tool_result": {
127
- const u = ev;
128
- toolBuffer.push(`<!-- Tool result: ${truncate(u.content, 200)} -->`);
129
- break;
130
- }
131
- case "error": {
132
- const u = ev;
133
- toolBuffer.push(`[Error: ${truncate(u.content, 200)}]`);
134
- break;
135
- }
136
- case "tool_progress":
137
- case "tool_use_summary":
138
- case "file":
139
- case "status":
140
- break;
141
- }
142
- }
143
- flushAssistant();
144
- return pairs;
145
- }
146
-
147
- // ../../packages/core/src/agents/rollout/claude.ts
148
- var _attachmentsCache = null;
149
- function loadClaudeAttachments() {
150
- if (_attachmentsCache)
151
- return _attachmentsCache;
152
- const raw = readFileSync(join2(FIXTURES_DIR, "claude-attachments.jsonl"), "utf8");
153
- const lines = parseJsonlText(raw);
154
- if (lines.length < 2) {
155
- throw new Error(`loadClaudeAttachments: expected >=2 entries in claude-attachments.jsonl, got ${lines.length}`);
156
- }
157
- _attachmentsCache = {
158
- deferredToolsDelta: lines[0],
159
- skillListing: lines[1]
160
- };
161
- return _attachmentsCache;
162
- }
163
- var CLAUDE_SDK_VERSION = "2.1.126";
164
- var CLAUDE_DEFAULT_MODEL = "claude-sonnet-5";
165
- var CLAUDE_DEFAULT_GIT_BRANCH = "HEAD";
166
- function encodeClaudeCwd(cwd) {
167
- const realCwd = cwd.startsWith("/tmp/") ? cwd.replace(/^\/tmp\//, "/private/tmp/") : cwd;
168
- return `-${realCwd.replaceAll(/[^a-zA-Z0-9]/g, "-").replace(/^-/, "")}`;
169
- }
170
- function writeClaudeRollout(opts) {
171
- const sessionId = opts.sessionId ?? randomUUID();
172
- assertUuidLike("sessionId", sessionId);
173
- ensureCwdExists(opts.cwd);
174
- const pairs = opts.pairs ?? extractChatPairs(opts.entries ?? []);
175
- const cwdReal = opts.cwd.startsWith("/tmp/") ? opts.cwd.replace(/^\/tmp\//, "/private/tmp/") : opts.cwd;
176
- const lines = [];
177
- const ts = () => new Date().toISOString();
178
- let lastUuid = null;
179
- lines.push({ type: "queue-operation", operation: "enqueue", timestamp: ts(), sessionId });
180
- lines.push({ type: "queue-operation", operation: "dequeue", timestamp: ts(), sessionId });
181
- const attachments = loadClaudeAttachments();
182
- for (const pair of pairs) {
183
- const userUuid = randomUUID();
184
- lines.push({
185
- parentUuid: lastUuid,
186
- isSidechain: false,
187
- promptId: randomUUID(),
188
- type: "user",
189
- message: { role: "user", content: [{ type: "text", text: pair.userText }] },
190
- uuid: userUuid,
191
- timestamp: ts(),
192
- permissionMode: "bypassPermissions",
193
- userType: "external",
194
- entrypoint: "sdk-ts",
195
- cwd: cwdReal,
196
- sessionId,
197
- version: CLAUDE_SDK_VERSION,
198
- gitBranch: CLAUDE_DEFAULT_GIT_BRANCH
199
- });
200
- const att1Uuid = randomUUID();
201
- const att1 = clone(attachments.deferredToolsDelta);
202
- att1.parentUuid = userUuid;
203
- att1.uuid = att1Uuid;
204
- att1.timestamp = ts();
205
- att1.sessionId = sessionId;
206
- att1.cwd = cwdReal;
207
- lines.push(att1);
208
- const att2Uuid = randomUUID();
209
- const att2 = clone(attachments.skillListing);
210
- att2.parentUuid = att1Uuid;
211
- att2.uuid = att2Uuid;
212
- att2.timestamp = ts();
213
- att2.sessionId = sessionId;
214
- att2.cwd = cwdReal;
215
- lines.push(att2);
216
- const assistantUuid = randomUUID();
217
- lines.push({
218
- parentUuid: att2Uuid,
219
- isSidechain: false,
220
- message: {
221
- model: opts.model ?? CLAUDE_DEFAULT_MODEL,
222
- id: `msg_${randomUUID().replace(/-/g, "").slice(0, 24)}`,
223
- type: "message",
224
- role: "assistant",
225
- content: [{ type: "text", text: pair.assistantText }],
226
- stop_reason: "end_turn",
227
- stop_sequence: null,
228
- stop_details: null,
229
- usage: {
230
- input_tokens: 0,
231
- cache_creation_input_tokens: 0,
232
- cache_read_input_tokens: 0,
233
- output_tokens: 0,
234
- server_tool_use: { web_search_requests: 0, web_fetch_requests: 0 },
235
- service_tier: "standard",
236
- cache_creation: { ephemeral_1h_input_tokens: 0, ephemeral_5m_input_tokens: 0 },
237
- inference_geo: "",
238
- iterations: [],
239
- speed: "standard"
240
- },
241
- diagnostics: null
242
- },
243
- requestId: `req_${randomUUID().replace(/-/g, "").slice(0, 22)}`,
244
- type: "assistant",
245
- uuid: assistantUuid,
246
- timestamp: ts(),
247
- userType: "external",
248
- entrypoint: "sdk-ts",
249
- cwd: cwdReal,
250
- sessionId,
251
- version: CLAUDE_SDK_VERSION,
252
- gitBranch: CLAUDE_DEFAULT_GIT_BRANCH
253
- });
254
- lastUuid = assistantUuid;
255
- }
256
- const projectsDir = join2(homedir(), ".claude", "projects", encodeClaudeCwd(opts.cwd));
257
- const path = join2(projectsDir, `${sessionId}.jsonl`);
258
- writeJsonlFile(path, lines);
259
- logger.info({ sessionId, path, pairs: pairs.length }, "writeClaudeRollout: synthetic rollout placed");
260
- return { sessionId, rolloutPath: path };
261
- }
262
-
263
- // ../../packages/core/src/agents/claude-registry.ts
264
- var ALIAS_MAP = {
265
- sonnet: MODEL_SONNET,
266
- opus: MODEL_OPUS,
267
- fable: MODEL_FABLE
268
- };
269
- var VALID_ALIASES = new Set(Object.keys(ALIAS_MAP));
270
- var VALID_EFFORTS = new Set(CLAUDE_EFFORT_VALUES);
271
- var claudeRegistry = {
272
- kind: "claude",
273
- defaultModel: "sonnet",
274
- defaultEffort: "high",
275
- expandModelAlias(s) {
276
- return ALIAS_MAP[s] ?? s;
277
- },
278
- validateModel(s) {
279
- return VALID_ALIASES.has(s);
280
- },
281
- validEfforts: CLAUDE_EFFORT_VALUES,
282
- validateEffort(s) {
283
- return VALID_EFFORTS.has(s);
284
- },
285
- footerLabel(model, effort) {
286
- return effort ? `${model} \xB7 ${effort}` : model;
287
- },
288
- writeRollout(opts) {
289
- const { sessionId, rolloutPath } = writeClaudeRollout({
290
- cwd: opts.cwd,
291
- entries: opts.entries,
292
- model: claudeRegistry.expandModelAlias(opts.model ?? claudeRegistry.defaultModel),
293
- ...opts.reuseSessionId ? { sessionId: opts.reuseSessionId } : {}
294
- });
295
- return { sessionId, rolloutPath };
296
- },
297
- async forkSession({ parentSessionId, cwd, title }) {
298
- const { forkSession } = await import("@anthropic-ai/claude-agent-sdk");
299
- const result = await forkSession(parentSessionId, {
300
- ...title ? { title } : {}
301
- });
302
- const projectsRoot = join3(homedir2(), ".claude", "projects");
303
- const destDir = join3(projectsRoot, encodeClaudeCwd(cwd));
304
- const destPath = join3(destDir, `${result.sessionId}.jsonl`);
305
- if (!existsSync2(destPath)) {
306
- const sourcePath = readdirSync(projectsRoot).map((d) => join3(projectsRoot, d, `${result.sessionId}.jsonl`)).find((p) => existsSync2(p));
307
- if (!sourcePath) {
308
- throw new Error(`claude forkSession: fork rollout ${result.sessionId}.jsonl not found under ${projectsRoot}`);
309
- }
310
- mkdirSync2(destDir, { recursive: true });
311
- renameSync(sourcePath, destPath);
312
- }
313
- return {
314
- forkId: result.sessionId,
315
- rolloutPath: destPath
316
- };
317
- },
318
- async cleanupRollouts({ cwd, sessionIds }) {
319
- const projectsDir = join3(homedir2(), ".claude", "projects", encodeClaudeCwd(cwd));
320
- const failures = [];
321
- for (const sid of sessionIds) {
322
- const path = join3(projectsDir, `${sid}.jsonl`);
323
- try {
324
- unlinkSync(path);
325
- } catch (e) {
326
- if (e?.code !== "ENOENT") {
327
- logger.warn({ err: e, path }, "claude cleanupRollouts: unlink failed");
328
- failures.push(e);
329
- }
330
- }
331
- }
332
- if (failures.length > 0) {
333
- throw new AggregateError(failures, "claude cleanupRollouts failed");
334
- }
335
- }
336
- };
337
-
338
- // ../../packages/core/src/agents/rollout/codex.ts
339
- import { randomBytes } from "crypto";
340
- import { existsSync as existsSync3, readFileSync as readFileSync2, statSync, unlinkSync as unlinkSync2 } from "fs";
341
- import { homedir as homedir3 } from "os";
342
- import { join as join4 } from "path";
343
- function codexSessionsDir() {
344
- return join4(process.env.CODEX_HOME || join4(homedir3(), ".codex"), "sessions");
345
- }
346
- var _shellCache = null;
347
- function loadCodexShell() {
348
- if (_shellCache)
349
- return _shellCache;
350
- const raw = readFileSync2(join4(FIXTURES_DIR, "codex-shell.jsonl"), "utf8");
351
- const lines = parseJsonlText(raw);
352
- if (lines.length < 5) {
353
- throw new Error(`loadCodexShell: expected >=5 entries in codex-shell.jsonl, got ${lines.length}`);
354
- }
355
- _shellCache = {
356
- sessionMeta: lines[0],
357
- taskStarted: lines[1],
358
- developerSetup: lines[2],
359
- envContext: lines[3],
360
- turnContext: lines[4]
361
- };
362
- return _shellCache;
363
- }
364
- function uuidv7() {
365
- const ts = Date.now();
366
- const tsHex = ts.toString(16).padStart(12, "0");
367
- const rand = randomBytes(10);
368
- rand[0] = rand[0] & 15 | 112;
369
- rand[2] = rand[2] & 63 | 128;
370
- return [
371
- tsHex.slice(0, 8),
372
- tsHex.slice(8, 12),
373
- rand.slice(0, 2).toString("hex"),
374
- rand.slice(2, 4).toString("hex"),
375
- rand.slice(4, 10).toString("hex")
376
- ].join("-");
377
- }
378
- function patchDeveloperSetup(developerSetup) {
379
- const payload = developerSetup.payload;
380
- if (!payload)
381
- return;
382
- payload.content = [
383
- {
384
- type: "input_text",
385
- text: [
386
- "<permissions instructions>",
387
- "Filesystem sandboxing is disabled for this runtime turn (`danger-full-access`).",
388
- "Approval policy is `never`.",
389
- "</permissions instructions>"
390
- ].join(`
391
- `)
392
- }
393
- ];
394
- }
395
- function patchEnvContext(envContext, cwd, currentDate, timezone) {
396
- const payload = envContext.payload;
397
- if (!payload)
398
- return;
399
- const content = payload.content;
400
- if (!Array.isArray(content))
401
- return;
402
- for (const block of content) {
403
- if (block.type === "input_text" && typeof block.text === "string") {
404
- block.text = block.text.replace(/<cwd>[^<]*<\/cwd>/, `<cwd>${cwd}</cwd>`).replace(/<current_date>[^<]*<\/current_date>/, `<current_date>${currentDate}</current_date>`).replace(/<timezone>[^<]*<\/timezone>/, `<timezone>${timezone}</timezone>`);
405
- }
406
- }
407
- }
408
- function extractLatestCodexContextUsage(jsonl) {
409
- const lines = jsonl.trimEnd().split(`
410
- `);
411
- for (let index = lines.length - 1;index >= 0; index -= 1) {
412
- try {
413
- const entry = JSON.parse(lines[index] ?? "");
414
- if (entry.type !== "event_msg" || entry.payload?.type !== "token_count")
415
- continue;
416
- const contextTokens = entry.payload.info?.last_token_usage?.total_tokens;
417
- const contextWindow = entry.payload.info?.model_context_window;
418
- if (typeof contextTokens === "number" && Number.isFinite(contextTokens) && contextTokens >= 0 && typeof contextWindow === "number" && Number.isFinite(contextWindow) && contextWindow > 0) {
419
- return { contextTokens, contextWindow };
420
- }
421
- } catch {}
422
- }
423
- return;
424
- }
425
- function readLatestCodexContextUsage(threadId) {
426
- const sessionsDir = codexSessionsDir();
427
- const candidates = [];
428
- const buckets = candidateDateBuckets(threadId);
429
- try {
430
- if (buckets) {
431
- for (const bucket of buckets) {
432
- const dir = join4(sessionsDir, bucket);
433
- if (!existsSync3(dir))
434
- continue;
435
- const glob = new Bun.Glob(`rollout-*-${threadId}.jsonl`);
436
- for (const rel of glob.scanSync({ cwd: dir, onlyFiles: true })) {
437
- candidates.push(join4(dir, rel));
438
- }
439
- }
440
- } else {
441
- const glob = new Bun.Glob(`**/rollout-*-${threadId}.jsonl`);
442
- for (const rel of glob.scanSync({ cwd: sessionsDir, onlyFiles: true })) {
443
- candidates.push(join4(sessionsDir, rel));
444
- }
445
- }
446
- const path = candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
447
- return path ? extractLatestCodexContextUsage(readFileSync2(path, "utf8")) : undefined;
448
- } catch (error) {
449
- logger.debug({ error, threadId }, "codex context usage: rollout read failed");
450
- return;
451
- }
452
- }
453
- function migrateCodexRolloutNativeMultiAgentMetadata(threadId) {
454
- const path = latestCodexRolloutPath(threadId);
455
- if (!path)
456
- return false;
457
- try {
458
- const entries = parseJsonlText(readFileSync2(path, "utf8"));
459
- let changed = false;
460
- for (const entry of entries) {
461
- if (entry.type !== "session_meta" && entry.type !== "turn_context")
462
- continue;
463
- if (!entry.payload)
464
- entry.payload = {};
465
- if (entry.payload.multi_agent_version !== "disabled") {
466
- entry.payload.multi_agent_version = "disabled";
467
- changed = true;
468
- }
469
- }
470
- if (changed) {
471
- writeJsonlFile(path, entries);
472
- logger.info({ threadId, path }, "codex rollout native multi-agent metadata disabled");
473
- }
474
- return changed;
475
- } catch (error) {
476
- logger.error({ error, threadId, path }, "codex rollout native multi-agent migration failed");
477
- throw new Error(`Failed to migrate Codex rollout '${threadId}'`, { cause: error });
478
- }
479
- }
480
- function latestCodexRolloutPath(threadId) {
481
- const sessionsDir = codexSessionsDir();
482
- const candidates = [];
483
- const buckets = candidateDateBuckets(threadId);
484
- try {
485
- if (buckets) {
486
- for (const bucket of buckets) {
487
- const dir = join4(sessionsDir, bucket);
488
- if (!existsSync3(dir))
489
- continue;
490
- const glob = new Bun.Glob(`rollout-*-${threadId}.jsonl`);
491
- for (const rel of glob.scanSync({ cwd: dir, onlyFiles: true })) {
492
- candidates.push(join4(dir, rel));
493
- }
494
- }
495
- }
496
- if (candidates.length === 0) {
497
- const glob = new Bun.Glob(`**/rollout-*-${threadId}.jsonl`);
498
- for (const rel of glob.scanSync({ cwd: sessionsDir, onlyFiles: true })) {
499
- candidates.push(join4(sessionsDir, rel));
500
- }
501
- }
502
- return candidates.sort((a, b) => statSync(b).mtimeMs - statSync(a).mtimeMs)[0];
503
- } catch (error) {
504
- logger.debug({ error, threadId }, "codex rollout lookup failed");
505
- return;
506
- }
507
- }
508
- function writeCodexRollout(opts) {
509
- const threadId = opts.threadId ?? uuidv7();
510
- assertUuidLike("threadId", threadId);
511
- ensureCwdExists(opts.cwd);
512
- const pairs = opts.pairs ?? extractChatPairs(opts.entries ?? []);
513
- const now = new Date;
514
- const tsIso = now.toISOString();
515
- const currentDate = [
516
- now.getFullYear(),
517
- String(now.getMonth() + 1).padStart(2, "0"),
518
- String(now.getDate()).padStart(2, "0")
519
- ].join("-");
520
- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || process.env.TZ || "UTC";
521
- const shell = loadCodexShell();
522
- const sessionMeta = clone(shell.sessionMeta);
523
- sessionMeta.payload.id = threadId;
524
- sessionMeta.payload.timestamp = tsIso;
525
- sessionMeta.payload.cwd = opts.cwd;
526
- sessionMeta.payload.multi_agent_version = "disabled";
527
- sessionMeta.timestamp = tsIso;
528
- const taskStarted = clone(shell.taskStarted);
529
- taskStarted.timestamp = tsIso;
530
- const developerSetup = clone(shell.developerSetup);
531
- developerSetup.timestamp = tsIso;
532
- patchDeveloperSetup(developerSetup);
533
- const envContext = clone(shell.envContext);
534
- envContext.timestamp = tsIso;
535
- patchEnvContext(envContext, opts.cwd, currentDate, timezone);
536
- const turnContext = clone(shell.turnContext);
537
- turnContext.timestamp = tsIso;
538
- const turnPayload = turnContext.payload;
539
- turnPayload.cwd = opts.cwd;
540
- turnPayload.current_date = currentDate;
541
- turnPayload.timezone = timezone;
542
- turnPayload.approval_policy = "never";
543
- turnPayload.sandbox_policy = { type: "danger-full-access" };
544
- turnPayload.multi_agent_version = "disabled";
545
- delete turnPayload.permission_profile;
546
- if (opts.model)
547
- turnPayload.model = opts.model;
548
- const collaborationMode = turnPayload.collaboration_mode;
549
- const collaborationSettings = collaborationMode?.settings;
550
- if (collaborationSettings) {
551
- if (opts.model)
552
- collaborationSettings.model = opts.model;
553
- if (opts.effort !== undefined)
554
- collaborationSettings.reasoning_effort = opts.effort;
555
- }
556
- const lines = [sessionMeta, taskStarted, developerSetup, envContext, turnContext];
557
- for (const pair of pairs) {
558
- lines.push({
559
- timestamp: tsIso,
560
- type: "response_item",
561
- payload: {
562
- type: "message",
563
- role: "user",
564
- content: [{ type: "input_text", text: pair.userText }]
565
- }
566
- });
567
- lines.push({
568
- timestamp: tsIso,
569
- type: "event_msg",
570
- payload: {
571
- type: "user_message",
572
- message: pair.userText,
573
- images: [],
574
- local_images: [],
575
- text_elements: []
576
- }
577
- });
578
- lines.push({
579
- timestamp: tsIso,
580
- type: "event_msg",
581
- payload: {
582
- type: "agent_message",
583
- message: pair.assistantText,
584
- phase: "final_answer",
585
- memory_citation: null
586
- }
587
- });
588
- lines.push({
589
- timestamp: tsIso,
590
- type: "response_item",
591
- payload: {
592
- type: "message",
593
- role: "assistant",
594
- content: [{ type: "output_text", text: pair.assistantText }],
595
- phase: "final_answer"
596
- }
597
- });
598
- }
599
- lines.push({
600
- timestamp: tsIso,
601
- type: "event_msg",
602
- payload: { type: "task_complete" }
603
- });
604
- const yyyy = now.getUTCFullYear();
605
- const mm = String(now.getUTCMonth() + 1).padStart(2, "0");
606
- const dd = String(now.getUTCDate()).padStart(2, "0");
607
- const tsStr = tsIso.replace(/[:.]/g, "-").slice(0, 19);
608
- const dir = join4(codexSessionsDir(), String(yyyy), mm, dd);
609
- const path = join4(dir, `rollout-${tsStr}-${threadId}.jsonl`);
610
- if (opts.threadId) {
611
- sweepPriorRolloutsForThread(opts.threadId);
612
- }
613
- writeJsonlFile(path, lines);
614
- logger.info({ threadId, path, pairs: pairs.length }, "writeCodexRollout: synthetic rollout placed");
615
- return { threadId, rolloutPath: path };
616
- }
617
- function sweepPriorRolloutsForThread(threadId) {
618
- const sessionsDir = codexSessionsDir();
619
- const buckets = candidateDateBuckets(threadId);
620
- if (!buckets) {
621
- sweepPriorRolloutsFullTree(threadId, sessionsDir);
622
- return;
623
- }
624
- for (const bucket of buckets) {
625
- const dir = join4(sessionsDir, bucket);
626
- if (!existsSync3(dir))
627
- continue;
628
- try {
629
- const glob = new Bun.Glob(`rollout-*-${threadId}.jsonl`);
630
- for (const rel of glob.scanSync({ cwd: dir, onlyFiles: true })) {
631
- const fullPath = join4(dir, rel);
632
- try {
633
- unlinkSync2(fullPath);
634
- } catch (e) {
635
- if (e?.code !== "ENOENT") {
636
- logger.warn({ err: e, path: fullPath }, "writeCodexRollout: prior-rollout unlink failed (continuing)");
637
- }
638
- }
639
- }
640
- } catch (e) {
641
- logger.warn({ err: e, threadId, bucket }, "writeCodexRollout: prior-rollout bucket scan failed (continuing)");
642
- }
643
- }
644
- }
645
- function sweepPriorRolloutsFullTree(threadId, sessionsDir) {
646
- try {
647
- const glob = new Bun.Glob(`**/rollout-*-${threadId}.jsonl`);
648
- for (const rel of glob.scanSync({ cwd: sessionsDir, onlyFiles: true })) {
649
- const fullPath = join4(sessionsDir, rel);
650
- try {
651
- unlinkSync2(fullPath);
652
- } catch (e) {
653
- if (e?.code !== "ENOENT") {
654
- logger.warn({ err: e, path: fullPath }, "writeCodexRollout: prior-rollout unlink failed (continuing)");
655
- }
656
- }
657
- }
658
- } catch (e) {
659
- logger.warn({ err: e, threadId }, "writeCodexRollout: full-tree prior-rollout sweep failed (continuing)");
660
- }
661
- }
662
- var MAX_DAY_SPAN = 30;
663
- var DAY_MS = 86400000;
664
- var LOCAL_DATE_SKEW_DAYS = 1;
665
- function candidateDateBuckets(threadId) {
666
- const tidMs = decodeUuidV7Timestamp(threadId);
667
- if (tidMs === null)
668
- return null;
669
- const nowMs = Date.now();
670
- const tidDay = Math.floor(tidMs / DAY_MS);
671
- const todayDay = Math.floor(nowMs / DAY_MS);
672
- const minDay = Math.min(tidDay, todayDay);
673
- const maxDay = Math.max(tidDay, todayDay);
674
- const span = maxDay - minDay;
675
- if (span > MAX_DAY_SPAN)
676
- return null;
677
- const buckets = new Set;
678
- for (let d = minDay - LOCAL_DATE_SKEW_DAYS;d <= maxDay + LOCAL_DATE_SKEW_DAYS; d++) {
679
- buckets.add(formatDateBucket(new Date(d * DAY_MS)));
680
- }
681
- return buckets;
682
- }
683
- function decodeUuidV7Timestamp(threadId) {
684
- if (typeof threadId !== "string")
685
- return null;
686
- const m = /^([0-9a-fA-F]{8})-([0-9a-fA-F]{4})-7[0-9a-fA-F]{3}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.exec(threadId);
687
- if (!m)
688
- return null;
689
- const hex = `${m[1]}${m[2]}`;
690
- const ms = Number.parseInt(hex, 16);
691
- if (!Number.isFinite(ms))
692
- return null;
693
- const MIN = 1577836800000;
694
- const MAX = 4102444800000;
695
- if (ms < MIN || ms > MAX)
696
- return null;
697
- return ms;
698
- }
699
- function formatDateBucket(d) {
700
- const yyyy = d.getUTCFullYear();
701
- const mm = String(d.getUTCMonth() + 1).padStart(2, "0");
702
- const dd = String(d.getUTCDate()).padStart(2, "0");
703
- return `${yyyy}/${mm}/${dd}`;
704
- }
705
-
706
- export { encodeClaudeCwd, claudeRegistry, readLatestCodexContextUsage, migrateCodexRolloutNativeMultiAgentMetadata, writeCodexRollout };
707
-
708
- //# debugId=71ABF0D7167D5AE464756E2164756E21