@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.
- package/CHANGELOG.md +147 -0
- package/README.md +142 -17
- package/dist/agents-store.js +7 -3
- package/dist/api-only.d.ts +2 -1
- package/dist/api-only.js +3 -2
- package/dist/capacity.d.ts +50 -0
- package/dist/capacity.js +49 -0
- package/dist/cli-learning/claude-wire.d.ts +41 -0
- package/dist/cli-learning/claude-wire.js +258 -0
- package/dist/cli-learning/cli.d.ts +11 -0
- package/dist/cli-learning/cli.js +241 -0
- package/dist/cli-learning/codex-worktree.d.ts +10 -0
- package/dist/cli-learning/codex-worktree.js +119 -0
- package/dist/cli-learning/connections.d.ts +62 -0
- package/dist/cli-learning/connections.js +87 -0
- package/dist/cli-learning/entry.d.ts +1 -0
- package/dist/cli-learning/entry.js +4 -0
- package/dist/cli-learning/evidence.d.ts +78 -0
- package/dist/cli-learning/evidence.js +492 -0
- package/dist/cli-learning/hook.d.ts +33 -0
- package/dist/cli-learning/hook.js +544 -0
- package/dist/cli-learning/install.d.ts +33 -0
- package/dist/cli-learning/install.js +335 -0
- package/dist/cli-learning/observation-proof.d.ts +14 -0
- package/dist/cli-learning/observation-proof.js +10 -0
- package/dist/cli-learning/policy.d.ts +48 -0
- package/dist/cli-learning/policy.js +363 -0
- package/dist/cli-learning/schema.d.ts +16 -0
- package/dist/cli-learning/schema.js +27 -0
- package/dist/cli-learning/state.d.ts +23 -0
- package/dist/cli-learning/state.js +61 -0
- package/dist/cli.js +24 -2
- package/dist/console/assets/index-Bt1B51b7.js +733 -0
- package/dist/console/assets/index-sVftE9Ht.css +1 -0
- package/dist/console/index.html +2 -2
- package/dist/email/email-faux.d.ts +3 -1
- package/dist/email/email-faux.js +3 -2
- package/dist/email/routes.js +22 -12
- package/dist/harness-install.d.ts +6 -2
- package/dist/harness-install.js +40 -8
- package/dist/harness.d.ts +1 -1
- package/dist/harness.js +2 -2
- package/dist/learn/secrets.js +14 -3
- package/dist/learning-words.d.ts +1 -1
- package/dist/learning-words.js +1 -1
- package/dist/mcp-pin-first.js +2 -1
- package/dist/mcp-private-hosts.d.ts +24 -3
- package/dist/mcp-private-hosts.js +53 -3
- package/dist/model-gateway.d.ts +2 -0
- package/dist/model-gateway.js +3 -1
- package/dist/native/runtimes.d.ts +2 -0
- package/dist/native/runtimes.js +2 -0
- package/dist/observation/learning.d.ts +32 -0
- package/dist/observation/learning.js +66 -0
- package/dist/observation/observer.d.ts +8 -1
- package/dist/observation/observer.js +89 -9
- package/dist/observation/schema.js +12 -4
- package/dist/observation/usage-identity.d.ts +9 -0
- package/dist/observation/usage-identity.js +11 -0
- package/dist/openapi.js +89 -13
- package/dist/run-launch.d.ts +14 -0
- package/dist/run-launch.js +4 -0
- package/dist/run-view.d.ts +2 -0
- package/dist/run-view.js +12 -7
- package/dist/runner/adapter-loop.js +29 -26
- package/dist/runner/adapter-run-spec.js +2 -2
- package/dist/runner/beside.d.ts +13 -0
- package/dist/runner/beside.js +27 -8
- package/dist/runner/cli-run-spec.js +2 -2
- package/dist/runner/disk-free.d.ts +44 -0
- package/dist/runner/disk-free.js +96 -0
- package/dist/runner/feedback-round.d.ts +12 -8
- package/dist/runner/feedback-round.js +16 -30
- package/dist/runner/harness-loops.js +3 -1
- package/dist/runner/journal-kinds.d.ts +1 -1
- package/dist/runner/learning-end.js +4 -0
- package/dist/runner/main.d.ts +17 -6
- package/dist/runner/main.js +187 -45
- package/dist/runner/presence.d.ts +11 -2
- package/dist/runner/presence.js +31 -3
- package/dist/runner/run-child-host.d.ts +12 -15
- package/dist/runner/run-child-host.js +46 -108
- package/dist/runner/run-errors.js +2 -0
- package/dist/runner/runner-check.d.ts +51 -0
- package/dist/runner/runner-check.js +206 -0
- package/dist/runner/runner-metrics.d.ts +19 -0
- package/dist/runner/runner-metrics.js +49 -0
- package/dist/runner/runner.d.ts +37 -0
- package/dist/runner/runner.js +43 -3
- package/dist/runner/sdk-loop.js +34 -22
- package/dist/runs-over-store.d.ts +8 -1
- package/dist/runs-over-store.js +57 -9
- package/dist/sdk/runs.d.ts +22 -2
- package/dist/sdk/runs.js +103 -34
- package/dist/server.d.ts +3 -0
- package/dist/server.js +149 -26
- package/dist/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/start-switches.js +2 -0
- package/dist/stats.d.ts +4 -0
- package/dist/stats.js +1 -1
- package/dist/store/agent-body.d.ts +12 -0
- package/dist/store/agent-body.js +16 -2
- package/dist/store/dialect.d.ts +2 -0
- package/dist/store/dialect.js +1 -0
- package/dist/store/index.d.ts +3 -3
- package/dist/store/index.js +2 -2
- package/dist/store/postgres/connection.d.ts +5 -2
- package/dist/store/postgres/connection.js +19 -7
- package/dist/store/postgres/dialect.js +1 -0
- package/dist/store/postgres/migrate.d.ts +30 -0
- package/dist/store/postgres/migrate.js +72 -5
- package/dist/store/postgres/migration-lint.d.ts +8 -0
- package/dist/store/postgres/migration-lint.js +119 -0
- package/dist/store/postgres/migrations/0024_runner_capacity.sql +28 -0
- package/dist/store/postgres/store.d.ts +8 -3
- package/dist/store/postgres/store.js +31 -11
- package/dist/store/schema.d.ts +18 -1
- package/dist/store/schema.js +33 -2
- package/dist/store/sqlite/run-launch.d.ts +9 -1
- package/dist/store/sqlite/run-launch.js +44 -0
- package/dist/store/sqlite/store.d.ts +17 -0
- package/dist/store/sqlite/store.js +87 -10
- package/dist/store/store-schema.d.ts +34 -0
- package/dist/store/store-schema.js +125 -0
- package/dist/store/store.d.ts +53 -1
- package/dist/store/store.js +13 -0
- package/dist/store-reads/analytics.d.ts +3 -2
- package/dist/store-reads/analytics.js +20 -8
- package/dist/store-view.d.ts +4 -3
- package/dist/store-view.js +11 -7
- package/dist/templates.d.ts +3 -2
- package/dist/tool-gate.d.ts +4 -2
- package/dist/unified-usage.d.ts +24 -0
- package/dist/unified-usage.js +400 -0
- package/dist/uploads-archil.d.ts +100 -0
- package/dist/uploads-archil.js +430 -0
- package/dist/uploads.d.ts +55 -1
- package/dist/uploads.js +185 -98
- package/dist/validate.js +1 -1
- package/dist/workspace/archil-disk.d.ts +6 -5
- package/dist/workspace/archil-disk.js +27 -12
- package/dist/workspace/archil.js +3 -2
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/console/assets/index-D0mr9wfZ.css +0 -1
- package/dist/console/assets/index-D7G6o-1E.js +0 -720
|
@@ -0,0 +1,492 @@
|
|
|
1
|
+
import { constants } from 'node:fs';
|
|
2
|
+
import { lstat, open } from 'node:fs/promises';
|
|
3
|
+
import { isAbsolute } from 'node:path';
|
|
4
|
+
import { stateHash } from './state.js';
|
|
5
|
+
const object = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
|
|
6
|
+
const identifier = (v) => typeof v === 'string' && /^[\w.:@+-]{1,200}$/.test(v);
|
|
7
|
+
const bounded = (v, max = 131072) => typeof v === 'string' && Buffer.byteLength(v) <= max;
|
|
8
|
+
/** SDK text is limited in UTF-16 code units. Also keep the source UTF-8 budget and
|
|
9
|
+
* leave room for an event envelope inside the SDK's 256 KB JSON batch. Call only
|
|
10
|
+
* after redacting the whole value, so a cut cannot expose part of a held secret. */
|
|
11
|
+
export function boundCaptureText(text, maxBytes = 131072) {
|
|
12
|
+
if (text.length <= 128000 && Buffer.byteLength(text) <= maxBytes
|
|
13
|
+
&& Buffer.byteLength(JSON.stringify(text)) <= 200000)
|
|
14
|
+
return { text, truncated: false };
|
|
15
|
+
let end = 0, bytes = 0, jsonBytes = 2;
|
|
16
|
+
for (const character of text) {
|
|
17
|
+
const width = Buffer.byteLength(character), encoded = Buffer.byteLength(JSON.stringify(character)) - 2;
|
|
18
|
+
if (end + character.length > 128000 || bytes + width > maxBytes || jsonBytes + encoded > 200000)
|
|
19
|
+
break;
|
|
20
|
+
end += character.length;
|
|
21
|
+
bytes += width;
|
|
22
|
+
jsonBytes += encoded;
|
|
23
|
+
}
|
|
24
|
+
return { text: text.slice(0, end), truncated: end !== text.length };
|
|
25
|
+
}
|
|
26
|
+
const tokenKeys = ['input_tokens', 'output_tokens', 'cache_read_tokens', 'cache_write_tokens'];
|
|
27
|
+
/** Match the importer's cache convention: Codex input includes cache tokens, Claude input excludes them. */
|
|
28
|
+
function nativeUsage(value, runtime) {
|
|
29
|
+
if (!object(value))
|
|
30
|
+
return;
|
|
31
|
+
const values = [value.input_tokens, value.output_tokens,
|
|
32
|
+
runtime === 'codex' ? value.cached_input_tokens : value.cache_read_input_tokens,
|
|
33
|
+
runtime === 'codex' ? value.cache_write_input_tokens : value.cache_creation_input_tokens];
|
|
34
|
+
if (!values.every(value => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0))
|
|
35
|
+
return;
|
|
36
|
+
const [input, output, cacheRead, cacheWrite] = values;
|
|
37
|
+
const uncached = runtime === 'codex' ? input - cacheRead - cacheWrite : input;
|
|
38
|
+
if (uncached < 0 || !Number.isSafeInteger(uncached + output + cacheRead + cacheWrite))
|
|
39
|
+
return;
|
|
40
|
+
return { input_tokens: uncached, output_tokens: output, cache_read_tokens: cacheRead, cache_write_tokens: cacheWrite };
|
|
41
|
+
}
|
|
42
|
+
/** The two harnesses use different prompt identities. Missing identities are not guessed from timestamps. */
|
|
43
|
+
export function normalizeHookInput(runtime, input) {
|
|
44
|
+
if (!object(input) || !identifier(input.session_id) || !bounded(input.cwd, 4096) || !isAbsolute(input.cwd))
|
|
45
|
+
return null;
|
|
46
|
+
if (!['UserPromptSubmit', 'Stop', 'Interrupt', 'StopFailure', 'SessionEnd'].includes(input.hook_event_name))
|
|
47
|
+
return null;
|
|
48
|
+
if (input.agent_id)
|
|
49
|
+
return null; // Independently enroll root sessions, not every spawned child.
|
|
50
|
+
const turnId = runtime === 'codex' ? input.turn_id : input.prompt_id;
|
|
51
|
+
if (input.hook_event_name !== 'SessionEnd' && !identifier(turnId))
|
|
52
|
+
return null;
|
|
53
|
+
if (input.hook_event_name === 'UserPromptSubmit' && !bounded(input.prompt, 1048576))
|
|
54
|
+
return null;
|
|
55
|
+
return {
|
|
56
|
+
event: input.hook_event_name,
|
|
57
|
+
sessionId: input.session_id,
|
|
58
|
+
...(identifier(turnId) ? { turnId } : {}),
|
|
59
|
+
cwd: input.cwd,
|
|
60
|
+
...(bounded(input.transcript_path, 4096) && isAbsolute(input.transcript_path) ? { transcriptPath: input.transcript_path } : {}),
|
|
61
|
+
// Preserve the whole bounded stdin value until the hook redacts it before cutting.
|
|
62
|
+
...(bounded(input.prompt, 1048576) ? { prompt: input.prompt } : {}),
|
|
63
|
+
...(bounded(input.last_assistant_message, 1048576) ? { answer: input.last_assistant_message } : {}),
|
|
64
|
+
...(bounded(input.model, 200) ? { model: input.model } : {}),
|
|
65
|
+
stopHookActive: input.stop_hook_active === true,
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
export async function captureTranscriptCursor(path, firstPrompt) {
|
|
69
|
+
if (!path)
|
|
70
|
+
return null;
|
|
71
|
+
const observedAt = Date.now();
|
|
72
|
+
try {
|
|
73
|
+
const file = await open(path, 'r');
|
|
74
|
+
try {
|
|
75
|
+
const info = await file.stat();
|
|
76
|
+
return info.isFile() ? { path, offset: info.size, dev: info.dev, ino: info.ino } : null;
|
|
77
|
+
}
|
|
78
|
+
finally {
|
|
79
|
+
await file.close();
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (error.code !== 'ENOENT' || firstPrompt?.runtime !== 'claude-code'
|
|
84
|
+
|| !isAbsolute(path) || !identifier(firstPrompt.sessionId) || !identifier(firstPrompt.turnId))
|
|
85
|
+
return null;
|
|
86
|
+
// open() also returns ENOENT for a dangling symlink. That is not evidence that the
|
|
87
|
+
// native transcript path itself did not exist at enrollment.
|
|
88
|
+
try {
|
|
89
|
+
await lstat(path);
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
catch (error) {
|
|
93
|
+
if (error.code !== 'ENOENT')
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
return { path, offset: 0, dev: -1, ino: -1,
|
|
97
|
+
absent: { observedAt, sessionId: firstPrompt.sessionId, turnId: firstPrompt.turnId } };
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const messageText = (content) => typeof content === 'string' ? content : Array.isArray(content)
|
|
101
|
+
? content.filter(item => object(item) && ['text', 'input_text', 'output_text'].includes(item.type) && typeof item.text === 'string').map(item => item.text).join('\n') : '';
|
|
102
|
+
const nonTextContent = new Set(['image', 'image_url', 'input_image', 'output_image', 'document', 'file', 'input_file', 'output_file', 'audio', 'input_audio', 'output_audio', 'video', 'input_video', 'output_video']);
|
|
103
|
+
const hasNonTextContent = (content) => (Array.isArray(content) ? content : [content])
|
|
104
|
+
.some(block => object(block) && nonTextContent.has(block.type));
|
|
105
|
+
const RECORD_BYTES = 1024 * 1024, METADATA_RECORD_BYTES = 16 * 1024 * 1024;
|
|
106
|
+
const largeClaudeMetadata = (row) => ['api-request-shape', 'api-request-blob'].includes(row.type)
|
|
107
|
+
|| (row.type === 'attachment' && object(row.attachment) && row.attachment.type === 'prompt_snapshot');
|
|
108
|
+
// This bounded prefix only permits buffering a larger record. The parsed native type below
|
|
109
|
+
// still decides eligibility, and snapshot records still pass source/session/ancestry checks.
|
|
110
|
+
const snapshotPrefix = /^\s*\{\s*(?:"(?:parentUuid|isSidechain|sessionId|uuid|timestamp|cwd|userType|version|type)"\s*:\s*(?:"(?:[^"\\]|\\.)*"|null|true|false|-?\d+(?:\.\d+)?)\s*,\s*)*"attachment"\s*:\s*\{\s*"type"\s*:\s*"prompt_snapshot"\s*[,}]/;
|
|
111
|
+
const largeClaudeMetadataPrefix = (prefix) => /^\s*\{\s*"type"\s*:\s*"api-request-(?:shape|blob)"\s*[,}]/.test(prefix) || snapshotPrefix.test(prefix);
|
|
112
|
+
/** Read only bytes written after enrollment for this prompt. Tool results and reasoning never become dialogue. */
|
|
113
|
+
export async function collectPromptEvidence(options) {
|
|
114
|
+
const result = { messages: [], tools: [], answer: '', complete: true, seedObserved: false };
|
|
115
|
+
const incomplete = (reason) => { result.complete = false; result.reason ??= reason; };
|
|
116
|
+
const capture = (text, maxBytes) => {
|
|
117
|
+
const redacted = options.redact?.(text) ?? text;
|
|
118
|
+
if (redacted !== text) {
|
|
119
|
+
result.redacted = true;
|
|
120
|
+
incomplete('Source dialogue contains withheld or redacted text.');
|
|
121
|
+
}
|
|
122
|
+
const bounded = boundCaptureText(redacted, maxBytes);
|
|
123
|
+
if (bounded.truncated) {
|
|
124
|
+
result.truncated = true;
|
|
125
|
+
incomplete('The prompt dialogue exceeds the evidence limit; retained text is truncated.');
|
|
126
|
+
}
|
|
127
|
+
return bounded.text;
|
|
128
|
+
};
|
|
129
|
+
result.answer = capture(options.answer ?? '');
|
|
130
|
+
if (!options.cursor) {
|
|
131
|
+
incomplete('The prompt transcript was unavailable at enrollment.');
|
|
132
|
+
return result;
|
|
133
|
+
}
|
|
134
|
+
const cursor = options.cursor;
|
|
135
|
+
if (cursor.absent && (options.runtime !== 'claude-code' || options.sessionId !== cursor.absent.sessionId
|
|
136
|
+
|| options.turnId !== cursor.absent.turnId || !Number.isFinite(cursor.absent.observedAt))) {
|
|
137
|
+
incomplete('The missing transcript receipt does not belong to this source prompt.');
|
|
138
|
+
return result;
|
|
139
|
+
}
|
|
140
|
+
let freshRootVerified = false, freshIdentityInvalid = false;
|
|
141
|
+
const requestUsage = new Map();
|
|
142
|
+
let invalidUsage = false;
|
|
143
|
+
const recordUsage = (id, value) => {
|
|
144
|
+
if (!identifier(id)) {
|
|
145
|
+
invalidUsage = true;
|
|
146
|
+
return;
|
|
147
|
+
}
|
|
148
|
+
const next = nativeUsage(value, options.runtime), previous = requestUsage.get(id);
|
|
149
|
+
if (options.runtime === 'claude-code' && value !== undefined && !next)
|
|
150
|
+
invalidUsage = true;
|
|
151
|
+
if (options.runtime === 'codex' && requestUsage.has(id)
|
|
152
|
+
&& (!next || !previous || tokenKeys.some(key => next[key] !== previous[key])))
|
|
153
|
+
invalidUsage = true;
|
|
154
|
+
// Claude repeats one message's counters across streamed blocks; later blocks finish those counts.
|
|
155
|
+
if (next)
|
|
156
|
+
requestUsage.set(id, previous && options.runtime === 'claude-code'
|
|
157
|
+
? Object.fromEntries(tokenKeys.map(key => [key, Math.max(previous[key], next[key])])) : next);
|
|
158
|
+
else if (!requestUsage.has(id))
|
|
159
|
+
requestUsage.set(id, undefined);
|
|
160
|
+
};
|
|
161
|
+
const tools = new Map();
|
|
162
|
+
let evidenceBytes = 0;
|
|
163
|
+
let finalAssistantText;
|
|
164
|
+
const message = (role, text) => {
|
|
165
|
+
if (!text)
|
|
166
|
+
return;
|
|
167
|
+
if (result.messages.length >= 200) {
|
|
168
|
+
incomplete('The prompt dialogue exceeds the evidence limit.');
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
const kept = capture(text, Math.max(0, 131072 - evidenceBytes));
|
|
172
|
+
evidenceBytes += Buffer.byteLength(kept);
|
|
173
|
+
if (kept)
|
|
174
|
+
result.messages.push({ role, text: kept });
|
|
175
|
+
};
|
|
176
|
+
const call = (id, name) => {
|
|
177
|
+
if (!identifier(id) || !bounded(name, 200))
|
|
178
|
+
return;
|
|
179
|
+
if (tools.size >= 500) {
|
|
180
|
+
incomplete('The prompt tool count exceeds the evidence limit.');
|
|
181
|
+
return;
|
|
182
|
+
}
|
|
183
|
+
tools.set(id, { id, name, status: 'started' });
|
|
184
|
+
};
|
|
185
|
+
const returned = (id, failed) => {
|
|
186
|
+
if (!identifier(id))
|
|
187
|
+
return;
|
|
188
|
+
const tool = tools.get(id);
|
|
189
|
+
if (tool)
|
|
190
|
+
tool.status = failed ? 'failed' : 'completed';
|
|
191
|
+
};
|
|
192
|
+
let lastClaudeUuid;
|
|
193
|
+
let sawClaudePrompt = false;
|
|
194
|
+
const consume = (line) => {
|
|
195
|
+
if (!line.trim())
|
|
196
|
+
return true;
|
|
197
|
+
let row;
|
|
198
|
+
try {
|
|
199
|
+
row = JSON.parse(line);
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
invalidUsage = true;
|
|
203
|
+
incomplete('A prompt transcript record could not be parsed.');
|
|
204
|
+
return true;
|
|
205
|
+
}
|
|
206
|
+
if (!object(row)) {
|
|
207
|
+
invalidUsage = true;
|
|
208
|
+
return true;
|
|
209
|
+
}
|
|
210
|
+
if (Buffer.byteLength(line) > RECORD_BYTES && !(options.runtime === 'claude-code' && largeClaudeMetadata(row))) {
|
|
211
|
+
invalidUsage = true;
|
|
212
|
+
incomplete('A transcript record exceeds the evidence limit.');
|
|
213
|
+
return true;
|
|
214
|
+
}
|
|
215
|
+
if (options.runtime === 'codex') {
|
|
216
|
+
const payload = row.payload;
|
|
217
|
+
if (!object(payload)) {
|
|
218
|
+
if (['token_usage_record', 'response_item', 'event_msg'].includes(row.type))
|
|
219
|
+
invalidUsage = true;
|
|
220
|
+
return true;
|
|
221
|
+
}
|
|
222
|
+
if ((row.type === 'session_meta' && options.sessionId && identifier(payload.id) && payload.id !== options.sessionId)
|
|
223
|
+
|| (options.sessionId && identifier(payload.session_id) && payload.session_id !== options.sessionId)) {
|
|
224
|
+
invalidUsage = true;
|
|
225
|
+
incomplete('The transcript includes a different session.');
|
|
226
|
+
return true;
|
|
227
|
+
}
|
|
228
|
+
if (identifier(payload.turn_id) && payload.turn_id !== options.turnId) {
|
|
229
|
+
incomplete('Another prompt started before the completion was captured.');
|
|
230
|
+
return false;
|
|
231
|
+
}
|
|
232
|
+
if (row.type === 'token_usage_record') {
|
|
233
|
+
// Only the native per-response record carries exact prompt identity. Session/turn totals and
|
|
234
|
+
// legacy token_count events can repeat earlier usage, so they are never added to this window.
|
|
235
|
+
if (options.sessionId && payload.thread_id === options.sessionId && payload.turn_id === options.turnId)
|
|
236
|
+
recordUsage(payload.response_id, payload.usage);
|
|
237
|
+
else
|
|
238
|
+
invalidUsage = true;
|
|
239
|
+
return true;
|
|
240
|
+
}
|
|
241
|
+
if (row.type === 'compacted') {
|
|
242
|
+
invalidUsage = true;
|
|
243
|
+
incomplete('The prompt compacted its execution evidence before capture completed.');
|
|
244
|
+
}
|
|
245
|
+
if (row.type === 'event_msg' && payload.type === 'turn_aborted' && payload.turn_id === options.turnId)
|
|
246
|
+
incomplete('The prompt was interrupted before capture completed.');
|
|
247
|
+
if (row.type !== 'response_item')
|
|
248
|
+
return true;
|
|
249
|
+
if (payload.type === 'message') {
|
|
250
|
+
const text = messageText(payload.content);
|
|
251
|
+
if (payload.role === 'developer' && options.seedMarker && text.includes(`AgentRun context receipt: ${options.seedMarker}`))
|
|
252
|
+
result.seedObserved = true;
|
|
253
|
+
if (payload.role === 'user') {
|
|
254
|
+
if (hasNonTextContent(payload.content))
|
|
255
|
+
incomplete('The prompt includes non-text source content that was not captured.');
|
|
256
|
+
message('user', text);
|
|
257
|
+
}
|
|
258
|
+
if (payload.role === 'assistant' && (payload.channel === undefined || ['final', 'commentary'].includes(payload.channel))
|
|
259
|
+
&& (payload.phase === undefined || ['final_answer', 'commentary'].includes(payload.phase))) {
|
|
260
|
+
if (hasNonTextContent(payload.content))
|
|
261
|
+
incomplete('The prompt includes non-text source content that was not captured.');
|
|
262
|
+
message('assistant', text);
|
|
263
|
+
if (text && payload.channel !== 'commentary' && payload.phase !== 'commentary')
|
|
264
|
+
finalAssistantText = text;
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
else if (payload.type === 'function_call' || payload.type === 'custom_tool_call')
|
|
268
|
+
call(payload.call_id, payload.name);
|
|
269
|
+
else if (payload.type === 'function_call_output' || payload.type === 'custom_tool_call_output')
|
|
270
|
+
returned(payload.call_id, payload.is_error === true);
|
|
271
|
+
}
|
|
272
|
+
else {
|
|
273
|
+
if (row.isSidechain === true)
|
|
274
|
+
return true;
|
|
275
|
+
if (cursor.absent && !freshRootVerified) {
|
|
276
|
+
// Metadata and attachments can precede the first user row, but no dialogue or
|
|
277
|
+
// tool history is accepted until that row proves this newly enrolled root prompt.
|
|
278
|
+
if (!['user', 'assistant'].includes(row.type))
|
|
279
|
+
return true;
|
|
280
|
+
if (row.type !== 'user' || row.sessionId !== cursor.absent.sessionId
|
|
281
|
+
|| (row.promptId ?? row.prompt_id) !== cursor.absent.turnId || row.parentUuid !== null
|
|
282
|
+
|| !identifier(row.uuid) || row.isMeta || row.toolUseResult || row.message?.role !== 'user') {
|
|
283
|
+
freshIdentityInvalid = true;
|
|
284
|
+
incomplete('The new Claude transcript does not begin with the enrolled root prompt.');
|
|
285
|
+
return false;
|
|
286
|
+
}
|
|
287
|
+
freshRootVerified = true;
|
|
288
|
+
}
|
|
289
|
+
if (options.sessionId && identifier(row.sessionId) && row.sessionId !== options.sessionId) {
|
|
290
|
+
invalidUsage = true;
|
|
291
|
+
if (cursor.absent) {
|
|
292
|
+
freshIdentityInvalid = true;
|
|
293
|
+
incomplete('The new transcript includes a different session.');
|
|
294
|
+
return false;
|
|
295
|
+
}
|
|
296
|
+
incomplete('The transcript includes a different session.');
|
|
297
|
+
return true;
|
|
298
|
+
}
|
|
299
|
+
const promptId = row.promptId ?? row.prompt_id;
|
|
300
|
+
if (identifier(promptId) && promptId !== options.turnId) {
|
|
301
|
+
freshIdentityInvalid ||= Boolean(cursor.absent);
|
|
302
|
+
incomplete('Another prompt started before the completion was captured.');
|
|
303
|
+
return false;
|
|
304
|
+
}
|
|
305
|
+
// A cursor starts within one linear native conversation. A later parent jump is a rewind or
|
|
306
|
+
// missing branch; do not attach its messages to this prompt merely because their bytes are later.
|
|
307
|
+
if (['user', 'assistant', 'attachment'].includes(row.type) && identifier(row.uuid)) {
|
|
308
|
+
if (lastClaudeUuid && row.uuid !== lastClaudeUuid && Object.hasOwn(row, 'parentUuid') && row.parentUuid !== lastClaudeUuid) {
|
|
309
|
+
invalidUsage = true;
|
|
310
|
+
freshIdentityInvalid ||= Boolean(cursor.absent);
|
|
311
|
+
incomplete('The transcript conversation branched or has missing ancestry.');
|
|
312
|
+
return false;
|
|
313
|
+
}
|
|
314
|
+
lastClaudeUuid = row.uuid;
|
|
315
|
+
}
|
|
316
|
+
if (row.type === 'system' && (row.subtype === 'compact_boundary' || row.subtype === 'microcompact_boundary')) {
|
|
317
|
+
invalidUsage = true;
|
|
318
|
+
incomplete('The prompt compacted its execution evidence before capture completed.');
|
|
319
|
+
}
|
|
320
|
+
if (row.type === 'attachment' && object(row.attachment) && row.attachment.type === 'hook_additional_context'
|
|
321
|
+
&& row.attachment.hookEvent === 'UserPromptSubmit' && Array.isArray(row.attachment.content)
|
|
322
|
+
&& row.attachment.content.every((item) => typeof item === 'string') && options.seedMarker
|
|
323
|
+
&& row.attachment.content.some((text) => text.includes(`AgentRun context receipt: ${options.seedMarker}`))) {
|
|
324
|
+
result.seedObserved = true;
|
|
325
|
+
}
|
|
326
|
+
const nativeMessage = row.message;
|
|
327
|
+
if (!object(nativeMessage)) {
|
|
328
|
+
if (row.type === 'assistant')
|
|
329
|
+
invalidUsage = true;
|
|
330
|
+
return true;
|
|
331
|
+
}
|
|
332
|
+
if (row.type === 'assistant' && nativeMessage.role !== 'assistant')
|
|
333
|
+
invalidUsage = true;
|
|
334
|
+
// Source role comes from the native message envelope, never a tool's content or a string prefix.
|
|
335
|
+
if ((row.type === 'user' || row.type === 'assistant') && nativeMessage.role === row.type) {
|
|
336
|
+
if (row.type === 'assistant' && (nativeMessage.model !== '<synthetic>' || row.isApiErrorMessage === true)) {
|
|
337
|
+
if (options.sessionId && row.sessionId === options.sessionId)
|
|
338
|
+
recordUsage(nativeMessage.id, nativeMessage.usage);
|
|
339
|
+
else
|
|
340
|
+
invalidUsage = true;
|
|
341
|
+
}
|
|
342
|
+
if (hasNonTextContent(nativeMessage.content))
|
|
343
|
+
incomplete('The prompt includes non-text source content that was not captured.');
|
|
344
|
+
const text = messageText(nativeMessage.content);
|
|
345
|
+
if (row.type === 'user' && text && !row.isMeta && !row.toolUseResult && !sawClaudePrompt) {
|
|
346
|
+
sawClaudePrompt = true;
|
|
347
|
+
if (options.prompt !== undefined && !identifier(promptId) && text.trim() !== options.prompt.trim()) {
|
|
348
|
+
invalidUsage = true;
|
|
349
|
+
incomplete('The transcript prompt does not match the submitted prompt.');
|
|
350
|
+
return false;
|
|
351
|
+
}
|
|
352
|
+
}
|
|
353
|
+
message(row.type, text);
|
|
354
|
+
if (row.type === 'assistant' && text) {
|
|
355
|
+
finalAssistantText = text;
|
|
356
|
+
result.model = bounded(nativeMessage.model, 200) && nativeMessage.model ? nativeMessage.model : undefined;
|
|
357
|
+
}
|
|
358
|
+
}
|
|
359
|
+
if (Array.isArray(nativeMessage.content))
|
|
360
|
+
for (const block of nativeMessage.content) {
|
|
361
|
+
if (!object(block))
|
|
362
|
+
continue;
|
|
363
|
+
if (row.type === 'assistant' && block.type === 'tool_use')
|
|
364
|
+
call(block.id, block.name);
|
|
365
|
+
if (row.type === 'user' && block.type === 'tool_result')
|
|
366
|
+
returned(block.tool_use_id, block.is_error === true);
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
return true;
|
|
370
|
+
};
|
|
371
|
+
const readCursor = await readWindow(cursor, options.maxBytes ?? 64 * 1024 * 1024, consume, reason => {
|
|
372
|
+
invalidUsage = true;
|
|
373
|
+
incomplete(reason);
|
|
374
|
+
}, options.runtime);
|
|
375
|
+
if (cursor.absent) {
|
|
376
|
+
if (!freshRootVerified || freshIdentityInvalid) {
|
|
377
|
+
incomplete('The first Claude transcript could not be bound to the enrolled prompt.');
|
|
378
|
+
result.messages = [];
|
|
379
|
+
tools.clear();
|
|
380
|
+
finalAssistantText = undefined;
|
|
381
|
+
result.seedObserved = false;
|
|
382
|
+
delete result.model;
|
|
383
|
+
invalidUsage = true;
|
|
384
|
+
}
|
|
385
|
+
else if (readCursor)
|
|
386
|
+
result.verifiedCursor = readCursor;
|
|
387
|
+
}
|
|
388
|
+
result.tools = [...tools.values()];
|
|
389
|
+
if (result.tools.some(tool => tool.status === 'started'))
|
|
390
|
+
incomplete('A tool call has no recorded result in this prompt window.');
|
|
391
|
+
const finalMatches = options.answerDigest !== undefined
|
|
392
|
+
? /^[a-f0-9]{64}$/.test(options.answerDigest) && finalAssistantText !== undefined && stateHash(finalAssistantText.trim()) === options.answerDigest
|
|
393
|
+
: finalAssistantText?.trim() === options.answer?.trim();
|
|
394
|
+
if (!options.answer?.trim() || !finalMatches) {
|
|
395
|
+
invalidUsage = true;
|
|
396
|
+
incomplete('The final assistant response is not yet present in this prompt transcript.');
|
|
397
|
+
}
|
|
398
|
+
if (!result.answer)
|
|
399
|
+
result.answer = capture(finalAssistantText ?? result.messages.filter(message => message.role === 'assistant').at(-1)?.text ?? '');
|
|
400
|
+
if (!invalidUsage && requestUsage.size && [...requestUsage.values()].every(value => value !== undefined)) {
|
|
401
|
+
const total = { input_tokens: 0, output_tokens: 0, cache_read_tokens: 0, cache_write_tokens: 0 };
|
|
402
|
+
for (const usage of requestUsage.values())
|
|
403
|
+
for (const key of tokenKeys)
|
|
404
|
+
total[key] += usage[key];
|
|
405
|
+
if (tokenKeys.every(key => Number.isSafeInteger(total[key]))
|
|
406
|
+
&& Number.isSafeInteger(tokenKeys.reduce((sum, key) => sum + total[key], 0)))
|
|
407
|
+
result.usage = { ...total, cost_usd: null };
|
|
408
|
+
}
|
|
409
|
+
return result;
|
|
410
|
+
}
|
|
411
|
+
/** Stream bounded records, not a whole transcript window. Oversized records never consume unbounded memory. */
|
|
412
|
+
async function readWindow(cursor, maxBytes, consume, incomplete, runtime) {
|
|
413
|
+
try {
|
|
414
|
+
const file = await open(cursor.path, cursor.absent ? constants.O_RDONLY | constants.O_NOFOLLOW : 'r');
|
|
415
|
+
try {
|
|
416
|
+
const info = await file.stat();
|
|
417
|
+
const identityMatches = cursor.absent
|
|
418
|
+
? info.birthtimeMs > 0 && info.birthtimeMs >= cursor.absent.observedAt && cursor.offset === 0
|
|
419
|
+
: info.dev === cursor.dev && info.ino === cursor.ino;
|
|
420
|
+
if (!info.isFile() || !identityMatches || info.size < cursor.offset) {
|
|
421
|
+
incomplete('The prompt transcript changed or was truncated.');
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
const length = info.size - cursor.offset;
|
|
425
|
+
if (length > maxBytes) {
|
|
426
|
+
incomplete('The prompt transcript exceeds the evidence byte limit.');
|
|
427
|
+
return;
|
|
428
|
+
}
|
|
429
|
+
if (!length)
|
|
430
|
+
return;
|
|
431
|
+
const stream = file.createReadStream({ start: cursor.offset, end: info.size - 1, autoClose: false, highWaterMark: 64 * 1024 });
|
|
432
|
+
let pending = Buffer.alloc(0), discarding = false, records = 0, bytes = 0, recordLimit = RECORD_BYTES;
|
|
433
|
+
for await (const raw of stream) {
|
|
434
|
+
const chunk = Buffer.from(raw);
|
|
435
|
+
bytes += chunk.length;
|
|
436
|
+
let start = 0;
|
|
437
|
+
while (start < chunk.length) {
|
|
438
|
+
const newline = chunk.indexOf(10, start);
|
|
439
|
+
const end = newline < 0 ? chunk.length : newline;
|
|
440
|
+
if (!discarding) {
|
|
441
|
+
const part = chunk.subarray(start, end);
|
|
442
|
+
if (pending.length + part.length > recordLimit && recordLimit === RECORD_BYTES && runtime === 'claude-code') {
|
|
443
|
+
const prefix = pending.length >= 4096 ? pending.subarray(0, 4096)
|
|
444
|
+
: Buffer.concat([pending, part.subarray(0, 4096 - pending.length)]);
|
|
445
|
+
if (largeClaudeMetadataPrefix(prefix.toString('utf8')))
|
|
446
|
+
recordLimit = METADATA_RECORD_BYTES;
|
|
447
|
+
}
|
|
448
|
+
if (pending.length + part.length > recordLimit) {
|
|
449
|
+
incomplete('A transcript record exceeds the evidence limit.');
|
|
450
|
+
pending = Buffer.alloc(0);
|
|
451
|
+
discarding = true;
|
|
452
|
+
}
|
|
453
|
+
else
|
|
454
|
+
pending = pending.length ? Buffer.concat([pending, part]) : part;
|
|
455
|
+
}
|
|
456
|
+
if (newline < 0)
|
|
457
|
+
break;
|
|
458
|
+
if (++records > 100_000) {
|
|
459
|
+
incomplete('The prompt transcript exceeds the record limit.');
|
|
460
|
+
return;
|
|
461
|
+
}
|
|
462
|
+
if (!discarding) {
|
|
463
|
+
let line;
|
|
464
|
+
try {
|
|
465
|
+
line = new TextDecoder('utf8', { fatal: true }).decode(pending);
|
|
466
|
+
}
|
|
467
|
+
catch {
|
|
468
|
+
incomplete('A transcript record contains invalid text.');
|
|
469
|
+
}
|
|
470
|
+
if (line !== undefined && !consume(line))
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
pending = Buffer.alloc(0);
|
|
474
|
+
discarding = false;
|
|
475
|
+
recordLimit = RECORD_BYTES;
|
|
476
|
+
start = newline + 1;
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (bytes !== length)
|
|
480
|
+
incomplete('The prompt transcript changed while reading.');
|
|
481
|
+
if (pending.length || discarding)
|
|
482
|
+
incomplete('The last transcript record is not yet flushed.');
|
|
483
|
+
return { path: cursor.path, offset: info.size, dev: info.dev, ino: info.ino };
|
|
484
|
+
}
|
|
485
|
+
finally {
|
|
486
|
+
await file.close();
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
catch {
|
|
490
|
+
incomplete('The prompt transcript could not be read.');
|
|
491
|
+
}
|
|
492
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { captureSourcePolicy } from './policy.js';
|
|
2
|
+
import { type TranscriptCursor } from './evidence.js';
|
|
3
|
+
import { type CliLearningRuntime } from './state.js';
|
|
4
|
+
export type CliLearningHookOptions = {
|
|
5
|
+
runtime: CliLearningRuntime;
|
|
6
|
+
project: string;
|
|
7
|
+
dataDir: string;
|
|
8
|
+
url?: string;
|
|
9
|
+
};
|
|
10
|
+
export type CliLearningHookDependencies = {
|
|
11
|
+
fetch?: typeof fetch;
|
|
12
|
+
env?: NodeJS.ProcessEnv;
|
|
13
|
+
snapshot?: typeof captureSourcePolicy;
|
|
14
|
+
/** Internal durable inbox cursor; native user input is captured before competing hooks finish. */
|
|
15
|
+
cursor?: TranscriptCursor | null;
|
|
16
|
+
processed?: () => Promise<void>;
|
|
17
|
+
sourceRedacted?: boolean;
|
|
18
|
+
sourceTruncated?: boolean;
|
|
19
|
+
/** Private proof of the full terminal answer when only its bounded prefix is stored. */
|
|
20
|
+
answerDigest?: string;
|
|
21
|
+
/** Original durable inbox time, retained when a queued hook is replayed. */
|
|
22
|
+
receivedAt?: number;
|
|
23
|
+
/** A queued hook must not change enrollment between reading its receipt and replaying it. */
|
|
24
|
+
connectionScope?: string;
|
|
25
|
+
};
|
|
26
|
+
/** Fail-open hook entrypoint. It never starts/resumes the user's CLI or changes its tools, permissions or policy. */
|
|
27
|
+
export declare function runCliLearningHook(options: CliLearningHookOptions, input: unknown, dependencies?: CliLearningHookDependencies): Promise<Record<string, unknown> | undefined>;
|
|
28
|
+
/** Retry terminal receipts only: no native task or model call is dispatched by this source-side drain. */
|
|
29
|
+
export declare function flushCliLearning(options: CliLearningHookOptions, dependencies?: Pick<CliLearningHookDependencies, 'fetch'>): Promise<{
|
|
30
|
+
delivered: number;
|
|
31
|
+
pending: number;
|
|
32
|
+
blocked_journals: number;
|
|
33
|
+
}>;
|