@parcha/agentrun-serve 0.1.0-beta.50 → 0.1.0-beta.52
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 +185 -0
- package/README.md +236 -30
- package/dist/adapters.js +1 -1
- package/dist/agent-delete.d.ts +13 -2
- package/dist/agent-delete.js +14 -5
- package/dist/agents-store.d.ts +5 -1
- package/dist/agents-store.js +17 -7
- package/dist/api-only.d.ts +6 -3
- package/dist/api-only.js +8 -5
- package/dist/archil-routes.d.ts +1 -0
- package/dist/archil-routes.js +28 -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/computer-setting.d.ts +8 -0
- package/dist/computer-setting.js +11 -0
- package/dist/computers.d.ts +6 -2
- package/dist/computers.js +2 -2
- package/dist/console/assets/index-B-D0EM3j.js +733 -0
- package/dist/console/assets/{index-D0mr9wfZ.css → index-DlQepP2J.css} +1 -1
- 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/fal-price.d.ts +76 -0
- package/dist/fal-price.js +368 -0
- 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/commit.d.ts +5 -0
- package/dist/learn/commit.js +4 -1
- package/dist/learn/compile.d.ts +13 -5
- package/dist/learn/compile.js +24 -7
- package/dist/learn/delete.d.ts +12 -6
- package/dist/learn/delete.js +17 -11
- package/dist/learn/folder.d.ts +11 -0
- package/dist/learn/folder.js +20 -3
- package/dist/learn/learning-of.d.ts +8 -0
- package/dist/learn/learning-of.js +8 -0
- package/dist/learn/learning.sh +14 -1
- package/dist/learn/promote.d.ts +51 -7
- package/dist/learn/promote.js +51 -8
- package/dist/learn/secrets.js +14 -3
- package/dist/learning-reset.d.ts +18 -0
- package/dist/learning-reset.js +115 -0
- package/dist/learning-routes.d.ts +1 -1
- package/dist/learning-words.d.ts +6 -1
- package/dist/learning-words.js +6 -1
- package/dist/learning.d.ts +8 -6
- package/dist/learning.js +5 -4
- package/dist/llms.txt +1 -0
- package/dist/mcp-gateway.d.ts +39 -2
- package/dist/mcp-gateway.js +41 -10
- package/dist/mcp-pin-first.js +3 -2
- package/dist/mcp-private-hosts.d.ts +24 -3
- package/dist/mcp-private-hosts.js +53 -3
- package/dist/mcp-servers-store.d.ts +1 -0
- package/dist/mcp-servers-store.js +2 -1
- package/dist/media-duration.d.ts +2 -0
- package/dist/media-duration.js +136 -0
- 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 +133 -24
- package/dist/provider.d.ts +8 -0
- package/dist/provider.js +14 -2
- package/dist/refusal-words.d.ts +0 -3
- package/dist/refusal-words.js +0 -3
- package/dist/request-metadata.d.ts +20 -0
- package/dist/request-metadata.js +24 -0
- package/dist/run-launch.d.ts +27 -4
- package/dist/run-launch.js +18 -3
- package/dist/run-learning-served.d.ts +2 -2
- package/dist/run-usage.d.ts +48 -4
- package/dist/run-usage.js +156 -39
- package/dist/run-view.d.ts +2 -0
- package/dist/run-view.js +8 -7
- package/dist/runner/adapter-loop.d.ts +3 -1
- package/dist/runner/adapter-loop.js +41 -35
- package/dist/runner/adapter-run-spec.d.ts +1 -1
- package/dist/runner/adapter-run-spec.js +15 -15
- package/dist/runner/audit.d.ts +8 -3
- package/dist/runner/audit.js +21 -6
- package/dist/runner/beside.d.ts +13 -0
- package/dist/runner/beside.js +27 -8
- package/dist/runner/claim-secrets.d.ts +2 -1
- package/dist/runner/claim-secrets.js +5 -3
- package/dist/runner/cli-run-spec.d.ts +1 -1
- package/dist/runner/cli-run-spec.js +14 -13
- package/dist/runner/conformance/harness.js +4 -2
- package/dist/runner/disk-free.d.ts +44 -0
- package/dist/runner/disk-free.js +96 -0
- package/dist/runner/dispatch.js +4 -2
- package/dist/runner/feedback-round.d.ts +12 -8
- package/dist/runner/feedback-round.js +16 -30
- package/dist/runner/harness-loops.js +8 -3
- package/dist/runner/journal-kinds.d.ts +4 -1
- package/dist/runner/learning-end.d.ts +2 -1
- package/dist/runner/learning-end.js +51 -22
- package/dist/runner/main.d.ts +17 -6
- package/dist/runner/main.js +187 -45
- package/dist/runner/mcp-claim.js +1 -1
- package/dist/runner/mcp-run.d.ts +9 -0
- package/dist/runner/mcp-run.js +16 -1
- package/dist/runner/model-route.js +7 -4
- package/dist/runner/presence.d.ts +11 -2
- package/dist/runner/presence.js +31 -3
- package/dist/runner/promotion.d.ts +40 -21
- package/dist/runner/promotion.js +130 -59
- package/dist/runner/run-child-host.d.ts +12 -15
- package/dist/runner/run-child-host.js +52 -112
- 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 +58 -6
- package/dist/runner/sdk-loop.d.ts +2 -2
- package/dist/runner/sdk-loop.js +37 -25
- package/dist/runner/store-port.d.ts +3 -0
- package/dist/runner/workflow-spec.js +3 -3
- package/dist/runs-over-store.d.ts +13 -3
- package/dist/runs-over-store.js +71 -16
- package/dist/sdk/check.d.ts +6 -5
- package/dist/sdk/check.js +17 -16
- package/dist/sdk/runs.d.ts +22 -2
- package/dist/sdk/runs.js +167 -82
- package/dist/server.d.ts +3 -0
- package/dist/server.js +230 -43
- 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 +16 -0
- package/dist/store/agent-body.js +20 -3
- 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/journal/storage.d.ts +2 -0
- package/dist/store/journal/storage.js +2 -1
- 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/migrations/0025_run_attempts.sql +27 -0
- package/dist/store/postgres/migrations/0026_run_disk.sql +23 -0
- package/dist/store/postgres/store.d.ts +8 -3
- package/dist/store/postgres/store.js +31 -11
- package/dist/store/schema.d.ts +32 -2
- package/dist/store/schema.js +74 -5
- package/dist/store/sqlite/run-launch.d.ts +31 -1
- package/dist/store/sqlite/run-launch.js +111 -2
- package/dist/store/sqlite/run-patch.d.ts +2 -1
- package/dist/store/sqlite/run-patch.js +4 -3
- package/dist/store/sqlite/store.d.ts +17 -0
- package/dist/store/sqlite/store.js +226 -37
- package/dist/store/store-schema.d.ts +34 -0
- package/dist/store/store-schema.js +125 -0
- package/dist/store/store.d.ts +120 -5
- 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-reads/learning.d.ts +12 -8
- package/dist/store-reads/learning.js +33 -24
- package/dist/store-reads/loop.d.ts +4 -3
- package/dist/store-reads/loop.js +7 -5
- package/dist/store-view.d.ts +4 -3
- package/dist/store-view.js +11 -7
- package/dist/template-eval.js +4 -4
- package/dist/templates.d.ts +6 -2
- package/dist/templates.js +7 -5
- package/dist/timeline/labels.js +1 -1
- package/dist/tool-gate.d.ts +4 -2
- package/dist/tools.js +1 -1
- 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 +431 -0
- package/dist/uploads.d.ts +52 -1
- package/dist/uploads.js +186 -108
- package/dist/validate.js +5 -1
- package/dist/web-save.d.ts +3 -0
- package/dist/web-save.js +17 -2
- package/dist/workspace/archil-disk.d.ts +6 -5
- package/dist/workspace/archil-disk.js +27 -12
- package/dist/workspace/archil-exec.js +1 -1
- package/dist/workspace/archil.js +4 -3
- package/dist/workspace/revision-skills.js +24 -11
- package/dist/workspace/synced-folder.d.ts +3 -3
- package/dist/workspace/synced-folder.js +7 -6
- package/package.json +10 -10
- package/skills/agentrun-serve/SKILL.md +52 -7
- package/dist/console/assets/index-D7G6o-1E.js +0 -720
|
@@ -0,0 +1,544 @@
|
|
|
1
|
+
import { mkdir, readdir, realpath, unlink } from 'node:fs/promises';
|
|
2
|
+
import { join, sep } from 'node:path';
|
|
3
|
+
import { redactSecrets } from '../learn/secrets.js';
|
|
4
|
+
import { runnerSecrets } from '../runner/redact.js';
|
|
5
|
+
import { captureSourcePolicy, CLI_POLICY_BYTES, CLAUDE_SNAPSHOT_PENDING, CLAUDE_IMPORTS_PENDING } from './policy.js';
|
|
6
|
+
import { boundCaptureText, captureTranscriptCursor, collectPromptEvidence, normalizeHookInput } from './evidence.js';
|
|
7
|
+
import { connectionScope, journalParent, journalRoot, readConnection, readPrivateJson, stateHash, writePrivateJson } from './state.js';
|
|
8
|
+
import { codexHookLocation } from './codex-worktree.js';
|
|
9
|
+
import { takeHold, releaseHold } from '../harness-install.js';
|
|
10
|
+
/** A retained receipt or busy lock never permanently occupies a bounded retry slot. Names,
|
|
11
|
+
* not array offsets, keep progress stable when hooks add or remove receipts between retries. */
|
|
12
|
+
function retryBatch(names, after) {
|
|
13
|
+
const sorted = names.slice().sort();
|
|
14
|
+
const next = typeof after === 'string' ? sorted.findIndex(name => name > after) : 0;
|
|
15
|
+
const start = next < 0 ? 0 : next;
|
|
16
|
+
return [...sorted.slice(start), ...sorted.slice(0, start)].slice(0, 100);
|
|
17
|
+
}
|
|
18
|
+
const rootOf = (options, connection) => journalRoot(options.dataDir, connection);
|
|
19
|
+
const changedEnrollment = () => new Error('CLI capture enrollment changed. The prior journal is preserved for review; it was not retried.');
|
|
20
|
+
function checkScope(connection, expected) {
|
|
21
|
+
const scope = connectionScope(connection);
|
|
22
|
+
if (expected !== undefined && expected !== scope)
|
|
23
|
+
throw changedEnrollment();
|
|
24
|
+
return scope;
|
|
25
|
+
}
|
|
26
|
+
const turnFile = (directory, key) => join(directory, `${key}.json`);
|
|
27
|
+
const receiptTime = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 ? value : undefined;
|
|
28
|
+
/** A legacy turn's creation is an upper bound on its submit. Equal or unknown times
|
|
29
|
+
* prove no order, so replay cannot invent an interruption of another prompt. */
|
|
30
|
+
function precedes(turn, receivedAt) {
|
|
31
|
+
const submittedAt = receiptTime(turn.submittedAt) ?? Date.parse(turn.createdAt);
|
|
32
|
+
return receivedAt !== undefined && Number.isFinite(submittedAt) && submittedAt < receivedAt;
|
|
33
|
+
}
|
|
34
|
+
const safeError = (error) => error instanceof TransportError ? `AgentRun request failed (${error.status}).` : 'CLI learning capture could not reach AgentRun; its receipt is retained for retry.';
|
|
35
|
+
class TransportError extends Error {
|
|
36
|
+
status;
|
|
37
|
+
constructor(status) {
|
|
38
|
+
super(`AgentRun request failed (${status}).`);
|
|
39
|
+
this.status = status;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
/** The payload never determines a destination. Only the private, explicitly enrolled loopback connection does. */
|
|
43
|
+
function baseUrl(connection) {
|
|
44
|
+
const url = new URL(connection.url);
|
|
45
|
+
if (!['http:', 'https:'].includes(url.protocol) || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname) || url.username || url.password) {
|
|
46
|
+
throw new Error('CLI learning requires the enrolled local AgentRun server.');
|
|
47
|
+
}
|
|
48
|
+
return url;
|
|
49
|
+
}
|
|
50
|
+
async function assertActiveConnection(dataDir, connection) {
|
|
51
|
+
const current = await readConnection(dataDir, connection.runtime, connection.project);
|
|
52
|
+
if (!current || current.revocation_pending)
|
|
53
|
+
throw changedEnrollment();
|
|
54
|
+
checkScope(current, connectionScope(connection));
|
|
55
|
+
}
|
|
56
|
+
async function post(dataDir, connection, path, token, body, key, fetcher) {
|
|
57
|
+
await assertActiveConnection(dataDir, connection);
|
|
58
|
+
const response = await fetcher(new URL(`/v2${path}`, baseUrl(connection)), {
|
|
59
|
+
method: 'POST', headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json', 'Idempotency-Key': key },
|
|
60
|
+
body: JSON.stringify(body), signal: AbortSignal.timeout(2000), redirect: 'error',
|
|
61
|
+
});
|
|
62
|
+
if (!response.ok)
|
|
63
|
+
throw new TransportError(response.status);
|
|
64
|
+
const text = await response.text();
|
|
65
|
+
return text ? JSON.parse(text) : undefined;
|
|
66
|
+
}
|
|
67
|
+
async function begin(dataDir, connection, path, turn, fetcher) {
|
|
68
|
+
if (turn.receipt)
|
|
69
|
+
return;
|
|
70
|
+
const receipt = await post(dataDir, connection, `/cli-learning/connections/${encodeURIComponent(connection.connection_id)}/runs`, connection.token, turn.start, turn.key, fetcher);
|
|
71
|
+
if (!receipt?.run_id || !receipt.token || receipt.agent_id !== connection.agent_id || !receipt.learning || typeof receipt.learning.context !== 'string' || !Array.isArray(receipt.learning.workflows)) {
|
|
72
|
+
throw new Error('Invalid CLI learning run receipt.');
|
|
73
|
+
}
|
|
74
|
+
turn.receipt = receipt;
|
|
75
|
+
await writePrivateJson(path, turn);
|
|
76
|
+
}
|
|
77
|
+
async function deliver(dataDir, connection, path, turn, fetcher) {
|
|
78
|
+
if (turn.delivered || !turn.completion || !turn.events)
|
|
79
|
+
return;
|
|
80
|
+
await begin(dataDir, connection, path, turn, fetcher);
|
|
81
|
+
const receipt = turn.receipt;
|
|
82
|
+
const batches = [];
|
|
83
|
+
let batch = [], bytes = 0;
|
|
84
|
+
for (const event of turn.events) {
|
|
85
|
+
const size = Buffer.byteLength(JSON.stringify(event));
|
|
86
|
+
if (batch.length && (batch.length >= 100 || bytes + size > 200_000)) {
|
|
87
|
+
batches.push(batch);
|
|
88
|
+
batch = [];
|
|
89
|
+
bytes = 0;
|
|
90
|
+
}
|
|
91
|
+
batch.push(event);
|
|
92
|
+
bytes += size;
|
|
93
|
+
}
|
|
94
|
+
if (batch.length)
|
|
95
|
+
batches.push(batch);
|
|
96
|
+
for (let index = turn.sentBatches ?? 0; index < batches.length; index++) {
|
|
97
|
+
const sequence = index + 1;
|
|
98
|
+
await post(dataDir, connection, `/cli-learning/runs/${encodeURIComponent(receipt.run_id)}/events`, receipt.token, { sequence, events: batches[index] }, `${receipt.run_id}:events:${sequence}`, fetcher);
|
|
99
|
+
turn.sentBatches = sequence;
|
|
100
|
+
await writePrivateJson(path, turn);
|
|
101
|
+
}
|
|
102
|
+
await post(dataDir, connection, `/cli-learning/runs/${encodeURIComponent(receipt.run_id)}/complete`, receipt.token, turn.completion, `${receipt.run_id}:complete`, fetcher);
|
|
103
|
+
turn.delivered = true;
|
|
104
|
+
delete turn.failure;
|
|
105
|
+
await writePrivateJson(path, turn);
|
|
106
|
+
}
|
|
107
|
+
async function locked(directory, task, processed) {
|
|
108
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
109
|
+
const holdPath = join(directory, '.lock');
|
|
110
|
+
// Recovery must prove the old owner is gone and still owns the lock being
|
|
111
|
+
// removed. A PID-only or incomplete legacy lock stays pending for explicit
|
|
112
|
+
// recovery; its age cannot authorize concurrent journal writers.
|
|
113
|
+
const token = await takeHold(directory, { holdPath, timeoutMs: Infinity, recoverUnknownOwner: false });
|
|
114
|
+
if (!token)
|
|
115
|
+
return undefined;
|
|
116
|
+
try {
|
|
117
|
+
const result = await task();
|
|
118
|
+
await processed?.();
|
|
119
|
+
return result;
|
|
120
|
+
}
|
|
121
|
+
finally {
|
|
122
|
+
await releaseHold(directory, token, { holdPath });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
async function hasPendingSubmit(root, sessionId, turnId, priorTo) {
|
|
126
|
+
const directory = join(root, 'pending');
|
|
127
|
+
if (turnId) {
|
|
128
|
+
const path = join(directory, `${stateHash(JSON.stringify([sessionId, turnId, 'UserPromptSubmit']))}.json`);
|
|
129
|
+
return Boolean(await readPrivateJson(path));
|
|
130
|
+
}
|
|
131
|
+
const names = (await readdir(directory).catch(() => [])).filter(name => /^[a-f0-9]{64}\.json$/.test(name));
|
|
132
|
+
// Read the whole pending index: a large queue of SessionEnd receipts alone
|
|
133
|
+
// must not make each one defer forever. Retry dispatch remains bounded.
|
|
134
|
+
for (const name of names) {
|
|
135
|
+
const pending = await readPrivateJson(join(directory, name));
|
|
136
|
+
if (pending?.input.hook_event_name !== 'UserPromptSubmit' || pending.input.session_id !== sessionId)
|
|
137
|
+
continue;
|
|
138
|
+
if (!priorTo)
|
|
139
|
+
return true;
|
|
140
|
+
if ((pending.input.turn_id ?? pending.input.prompt_id) === priorTo.turnId)
|
|
141
|
+
continue;
|
|
142
|
+
const receivedAt = receiptTime(pending.createdAt);
|
|
143
|
+
// A possibly earlier submit has not yet contributed its dialogue. Neither a
|
|
144
|
+
// tied timestamp nor a legacy receipt with no time proves it was later.
|
|
145
|
+
if (receivedAt === undefined || priorTo.receivedAt === undefined || receivedAt <= priorTo.receivedAt)
|
|
146
|
+
return true;
|
|
147
|
+
}
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
const historyLimit = (history) => {
|
|
151
|
+
const out = [];
|
|
152
|
+
let bytes = 0;
|
|
153
|
+
for (const message of history.slice().reverse()) {
|
|
154
|
+
bytes += Buffer.byteLength(message.text);
|
|
155
|
+
if (bytes > 64 * 1024 || out.length >= 100)
|
|
156
|
+
break;
|
|
157
|
+
out.unshift(message);
|
|
158
|
+
}
|
|
159
|
+
return { history: out, truncated: out.length !== history.length };
|
|
160
|
+
};
|
|
161
|
+
async function inProject(runtime, project, cwd) {
|
|
162
|
+
if (cwd !== project && !cwd.startsWith(project + sep))
|
|
163
|
+
return false;
|
|
164
|
+
if (runtime === 'codex' && cwd !== project) {
|
|
165
|
+
// Codex shares hook declarations across linked worktrees. A nested worktree must not also
|
|
166
|
+
// be captured by its main checkout's handler, even though it is inside that directory.
|
|
167
|
+
const [enrolled, source] = await Promise.all([codexHookLocation(project), codexHookLocation(cwd)]);
|
|
168
|
+
if (enrolled.checkoutRoot && source.checkoutRoot && enrolled.checkoutRoot !== source.checkoutRoot)
|
|
169
|
+
return false;
|
|
170
|
+
}
|
|
171
|
+
return true;
|
|
172
|
+
}
|
|
173
|
+
/** Fail-open hook entrypoint. It never starts/resumes the user's CLI or changes its tools, permissions or policy. */
|
|
174
|
+
export async function runCliLearningHook(options, input, dependencies = {}) {
|
|
175
|
+
const env = dependencies.env ?? process.env;
|
|
176
|
+
if (env.AGENTRUN_CLI_LEARNING_CHILD === '1')
|
|
177
|
+
return;
|
|
178
|
+
const hook = normalizeHookInput(options.runtime, input);
|
|
179
|
+
if (!hook)
|
|
180
|
+
return;
|
|
181
|
+
const project = await realpath(options.project), cwd = await realpath(hook.cwd);
|
|
182
|
+
if (!await inProject(options.runtime, project, cwd))
|
|
183
|
+
return;
|
|
184
|
+
options = { ...options, project };
|
|
185
|
+
const connection = await readConnection(options.dataDir, options.runtime, project);
|
|
186
|
+
if (!connection || connection.revocation_pending)
|
|
187
|
+
return;
|
|
188
|
+
baseUrl(connection);
|
|
189
|
+
// A CLI may still hold its old hook command after reconnecting elsewhere. Refuse that
|
|
190
|
+
// destination mismatch before saving anything that a later retry could deliver.
|
|
191
|
+
if (options.url && new URL(options.url).origin !== baseUrl(connection).origin)
|
|
192
|
+
return;
|
|
193
|
+
const scope = checkScope(connection, dependencies.connectionScope);
|
|
194
|
+
const secrets = runnerSecrets(env, [connection.token]);
|
|
195
|
+
const redact = (text) => redactSecrets(text, secrets, CLI_POLICY_BYTES);
|
|
196
|
+
const path = join(rootOf(options, connection), 'pending', `${stateHash(JSON.stringify([hook.sessionId, hook.turnId, hook.event]))}.json`);
|
|
197
|
+
let pending = await readPrivateJson(path);
|
|
198
|
+
if (!pending) {
|
|
199
|
+
const redacted = [hook.prompt, hook.answer, hook.model].some(value => value !== undefined && redact(value) !== value);
|
|
200
|
+
const prompt = hook.prompt === undefined ? undefined : boundCaptureText(redact(hook.prompt));
|
|
201
|
+
const answer = hook.answer === undefined ? undefined : boundCaptureText(redact(hook.answer));
|
|
202
|
+
pending = { version: 1, createdAt: Date.now(), redacted, truncated: prompt?.truncated || answer?.truncated,
|
|
203
|
+
...(answer?.truncated && hook.answer && redact(hook.answer) === hook.answer ? { answerDigest: stateHash(hook.answer.trim()) } : {}), input: {
|
|
204
|
+
hook_event_name: hook.event, session_id: hook.sessionId, cwd,
|
|
205
|
+
...(hook.turnId ? { [options.runtime === 'codex' ? 'turn_id' : 'prompt_id']: hook.turnId } : {}),
|
|
206
|
+
...(prompt ? { prompt: prompt.text } : {}),
|
|
207
|
+
...(answer ? { last_assistant_message: answer.text } : {}),
|
|
208
|
+
...(hook.transcriptPath ? { transcript_path: hook.transcriptPath } : {}),
|
|
209
|
+
...(hook.model ? { model: redact(hook.model) } : {}), stop_hook_active: hook.stopHookActive,
|
|
210
|
+
}, ...(hook.event === 'UserPromptSubmit' ? { cursor: await captureTranscriptCursor(hook.transcriptPath, { runtime: options.runtime, sessionId: hook.sessionId, turnId: hook.turnId }) } : {}) };
|
|
211
|
+
await writePrivateJson(path, pending);
|
|
212
|
+
}
|
|
213
|
+
return processCliLearningHook(options, pending.input, { ...dependencies, cursor: pending.cursor, sourceRedacted: pending.redacted, sourceTruncated: pending.truncated, answerDigest: pending.answerDigest, receivedAt: pending.createdAt, connectionScope: scope, processed: () => unlink(path).catch(() => { }) });
|
|
214
|
+
}
|
|
215
|
+
async function processCliLearningHook(options, input, dependencies) {
|
|
216
|
+
const env = dependencies.env ?? process.env;
|
|
217
|
+
if (env.AGENTRUN_CLI_LEARNING_CHILD === '1')
|
|
218
|
+
return;
|
|
219
|
+
const hook = normalizeHookInput(options.runtime, input);
|
|
220
|
+
if (!hook)
|
|
221
|
+
return;
|
|
222
|
+
const project = await realpath(options.project);
|
|
223
|
+
const cwd = await realpath(hook.cwd);
|
|
224
|
+
if (!await inProject(options.runtime, project, cwd))
|
|
225
|
+
return;
|
|
226
|
+
options = { ...options, project };
|
|
227
|
+
const connection = await readConnection(options.dataDir, options.runtime, project);
|
|
228
|
+
if (!connection || connection.revocation_pending)
|
|
229
|
+
return;
|
|
230
|
+
baseUrl(connection);
|
|
231
|
+
checkScope(connection, dependencies.connectionScope);
|
|
232
|
+
if (options.url && new URL(options.url).origin !== baseUrl(connection).origin)
|
|
233
|
+
return;
|
|
234
|
+
const fetcher = dependencies.fetch ?? fetch;
|
|
235
|
+
const secrets = runnerSecrets(env, [connection.token]);
|
|
236
|
+
const redact = (text) => redactSecrets(text, secrets, CLI_POLICY_BYTES);
|
|
237
|
+
const root = rootOf(options, connection);
|
|
238
|
+
const directory = join(root, stateHash(hook.sessionId));
|
|
239
|
+
const receivedAt = receiptTime(dependencies.receivedAt);
|
|
240
|
+
let deferred = false;
|
|
241
|
+
return locked(directory, async () => {
|
|
242
|
+
const sessionPath = join(directory, 'session.json');
|
|
243
|
+
const session = await readPrivateJson(sessionPath) ?? { active: [], history: [], completed: [] };
|
|
244
|
+
// Current evidence is persisted before any network work. Old receipts are drained by `learning retry`,
|
|
245
|
+
// never allowed to consume a new prompt's hook deadline while AgentRun is unavailable.
|
|
246
|
+
if (hook.event === 'SessionEnd') {
|
|
247
|
+
if (await hasPendingSubmit(root, hook.sessionId)) {
|
|
248
|
+
deferred = true;
|
|
249
|
+
return;
|
|
250
|
+
}
|
|
251
|
+
for (const key of session.active) {
|
|
252
|
+
const path = turnFile(directory, key), previous = await readPrivateJson(path);
|
|
253
|
+
if (previous && !previous.completion && precedes(previous, receivedAt))
|
|
254
|
+
await finish(previous, path, { ...hook, event: 'Interrupt', turnId: previous.start.turn_id }, session, false);
|
|
255
|
+
}
|
|
256
|
+
await writePrivateJson(sessionPath, session);
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
const key = stateHash(JSON.stringify([options.runtime, project, hook.sessionId, hook.turnId]));
|
|
260
|
+
const path = turnFile(directory, key);
|
|
261
|
+
let turn = await readPrivateJson(path);
|
|
262
|
+
if (turn && turn.connectionId === connection.connection_id && !turn.delivered && !session.active.includes(key)) {
|
|
263
|
+
// A process can die between the durable turn write and its session index write.
|
|
264
|
+
// Replaying the pending source event repairs that index without registering a new run.
|
|
265
|
+
session.active.push(key);
|
|
266
|
+
await writePrivateJson(sessionPath, session);
|
|
267
|
+
}
|
|
268
|
+
if (hook.event !== 'UserPromptSubmit' && !turn) {
|
|
269
|
+
// Lock contention can leave the preceding submit queued but not indexed yet. An
|
|
270
|
+
// unrelated pre-enrollment terminal has no queued submit and is safe to acknowledge.
|
|
271
|
+
deferred = await hasPendingSubmit(root, hook.sessionId, hook.turnId);
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
274
|
+
if (hook.event === 'UserPromptSubmit') {
|
|
275
|
+
if (!turn) {
|
|
276
|
+
// Only a later source receipt ends a prior window lacking Stop. Replay order
|
|
277
|
+
// is not source order: an older queued submit must leave newer windows open.
|
|
278
|
+
for (const active of session.active) {
|
|
279
|
+
const oldPath = turnFile(directory, active), previous = await readPrivateJson(oldPath);
|
|
280
|
+
if (previous && !previous.completion && precedes(previous, receivedAt))
|
|
281
|
+
await finish(previous, oldPath, { ...hook, event: 'Interrupt', turnId: previous.start.turn_id, answer: undefined }, session, false);
|
|
282
|
+
}
|
|
283
|
+
const cursor = dependencies.cursor !== undefined ? dependencies.cursor : await captureTranscriptCursor(hook.transcriptPath, { runtime: options.runtime, sessionId: hook.sessionId, turnId: hook.turnId });
|
|
284
|
+
const historyThrough = receiptTime(session.historyThrough);
|
|
285
|
+
const priorUnordered = (session.history.length > 0 && (session.historyUnordered || historyThrough === undefined || receivedAt === undefined || historyThrough >= receivedAt))
|
|
286
|
+
|| await hasPendingSubmit(root, hook.sessionId, undefined, { turnId: hook.turnId, receivedAt });
|
|
287
|
+
const submittedInput = boundCaptureText(redact(hook.prompt));
|
|
288
|
+
turn = {
|
|
289
|
+
version: 1, key, connectionId: connection.connection_id, createdAt: new Date().toISOString(), submittedAt: receivedAt, cursor,
|
|
290
|
+
start: { session_id: hook.sessionId, turn_id: hook.turnId, input: submittedInput.text,
|
|
291
|
+
instructions: 'Source policy capture did not finish; automatic promotion is disabled.', policy_complete: false,
|
|
292
|
+
...(hook.model ? { model: redact(hook.model) } : {}) }, prior: priorUnordered ? [] : session.history, priorUnordered, priorTruncated: session.historyTruncated, priorWithheld: session.historyWithheld, sourceRedacted: dependencies.sourceRedacted, sourceTruncated: dependencies.sourceTruncated || submittedInput.truncated,
|
|
293
|
+
};
|
|
294
|
+
await writePrivateJson(path, turn);
|
|
295
|
+
session.active.push(key);
|
|
296
|
+
await writePrivateJson(sessionPath, session);
|
|
297
|
+
let snapshot;
|
|
298
|
+
try {
|
|
299
|
+
snapshot = await (dependencies.snapshot ?? captureSourcePolicy)({ runtime: options.runtime, project: cwd, cursor, env, redact, sessionId: hook.sessionId, cachePath: join(directory, 'policy.json') });
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
snapshot = { text: '', files: [], truncated: false, incomplete: 'The source standing policy could not be captured.' };
|
|
303
|
+
}
|
|
304
|
+
const policyText = `${snapshot.text}${snapshot.incomplete ? `\n[Incomplete source policy: ${snapshot.incomplete}]` : ''}`;
|
|
305
|
+
const instructions = redact(policyText);
|
|
306
|
+
turn.sourceStanding = snapshot.sourceStanding;
|
|
307
|
+
turn.policyRecoveryAllowed = !snapshot.truncated && instructions === policyText
|
|
308
|
+
&& (!snapshot.incomplete || snapshot.incomplete === CLAUDE_SNAPSHOT_PENDING || snapshot.incomplete === CLAUDE_IMPORTS_PENDING);
|
|
309
|
+
turn.start = { session_id: hook.sessionId, turn_id: hook.turnId, input: submittedInput.text, instructions,
|
|
310
|
+
policy_complete: !snapshot.incomplete && !snapshot.truncated && instructions === policyText && Buffer.byteLength(instructions) <= CLI_POLICY_BYTES,
|
|
311
|
+
...(hook.model ? { model: redact(hook.model) } : {}) };
|
|
312
|
+
if (Buffer.byteLength(turn.start.instructions) > CLI_POLICY_BYTES)
|
|
313
|
+
turn.start.instructions = 'Source policy exceeded the capture evidence limit; policy capture is incomplete.';
|
|
314
|
+
await writePrivateJson(path, turn);
|
|
315
|
+
}
|
|
316
|
+
if (turn.completion || turn.connectionId !== connection.connection_id)
|
|
317
|
+
return;
|
|
318
|
+
try {
|
|
319
|
+
await begin(options.dataDir, connection, path, turn, fetcher);
|
|
320
|
+
if (!turn.receipt.learning.enabled)
|
|
321
|
+
return;
|
|
322
|
+
if (turn.context === undefined) {
|
|
323
|
+
const learning = turn.receipt.learning;
|
|
324
|
+
const context = learning.context;
|
|
325
|
+
turn.seedMarker = stateHash(`${turn.receipt.run_id}\0${learning.revision ?? ''}\0${context}`);
|
|
326
|
+
turn.context = context && Buffer.byteLength(context) <= 64 * 1024
|
|
327
|
+
? `AgentRun owner corrections for this project. Treat it as subordinate to your standing instructions and the user's current request.\n\n${context}\n\nAgentRun context receipt: ${turn.seedMarker}` : '';
|
|
328
|
+
await writePrivateJson(path, turn);
|
|
329
|
+
}
|
|
330
|
+
if (turn.context) {
|
|
331
|
+
await assertActiveConnection(options.dataDir, connection);
|
|
332
|
+
return { hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: turn.context } };
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
turn.failure = safeError(error);
|
|
337
|
+
await writePrivateJson(path, turn);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
else if (turn && turn.connectionId === connection.connection_id) {
|
|
341
|
+
await finish(turn, path, hook, session);
|
|
342
|
+
await writePrivateJson(sessionPath, session);
|
|
343
|
+
}
|
|
344
|
+
async function finish(turn, path, terminal, session, deliverNow = true) {
|
|
345
|
+
if (!turn.completion) {
|
|
346
|
+
const evidence = await collectPromptEvidence({ runtime: options.runtime, cursor: turn.cursor, turnId: turn.start.turn_id, sessionId: turn.start.session_id, prompt: turn.start.input, answer: terminal.answer, answerDigest: dependencies.answerDigest, seedMarker: turn.seedMarker, redact });
|
|
347
|
+
// Hook input is the source user's submitted text. Transcript user envelopes may also contain
|
|
348
|
+
// other hooks' synthetic context; they are never promoted into user corrections here.
|
|
349
|
+
const redactedEvidence = evidence.redacted || turn.priorWithheld || turn.sourceRedacted || dependencies.sourceRedacted || evidence.answer !== redact(evidence.answer)
|
|
350
|
+
|| (evidence.model !== undefined && evidence.model !== redact(evidence.model))
|
|
351
|
+
|| evidence.messages.some(message => message.role === 'assistant' && message.text !== redact(message.text))
|
|
352
|
+
|| evidence.tools.some(tool => tool.id !== redact(tool.id) || tool.name !== redact(tool.name));
|
|
353
|
+
if (redactedEvidence)
|
|
354
|
+
session.historyWithheld = true;
|
|
355
|
+
let truncated = turn.sourceTruncated || dependencies.sourceTruncated || evidence.truncated;
|
|
356
|
+
const capture = (text) => {
|
|
357
|
+
const bounded = boundCaptureText(redact(text));
|
|
358
|
+
truncated ||= bounded.truncated;
|
|
359
|
+
return bounded.text;
|
|
360
|
+
};
|
|
361
|
+
const dialogue = evidence.messages.filter(message => message.role === 'assistant').map(message => ({ ...message, text: capture(message.text) }));
|
|
362
|
+
const initial = { role: 'user', text: capture(turn.start.input) };
|
|
363
|
+
if (!dialogue.some(message => message.role === 'user' && message.text === initial.text))
|
|
364
|
+
dialogue.unshift(initial);
|
|
365
|
+
const answer = capture(evidence.answer);
|
|
366
|
+
if (answer && !dialogue.some(message => message.role === 'assistant' && message.text === answer))
|
|
367
|
+
dialogue.push({ role: 'assistant', text: answer });
|
|
368
|
+
turn.dialogue = dialogue;
|
|
369
|
+
turn.events = [
|
|
370
|
+
...turn.prior.map(message => ({ type: 'message', ...message, text: capture(message.text) })),
|
|
371
|
+
...dialogue.map(message => ({ type: 'message', ...message })),
|
|
372
|
+
...evidence.tools.map(tool => ({ type: 'tool', ...tool, id: redact(tool.id), name: redact(tool.name) })),
|
|
373
|
+
];
|
|
374
|
+
turn.sourceTruncated ||= truncated;
|
|
375
|
+
turn.completion = {
|
|
376
|
+
status: terminal.event === 'Stop' ? 'completed' : terminal.event === 'StopFailure' ? 'failed' : 'cancelled',
|
|
377
|
+
answer, evidence_complete: terminal.event === 'Stop' && evidence.complete && Boolean(terminal.answer) && !terminal.stopHookActive && !truncated && !turn.priorTruncated && !turn.priorUnordered && !redactedEvidence,
|
|
378
|
+
seed_observed: evidence.seedObserved,
|
|
379
|
+
...(evidence.seedObserved && turn.receipt?.learning.revision ? { seed_revision: turn.receipt.learning.revision } : {}),
|
|
380
|
+
...(redactedEvidence ? { error: 'Source dialogue or tool metadata contains withheld or redacted text; automatic promotion is disabled.' } : turn.priorUnordered ? { error: 'Earlier post-enrollment dialogue order could not be verified; automatic promotion is disabled.' } : truncated ? { error: 'Source dialogue exceeded the capture limit; retained text is truncated.' } : turn.priorTruncated ? { error: 'Earlier post-enrollment dialogue exceeded the capture limit; automatic promotion is disabled for this session.' } : evidence.reason ? { error: evidence.reason } : {}),
|
|
381
|
+
...(terminal.model ?? evidence.model ? { model: redact((terminal.model ?? evidence.model)) } : {}), session_id: turn.start.session_id,
|
|
382
|
+
...(evidence.usage ? { usage: evidence.usage } : {}),
|
|
383
|
+
};
|
|
384
|
+
if (options.runtime === 'claude-code') {
|
|
385
|
+
// Claude renders its real system snapshot after UserPromptSubmit. Pin it at completion,
|
|
386
|
+
// including inherited snapshots only when the native main chain still belongs to this prompt.
|
|
387
|
+
let snapshot;
|
|
388
|
+
try {
|
|
389
|
+
snapshot = await (dependencies.snapshot ?? captureSourcePolicy)({ runtime: options.runtime, project: cwd,
|
|
390
|
+
cursor: turn.cursor?.absent ? evidence.verifiedCursor ?? null : await captureTranscriptCursor(turn.cursor?.path), env, redact, sessionId: turn.start.session_id,
|
|
391
|
+
turnId: turn.start.turn_id, cachePath: join(directory, 'policy.json'), pinnedStanding: turn.sourceStanding });
|
|
392
|
+
}
|
|
393
|
+
catch {
|
|
394
|
+
snapshot = { text: '', files: [], truncated: false, incomplete: 'The completed source policy could not be captured.' };
|
|
395
|
+
}
|
|
396
|
+
const instructions = redact(snapshot.text);
|
|
397
|
+
turn.completion.source_policy = { instructions: Buffer.byteLength(instructions) <= CLI_POLICY_BYTES ? instructions : '',
|
|
398
|
+
complete: Boolean(turn.policyRecoveryAllowed) && !snapshot.incomplete && !snapshot.truncated
|
|
399
|
+
&& instructions === snapshot.text && Buffer.byteLength(instructions) <= CLI_POLICY_BYTES };
|
|
400
|
+
}
|
|
401
|
+
turn.completedAt = receivedAt;
|
|
402
|
+
await writePrivateJson(path, turn);
|
|
403
|
+
}
|
|
404
|
+
if (!session.completed.includes(turn.key)) {
|
|
405
|
+
const submittedAt = receiptTime(turn.submittedAt), completedAt = receiptTime(turn.completedAt), historyThrough = receiptTime(session.historyThrough);
|
|
406
|
+
// Keep the private history, but never serve out-of-order completions as a
|
|
407
|
+
// verified sequence of prior dialogue. Legacy history has no order proof.
|
|
408
|
+
session.historyUnordered ||= submittedAt === undefined || completedAt === undefined || completedAt < submittedAt
|
|
409
|
+
|| (session.history.length > 0 && (historyThrough === undefined || submittedAt <= historyThrough));
|
|
410
|
+
if (completedAt !== undefined)
|
|
411
|
+
session.historyThrough = Math.max(historyThrough ?? completedAt, completedAt);
|
|
412
|
+
const kept = historyLimit([...session.history, ...(turn.dialogue ?? [])]);
|
|
413
|
+
session.history = kept.history;
|
|
414
|
+
session.historyTruncated ||= kept.truncated || turn.sourceTruncated;
|
|
415
|
+
session.completed.push(turn.key);
|
|
416
|
+
}
|
|
417
|
+
await writePrivateJson(sessionPath, session);
|
|
418
|
+
if (!deliverNow)
|
|
419
|
+
return;
|
|
420
|
+
try {
|
|
421
|
+
await deliver(options.dataDir, connection, path, turn, fetcher);
|
|
422
|
+
}
|
|
423
|
+
catch (error) {
|
|
424
|
+
turn.failure = safeError(error);
|
|
425
|
+
await writePrivateJson(path, turn);
|
|
426
|
+
}
|
|
427
|
+
if (turn.delivered)
|
|
428
|
+
session.active = session.active.filter(key => key !== turn.key);
|
|
429
|
+
}
|
|
430
|
+
}, async () => { if (!deferred)
|
|
431
|
+
await dependencies.processed?.(); });
|
|
432
|
+
}
|
|
433
|
+
/** Old or unbound receipts remain untouched. Read only their indexes to make withheld recovery observable. */
|
|
434
|
+
async function blockedJournals(options, connection) {
|
|
435
|
+
const parent = journalParent(options.dataDir, options.runtime, options.project);
|
|
436
|
+
const hasPending = async (root) => {
|
|
437
|
+
const pending = await readdir(join(root, 'pending')).catch(() => []);
|
|
438
|
+
if (pending.some(name => /^[a-f0-9]{64}\.json$/.test(name)))
|
|
439
|
+
return true;
|
|
440
|
+
const entries = await readdir(root, { withFileTypes: true }).catch(() => []);
|
|
441
|
+
for (const entry of entries) {
|
|
442
|
+
if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name))
|
|
443
|
+
continue;
|
|
444
|
+
try {
|
|
445
|
+
const session = await readPrivateJson(join(root, entry.name, 'session.json'));
|
|
446
|
+
if (session?.active?.length)
|
|
447
|
+
return true;
|
|
448
|
+
}
|
|
449
|
+
catch {
|
|
450
|
+
return true;
|
|
451
|
+
} // An unreadable old journal needs review too; never echo its text.
|
|
452
|
+
}
|
|
453
|
+
return false;
|
|
454
|
+
};
|
|
455
|
+
let blocked = Number(await hasPending(parent)); // Before scope pinning, this was the journal itself.
|
|
456
|
+
const epochs = await readdir(join(parent, 'epochs'), { withFileTypes: true }).catch(() => []);
|
|
457
|
+
for (const entry of epochs) {
|
|
458
|
+
if (entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name) && entry.name !== connectionScope(connection)
|
|
459
|
+
&& await hasPending(join(parent, 'epochs', entry.name)))
|
|
460
|
+
blocked++;
|
|
461
|
+
}
|
|
462
|
+
return blocked;
|
|
463
|
+
}
|
|
464
|
+
/** Retry terminal receipts only: no native task or model call is dispatched by this source-side drain. */
|
|
465
|
+
export async function flushCliLearning(options, dependencies = {}) {
|
|
466
|
+
const connection = await readConnection(options.dataDir, options.runtime, options.project);
|
|
467
|
+
const counts = { delivered: 0, pending: 0, blocked_journals: 0 };
|
|
468
|
+
if (!connection)
|
|
469
|
+
return counts;
|
|
470
|
+
if (connection.revocation_pending)
|
|
471
|
+
throw new Error('Capture is disabled while server revocation is pending. Run learning disconnect when the server is available.');
|
|
472
|
+
baseUrl(connection);
|
|
473
|
+
const scope = connectionScope(connection);
|
|
474
|
+
counts.blocked_journals = await blockedJournals(options, connection);
|
|
475
|
+
const root = rootOf(options, connection);
|
|
476
|
+
const cursorPath = join(root, 'retry.json');
|
|
477
|
+
const cursor = await readPrivateJson(cursorPath) ?? {};
|
|
478
|
+
const pendingDirectory = join(root, 'pending');
|
|
479
|
+
const pending = await readdir(pendingDirectory).catch(() => []);
|
|
480
|
+
const selected = retryBatch(pending.filter(name => /^[a-f0-9]{64}\.json$/.test(name)), cursor.pendingAfter);
|
|
481
|
+
if (selected.length) {
|
|
482
|
+
cursor.pendingAfter = selected.at(-1);
|
|
483
|
+
await writePrivateJson(cursorPath, cursor);
|
|
484
|
+
}
|
|
485
|
+
const queued = [];
|
|
486
|
+
for (const name of selected) {
|
|
487
|
+
const receipt = await readPrivateJson(join(pendingDirectory, name));
|
|
488
|
+
if (receipt)
|
|
489
|
+
queued.push(receipt);
|
|
490
|
+
}
|
|
491
|
+
queued.sort((a, b) => a.createdAt - b.createdAt || Number(b.input.hook_event_name === 'UserPromptSubmit') - Number(a.input.hook_event_name === 'UserPromptSubmit'));
|
|
492
|
+
for (const receipt of queued)
|
|
493
|
+
await runCliLearningHook(options, receipt.input, { ...dependencies, connectionScope: scope });
|
|
494
|
+
const directories = (await readdir(root, { withFileTypes: true }).catch(() => []))
|
|
495
|
+
.filter(entry => entry.isDirectory() && /^[a-f0-9]{64}$/.test(entry.name));
|
|
496
|
+
const sessions = retryBatch(directories.map(entry => entry.name), cursor.sessionAfter);
|
|
497
|
+
if (sessions.length) {
|
|
498
|
+
cursor.sessionAfter = sessions.at(-1);
|
|
499
|
+
await writePrivateJson(cursorPath, cursor);
|
|
500
|
+
}
|
|
501
|
+
for (const name of sessions) {
|
|
502
|
+
const directory = join(root, name);
|
|
503
|
+
await locked(directory, async () => {
|
|
504
|
+
const session = await readPrivateJson(join(directory, 'session.json'));
|
|
505
|
+
if (!session)
|
|
506
|
+
return;
|
|
507
|
+
const keys = retryBatch(session.active, session.retryAfter);
|
|
508
|
+
if (keys.length) {
|
|
509
|
+
session.retryAfter = keys.at(-1);
|
|
510
|
+
await writePrivateJson(join(directory, 'session.json'), session);
|
|
511
|
+
}
|
|
512
|
+
for (const key of keys) {
|
|
513
|
+
const path = turnFile(directory, key), turn = await readPrivateJson(path);
|
|
514
|
+
if (!turn?.completion || turn.connectionId !== connection.connection_id)
|
|
515
|
+
continue;
|
|
516
|
+
try {
|
|
517
|
+
await deliver(options.dataDir, connection, path, turn, dependencies.fetch ?? fetch);
|
|
518
|
+
}
|
|
519
|
+
catch (error) {
|
|
520
|
+
turn.failure = safeError(error);
|
|
521
|
+
await writePrivateJson(path, turn);
|
|
522
|
+
}
|
|
523
|
+
if (turn.delivered) {
|
|
524
|
+
counts.delivered++;
|
|
525
|
+
session.active = session.active.filter(active => active !== key);
|
|
526
|
+
}
|
|
527
|
+
// Pending status is read from the durable queue after the drain, including busy locks.
|
|
528
|
+
}
|
|
529
|
+
await writePrivateJson(join(directory, 'session.json'), session);
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
const remaining = await readdir(pendingDirectory).catch(() => []);
|
|
533
|
+
counts.pending = remaining.filter(name => /^[a-f0-9]{64}\.json$/.test(name)).length;
|
|
534
|
+
for (const entry of directories) {
|
|
535
|
+
const directory = join(root, entry.name);
|
|
536
|
+
const session = await readPrivateJson(join(directory, 'session.json'));
|
|
537
|
+
for (const key of session?.active ?? []) {
|
|
538
|
+
const turn = await readPrivateJson(turnFile(directory, key));
|
|
539
|
+
if (turn?.completion && !turn.delivered && turn.connectionId === connection.connection_id)
|
|
540
|
+
counts.pending++;
|
|
541
|
+
}
|
|
542
|
+
}
|
|
543
|
+
return counts;
|
|
544
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export type CliLearningRuntime = 'codex' | 'claude-code';
|
|
2
|
+
export type CliLearningLocation = {
|
|
3
|
+
project: string;
|
|
4
|
+
runtime: CliLearningRuntime;
|
|
5
|
+
};
|
|
6
|
+
export type CliLearningInstallOptions = CliLearningLocation & {
|
|
7
|
+
dataDir: string;
|
|
8
|
+
url?: string;
|
|
9
|
+
/** Executable plus fixed arguments. Never shell source; every element is quoted separately. */
|
|
10
|
+
command?: string[];
|
|
11
|
+
};
|
|
12
|
+
export type CliLearningInstallStatus = {
|
|
13
|
+
runtime: CliLearningRuntime;
|
|
14
|
+
project: string;
|
|
15
|
+
configPath: string;
|
|
16
|
+
receiptPath: string;
|
|
17
|
+
state: 'not-installed' | 'configured' | 'partial' | 'migration-required';
|
|
18
|
+
configured: boolean;
|
|
19
|
+
activation: 'unverified';
|
|
20
|
+
events: {
|
|
21
|
+
event: string;
|
|
22
|
+
configured: boolean;
|
|
23
|
+
}[];
|
|
24
|
+
instructions: string[];
|
|
25
|
+
warnings: string[];
|
|
26
|
+
};
|
|
27
|
+
export declare function cliLearningUrl(value?: string): string;
|
|
28
|
+
/** Reads configuration evidence only: never claims the CLI has loaded or trusted a hook. */
|
|
29
|
+
export declare function statusCliLearning(options: CliLearningLocation): Promise<CliLearningInstallStatus>;
|
|
30
|
+
/** Additive, project-scoped install. The receipt owns exact handlers, not an entire settings file. */
|
|
31
|
+
export declare function installCliLearning(options: CliLearningInstallOptions): Promise<CliLearningInstallStatus>;
|
|
32
|
+
/** Removes only unchanged handlers recorded by this installer; never restores a stale whole-file backup. */
|
|
33
|
+
export declare function removeCliLearning(options: CliLearningLocation): Promise<CliLearningInstallStatus>;
|