negotium 0.1.11 → 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 (165) hide show
  1. package/README.md +11 -2
  2. package/dist/canonical-mcp-bridge.js +2 -3
  3. package/dist/canonical-mcp-bridge.js.map +1 -1
  4. package/dist/{chunk-gz12qcf0.js → chunk-a9y2rwxf.js} +2 -2
  5. package/dist/{chunk-gz12qcf0.js.map → chunk-a9y2rwxf.js.map} +3 -3
  6. package/dist/{chunk-j0kjscb7.js → chunk-s2gez3wg.js} +20 -2
  7. package/dist/{chunk-j0kjscb7.js.map → chunk-s2gez3wg.js.map} +2 -2
  8. package/dist/cron.js +292 -256
  9. package/dist/cron.js.map +23 -22
  10. package/dist/hosted-agent.js +3012 -17
  11. package/dist/hosted-agent.js.map +30 -3
  12. package/dist/main.js +31323 -36
  13. package/dist/main.js.map +198 -3
  14. package/dist/prompts.js +12 -9
  15. package/dist/prompts.js.map +5 -5
  16. package/dist/registry.js +10 -6
  17. package/dist/registry.js.map +3 -3
  18. package/dist/rollout.js +1 -1
  19. package/dist/runtime/cron/store.ts +24 -1
  20. package/dist/runtime/src/application/submit-user-message.ts +3 -0
  21. package/dist/runtime/src/index.ts +7 -0
  22. package/dist/runtime/src/mcp/runtime-spec.ts +3 -0
  23. package/dist/runtime/src/mcp/session-comm/server.ts +1 -1
  24. package/dist/runtime/src/platform/config.ts +2 -2
  25. package/dist/runtime/src/platform/mcp-config.ts +13 -0
  26. package/dist/runtime/src/prompts/builders.ts +20 -6
  27. package/dist/runtime/src/query/active-rooms.ts +2 -0
  28. package/dist/runtime/src/runtime/delivery-ack.ts +112 -0
  29. package/dist/runtime/src/runtime/errors.ts +12 -12
  30. package/dist/runtime/src/runtime/turn-runner.ts +12 -0
  31. package/dist/runtime/src/storage/api-messages.ts +7 -5
  32. package/dist/runtime/src/storage/api-topics.ts +5 -2
  33. package/dist/runtime/src/storage/forum-db.ts +4 -1
  34. package/dist/runtime/src/storage/runtime-turn-requests.ts +1 -0
  35. package/dist/runtime/src/storage/session-asks.ts +13 -5
  36. package/dist/runtime/src/storage/storage-contract.ts +54 -0
  37. package/dist/runtime/src/storage/storage-host.ts +89 -36
  38. package/dist/runtime/src/storage/storage-public-host.ts +16 -0
  39. package/dist/runtime/src/storage/storage-public.ts +21 -5
  40. package/dist/runtime/src/storage/token-stats.ts +1 -1
  41. package/dist/runtime/src/types/api.ts +2 -0
  42. package/dist/runtime/src/types.ts +2 -0
  43. package/dist/runtime/src/version.ts +1 -1
  44. package/dist/runtime-helpers.js +29 -18
  45. package/dist/runtime-helpers.js.map +8 -7
  46. package/dist/storage.js +260 -202
  47. package/dist/storage.js.map +11 -9
  48. package/dist/types/packages/core/src/mcp/runtime-spec.d.ts +2 -0
  49. package/dist/types/packages/core/src/platform/mcp-config.d.ts +4 -0
  50. package/dist/types/packages/core/src/prompts/builders.d.ts +2 -0
  51. package/dist/types/packages/core/src/storage/api-messages.d.ts +6 -6
  52. package/dist/types/packages/core/src/storage/api-topics.d.ts +20 -2
  53. package/dist/types/packages/core/src/storage/forum-db.d.ts +2 -1
  54. package/dist/types/packages/core/src/storage/session-asks.d.ts +3 -2
  55. package/dist/types/packages/core/src/storage/storage-contract.d.ts +46 -0
  56. package/dist/types/packages/core/src/storage/storage-host.d.ts +12 -19
  57. package/dist/types/packages/core/src/storage/storage-public-host.d.ts +7 -0
  58. package/dist/types/packages/core/src/storage/storage-public.d.ts +4 -2
  59. package/dist/types/packages/core/src/types/api.d.ts +2 -0
  60. package/dist/types/packages/core/src/types.d.ts +2 -0
  61. package/dist/types/packages/core/src/version.d.ts +1 -1
  62. package/dist/types/packages/module-cron/src/store.d.ts +22 -2
  63. package/dist/vault.js +2 -2
  64. package/dist/vault.js.map +3 -3
  65. package/package.json +1 -1
  66. package/dist/chunk-01xcc856.js +0 -149
  67. package/dist/chunk-01xcc856.js.map +0 -10
  68. package/dist/chunk-1a6kv9vt.js +0 -118
  69. package/dist/chunk-1a6kv9vt.js.map +0 -10
  70. package/dist/chunk-1b62d730.js +0 -117
  71. package/dist/chunk-1b62d730.js.map +0 -10
  72. package/dist/chunk-1k7t7bnx.js +0 -97
  73. package/dist/chunk-1k7t7bnx.js.map +0 -10
  74. package/dist/chunk-28apmz4r.js +0 -431
  75. package/dist/chunk-28apmz4r.js.map +0 -11
  76. package/dist/chunk-2fvydfkx.js +0 -141
  77. package/dist/chunk-2fvydfkx.js.map +0 -10
  78. package/dist/chunk-41ygvg5k.js +0 -2387
  79. package/dist/chunk-41ygvg5k.js.map +0 -26
  80. package/dist/chunk-4q966ttx.js +0 -371
  81. package/dist/chunk-4q966ttx.js.map +0 -11
  82. package/dist/chunk-51rcsavw.js +0 -1712
  83. package/dist/chunk-51rcsavw.js.map +0 -18
  84. package/dist/chunk-59d0shyj.js +0 -103
  85. package/dist/chunk-59d0shyj.js.map +0 -10
  86. package/dist/chunk-5fzgvn79.js +0 -3536
  87. package/dist/chunk-5fzgvn79.js.map +0 -20
  88. package/dist/chunk-61px0717.js +0 -153
  89. package/dist/chunk-61px0717.js.map +0 -11
  90. package/dist/chunk-66y0hr8c.js +0 -2136
  91. package/dist/chunk-66y0hr8c.js.map +0 -29
  92. package/dist/chunk-69k45zg8.js +0 -250
  93. package/dist/chunk-69k45zg8.js.map +0 -11
  94. package/dist/chunk-6ah5farg.js +0 -130
  95. package/dist/chunk-6ah5farg.js.map +0 -10
  96. package/dist/chunk-6d4fmea5.js +0 -117
  97. package/dist/chunk-6d4fmea5.js.map +0 -12
  98. package/dist/chunk-8cahx7xc.js +0 -46
  99. package/dist/chunk-8cahx7xc.js.map +0 -10
  100. package/dist/chunk-8f20fk4n.js +0 -252
  101. package/dist/chunk-8f20fk4n.js.map +0 -10
  102. package/dist/chunk-91ckrvk8.js +0 -318
  103. package/dist/chunk-91ckrvk8.js.map +0 -10
  104. package/dist/chunk-93krf6ng.js +0 -3069
  105. package/dist/chunk-93krf6ng.js.map +0 -32
  106. package/dist/chunk-9qx1t77a.js +0 -214
  107. package/dist/chunk-9qx1t77a.js.map +0 -10
  108. package/dist/chunk-beqhdr9w.js +0 -589
  109. package/dist/chunk-beqhdr9w.js.map +0 -11
  110. package/dist/chunk-bftftsgq.js +0 -1637
  111. package/dist/chunk-bftftsgq.js.map +0 -15
  112. package/dist/chunk-c500xe9z.js +0 -33
  113. package/dist/chunk-c500xe9z.js.map +0 -10
  114. package/dist/chunk-cjsnkvq2.js +0 -23
  115. package/dist/chunk-cjsnkvq2.js.map +0 -10
  116. package/dist/chunk-cxa7yghg.js +0 -577
  117. package/dist/chunk-cxa7yghg.js.map +0 -14
  118. package/dist/chunk-edb07sjp.js +0 -567
  119. package/dist/chunk-edb07sjp.js.map +0 -14
  120. package/dist/chunk-f361dwba.js +0 -589
  121. package/dist/chunk-f361dwba.js.map +0 -11
  122. package/dist/chunk-f5xgprg1.js +0 -59
  123. package/dist/chunk-f5xgprg1.js.map +0 -10
  124. package/dist/chunk-ffefbd3r.js +0 -17
  125. package/dist/chunk-ffefbd3r.js.map +0 -10
  126. package/dist/chunk-fswhzdf5.js +0 -64
  127. package/dist/chunk-fswhzdf5.js.map +0 -10
  128. package/dist/chunk-g144wdrs.js +0 -2907
  129. package/dist/chunk-g144wdrs.js.map +0 -24
  130. package/dist/chunk-h980hb2n.js +0 -512
  131. package/dist/chunk-h980hb2n.js.map +0 -13
  132. package/dist/chunk-h9vbhhgr.js +0 -1337
  133. package/dist/chunk-h9vbhhgr.js.map +0 -16
  134. package/dist/chunk-hwy3n31w.js +0 -21
  135. package/dist/chunk-hwy3n31w.js.map +0 -9
  136. package/dist/chunk-jtrk0khr.js +0 -108
  137. package/dist/chunk-jtrk0khr.js.map +0 -10
  138. package/dist/chunk-jzz91jwh.js +0 -70
  139. package/dist/chunk-jzz91jwh.js.map +0 -10
  140. package/dist/chunk-m9e3tbr8.js +0 -708
  141. package/dist/chunk-m9e3tbr8.js.map +0 -14
  142. package/dist/chunk-mh5mexsf.js +0 -147
  143. package/dist/chunk-mh5mexsf.js.map +0 -11
  144. package/dist/chunk-npd8n03v.js +0 -2152
  145. package/dist/chunk-npd8n03v.js.map +0 -15
  146. package/dist/chunk-pg1azh6n.js +0 -2
  147. package/dist/chunk-pg1azh6n.js.map +0 -9
  148. package/dist/chunk-qwy57177.js +0 -237
  149. package/dist/chunk-qwy57177.js.map +0 -11
  150. package/dist/chunk-r31q21h5.js +0 -53
  151. package/dist/chunk-r31q21h5.js.map +0 -10
  152. package/dist/chunk-rbvctv1n.js +0 -366
  153. package/dist/chunk-rbvctv1n.js.map +0 -10
  154. package/dist/chunk-sa874j5c.js +0 -9
  155. package/dist/chunk-sa874j5c.js.map +0 -10
  156. package/dist/chunk-sctcs5zb.js +0 -281
  157. package/dist/chunk-sctcs5zb.js.map +0 -10
  158. package/dist/chunk-tsstrcfc.js +0 -122
  159. package/dist/chunk-tsstrcfc.js.map +0 -10
  160. package/dist/chunk-wk2qf31s.js +0 -58
  161. package/dist/chunk-wk2qf31s.js.map +0 -10
  162. package/dist/chunk-wx7ag4dd.js +0 -2936
  163. package/dist/chunk-wx7ag4dd.js.map +0 -20
  164. package/dist/chunk-znx1fpfd.js +0 -61
  165. package/dist/chunk-znx1fpfd.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-qwy57177.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