@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.51

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 (146) hide show
  1. package/CHANGELOG.md +147 -0
  2. package/README.md +142 -17
  3. package/dist/agents-store.js +7 -3
  4. package/dist/api-only.d.ts +2 -1
  5. package/dist/api-only.js +3 -2
  6. package/dist/capacity.d.ts +50 -0
  7. package/dist/capacity.js +49 -0
  8. package/dist/cli-learning/claude-wire.d.ts +41 -0
  9. package/dist/cli-learning/claude-wire.js +258 -0
  10. package/dist/cli-learning/cli.d.ts +11 -0
  11. package/dist/cli-learning/cli.js +241 -0
  12. package/dist/cli-learning/codex-worktree.d.ts +10 -0
  13. package/dist/cli-learning/codex-worktree.js +119 -0
  14. package/dist/cli-learning/connections.d.ts +62 -0
  15. package/dist/cli-learning/connections.js +87 -0
  16. package/dist/cli-learning/entry.d.ts +1 -0
  17. package/dist/cli-learning/entry.js +4 -0
  18. package/dist/cli-learning/evidence.d.ts +78 -0
  19. package/dist/cli-learning/evidence.js +492 -0
  20. package/dist/cli-learning/hook.d.ts +33 -0
  21. package/dist/cli-learning/hook.js +544 -0
  22. package/dist/cli-learning/install.d.ts +33 -0
  23. package/dist/cli-learning/install.js +335 -0
  24. package/dist/cli-learning/observation-proof.d.ts +14 -0
  25. package/dist/cli-learning/observation-proof.js +10 -0
  26. package/dist/cli-learning/policy.d.ts +48 -0
  27. package/dist/cli-learning/policy.js +363 -0
  28. package/dist/cli-learning/schema.d.ts +16 -0
  29. package/dist/cli-learning/schema.js +27 -0
  30. package/dist/cli-learning/state.d.ts +23 -0
  31. package/dist/cli-learning/state.js +61 -0
  32. package/dist/cli.js +24 -2
  33. package/dist/console/assets/index-Bt1B51b7.js +733 -0
  34. package/dist/console/assets/index-sVftE9Ht.css +1 -0
  35. package/dist/console/index.html +2 -2
  36. package/dist/email/email-faux.d.ts +3 -1
  37. package/dist/email/email-faux.js +3 -2
  38. package/dist/email/routes.js +22 -12
  39. package/dist/harness-install.d.ts +6 -2
  40. package/dist/harness-install.js +40 -8
  41. package/dist/harness.d.ts +1 -1
  42. package/dist/harness.js +2 -2
  43. package/dist/learn/secrets.js +14 -3
  44. package/dist/learning-words.d.ts +1 -1
  45. package/dist/learning-words.js +1 -1
  46. package/dist/mcp-pin-first.js +2 -1
  47. package/dist/mcp-private-hosts.d.ts +24 -3
  48. package/dist/mcp-private-hosts.js +53 -3
  49. package/dist/model-gateway.d.ts +2 -0
  50. package/dist/model-gateway.js +3 -1
  51. package/dist/native/runtimes.d.ts +2 -0
  52. package/dist/native/runtimes.js +2 -0
  53. package/dist/observation/learning.d.ts +32 -0
  54. package/dist/observation/learning.js +66 -0
  55. package/dist/observation/observer.d.ts +8 -1
  56. package/dist/observation/observer.js +89 -9
  57. package/dist/observation/schema.js +12 -4
  58. package/dist/observation/usage-identity.d.ts +9 -0
  59. package/dist/observation/usage-identity.js +11 -0
  60. package/dist/openapi.js +89 -13
  61. package/dist/run-launch.d.ts +14 -0
  62. package/dist/run-launch.js +4 -0
  63. package/dist/run-view.d.ts +2 -0
  64. package/dist/run-view.js +12 -7
  65. package/dist/runner/adapter-loop.js +29 -26
  66. package/dist/runner/adapter-run-spec.js +2 -2
  67. package/dist/runner/beside.d.ts +13 -0
  68. package/dist/runner/beside.js +27 -8
  69. package/dist/runner/cli-run-spec.js +2 -2
  70. package/dist/runner/disk-free.d.ts +44 -0
  71. package/dist/runner/disk-free.js +96 -0
  72. package/dist/runner/feedback-round.d.ts +12 -8
  73. package/dist/runner/feedback-round.js +16 -30
  74. package/dist/runner/harness-loops.js +3 -1
  75. package/dist/runner/journal-kinds.d.ts +1 -1
  76. package/dist/runner/learning-end.js +4 -0
  77. package/dist/runner/main.d.ts +17 -6
  78. package/dist/runner/main.js +187 -45
  79. package/dist/runner/presence.d.ts +11 -2
  80. package/dist/runner/presence.js +31 -3
  81. package/dist/runner/run-child-host.d.ts +12 -15
  82. package/dist/runner/run-child-host.js +46 -108
  83. package/dist/runner/run-errors.js +2 -0
  84. package/dist/runner/runner-check.d.ts +51 -0
  85. package/dist/runner/runner-check.js +206 -0
  86. package/dist/runner/runner-metrics.d.ts +19 -0
  87. package/dist/runner/runner-metrics.js +49 -0
  88. package/dist/runner/runner.d.ts +37 -0
  89. package/dist/runner/runner.js +43 -3
  90. package/dist/runner/sdk-loop.js +34 -22
  91. package/dist/runs-over-store.d.ts +8 -1
  92. package/dist/runs-over-store.js +57 -9
  93. package/dist/sdk/runs.d.ts +22 -2
  94. package/dist/sdk/runs.js +103 -34
  95. package/dist/server.d.ts +3 -0
  96. package/dist/server.js +149 -26
  97. package/dist/skills/agentrun-serve/SKILL.md +52 -7
  98. package/dist/start-switches.js +2 -0
  99. package/dist/stats.d.ts +4 -0
  100. package/dist/stats.js +1 -1
  101. package/dist/store/agent-body.d.ts +12 -0
  102. package/dist/store/agent-body.js +16 -2
  103. package/dist/store/dialect.d.ts +2 -0
  104. package/dist/store/dialect.js +1 -0
  105. package/dist/store/index.d.ts +3 -3
  106. package/dist/store/index.js +2 -2
  107. package/dist/store/postgres/connection.d.ts +5 -2
  108. package/dist/store/postgres/connection.js +19 -7
  109. package/dist/store/postgres/dialect.js +1 -0
  110. package/dist/store/postgres/migrate.d.ts +30 -0
  111. package/dist/store/postgres/migrate.js +72 -5
  112. package/dist/store/postgres/migration-lint.d.ts +8 -0
  113. package/dist/store/postgres/migration-lint.js +119 -0
  114. package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
  115. package/dist/store/postgres/store.d.ts +8 -3
  116. package/dist/store/postgres/store.js +31 -11
  117. package/dist/store/schema.d.ts +18 -1
  118. package/dist/store/schema.js +33 -2
  119. package/dist/store/sqlite/run-launch.d.ts +9 -1
  120. package/dist/store/sqlite/run-launch.js +44 -0
  121. package/dist/store/sqlite/store.d.ts +17 -0
  122. package/dist/store/sqlite/store.js +87 -10
  123. package/dist/store/store-schema.d.ts +34 -0
  124. package/dist/store/store-schema.js +125 -0
  125. package/dist/store/store.d.ts +53 -1
  126. package/dist/store/store.js +13 -0
  127. package/dist/store-reads/analytics.d.ts +3 -2
  128. package/dist/store-reads/analytics.js +20 -8
  129. package/dist/store-view.d.ts +4 -3
  130. package/dist/store-view.js +11 -7
  131. package/dist/templates.d.ts +3 -2
  132. package/dist/tool-gate.d.ts +4 -2
  133. package/dist/unified-usage.d.ts +24 -0
  134. package/dist/unified-usage.js +400 -0
  135. package/dist/uploads-archil.d.ts +100 -0
  136. package/dist/uploads-archil.js +430 -0
  137. package/dist/uploads.d.ts +55 -1
  138. package/dist/uploads.js +185 -98
  139. package/dist/validate.js +1 -1
  140. package/dist/workspace/archil-disk.d.ts +6 -5
  141. package/dist/workspace/archil-disk.js +27 -12
  142. package/dist/workspace/archil.js +3 -2
  143. package/package.json +10 -10
  144. package/skills/agentrun-serve/SKILL.md +52 -7
  145. package/dist/console/assets/index-D0mr9wfZ.css +0 -1
  146. package/dist/console/assets/index-D7G6o-1E.js +0 -720
@@ -0,0 +1,363 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { open } from 'node:fs/promises';
3
+ import { isAbsolute } from 'node:path';
4
+ import { discoverNative } from '../native/discovery.js';
5
+ import { snapshotNativeInstructions } from '../native/instructions.js';
6
+ import { updateClaudeWire } from './claude-wire.js';
7
+ import { readPrivateJson, writePrivateJson } from './state.js';
8
+ export const CLI_POLICY_BYTES = 256 * 1024;
9
+ export const CLAUDE_IMPORTS_PENDING = 'Claude standing instructions contain imports whose policy files were not captured.';
10
+ export const CLAUDE_SNAPSHOT_PENDING = 'A current native Claude system-prompt snapshot has not been recorded.';
11
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
12
+ const contentText = (content) => typeof content === 'string' ? content : Array.isArray(content)
13
+ ? content.filter(item => object(item) && ['input_text', 'output_text', 'text'].includes(item.type) && typeof item.text === 'string').map(item => item.text).join('\n') : '';
14
+ const policyMessage = (item) => item?.type === 'message' && ['system', 'developer'].includes(item.role)
15
+ ? contentText(item.content) : '';
16
+ /** Read only policy metadata before enrollment, not historical dialogue. Cached append offsets make long sessions
17
+ * cheap after their first scan. A deadline checkpoint is incomplete until a later invocation reaches the boundary. */
18
+ export async function readTranscriptPolicy(options) {
19
+ const cursor = options.cursor, redact = options.redact ?? (text => text);
20
+ if (!cursor)
21
+ return { text: '', incomplete: 'Native session policy metadata is unavailable.' };
22
+ if (options.runtime === 'claude-code' && cursor.absent)
23
+ return { text: '', incomplete: CLAUDE_SNAPSHOT_PENDING };
24
+ const version = options.runtime === 'claude-code' ? 3 : 1;
25
+ let cache = options.cachePath ? await readPrivateJson(options.cachePath) : undefined;
26
+ if (!cache || cache.version !== version || cache.runtime !== options.runtime || cache.dev !== cursor.dev || cache.ino !== cursor.ino || cache.offset > cursor.offset) {
27
+ cache = { version, runtime: options.runtime, dev: cursor.dev, ino: cursor.ino, offset: 0, base: '', developer: [], world: {} };
28
+ }
29
+ const inspected = cache;
30
+ const clean = (text) => {
31
+ const value = redact(text);
32
+ if (value !== text)
33
+ inspected.incomplete ??= 'Source policy contains withheld or redacted text.';
34
+ return value;
35
+ };
36
+ const appendDeveloper = (text) => {
37
+ if (!text || text.includes('AgentRun context receipt:'))
38
+ return;
39
+ const value = clean(text);
40
+ if (!inspected.developer.includes(value))
41
+ inspected.developer.push(value);
42
+ if (Buffer.byteLength(inspected.developer.join('\n')) > CLI_POLICY_BYTES) {
43
+ inspected.developer.pop();
44
+ inspected.incomplete = 'Native developer policy exceeds the supported grading limit.';
45
+ }
46
+ };
47
+ const record = (row, recordOffset) => {
48
+ if (!object(row))
49
+ return;
50
+ if (options.runtime === 'claude-code') {
51
+ if (row.isSidechain === true || row.agentId || (options.sessionId && row.sessionId && row.sessionId !== options.sessionId))
52
+ return;
53
+ inspected.claudeWire = updateClaudeWire(inspected.claudeWire, row, { promptId: inspected.claudePrompt, redact: clean, recordOffset });
54
+ if (['api-request-shape', 'api-request-blob', 'api-request'].includes(row.type)) {
55
+ const current = inspected.claudeWire.current;
56
+ if (row.type === 'api-request' && current && current.prompt === inspected.claudePrompt && !current.complete)
57
+ inspected.claudePromptWireIncomplete = current.reason ?? 'Native request policy coverage is incomplete.';
58
+ if (row.type === 'api-request' && inspected.claudeFirst?.wire && current && current.prompt === inspected.claudePrompt
59
+ && (current.stableText ?? current.text) !== (inspected.claudeFirst.wire.stableText ?? inspected.claudeFirst.wire.text))
60
+ inspected.claudePromptChanged = true;
61
+ return;
62
+ }
63
+ // Native stop-hook summaries are real parent-chain nodes between ordinary prompts.
64
+ // Follow their identity without importing their contents as source instructions.
65
+ if ((['user', 'assistant', 'attachment'].includes(row.type) || (row.type === 'system' && row.subtype === 'stop_hook_summary')) && typeof row.uuid === 'string') {
66
+ if (inspected.claudeLeaf && row.uuid !== inspected.claudeLeaf && Object.hasOwn(row, 'parentUuid') && row.parentUuid !== inspected.claudeLeaf) {
67
+ inspected.incomplete ??= 'Native Claude policy ancestry branched or is incomplete.';
68
+ }
69
+ inspected.claudeLeaf = row.uuid;
70
+ }
71
+ const promptId = row.promptId ?? row.prompt_id;
72
+ if (row.type === 'user' && typeof promptId === 'string' && promptId !== inspected.claudePrompt) {
73
+ inspected.claudePrompt = promptId;
74
+ delete inspected.claudeFirst;
75
+ inspected.claudePromptChanged = false;
76
+ delete inspected.claudePromptWireIncomplete;
77
+ }
78
+ if (row.type === 'assistant' && row.message?.role === 'assistant' && inspected.claudePrompt && !inspected.claudeFirst && inspected.claude) {
79
+ inspected.claudeFirst = { prompt: inspected.claudePrompt, systemPrompt: [...inspected.claude.systemPrompt],
80
+ instructions: structuredClone(inspected.claudeInstructions), instructionsComplete: inspected.claudeInstructionsComplete, invalidated: inspected.invalidated,
81
+ ...(inspected.claudeWire?.current?.prompt === inspected.claudePrompt ? { wire: structuredClone(inspected.claudeWire.current) } : {}), context: inspected.claudeContext };
82
+ }
83
+ const attachment = row.attachment;
84
+ if (row.type !== 'attachment' || !object(attachment))
85
+ return;
86
+ if (attachment.type === 'session_context') {
87
+ if (row.renderedRole !== 'user' || !Array.isArray(row.rendered) || row.rendered.some((part) => !object(part) || typeof part.content !== 'string')) {
88
+ inspected.incomplete ??= 'The native lower-trust session context was not recorded completely.';
89
+ }
90
+ else {
91
+ inspected.claudeContext = clean(row.rendered.map((part) => part.content).join('\n\n'));
92
+ if (inspected.claudeFirst && inspected.claudeFirst.context !== inspected.claudeContext)
93
+ inspected.claudePromptChanged = true;
94
+ }
95
+ }
96
+ if (attachment.type === 'instructions') {
97
+ const valid = Array.isArray(attachment.files) && attachment.files.every((file) => object(file)
98
+ && typeof file.path === 'string' && isAbsolute(file.path) && file.path.length <= 4096
99
+ && typeof file.content === 'string' && typeof file.type === 'string' && file.unverified !== true)
100
+ && (attachment.removed === undefined || (Array.isArray(attachment.removed) && attachment.removed.every((path) => typeof path === 'string')));
101
+ if (!valid || (attachment.changed === true && !inspected.claudeInstructionsComplete)) {
102
+ inspected.incomplete ??= 'Native Claude loaded instructions have incomplete coverage.';
103
+ }
104
+ else {
105
+ if (attachment.changed !== true) {
106
+ inspected.claudeInstructions = {};
107
+ inspected.claudeInstructionsComplete = true;
108
+ }
109
+ for (const file of attachment.files)
110
+ inspected.claudeInstructions[clean(file.path)] = { type: clean(file.type), content: clean(file.content) };
111
+ for (const path of attachment.removed ?? [])
112
+ delete inspected.claudeInstructions[clean(path)];
113
+ if (Buffer.byteLength(JSON.stringify(inspected.claudeInstructions)) > CLI_POLICY_BYTES) {
114
+ inspected.claudeInstructions = {};
115
+ inspected.claudeInstructionsComplete = false;
116
+ inspected.incomplete ??= 'Native Claude loaded instructions exceed the grading limit.';
117
+ }
118
+ }
119
+ }
120
+ if (attachment.type === 'prompt_render_point')
121
+ inspected.invalidated = true;
122
+ if (attachment.type === 'prompt_snapshot' && Array.isArray(attachment.systemPrompt) && attachment.systemPrompt.every((value) => typeof value === 'string')) {
123
+ const systemPrompt = attachment.systemPrompt.map(clean);
124
+ if (Buffer.byteLength(systemPrompt.join('\n')) > CLI_POLICY_BYTES) {
125
+ inspected.incomplete = 'Native Claude system policy exceeds the supported grading limit.';
126
+ return;
127
+ }
128
+ inspected.claude = { systemPrompt, ...(typeof row.uuid === 'string' ? { uuid: row.uuid } : {}), ...(typeof row.parentUuid === 'string' ? { parentUuid: row.parentUuid } : {}) };
129
+ inspected.invalidated = false;
130
+ }
131
+ if (inspected.claudeFirst && ['instructions', 'prompt_snapshot'].includes(attachment.type)) {
132
+ const ordered = (files) => Object.entries(files ?? {}).sort(([a], [b]) => a.localeCompare(b));
133
+ if (JSON.stringify(inspected.claudeFirst.systemPrompt) !== JSON.stringify(inspected.claude?.systemPrompt)
134
+ || JSON.stringify(ordered(inspected.claudeFirst.instructions)) !== JSON.stringify(ordered(inspected.claudeInstructions)))
135
+ inspected.claudePromptChanged = true;
136
+ }
137
+ return;
138
+ }
139
+ const payload = row.payload;
140
+ if (!object(payload))
141
+ return;
142
+ if (row.type === 'session_meta') {
143
+ if (options.sessionId && (payload.id ?? payload.session_id) !== options.sessionId) {
144
+ inspected.incomplete = 'Native policy metadata belongs to another session.';
145
+ return;
146
+ }
147
+ const base = typeof payload.base_instructions === 'string' ? payload.base_instructions : payload.base_instructions?.text;
148
+ if (typeof base === 'string' && Buffer.byteLength(base) <= CLI_POLICY_BYTES)
149
+ inspected.base = clean(base);
150
+ else
151
+ inspected.incomplete = 'Codex native system policy is missing or exceeds the grading limit.';
152
+ }
153
+ else if (row.type === 'response_item')
154
+ appendDeveloper(policyMessage(payload));
155
+ else if (row.type === 'compacted' && Array.isArray(payload.replacement_history)) {
156
+ // Replacement history is the native retained context, not a guessed summary of old conversation.
157
+ inspected.developer = [];
158
+ for (const item of payload.replacement_history)
159
+ appendDeveloper(policyMessage(item));
160
+ if (inspected.decodeFault)
161
+ inspected.decodeFault.replacement = true;
162
+ }
163
+ else if (row.type === 'world_state' && object(payload.state)) {
164
+ if (payload.full) {
165
+ inspected.world = {};
166
+ if (inspected.decodeFault)
167
+ inspected.decodeFault.world = true;
168
+ }
169
+ const state = payload.state;
170
+ for (const [name, field] of [['agents_md', 'text'], ['permissions', 'instructions'], ['model', 'instructions'], ['collaboration_mode', 'instructions']]) {
171
+ if (!(name in state))
172
+ continue;
173
+ const text = state[name]?.[field];
174
+ if (typeof text === 'string')
175
+ inspected.world[name] = clean(text);
176
+ else if (text === null || state[name] === null)
177
+ delete inspected.world[name];
178
+ }
179
+ if ('managed_developer_instructions' in state) {
180
+ const value = state.managed_developer_instructions;
181
+ if (Array.isArray(value) && value.every(item => typeof item === 'string'))
182
+ inspected.world.managed = clean(value.join('\n'));
183
+ else if (value && Object.keys(value).length)
184
+ inspected.incomplete = 'Native host developer policy uses an unsupported metadata shape.';
185
+ }
186
+ }
187
+ // A full native compaction records the retained developer context; a subsequent full world
188
+ // snapshot records effective policy layers. Together they recover current policy after an
189
+ // old malformed record, without recovering or importing any historical conversation.
190
+ if (inspected.base && inspected.decodeFault?.replacement && inspected.decodeFault.world)
191
+ delete inspected.decodeFault;
192
+ };
193
+ let unfinished = false;
194
+ try {
195
+ const file = await open(cursor.path, 'r');
196
+ try {
197
+ const info = await file.stat();
198
+ if (!info.isFile() || info.dev !== cursor.dev || info.ino !== cursor.ino || info.size < cursor.offset)
199
+ throw new Error('changed');
200
+ }
201
+ finally {
202
+ await file.close();
203
+ }
204
+ if (inspected.offset < cursor.offset) {
205
+ const started = Date.now(), deadline = options.budgetMs ?? 1500;
206
+ const replayFrom = options.runtime === 'claude-code' ? inspected.claudeWire?.replayFrom : undefined;
207
+ if (Number.isSafeInteger(replayFrom) && replayFrom >= 0 && replayFrom < inspected.offset) {
208
+ if (inspected.offset - replayFrom > 64 * 1024 * 1024)
209
+ throw new Error('native-replay-limit');
210
+ // Native request logs omit blobs already represented by ordinary transcript messages.
211
+ // Rehydrate only the pending canonical hash across a checkpoint, never persisted dialogue.
212
+ const replay = createReadStream(cursor.path, { start: replayFrom, end: inspected.offset - 1, highWaterMark: 64 * 1024 });
213
+ let bytes = Buffer.alloc(0), offset = replayFrom;
214
+ try {
215
+ for await (const chunk of replay) {
216
+ bytes = Buffer.concat([bytes, chunk]);
217
+ let newline;
218
+ while ((newline = bytes.indexOf(10)) >= 0) {
219
+ const line = bytes.subarray(0, newline);
220
+ if (line.length > 16 * 1024 * 1024)
221
+ throw new Error('oversized');
222
+ if (line.length) {
223
+ const row = JSON.parse(new TextDecoder('utf8', { fatal: true }).decode(line));
224
+ if (object(row) && !row.isSidechain && !row.agentId && (!options.sessionId || !row.sessionId || row.sessionId === options.sessionId)
225
+ && ['user', 'assistant', 'attachment'].includes(row.type))
226
+ inspected.claudeWire = updateClaudeWire(inspected.claudeWire, row, { promptId: inspected.claudePrompt, redact: clean, recordOffset: offset });
227
+ }
228
+ offset += newline + 1;
229
+ bytes = bytes.subarray(newline + 1);
230
+ }
231
+ if (bytes.length > 16 * 1024 * 1024)
232
+ throw new Error('oversized');
233
+ if (Date.now() - started >= deadline) {
234
+ unfinished = offset < inspected.offset;
235
+ break;
236
+ }
237
+ }
238
+ if (bytes.length)
239
+ unfinished = true;
240
+ }
241
+ finally {
242
+ replay.destroy();
243
+ }
244
+ }
245
+ const stream = createReadStream(cursor.path, { start: inspected.offset, end: cursor.offset - 1, highWaterMark: 64 * 1024 });
246
+ let pending = Buffer.alloc(0), skipped = 0;
247
+ try {
248
+ for await (const chunk of stream) {
249
+ if (unfinished)
250
+ break;
251
+ pending = Buffer.concat([pending, chunk]);
252
+ let newline;
253
+ while ((newline = pending.indexOf(10)) >= 0) {
254
+ const line = pending.subarray(0, newline);
255
+ if (!skipped && line.length) {
256
+ try {
257
+ record(JSON.parse(new TextDecoder('utf8', { fatal: true }).decode(line)), inspected.offset);
258
+ }
259
+ catch {
260
+ if (options.runtime === 'codex')
261
+ inspected.decodeFault = { replacement: false, world: false };
262
+ else
263
+ inspected.incomplete = 'A native policy transcript record could not be decoded.';
264
+ }
265
+ }
266
+ inspected.offset += skipped + newline + 1;
267
+ skipped = 0;
268
+ pending = pending.subarray(newline + 1);
269
+ }
270
+ if (pending.length > 16 * 1024 * 1024) {
271
+ skipped += pending.length;
272
+ pending = Buffer.alloc(0);
273
+ inspected.incomplete = 'A native policy transcript record exceeds the inspection limit.';
274
+ }
275
+ if (Date.now() - started >= deadline) {
276
+ unfinished = inspected.offset < cursor.offset;
277
+ break;
278
+ }
279
+ }
280
+ }
281
+ finally {
282
+ stream.destroy();
283
+ }
284
+ if (pending.length || skipped)
285
+ unfinished = true;
286
+ }
287
+ }
288
+ catch (error) {
289
+ inspected.incomplete = error instanceof Error && error.message === 'native-replay-limit'
290
+ ? 'Native pending message reconstruction exceeds the 64 MiB inspection limit.' : 'Native session policy metadata could not be read.';
291
+ }
292
+ if (options.cachePath)
293
+ await writePrivateJson(options.cachePath, inspected);
294
+ let text;
295
+ let incomplete = inspected.incomplete ?? (inspected.decodeFault ? 'A native policy transcript record could not be decoded and current policy has not been restored.' : undefined);
296
+ let instructionsCaptured = inspected.claudeInstructionsComplete, wireCaptured = false;
297
+ if (options.runtime === 'claude-code') {
298
+ const first = options.turnId && inspected.claudeFirst?.prompt === options.turnId ? inspected.claudeFirst : undefined;
299
+ const currentWire = inspected.claudeWire?.current;
300
+ const wire = first ? first.wire : currentWire && currentWire.prompt === inspected.claudePrompt ? currentWire : undefined;
301
+ wireCaptured = wire?.complete === true && !inspected.claudePromptWireIncomplete;
302
+ const system = first?.systemPrompt ?? inspected.claude?.systemPrompt;
303
+ const instructionFiles = first ? first.instructions : inspected.claudeInstructions;
304
+ instructionsCaptured = first ? first.instructionsComplete : inspected.claudeInstructionsComplete;
305
+ text = system ? `Native Claude system policy (recorded prompt snapshot):\n${system.join('\n\n')}` : '';
306
+ if (wireCaptured)
307
+ text = !inspected.claudePromptChanged && currentWire?.complete && currentWire.prompt === options.turnId
308
+ ? currentWire.text : wire.text;
309
+ if (options.requireWire && !wireCaptured)
310
+ incomplete ??= inspected.claudePromptWireIncomplete ?? wire?.reason ?? 'The native request system/developer policy was not recorded completely.';
311
+ const context = first ? first.context : inspected.claudeContext;
312
+ if (context)
313
+ text += `\n\nNative lower-trust session context (user role, not standing system instructions):\n${context}`;
314
+ if (instructionsCaptured)
315
+ text += '\n\n' + Object.entries(instructionFiles ?? {}).map(([path, file]) => `Native loaded ${file.type} instructions (${path}):\n${file.content}`).join('\n\n');
316
+ if (!system || inspected.invalidated || first?.invalidated)
317
+ incomplete ??= CLAUDE_SNAPSHOT_PENDING;
318
+ if (options.turnId && inspected.claudePromptChanged)
319
+ incomplete ??= 'Native loaded policy changed during this prompt; automatic promotion is disabled.';
320
+ if (options.turnId && inspected.claudePrompt !== options.turnId)
321
+ incomplete ??= 'Native Claude policy does not belong to the completed prompt.';
322
+ }
323
+ else {
324
+ text = [`Native Codex system policy:\n${inspected.base}`, ...inspected.developer.map(text => `Native developer policy:\n${text}`), ...Object.entries(inspected.world).map(([name, text]) => `Native ${name} policy:\n${text}`)].join('\n\n');
325
+ if (!inspected.base)
326
+ incomplete ??= 'Codex native system policy was not recorded in the transcript.';
327
+ }
328
+ if ((unfinished || inspected.offset < cursor.offset) && !inspected.incomplete)
329
+ incomplete = 'Native policy inspection is checkpointed and not yet complete.';
330
+ return { text, scannedBytes: inspected.offset, totalBytes: cursor.offset, ...(incomplete ? { incomplete } : {}), ...(instructionsCaptured ? { instructionsCaptured: true } : {}), ...(wireCaptured ? { wireCaptured: true } : {}) };
331
+ }
332
+ /** Existing native discovery checks imports/configuration coverage. The active transcript supplies the actual
333
+ * session policy, including CLI-only system overrides, without uploading config values or historical conversation. */
334
+ export async function captureSourcePolicy(options) {
335
+ let withheld = false;
336
+ const redact = (text) => { const value = options.redact(text); withheld ||= value !== text; return value; };
337
+ let standing = options.pinnedStanding;
338
+ if (!standing) {
339
+ const target = (await discoverNative({ runtime: options.runtime, project: options.project, env: options.env })).targets.find(target => target.selector.kind === 'project');
340
+ if (!target)
341
+ throw new Error('The source CLI project could not be discovered.');
342
+ standing = await snapshotNativeInstructions(target, redact);
343
+ }
344
+ const recorded = await readTranscriptPolicy({ runtime: options.runtime, cursor: options.cursor, sessionId: options.sessionId, turnId: options.turnId, requireWire: options.runtime === 'claude-code' && Boolean(options.turnId), cachePath: options.cachePath, redact });
345
+ // The active Codex system/developer envelopes cover CLI configuration-supplied prompt text. Other
346
+ // discovery failures (unreadable files or unresolved sources) remain explicit refusal conditions.
347
+ const coveredOverride = !recorded.incomplete && options.runtime === 'codex'
348
+ && standing.incomplete === 'Codex configuration can supply custom policy outside the captured standing instruction files.';
349
+ const coveredImports = options.runtime === 'claude-code' && recorded.instructionsCaptured && !recorded.incomplete
350
+ && standing.incomplete === CLAUDE_IMPORTS_PENDING;
351
+ // Claude's typed instruction attachments are what its native renderer actually loaded. This
352
+ // includes imports and exact per-session revisions, without reading unrelated settings values.
353
+ const standingText = coveredImports ? 'Native loaded instructions below are source policy evidence for the learning grader.' : coveredOverride ? standing.text.replace(`\n\n[Incomplete native instruction evidence: ${standing.incomplete} Automatic learning cannot promote a proposal from this snapshot.]`, '') : standing.text;
354
+ const text = [standingText, recorded.text].filter(Boolean).join('\n\n');
355
+ const incomplete = (coveredOverride || coveredImports ? undefined : standing.incomplete) ?? recorded.incomplete
356
+ ?? (withheld ? 'Source policy contains withheld or redacted text.' : undefined);
357
+ const oversized = Buffer.byteLength(text) > CLI_POLICY_BYTES;
358
+ return { ...standing, sourceStanding: standing, text: oversized ? 'The source policy exceeds the CLI grading limit; automatic promotion is disabled.' : text,
359
+ truncated: standing.truncated || oversized, incomplete };
360
+ }
361
+ export async function readCodexPolicy(cursor) {
362
+ return readTranscriptPolicy({ runtime: 'codex', cursor });
363
+ }
@@ -0,0 +1,16 @@
1
+ export declare const CLI_LEARNING_BINDING: {
2
+ 'x-agentrun-serve': string;
3
+ description: string;
4
+ type: string;
5
+ additionalProperties: boolean;
6
+ properties: Record<string, unknown>;
7
+ required: string[];
8
+ };
9
+ export declare const CLI_LEARNING_RUN: {
10
+ 'x-agentrun-serve': string;
11
+ type: string;
12
+ additionalProperties: boolean;
13
+ properties: Record<string, unknown>;
14
+ required: string[];
15
+ };
16
+ export declare const CLI_LEARNING_PATHS: Record<string, Record<string, unknown>>;
@@ -0,0 +1,27 @@
1
+ import { SDK_PATHS, SDK_RUN } from '../sdk/schema.js';
2
+ const text = { type: 'string' };
3
+ const object = (properties, required = Object.keys(properties)) => ({ type: 'object', additionalProperties: false, properties, required });
4
+ const response = (schema) => ({ description: 'Local CLI learning connection or prompt window.', content: { 'application/json': { schema } } });
5
+ const body = (schema) => ({ required: true, content: { 'application/json': { schema } } });
6
+ const id = (name) => ({ name, in: 'path', required: true, schema: text });
7
+ const mark = { 'x-agentrun-serve': 'clilearning/1', security: [{ bearer: [] }], tags: ['cli-learning'] };
8
+ const owner = { ...mark, security: [{ bearer: [] }, { ownerSession: [] }] };
9
+ export const CLI_LEARNING_BINDING = { ...object({ runtime: { enum: ['codex', 'claude-code'] }, connection_id: text, project: text }), 'x-agentrun-serve': 'clilearning/1', description: 'An enrolled existing CLI. Execution and tools remain in its original session. Only local owner enrollment creates this reference.' };
10
+ export const CLI_LEARNING_RUN = { ...object({ runtime: { enum: ['codex-cli', 'claude-code-cli'] }, session_id: text, turn_id: text, model: { type: ['string', 'null'] }, learning_revision: { type: ['string', 'null'] }, seed_observed: { type: 'boolean' }, policy_complete: { type: 'boolean' }, evidence_complete: { type: 'boolean' }, usage: SDK_RUN.oneOf[0].properties.usage }), 'x-agentrun-serve': 'clilearning/1' };
11
+ const connection = object({ connection_id: text, agent_id: text, runtime: { enum: ['codex', 'claude-code'] }, project: text, active: { type: 'boolean' }, last_hook_at: { ...text, format: 'date-time' }, last_run_id: text }, ['connection_id', 'agent_id', 'runtime', 'project', 'active']);
12
+ const events = SDK_PATHS['/sdk-runs/{run_id}/events'].post;
13
+ const completion = SDK_PATHS['/sdk-runs/{run_id}/complete'].post;
14
+ const eventSchema = events.requestBody.content['application/json'].schema;
15
+ const completionSchema = completion.requestBody.content['application/json'].schema;
16
+ const receipt = SDK_PATHS['/agents/{agent_id}/sdk-runs'].post.responses[201];
17
+ export const CLI_LEARNING_PATHS = {
18
+ '/cli-learning/connections': {
19
+ post: { ...owner, operationId: 'enrollCliLearning', summary: 'Enable learning for an existing local CLI without launching it', description: 'Owner authenticated, source server bound to loopback without a public URL. Verifies native sign-in without a model call. Repeated enrollment preserves the same agent and learned files, and keeps its current Learning Off setting. Store the returned connection token privately, never give it to a model.', requestBody: body(object({ runtime: { enum: ['codex', 'claude-code'] }, project: text, name: text }, ['runtime', 'project'])), responses: { 201: response(object({ ...connection.properties, token: text }, [...connection.required, "token"])) } },
20
+ get: { ...owner, operationId: 'listCliLearning', summary: 'Read enrolled CLI learning connections', responses: { 200: response(object({ connections: { type: 'array', items: connection } })) } }
21
+ },
22
+ '/cli-learning/connections/{connection_id}': { delete: { ...owner, operationId: 'revokeCliLearning', summary: 'Revoke CLI capture and guidance delivery, retaining history and learned files', parameters: [id('connection_id')], responses: { 200: response(connection) } } },
23
+ '/cli-learning/connections/{connection_id}/runs': { post: { ...mark, operationId: 'startCliLearningRun', summary: 'Register one prompt window from an existing CLI session', description: 'Requires the dedicated connection token and Idempotency-Key. The connection, session_id and turn_id identify one immutable window even when a retry uses another transport key. Return pinned owner corrections to the original harness; receipt delivery alone does not prove it accepted that context. Source hooks have no workflow execution bridge and do not launch native reflection or grading sessions. Original execution/auth/tools are unchanged. Each prompt window expires after 24 hours; a missing completion remains unknown and is never replayed. Captured policy is bounded to 256 KiB when learning is enabled; incomplete policy or evidence stays explicit. Source dialogue is evidence, never an automatic owner correction.', parameters: [id('connection_id'), { name: 'Idempotency-Key', in: 'header', required: true, schema: { ...text, minLength: 1, maxLength: 255 } }], requestBody: body(object({ session_id: { ...text, minLength: 1, maxLength: 256 }, turn_id: { ...text, minLength: 1, maxLength: 256 }, input: { ...text, maxLength: 128000 }, instructions: { ...text, maxLength: 262144 }, policy_complete: { type: 'boolean' }, model: { ...text, maxLength: 256 } }, ['session_id', 'turn_id', 'input', 'instructions', 'policy_complete'])), responses: { 201: { ...receipt, description: 'Prompt window receipt and a token scoped only to its CLI learning endpoints.' } } } },
24
+ '/cli-learning/runs/{run_id}': { get: { ...SDK_PATHS['/sdk-runs/{run_id}'].get, ...mark, operationId: 'getCliLearningRun', summary: 'Read CLI prompt-window learning progress', description: 'Only the run token from this CLI window is accepted. Revoking or replacing enrollment invalidates its scope.' } },
25
+ '/cli-learning/runs/{run_id}/events': { post: { ...events, ...mark, operationId: 'cliLearningEvents', summary: 'Upload bounded role-preserving CLI dialogue and tool evidence', description: 'Contiguous batch sequence numbers starting at 1, incremented once per batch (not per event), at most 100 events/256 KB per batch and 4 MB per window. Exact retries are accepted. Retain user and assistant roles; model output never becomes a user instruction. No tool is executed by this endpoint.', requestBody: body({ ...eventSchema, properties: { sequence: { type: 'integer', minimum: 1 }, events: { type: 'array', maxItems: 100, items: { oneOf: [object({ type: { const: 'message' }, role: { enum: ['user', 'assistant'] }, text: { ...text, maxLength: 128000 } }), ...(eventSchema.properties.events.items.oneOf)] } } } }) } },
26
+ '/cli-learning/runs/{run_id}/complete': { post: { ...completion, ...mark, operationId: 'completeCliLearningRun', summary: 'Close an existing CLI prompt window exactly once', description: 'Immutable completion, exact retries accepted. A complete capture requires explicit evidence_complete:true and a complete source policy. Missing/false evidence preserves the answer with the limitation recorded. Claude windows require source_policy captured from that same prompt final native policy snapshot, including the first prompt; provisional begin policy never establishes complete capture. Codex refuses this override. seed_observed:true requires source transcript proof plus the matching seed_revision from this window receipt; never infer it from a successful HTTP response.', requestBody: body({ ...completionSchema, properties: { ...completionSchema.properties, seed_observed: { type: 'boolean' }, seed_revision: { ...text, maxLength: 128 }, source_policy: object({ instructions: { ...text, maxLength: 262144 }, complete: { type: "boolean" } }) } }) } }
27
+ };
@@ -0,0 +1,23 @@
1
+ export type CliLearningRuntime = 'codex' | 'claude-code';
2
+ export type CliLearningConnection = {
3
+ version: 1;
4
+ runtime: CliLearningRuntime;
5
+ project: string;
6
+ url: string;
7
+ connection_id: string;
8
+ agent_id: string;
9
+ token: string;
10
+ /** Local capture stops before the server acknowledges a disconnect. Keep the credential only to revoke it. */
11
+ revocation_pending?: true;
12
+ };
13
+ export declare const stateHash: (value: string) => string;
14
+ export declare const connectionFile: (dataDir: string, runtime: CliLearningRuntime, project: string) => string;
15
+ /** The scoped credential changes on re-enrollment. Hash it with the destination; never persist or show it in paths. */
16
+ export declare const connectionScope: (connection: CliLearningConnection) => string;
17
+ export declare const journalParent: (dataDir: string, runtime: CliLearningRuntime, project: string) => string;
18
+ export declare const journalRoot: (dataDir: string, connection: CliLearningConnection) => string;
19
+ /** Credentials and prompt receipts belong to private AgentRun data, never source control or hook arguments. */
20
+ export declare function writePrivateJson(path: string, value: unknown): Promise<void>;
21
+ export declare function readPrivateJson<T>(path: string): Promise<T | undefined>;
22
+ export declare function readConnection(dataDir: string, runtime: CliLearningRuntime, project: string): Promise<CliLearningConnection | undefined>;
23
+ export declare function saveConnection(dataDir: string, connection: CliLearningConnection): Promise<void>;
@@ -0,0 +1,61 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdir, open, readFile, rename, unlink } from 'node:fs/promises';
3
+ import { dirname, join, resolve } from 'node:path';
4
+ export const stateHash = (value) => createHash('sha256').update(value).digest('hex');
5
+ export const connectionFile = (dataDir, runtime, project) => join(resolve(dataDir), 'cli-learning', 'connections', `${stateHash(`${runtime}\0${resolve(project)}`)}.json`);
6
+ /** The scoped credential changes on re-enrollment. Hash it with the destination; never persist or show it in paths. */
7
+ export const connectionScope = (connection) => stateHash(JSON.stringify([
8
+ 'agentrun-cli-journal-v1', new URL(connection.url).origin, connection.runtime, resolve(connection.project),
9
+ connection.connection_id, connection.agent_id, connection.token,
10
+ ]));
11
+ export const journalParent = (dataDir, runtime, project) => join(resolve(dataDir), 'cli-learning', 'sessions', stateHash(`${runtime}\0${resolve(project)}`));
12
+ export const journalRoot = (dataDir, connection) => join(journalParent(dataDir, connection.runtime, connection.project), 'epochs', connectionScope(connection));
13
+ /** Credentials and prompt receipts belong to private AgentRun data, never source control or hook arguments. */
14
+ export async function writePrivateJson(path, value) {
15
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
16
+ const temporary = `${path}.${randomUUID()}.tmp`;
17
+ const file = await open(temporary, 'wx', 0o600);
18
+ try {
19
+ await file.writeFile(JSON.stringify(value));
20
+ await file.sync();
21
+ }
22
+ finally {
23
+ await file.close();
24
+ }
25
+ try {
26
+ await rename(temporary, path);
27
+ const directory = await open(dirname(path), 'r');
28
+ try {
29
+ await directory.sync();
30
+ }
31
+ finally {
32
+ await directory.close();
33
+ }
34
+ }
35
+ finally {
36
+ await unlink(temporary).catch(() => { });
37
+ }
38
+ }
39
+ export async function readPrivateJson(path) {
40
+ try {
41
+ return JSON.parse(await readFile(path, 'utf8'));
42
+ }
43
+ catch (error) {
44
+ if (error.code === 'ENOENT')
45
+ return undefined;
46
+ throw error;
47
+ }
48
+ }
49
+ export async function readConnection(dataDir, runtime, project) {
50
+ const value = await readPrivateJson(connectionFile(dataDir, runtime, project));
51
+ if (!value)
52
+ return undefined;
53
+ if (value.version !== 1 || value.runtime !== runtime || resolve(value.project) !== resolve(project)
54
+ || !value.connection_id || !value.agent_id || !value.token || typeof value.url !== 'string') {
55
+ throw new Error('Invalid CLI learning connection. Reconnect this project.');
56
+ }
57
+ return value;
58
+ }
59
+ export async function saveConnection(dataDir, connection) {
60
+ await writePrivateJson(connectionFile(dataDir, connection.runtime, connection.project), connection);
61
+ }
package/dist/cli.js CHANGED
@@ -36,8 +36,13 @@ const USAGE = `usage: agentrun-serve [--data DIR] [--listen ADDR] [--port N] [--
36
36
  agentrun-serve check-harness --recipe FILE [--model PROVIDER/MODEL] [--data DIR] [--report FILE] [--cap USD]
37
37
  agentrun-serve eval-template DIR [--case NAME ...] [--runs N] [--server URL | --on-data DIR] [--grader-model PROVIDER/MODEL] [--report FILE] [--faux MODULE]
38
38
  agentrun-serve import [--data DIR] [--from claude-code,codex,pi] [--dry-run] [--include-deleted] [--all] [--verbose] [--port N]
39
+ agentrun-serve learning connect|status|disconnect|retry --project PATH --runtime codex|claude-code [--url URL] [--data DIR]
39
40
  agentrun-serve runner --data DIR [--loops N] [--drain-timeout D] [--name NAME]
40
41
  agentrun-serve runner --check --data DIR [--name NAME]
42
+ agentrun-serve runner --check --env [--data DIR]
43
+ agentrun-serve runner --check --heartbeat --data DIR [--name NAME]
44
+ agentrun-serve store-schema [--data DIR]
45
+ agentrun-serve store-schema --build
41
46
  agentrun-serve native discover|connect --project PATH [--runtime claude-code|codex] [--agent NAME|--profile NAME] [--url URL] [--data DIR]
42
47
 
43
48
  --data DIR the agent store and its runs (default ~/.local/share/agentrun/agents); the token is DIR/.token, mode 0600
@@ -121,6 +126,13 @@ deleted worktree's); --all keeps those and temporary ones too. Each run keeps wh
121
126
  time at work), priced at the catalog's list prices when its source did not price it. Both end with a summary of every
122
127
  session found, those imported before included, and the address to open the console at (--port as the server takes it).
123
128
 
129
+ \`agentrun-serve store-schema\` prints, as one line of JSON, the store's schema version and runner floor (the oldest version
130
+ a runner's build must know to run on it) beside the version this build knows, and what this build's server and runner do
131
+ on it: for a deploy's check before it starts a build, which must not be older than the store. It reads and changes
132
+ nothing (no lock, no migration). The store is the server's: AGENTRUN_STORE_URL's Postgres, else SQLite in --data. Exit 0
133
+ once read, 1 when the store could not be read, 2 for bad arguments. --build reads no store and prints only the versions
134
+ this build knows. A running server says the same in GET /v2/capabilities (store_schema).
135
+
124
136
  \`agentrun-serve eval-template DIR\` runs a template package's eval cases (all, or each --case) as real runs of its agent
125
137
  and grades each run with the case's graders (templates/README.md, "Running the evals"). By default on a server of its
126
138
  own in this process, over a temp data directory removed at the end, so it never touches your server; --server URL runs
@@ -155,6 +167,10 @@ if (process.argv[2] === "remote-bridge") {
155
167
  await runRemoteWorkerBridge();
156
168
  process.exit(0);
157
169
  }
170
+ if (process.argv[2] === "learning") {
171
+ const { learningMain } = await import("./cli-learning/cli.js");
172
+ process.exit(await learningMain(process.argv.slice(3)));
173
+ }
158
174
  if (process.argv[2] === "native") {
159
175
  const { nativeMain } = await import("./native/cli.js");
160
176
  process.exit(await nativeMain(process.argv.slice(3), commandUsage));
@@ -375,12 +391,18 @@ if (process.argv[2] === "eval-template") {
375
391
  }
376
392
  }
377
393
  // The runner process (runner/main.ts): beside the server, its own store connection in --data, claiming runs until SIGTERM
378
- // or SIGINT. Its exit: 2 bad arguments, 3 a store schema it does not know, 1 anything else, 0 closed. `--check` reads its
379
- // heartbeat (0 fresh, 1 not).
394
+ // or SIGINT. Its exit: 2 bad arguments, 3 a store schema it does not know (or one whose runner floor rose above it while it
395
+ // ran: its runs handed back), 1 anything else, 0 closed. `--check` checks its environment by name (runner-check.ts) and its
396
+ // heartbeat; `--check --env` its environment alone (0 complete, 1 a gap).
380
397
  if (process.argv[2] === "runner") {
381
398
  const { runnerMain } = await import("./runner/main.js");
382
399
  process.exit(await runnerMain(process.argv.slice(3)));
383
400
  }
401
+ // The store's schema and runner floor, read-only (store/store-schema.ts), for a deploy's skew check.
402
+ if (process.argv[2] === "store-schema") {
403
+ const { storeSchemaMain } = await import("./store/store-schema.js");
404
+ process.exit(await storeSchemaMain(process.argv.slice(3), defaultData(), USAGE));
405
+ }
384
406
  if (process.argv[2] === "import") {
385
407
  const { importCommand } = await import("./import.js");
386
408
  process.exit(await importCommand(process.argv.slice(3), USAGE));