@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,50 @@
1
+ import type { Runners } from "./store/store.js";
2
+ /** The hand-back window when none is asked, in minutes. */
3
+ export declare const CAPACITY_WINDOW_MINUTES = 15;
4
+ /** The longest window, in minutes: the hand-backs the store keeps (schema.ts HAND_BACKS_KEPT_MS). */
5
+ export declare const CAPACITY_WINDOW_MAX_MINUTES: number;
6
+ /** One live runner, as the capacity read shows it. */
7
+ export interface CapacityRunner {
8
+ /** The runner's name (--name, AGENTRUN_RUNNER_NAME, or its host and process). */
9
+ readonly id: string;
10
+ /** Its build's version; null for a runner of a build before this read. */
11
+ readonly version: string | null;
12
+ /** The most runs it holds at once (its loops); null when it did not say (a build before this read, or a runner that
13
+ * refused to claim). */
14
+ readonly slots: number | null;
15
+ /** The runs its live claims hold now. */
16
+ readonly executing: number;
17
+ /** Its slots less what it holds (never below 0), 0 for a runner that refused to claim, null with no slots said. A
18
+ * runner also claims by its host's memory (memory-claim.ts), so a free slot is the most it may take, not a promise. */
19
+ readonly free_slots: number | null;
20
+ /** It refused to claim any run (its run isolation refused): it takes none. Its words are in capabilities' runner_refused. */
21
+ readonly refused: boolean;
22
+ /** When it last said it was there (the deadlines' clock). */
23
+ readonly seen_at: string;
24
+ }
25
+ /** The capacity read's answer. */
26
+ export interface CapacityView {
27
+ /** When it was read (the deadlines' clock: the database's on Postgres). */
28
+ readonly at: string;
29
+ readonly runs: {
30
+ /** Runs waiting for a runner now: queued, handed back or with their claim run out (past any backoff), or parked with
31
+ * something to wake them; the backlog a scaler reads. */
32
+ readonly queued: number;
33
+ /** Runs a live claim holds now, on any runner. */
34
+ readonly executing: number;
35
+ };
36
+ /** The live runners, by name. */
37
+ readonly runners: readonly CapacityRunner[];
38
+ /** The free slots of every live runner that said its slots. */
39
+ readonly free_slots: number;
40
+ /** Runs given back still running (a drain, a loop that closed itself, a claim given back) within the window. */
41
+ readonly hand_backs: {
42
+ readonly window_minutes: number;
43
+ readonly count: number;
44
+ };
45
+ }
46
+ /** The `window` query parameter in minutes: CAPACITY_WINDOW_MINUTES when absent; a whole number from 1 to
47
+ * CAPACITY_WINDOW_MAX_MINUTES, else 400 bad_request. */
48
+ export declare function capacityWindowOf(url: URL): number;
49
+ /** The capacity read over `runners` (the store's), with hand-backs over the last `windowMinutes`. */
50
+ export declare function capacityOverStore(runners: Pick<Runners, "live" | "capacity">, windowMinutes: number, staleMs?: number): Promise<CapacityView>;
@@ -0,0 +1,49 @@
1
+ // GET /v2/capacity: what an operator, or an autoscaler, reads to size the runners. Read from the store alone, so a server
2
+ // with no runner beside it (--no-runner, the API-only profile) answers for every runner on its store: the runs waiting for
3
+ // a runner and the runs a claim holds, each live runner (its row seen within PRESENCE_STALE_MS) with its version, its
4
+ // slots and how many are free, and the hand-backs within a window. Counts, runner names and versions only: no run id,
5
+ // agent, prompt, address or customer's word. Behind the server's token, as every route but capabilities and health.
6
+ import { ApiError } from "./errors.js";
7
+ import { PRESENCE_STALE_MS } from "./runner/presence.js";
8
+ /** The hand-back window when none is asked, in minutes. */
9
+ export const CAPACITY_WINDOW_MINUTES = 15;
10
+ /** The longest window, in minutes: the hand-backs the store keeps (schema.ts HAND_BACKS_KEPT_MS). */
11
+ export const CAPACITY_WINDOW_MAX_MINUTES = 24 * 60;
12
+ /** The `window` query parameter in minutes: CAPACITY_WINDOW_MINUTES when absent; a whole number from 1 to
13
+ * CAPACITY_WINDOW_MAX_MINUTES, else 400 bad_request. */
14
+ export function capacityWindowOf(url) {
15
+ const text = url.searchParams.get("window");
16
+ if (text === null)
17
+ return CAPACITY_WINDOW_MINUTES;
18
+ const minutes = /^\d{1,5}$/.test(text) ? Number(text) : NaN;
19
+ if (!(minutes >= 1 && minutes <= CAPACITY_WINDOW_MAX_MINUTES))
20
+ throw new ApiError("bad_request", `window is a whole number of minutes from 1 to ${CAPACITY_WINDOW_MAX_MINUTES}, not ${JSON.stringify(text)}`);
21
+ return minutes;
22
+ }
23
+ /** The capacity read over `runners` (the store's), with hand-backs over the last `windowMinutes`. */
24
+ export async function capacityOverStore(runners, windowMinutes, staleMs = PRESENCE_STALE_MS) {
25
+ const [counts, live] = await Promise.all([runners.capacity(windowMinutes * 60_000), runners.live(staleMs)]);
26
+ const shown = live.map((row) => {
27
+ const executing = counts.held.get(row.runner) ?? 0;
28
+ const refused = row.refused !== null;
29
+ return {
30
+ id: row.runner,
31
+ version: row.version,
32
+ slots: row.slots,
33
+ executing,
34
+ free_slots: refused ? 0 : row.slots === null ? null : Math.max(0, row.slots - executing),
35
+ refused,
36
+ seen_at: new Date(row.seenAt).toISOString(),
37
+ };
38
+ });
39
+ let executing = 0;
40
+ for (const count of counts.held.values())
41
+ executing += count;
42
+ return {
43
+ at: new Date(counts.at).toISOString(),
44
+ runs: { queued: counts.queued, executing },
45
+ runners: shown,
46
+ free_slots: shown.reduce((sum, runner) => sum + (runner.free_slots ?? 0), 0),
47
+ hand_backs: { window_minutes: windowMinutes, count: counts.handBacks },
48
+ };
49
+ }
@@ -0,0 +1,41 @@
1
+ type Policy = {
2
+ text: string;
3
+ complete: boolean;
4
+ reason?: string;
5
+ };
6
+ type Blob = {
7
+ role: string;
8
+ text?: string;
9
+ complete: boolean;
10
+ reason?: string;
11
+ };
12
+ type Request = {
13
+ shapeHash: string;
14
+ refs: string[];
15
+ complete: boolean;
16
+ reason?: string;
17
+ };
18
+ export type ClaudeWireState = {
19
+ version: 1;
20
+ shapes: Record<string, Policy>;
21
+ blobs: Record<string, Blob>;
22
+ requests: Record<string, Request>;
23
+ current?: {
24
+ prompt: string;
25
+ text: string;
26
+ stableText?: string;
27
+ complete: boolean;
28
+ reason?: string;
29
+ };
30
+ /** Re-read ordinary source rows from this byte offset after restoring the JSON cache. */
31
+ replayFrom?: number;
32
+ reminders?: string[];
33
+ };
34
+ /** Keep native request policy only. User/assistant/tool blobs contribute roles and hashes,
35
+ * never conversation text, tool descriptions, arguments, credentials, or raw request bodies. */
36
+ export declare function updateClaudeWire(state: ClaudeWireState | undefined, row: unknown, options: {
37
+ promptId?: string;
38
+ redact: (text: string) => string;
39
+ recordOffset?: number;
40
+ }): ClaudeWireState;
41
+ export {};
@@ -0,0 +1,258 @@
1
+ import { createHash } from 'node:crypto';
2
+ const POLICY_BYTES = 256 * 1024, CACHE_BYTES = 4 * 1024 * 1024, MAX_REFS = 4096;
3
+ const object = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
4
+ const hash = (value) => typeof value === 'string' && /^[a-f0-9]{64}$/.test(value);
5
+ const requestId = (value) => typeof value === 'string' && /^[a-f0-9]{8}(?:-[a-f0-9]{4}){3}-[a-f0-9]{12}$/i.test(value);
6
+ const refused = (reason) => ({ text: '', complete: false, reason });
7
+ // Incremental digests contain no recoverable conversation text and are never serialized.
8
+ // On a cache reload the caller replays typed rows from replayFrom to hydrate this state.
9
+ const sourceRuns = new WeakMap();
10
+ function hashValue(value, write, depth = 0) {
11
+ if (depth > 64)
12
+ throw new Error('Native message nesting exceeds the hashing bound.');
13
+ if (typeof value === 'string') {
14
+ write('"');
15
+ for (let start = 0; start < value.length;) {
16
+ let end = Math.min(start + 65536, value.length);
17
+ if (end < value.length && value.charCodeAt(end - 1) >= 0xd800 && value.charCodeAt(end - 1) <= 0xdbff)
18
+ end--;
19
+ write(JSON.stringify(value.slice(start, end)).slice(1, -1));
20
+ start = end;
21
+ }
22
+ write('"');
23
+ return;
24
+ }
25
+ if (value === null || typeof value !== 'object') {
26
+ write(JSON.stringify(value) ?? 'null');
27
+ return;
28
+ }
29
+ if (Array.isArray(value)) {
30
+ write('[');
31
+ value.forEach((item, index) => { if (index)
32
+ write(','); hashValue(item, write, depth + 1); });
33
+ write(']');
34
+ return;
35
+ }
36
+ write('{');
37
+ let first = true;
38
+ for (const key of Object.keys(value).sort()) {
39
+ const item = value[key];
40
+ if (key === 'cache_control' || item === undefined)
41
+ continue;
42
+ if (!first)
43
+ write(',');
44
+ first = false;
45
+ write(JSON.stringify(key));
46
+ write(':');
47
+ hashValue(item, write, depth + 1);
48
+ }
49
+ write('}');
50
+ }
51
+ function sourceMessage(previous, next, row, offset) {
52
+ const message = row.message;
53
+ if (!object(message) || message.role !== row.type || message.content == null) {
54
+ sourceRuns.delete(next);
55
+ delete next.replayFrom;
56
+ return;
57
+ }
58
+ const role = message.role, messageId = typeof message.id === 'string' ? message.id : undefined;
59
+ const before = sourceRuns.get(previous);
60
+ if (offset !== undefined && before?.lastOffset !== undefined && offset <= before.lastOffset && offset !== previous.replayFrom)
61
+ return;
62
+ const restarting = offset !== undefined && offset === previous.replayFrom;
63
+ const same = !restarting && before?.role === role && (role === 'user' || (messageId !== undefined && messageId === before?.messageId));
64
+ const unprimed = !before && previous.replayFrom !== undefined && offset !== previous.replayFrom;
65
+ const run = same ? { ...before, value: before.value?.copy() } : {
66
+ role, ...(messageId ? { messageId } : {}), blocks: 0, bytes: 0,
67
+ ...(!unprimed ? { value: createHash('sha256').update('{"content":[') } : {}),
68
+ };
69
+ if (!same && !unprimed) {
70
+ if (offset !== undefined)
71
+ next.replayFrom = offset;
72
+ else
73
+ delete next.replayFrom;
74
+ }
75
+ run.lastOffset = offset;
76
+ sourceRuns.set(next, run);
77
+ if (!run.value)
78
+ return;
79
+ const blocks = typeof message.content === 'string' ? [{ type: 'text', text: message.content }]
80
+ : Array.isArray(message.content) ? message.content : [message.content];
81
+ try {
82
+ const write = (part) => {
83
+ run.bytes += Buffer.byteLength(part);
84
+ if (run.bytes > 64 * 1024 * 1024)
85
+ throw new Error('Native message hashing exceeds the byte bound.');
86
+ run.value.update(part);
87
+ };
88
+ for (const block of blocks) {
89
+ if (run.blocks++ > 100_000)
90
+ throw new Error('Native message hashing exceeds the block bound.');
91
+ if (run.blocks > 1)
92
+ write(',');
93
+ hashValue(block, write);
94
+ }
95
+ const digest = run.value.copy().update(`],"role":${JSON.stringify(role)}}`).digest('hex');
96
+ const known = next.blobs[digest];
97
+ put(next.blobs, digest, known && known.role !== role ? { role: 'unknown', complete: false, reason: 'A native transcript hash conflicts with its recorded role.' }
98
+ : { role, complete: true }, 8192);
99
+ }
100
+ catch {
101
+ delete run.value;
102
+ }
103
+ }
104
+ function policy(content, redact) {
105
+ const values = typeof content === 'string' ? [content] : Array.isArray(content)
106
+ && content.every(block => object(block) && block.type === 'text' && typeof block.text === 'string')
107
+ ? content.map(block => block.text) : undefined;
108
+ if (!values)
109
+ return refused('The native request contains unsupported system policy content.');
110
+ if (values.reduce((size, value) => size + Buffer.byteLength(value) + 2, 0) > POLICY_BYTES)
111
+ return refused('The native request policy exceeds the 256 KiB evidence limit.');
112
+ const original = values.join('\n\n');
113
+ let text;
114
+ try {
115
+ text = redact(original);
116
+ }
117
+ catch {
118
+ return refused('The native request policy could not be safely captured.');
119
+ }
120
+ if (typeof text !== 'string' || Buffer.byteLength(text) > POLICY_BYTES)
121
+ return refused('The native request policy exceeds the 256 KiB evidence limit.');
122
+ return { text, complete: text === original, ...(text !== original ? { reason: 'The native request policy contains withheld or redacted text.' } : {}) };
123
+ }
124
+ function put(map, key, value, limit) {
125
+ delete map[key];
126
+ map[key] = value;
127
+ while (Object.keys(map).length > limit)
128
+ delete map[Object.keys(map)[0]];
129
+ }
130
+ function bounded(state) {
131
+ // Eviction only removes reconstruction inputs. A later request referring to an evicted
132
+ // record becomes explicitly incomplete; the independently retained current snapshot stays pinned.
133
+ while (Buffer.byteLength(JSON.stringify(state)) > CACHE_BYTES) {
134
+ const map = Object.keys(state.requests).length ? state.requests : Object.keys(state.blobs).length ? state.blobs : state.shapes;
135
+ const key = Object.keys(map)[0];
136
+ if (!key) {
137
+ state.current = state.current ? { prompt: state.current.prompt, ...refused('The native request cache exceeds its evidence limit.') } : undefined;
138
+ break;
139
+ }
140
+ delete map[key];
141
+ }
142
+ return state;
143
+ }
144
+ /** Keep native request policy only. User/assistant/tool blobs contribute roles and hashes,
145
+ * never conversation text, tool descriptions, arguments, credentials, or raw request bodies. */
146
+ export function updateClaudeWire(state, row, options) {
147
+ const previous = state ?? { version: 1, shapes: {}, blobs: {}, requests: {} };
148
+ if (!object(row) || row.agentId || row.isSidechain || !['user', 'assistant', 'attachment', 'api-request-shape', 'api-request-blob', 'api-request'].includes(row.type))
149
+ return previous;
150
+ const next = { ...previous, shapes: { ...previous.shapes }, blobs: { ...previous.blobs }, requests: { ...previous.requests } };
151
+ const run = sourceRuns.get(previous);
152
+ if (run)
153
+ sourceRuns.set(next, run);
154
+ if (row.type === 'user' || row.type === 'assistant') {
155
+ sourceMessage(previous, next, row, Number.isSafeInteger(options.recordOffset) && options.recordOffset >= 0 ? options.recordOffset : undefined);
156
+ return bounded(next);
157
+ }
158
+ if (row.type === 'attachment') {
159
+ const attachment = row.attachment;
160
+ if (object(attachment) && attachment.type === 'total_tokens_reminder' && row.renderedRole === 'system'
161
+ && typeof attachment.text === 'string' && /^<total_tokens>(?:\d{1,20}|Infinite) tokens left<\/total_tokens>$/.test(attachment.text)
162
+ && Array.isArray(row.rendered) && row.rendered.length === 1
163
+ && row.rendered[0]?.content === `<system-reminder>\n${attachment.text}\n</system-reminder>`) {
164
+ next.reminders = [...(next.reminders ?? []).filter(text => text !== attachment.text), attachment.text].slice(-256);
165
+ }
166
+ return bounded(next);
167
+ }
168
+ if (row.type === 'api-request-shape') {
169
+ if (!hash(row.shapeHash))
170
+ return previous;
171
+ const captured = object(row.shape) ? policy(row.shape.system, options.redact) : refused('The native request shape has no captured system policy.');
172
+ const known = next.shapes[row.shapeHash];
173
+ put(next.shapes, row.shapeHash, known && JSON.stringify(known) !== JSON.stringify(captured)
174
+ ? refused('A native shape hash was reused for different policy.') : captured, 128);
175
+ return bounded(next);
176
+ }
177
+ if (row.type === 'api-request-blob') {
178
+ if (!hash(row.hash))
179
+ return previous;
180
+ const message = row.message;
181
+ const role = object(message) && typeof message.role === 'string' ? message.role : 'unknown';
182
+ const captured = ['system', 'developer'].includes(role)
183
+ ? { role, ...policy(message.content, options.redact) }
184
+ : ['user', 'assistant', 'tool'].includes(role) ? { role, complete: true }
185
+ : { role: 'unknown', complete: false, reason: 'A referenced native message has an unsupported role.' };
186
+ const known = next.blobs[row.hash];
187
+ put(next.blobs, row.hash, known && JSON.stringify(known) !== JSON.stringify(captured)
188
+ ? { role: 'unknown', complete: false, reason: 'A native message hash was reused for different policy.' } : captured, 8192);
189
+ return bounded(next);
190
+ }
191
+ const main = row.querySource === 'sdk' || (typeof row.querySource === 'string' && row.querySource.startsWith('repl_main_thread'));
192
+ const prompt = typeof options.promptId === 'string' && options.promptId.length > 0 && options.promptId.length <= 200 ? options.promptId : undefined;
193
+ const failCurrent = (reason) => { if (main)
194
+ next.current = prompt ? { prompt, ...refused(reason) } : undefined; };
195
+ if (!requestId(row.id) || !hash(row.shapeHash) || !Number.isSafeInteger(row.keep) || row.keep < 0 || row.keep > MAX_REFS
196
+ || !Array.isArray(row.tail) || row.tail.length > MAX_REFS || !row.tail.every(hash)) {
197
+ failCurrent('The native request has malformed or oversized reconstruction metadata.');
198
+ return bounded(next);
199
+ }
200
+ let reason;
201
+ const fail = (value) => { reason ??= value; };
202
+ let refs = [];
203
+ if (row.keep > 0) {
204
+ const base = requestId(row.base) ? next.requests[row.base] : undefined;
205
+ if (!base || !base.complete || base.refs.length < row.keep)
206
+ fail('The native request base is missing, incomplete, or shorter than its retained prefix.');
207
+ else
208
+ refs = base.refs.slice(0, row.keep);
209
+ }
210
+ if (refs.length + row.tail.length > MAX_REFS)
211
+ fail('The native request has too many referenced messages.');
212
+ else
213
+ refs.push(...row.tail);
214
+ if (Object.hasOwn(row, 'cut') || Object.hasOwn(row, 'withheld'))
215
+ fail('The native request declares cut or withheld evidence.');
216
+ const shape = next.shapes[row.shapeHash];
217
+ if (!shape)
218
+ fail('The native request shape is missing from the bounded policy cache.');
219
+ else if (!shape.complete)
220
+ fail(shape.reason ?? 'The native request shape policy is incomplete.');
221
+ const parts = [], stableParts = [];
222
+ let policyBytes = 0, oversized = false;
223
+ const include = (label, content, reminder = false) => {
224
+ if (!content || oversized)
225
+ return;
226
+ const size = Buffer.byteLength(label) + 1 + Buffer.byteLength(content) + (parts.length ? 2 : 0);
227
+ if (policyBytes + size > POLICY_BYTES) {
228
+ oversized = true;
229
+ fail('The reconstructed native policy exceeds the 256 KiB evidence limit.');
230
+ return;
231
+ }
232
+ parts.push(`${label}\n${content}`);
233
+ if (!reminder)
234
+ stableParts.push(`${label}\n${content}`);
235
+ policyBytes += size;
236
+ };
237
+ if (shape)
238
+ include('Native API system policy:', shape.text);
239
+ for (const ref of refs) {
240
+ const entry = next.blobs[ref];
241
+ if (!entry) {
242
+ fail('A native request message is missing from the bounded policy cache.');
243
+ continue;
244
+ }
245
+ if (!entry.complete)
246
+ fail(entry.reason ?? 'A referenced native policy message is incomplete.');
247
+ if (entry.role === 'system' || entry.role === 'developer')
248
+ include(`Native API ${entry.role} message:`, entry.text ?? '', entry.role === 'system' && (next.reminders ?? []).includes(entry.text ?? ''));
249
+ }
250
+ const text = oversized ? '' : parts.join('\n\n');
251
+ const known = next.requests[row.id];
252
+ if (known && (known.shapeHash !== row.shapeHash || JSON.stringify(known.refs) !== JSON.stringify(refs)))
253
+ fail('A native request identity was reused for different reconstruction metadata.');
254
+ put(next.requests, row.id, { shapeHash: row.shapeHash, refs, complete: !reason, ...(reason ? { reason } : {}) }, 32);
255
+ if (main)
256
+ next.current = prompt ? { prompt, text, stableText: oversized ? '' : stableParts.join('\n\n'), complete: !reason, ...(reason ? { reason } : {}) } : undefined;
257
+ return bounded(next);
258
+ }
@@ -0,0 +1,11 @@
1
+ type CliIO = {
2
+ stdout?: (text: string) => void;
3
+ stderr?: (text: string) => void;
4
+ stdin?: AsyncIterable<string | Uint8Array>;
5
+ fetch?: typeof fetch;
6
+ /** Test/packaging boundary: executable plus arguments, never evaluated while installing. */
7
+ command?: string[];
8
+ };
9
+ /** Installer/status command plus the bounded stdin worker invoked by ordinary CLI hooks. */
10
+ export declare function learningMain(argv: string[], io?: CliIO): Promise<number>;
11
+ export {};
@@ -0,0 +1,241 @@
1
+ import { mkdir, readFile, realpath, rm } from 'node:fs/promises';
2
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ import { parseArgs } from 'node:util';
4
+ import { secret } from '../secrets.js';
5
+ import { defaultData } from '../server-fs.js';
6
+ import { takeHold, releaseHold } from '../harness-install.js';
7
+ import { cliLearningUrl, installCliLearning, removeCliLearning, statusCliLearning } from './install.js';
8
+ import { connectionFile, readConnection, saveConnection } from './state.js';
9
+ const USAGE = 'usage: agentrun-serve learning connect|status|disconnect|retry --runtime codex|claude-code [--project PATH] [--url LOOPBACK_URL] [--data SERVER_DATA]';
10
+ async function ownerToken(data) {
11
+ const fromEnvironment = secret('AGENTRUN_API_KEY') || secret('AGENTRUN_TOKEN');
12
+ if (fromEnvironment)
13
+ return fromEnvironment;
14
+ let value;
15
+ try {
16
+ value = (await readFile(join(data, '.token'), 'utf8')).trim();
17
+ }
18
+ catch {
19
+ throw new Error('Cannot read the local server token. Start AgentRun and use its --data directory.');
20
+ }
21
+ if (!value)
22
+ throw new Error('The local server token is empty.');
23
+ return value;
24
+ }
25
+ async function serverUrl(value, data) {
26
+ if (value)
27
+ return cliLearningUrl(value);
28
+ let recorded;
29
+ try {
30
+ const record = JSON.parse(await readFile(join(data, '.server.json'), 'utf8'));
31
+ if (typeof record.base_url === 'string')
32
+ recorded = record.base_url;
33
+ }
34
+ catch { /* A stopped/default server has no record. */ }
35
+ return cliLearningUrl(recorded);
36
+ }
37
+ async function request(fetcher, url, path, token, method, body) {
38
+ return fetcher(new URL(path, cliLearningUrl(url)), {
39
+ method, redirect: 'error', signal: AbortSignal.timeout(8_000),
40
+ headers: { authorization: `Bearer ${token}`, 'content-type': 'application/json' },
41
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
42
+ });
43
+ }
44
+ async function revoke(fetcher, connection, token) {
45
+ const response = await request(fetcher, connection.url, `/v2/cli-learning/connections/${encodeURIComponent(connection.connection_id)}`, token, 'DELETE');
46
+ if (!response.ok && response.status !== 404)
47
+ throw new Error(`Server refused disconnection (HTTP ${response.status}).`);
48
+ }
49
+ async function hookInput(input) {
50
+ const chunks = [];
51
+ let bytes = 0;
52
+ for await (const chunk of input) {
53
+ const buffer = Buffer.from(chunk);
54
+ bytes += buffer.byteLength;
55
+ if (bytes > 1_048_576)
56
+ throw new Error('Hook input exceeds the limit.');
57
+ chunks.push(buffer);
58
+ }
59
+ return JSON.parse(Buffer.concat(chunks).toString('utf8'));
60
+ }
61
+ async function connectionLock(file, operation) {
62
+ await mkdir(dirname(file), { recursive: true, mode: 0o700 });
63
+ const holdPath = `${file}.lock`;
64
+ // A long retry must never lose its hold merely because time passed. A dead local
65
+ // process (including PID reuse) or an abandoned legacy empty lock is recoverable.
66
+ const token = await takeHold(dirname(file), { holdPath, timeoutMs: Infinity });
67
+ if (!token)
68
+ throw new Error('Another learning connection change is in progress for this project.');
69
+ try {
70
+ return await operation();
71
+ }
72
+ finally {
73
+ await releaseHold(dirname(file), token, { holdPath });
74
+ }
75
+ }
76
+ /** Installer/status command plus the bounded stdin worker invoked by ordinary CLI hooks. */
77
+ export async function learningMain(argv, io = {}) {
78
+ const output = io.stdout ?? ((text) => console.log(text));
79
+ const errorOutput = io.stderr ?? ((text) => console.error(text));
80
+ const fetcher = io.fetch ?? fetch;
81
+ const isHook = argv[0] === 'hook';
82
+ try {
83
+ const { values, positionals } = parseArgs({ args: argv, allowPositionals: true, options: {
84
+ project: { type: 'string' }, runtime: { type: 'string' }, data: { type: 'string' }, url: { type: 'string' },
85
+ json: { type: 'boolean' }, help: { type: 'boolean' },
86
+ } });
87
+ if (values.help) {
88
+ output(USAGE);
89
+ return 0;
90
+ }
91
+ const operation = positionals[0];
92
+ if (positionals.length !== 1 || !['connect', 'status', 'disconnect', 'retry', 'hook'].includes(operation ?? ''))
93
+ throw new Error(USAGE);
94
+ if (values.runtime !== 'codex' && values.runtime !== 'claude-code')
95
+ throw new Error(`--runtime must be codex or claude-code.\n${USAGE}`);
96
+ const runtime = values.runtime;
97
+ const project = await realpath(resolve(values.project ?? process.cwd()));
98
+ const requestedData = resolve(values.data ?? defaultData());
99
+ const dataDir = await realpath(requestedData).catch((error) => {
100
+ if (error.code === 'ENOENT')
101
+ return requestedData;
102
+ throw error;
103
+ });
104
+ const dataRelative = relative(project, dataDir);
105
+ if (dataRelative === '' || (dataRelative !== '..' && !dataRelative.startsWith(`..${sep}`) && !isAbsolute(dataRelative))) {
106
+ throw new Error('Use a server --data directory outside the project so connection credentials stay out of source control.');
107
+ }
108
+ const options = { runtime, project, dataDir };
109
+ if (operation === 'hook') {
110
+ const input = await hookInput(io.stdin ?? process.stdin);
111
+ const { runCliLearningHook } = await import('./hook.js');
112
+ const result = await runCliLearningHook({ ...options, ...(values.url ? { url: cliLearningUrl(values.url) } : {}) }, input);
113
+ if (result !== undefined)
114
+ output(JSON.stringify(result));
115
+ return 0;
116
+ }
117
+ const execute = async () => {
118
+ const existing = await readConnection(dataDir, runtime, project);
119
+ if (operation === 'retry') {
120
+ const { flushCliLearning } = await import('./hook.js');
121
+ const result = await flushCliLearning(options, { fetch: fetcher });
122
+ output(JSON.stringify(result));
123
+ if (result.blocked_journals)
124
+ errorOutput('CLI capture journals from another enrollment or without a destination binding are preserved for review. They were not retried.');
125
+ return result.pending > 0 || result.blocked_journals > 0 ? 1 : 0;
126
+ }
127
+ if (operation === 'status') {
128
+ const installation = await statusCliLearning(options);
129
+ let server = null;
130
+ if (existing) {
131
+ try {
132
+ const response = await request(fetcher, existing.url, '/v2/cli-learning/connections', await ownerToken(dataDir), 'GET');
133
+ if (!response.ok)
134
+ throw new Error('Unavailable');
135
+ const body = await response.json();
136
+ if (!Array.isArray(body.connections))
137
+ throw new Error('Invalid status');
138
+ const connection = body.connections.find((c) => c && typeof c === 'object' && c.connection_id === existing.connection_id);
139
+ server = { reachable: true, enrolled: !!connection, active: connection?.active === true,
140
+ ...(typeof connection?.last_hook_at === 'string' ? { last_hook_at: connection.last_hook_at } : {}),
141
+ ...(typeof connection?.last_run_id === 'string' ? { last_run_id: connection.last_run_id } : {}) };
142
+ }
143
+ catch {
144
+ server = { reachable: false };
145
+ }
146
+ }
147
+ output(JSON.stringify({ ...installation, connection: existing ? { connection_id: existing.connection_id, agent_id: existing.agent_id, url: existing.url, capture_enabled: !existing.revocation_pending } : null, server }, null, 2));
148
+ return 0;
149
+ }
150
+ if (operation === 'disconnect') {
151
+ // Loaded CLI sessions can retain hooks after their files are removed. Disable capture durably first.
152
+ if (existing)
153
+ await saveConnection(dataDir, { ...existing, revocation_pending: true });
154
+ const installation = await removeCliLearning(options);
155
+ if (existing) {
156
+ try {
157
+ await revoke(fetcher, existing, await ownerToken(dataDir));
158
+ }
159
+ catch {
160
+ output(JSON.stringify({ ...installation, revoked: false, warnings: [...installation.warnings, 'Hooks removed; server revocation is pending. Run disconnect again when the server is available.'] }, null, 2));
161
+ return 1;
162
+ }
163
+ await rm(connectionFile(dataDir, runtime, project), { force: true });
164
+ }
165
+ output(JSON.stringify({ ...installation, revoked: true }, null, 2));
166
+ return 0;
167
+ }
168
+ const url = await serverUrl(values.url, dataDir);
169
+ const before = await statusCliLearning(options);
170
+ if (before.state === 'partial')
171
+ throw new Error('AgentRun hooks were changed or disabled. Run learning disconnect before reconnecting.');
172
+ if (existing) {
173
+ if (existing.revocation_pending)
174
+ throw new Error('Capture is disabled while server revocation is pending. Run learning disconnect before reconnecting.');
175
+ if (existing.url !== url)
176
+ throw new Error('This project is connected to another server. Run learning disconnect before reconnecting.');
177
+ let active = false;
178
+ try {
179
+ const response = await request(fetcher, url, '/v2/cli-learning/connections', await ownerToken(dataDir), 'GET');
180
+ if (!response.ok)
181
+ throw new Error('Unavailable');
182
+ const body = await response.json();
183
+ if (!Array.isArray(body.connections))
184
+ throw new Error('Invalid status');
185
+ active = body.connections.some((c) => c && typeof c === 'object'
186
+ && c.connection_id === existing.connection_id
187
+ && c.active === true);
188
+ }
189
+ catch {
190
+ throw new Error('Cannot verify the existing learning connection. Retry when the local server is available.');
191
+ }
192
+ if (!active)
193
+ throw new Error('This learning connection is inactive. Run learning disconnect, then learning connect to enroll again.');
194
+ const installation = await installCliLearning({ ...options, url, command: io.command });
195
+ output(JSON.stringify({ ...installation, connection_id: existing.connection_id, agent_id: existing.agent_id }, null, 2));
196
+ return 0;
197
+ }
198
+ const token = await ownerToken(dataDir);
199
+ const response = await request(fetcher, url, '/v2/cli-learning/connections', token, 'POST', { project, runtime });
200
+ if (!response.ok)
201
+ throw new Error(`Server refused the learning connection (HTTP ${response.status}).`);
202
+ const body = await response.json();
203
+ if (!body || typeof body.connection_id !== 'string' || typeof body.agent_id !== 'string' || typeof body.token !== 'string'
204
+ || !body.connection_id || !body.agent_id || !body.token)
205
+ throw new Error('The server returned an invalid learning connection.');
206
+ const connection = { version: 1, project, runtime, url, connection_id: body.connection_id, agent_id: body.agent_id, token: body.token };
207
+ let saved = false;
208
+ try {
209
+ await saveConnection(dataDir, connection);
210
+ saved = true;
211
+ const installation = await installCliLearning({ ...options, url, command: io.command });
212
+ output(JSON.stringify({ ...installation, connection_id: connection.connection_id, agent_id: connection.agent_id }, null, 2));
213
+ return 0;
214
+ }
215
+ catch (error) {
216
+ if (saved)
217
+ await saveConnection(dataDir, { ...connection, revocation_pending: true });
218
+ if (before.state === 'not-installed')
219
+ await removeCliLearning(options).catch(() => undefined);
220
+ try {
221
+ await revoke(fetcher, connection, token);
222
+ if (saved)
223
+ await rm(connectionFile(dataDir, runtime, project), { force: true });
224
+ }
225
+ catch {
226
+ throw new Error('Connection setup failed and server revocation is pending. Run learning disconnect when the server is available.');
227
+ }
228
+ throw error;
229
+ }
230
+ };
231
+ return operation === 'status' ? await execute() : await connectionLock(connectionFile(dataDir, runtime, project), execute);
232
+ }
233
+ catch (error) {
234
+ if (isHook) {
235
+ errorOutput('AgentRun learning hook skipped; use learning status to check the connection.');
236
+ return 0;
237
+ }
238
+ errorOutput(`agentrun learning: ${error instanceof Error ? error.message : 'Command failed.'}`);
239
+ return 2;
240
+ }
241
+ }
@@ -0,0 +1,10 @@
1
+ /** A bounded, non-following read: project configuration must be a regular file we own. */
2
+ export declare function readConfigText(path: string): Promise<string | undefined>;
3
+ type CodexHookLocation = {
4
+ checkoutRoot?: string;
5
+ configRoot: string;
6
+ linkedWorktree: boolean;
7
+ };
8
+ /** Match Codex's root-checkout hook mapping, including Git's reciprocal worktree ownership checks. */
9
+ export declare function codexHookLocation(project: string): Promise<CodexHookLocation>;
10
+ export {};