@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,335 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstat, mkdir, open, realpath, rename, rm, stat } from 'node:fs/promises';
|
|
3
|
+
import { join, resolve } from 'node:path';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { isDeepStrictEqual } from 'node:util';
|
|
6
|
+
import { codexHookLocation, readConfigText } from './codex-worktree.js';
|
|
7
|
+
import { takeHold, releaseHold } from '../harness-install.js';
|
|
8
|
+
const eventsFor = (runtime) => runtime === 'codex'
|
|
9
|
+
? ['UserPromptSubmit', 'Stop', 'Interrupt', 'SessionEnd']
|
|
10
|
+
: ['UserPromptSubmit', 'Stop', 'StopFailure', 'SessionEnd'];
|
|
11
|
+
const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
|
|
12
|
+
const missing = (error) => error.code === 'ENOENT';
|
|
13
|
+
const quote = (value) => `'${value.replaceAll("'", "'\"'\"'")}'`;
|
|
14
|
+
export function cliLearningUrl(value = 'http://127.0.0.1:7340') {
|
|
15
|
+
let url;
|
|
16
|
+
try {
|
|
17
|
+
url = new URL(value);
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
throw new Error('AgentRun learning requires an HTTP(S) loopback URL.');
|
|
21
|
+
}
|
|
22
|
+
if (!['http:', 'https:'].includes(url.protocol) || !['localhost', '127.0.0.1', '[::1]'].includes(url.hostname)) {
|
|
23
|
+
throw new Error('AgentRun learning requires an HTTP(S) loopback URL on this machine.');
|
|
24
|
+
}
|
|
25
|
+
if (url.username || url.password || url.search || url.hash || url.pathname !== '/') {
|
|
26
|
+
throw new Error('Use a loopback server origin without credentials, query parameters or a path.');
|
|
27
|
+
}
|
|
28
|
+
return url.origin;
|
|
29
|
+
}
|
|
30
|
+
async function noSymlink(path) {
|
|
31
|
+
try {
|
|
32
|
+
if ((await lstat(path)).isSymbolicLink())
|
|
33
|
+
throw new Error(`Refusing project configuration symlink: ${path}`);
|
|
34
|
+
}
|
|
35
|
+
catch (error) {
|
|
36
|
+
if (!missing(error))
|
|
37
|
+
throw error;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async function location(options) {
|
|
41
|
+
if (!['codex', 'claude-code'].includes(options.runtime))
|
|
42
|
+
throw new Error('runtime must be codex or claude-code');
|
|
43
|
+
const project = await realpath(resolve(options.project));
|
|
44
|
+
if (!(await stat(project)).isDirectory())
|
|
45
|
+
throw new Error('project must be a directory');
|
|
46
|
+
const mapping = options.runtime === 'codex' ? await codexHookLocation(project) : { configRoot: project, linkedWorktree: false };
|
|
47
|
+
const localScope = join(project, options.runtime === 'codex' ? '.codex' : '.claude');
|
|
48
|
+
const localPath = join(localScope, options.runtime === 'codex' ? 'hooks.json' : 'settings.local.json');
|
|
49
|
+
const scope = join(mapping.configRoot, options.runtime === 'codex' ? '.codex' : '.claude');
|
|
50
|
+
const configPath = join(scope, options.runtime === 'codex' ? 'hooks.json' : 'settings.local.json');
|
|
51
|
+
const receiptDir = join(project, '.agentrun', 'cli-learning');
|
|
52
|
+
const receiptPath = join(receiptDir, `${options.runtime}.json`);
|
|
53
|
+
for (const path of [localScope, localPath, scope, configPath, join(project, '.agentrun'), receiptDir, receiptPath])
|
|
54
|
+
await noSymlink(path);
|
|
55
|
+
let localAvailable = false;
|
|
56
|
+
try {
|
|
57
|
+
localAvailable = (await stat(localScope)).isDirectory();
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
if (!missing(error))
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
return { project, scope, configPath, localScope, localPath, localAvailable, ...mapping, receiptDir, receiptPath };
|
|
64
|
+
}
|
|
65
|
+
async function readJson(path) {
|
|
66
|
+
const text = await readConfigText(path);
|
|
67
|
+
if (text === undefined)
|
|
68
|
+
return;
|
|
69
|
+
try {
|
|
70
|
+
const value = JSON.parse(text);
|
|
71
|
+
if (!object(value))
|
|
72
|
+
throw new Error();
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
catch {
|
|
76
|
+
throw new Error(`Invalid JSON object in ${path}; nothing was replaced.`);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function configuration(path) {
|
|
80
|
+
const config = await readJson(path) ?? {};
|
|
81
|
+
if (config.hooks !== undefined) {
|
|
82
|
+
if (!object(config.hooks))
|
|
83
|
+
throw new Error(`Invalid hooks in ${path}; nothing was replaced.`);
|
|
84
|
+
for (const groups of Object.values(config.hooks)) {
|
|
85
|
+
if (!Array.isArray(groups) || groups.some((g) => !object(g) || !Array.isArray(g.hooks))) {
|
|
86
|
+
throw new Error(`Invalid hook groups in ${path}; nothing was replaced.`);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return config;
|
|
91
|
+
}
|
|
92
|
+
function validReceipt(value, project, runtime, configRoot) {
|
|
93
|
+
if (!object(value) || ![1, 2].includes(value.version) || value.project !== project || value.runtime !== runtime || typeof value.dataDir !== 'string'
|
|
94
|
+
|| typeof value.url !== 'string' || typeof value.hadHooks !== 'boolean' || !Array.isArray(value.createdEvents)
|
|
95
|
+
|| value.createdEvents.some((event) => typeof event !== 'string' || !eventsFor(runtime).includes(event)) || !object(value.handlers)
|
|
96
|
+
|| !isDeepStrictEqual(Object.keys(value.handlers).sort(), eventsFor(runtime).sort())
|
|
97
|
+
|| Object.values(value.handlers).some((h) => !object(h) || h.type !== 'command' || typeof h.command !== 'string' || !Number.isFinite(h.timeout)))
|
|
98
|
+
return false;
|
|
99
|
+
if (value.version === 1)
|
|
100
|
+
return true;
|
|
101
|
+
return runtime === 'codex' && value.format === 'codex-shared-json' && value.configRoot === configRoot && configRoot !== project
|
|
102
|
+
&& (value.legacy === undefined || (object(value.legacy) && value.legacy.version === 1
|
|
103
|
+
&& validReceipt(value.legacy, project, runtime, configRoot) && value.legacy.dataDir === value.dataDir && value.legacy.url === value.url
|
|
104
|
+
&& isDeepStrictEqual(value.legacy.handlers, value.handlers)));
|
|
105
|
+
}
|
|
106
|
+
async function receipt(path, project, runtime, configRoot) {
|
|
107
|
+
const value = await readJson(path);
|
|
108
|
+
if (!value)
|
|
109
|
+
return;
|
|
110
|
+
if (!validReceipt(value, project, runtime, configRoot)) {
|
|
111
|
+
throw new Error(`Invalid AgentRun hook receipt in ${path}; nothing was replaced.`);
|
|
112
|
+
}
|
|
113
|
+
return value;
|
|
114
|
+
}
|
|
115
|
+
function jsonText(value) {
|
|
116
|
+
const text = `${JSON.stringify(value, null, 2)}\n`;
|
|
117
|
+
if (Buffer.byteLength(text) > 64 * 1024)
|
|
118
|
+
throw new Error('AgentRun hooks would exceed the project configuration size limit; nothing was replaced.');
|
|
119
|
+
return text;
|
|
120
|
+
}
|
|
121
|
+
async function writeJson(path, value) {
|
|
122
|
+
const text = jsonText(value);
|
|
123
|
+
let mode = 0o600;
|
|
124
|
+
try {
|
|
125
|
+
mode = (await stat(path)).mode & 0o777;
|
|
126
|
+
}
|
|
127
|
+
catch (error) {
|
|
128
|
+
if (!missing(error))
|
|
129
|
+
throw error;
|
|
130
|
+
}
|
|
131
|
+
const temporary = `${path}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
|
|
132
|
+
const handle = await open(temporary, 'wx', mode);
|
|
133
|
+
try {
|
|
134
|
+
await handle.writeFile(text);
|
|
135
|
+
await handle.sync();
|
|
136
|
+
}
|
|
137
|
+
finally {
|
|
138
|
+
await handle.close();
|
|
139
|
+
}
|
|
140
|
+
try {
|
|
141
|
+
await rename(temporary, path);
|
|
142
|
+
}
|
|
143
|
+
finally {
|
|
144
|
+
await rm(temporary, { force: true });
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
function result(options, paths, config, owned) {
|
|
148
|
+
const events = eventsFor(options.runtime).map((event) => ({ event, configured: !!owned && (!paths.linkedWorktree || paths.localAvailable) && config.disableAllHooks !== true
|
|
149
|
+
&& (config.hooks?.[event] ?? []).some((group) => (group.matcher === undefined || group.matcher === '' || group.matcher === '*')
|
|
150
|
+
&& group.hooks.some((handler) => isDeepStrictEqual(handler, owned.handlers[event]))) }));
|
|
151
|
+
const configured = events.every((event) => event.configured);
|
|
152
|
+
return {
|
|
153
|
+
runtime: options.runtime, project: paths.project, configPath: paths.configPath, receiptPath: paths.receiptPath,
|
|
154
|
+
state: !owned ? 'not-installed' : configured ? 'configured' : 'partial', configured, activation: 'unverified', events,
|
|
155
|
+
instructions: options.runtime === 'codex' ? [
|
|
156
|
+
'In this project’s Codex session, open /hooks and trust the AgentRun hook definitions after reviewing them.',
|
|
157
|
+
'Open a new Codex session, or close and resume the existing session, to load project configuration. Already loaded project layers do not hot reload.',
|
|
158
|
+
'Verify /hooks lists and enables the installed events before the next prompt.',
|
|
159
|
+
'Configuration alone does not prove activation. Submit a prompt and check that its run appears in AgentRun.',
|
|
160
|
+
] : [
|
|
161
|
+
'In this project’s Claude Code session, verify /hooks lists the AgentRun hooks. Settings edits normally load automatically.',
|
|
162
|
+
'The project must be trusted. If /hooks does not update after a few seconds, resume the session to reload it; managed policy may prohibit custom hooks.',
|
|
163
|
+
'Submit a prompt and check that its run appears in AgentRun. Existing transcript history is not imported.',
|
|
164
|
+
],
|
|
165
|
+
warnings: config.disableAllHooks === true ? ['Hooks are disabled by this configuration.'] : [],
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/** Reads configuration evidence only: never claims the CLI has loaded or trusted a hook. */
|
|
169
|
+
export async function statusCliLearning(options) {
|
|
170
|
+
const paths = await location(options);
|
|
171
|
+
const owned = await receipt(paths.receiptPath, paths.project, options.runtime, paths.configRoot);
|
|
172
|
+
const config = await configuration(paths.configPath);
|
|
173
|
+
if (paths.linkedWorktree && owned?.version === 1) {
|
|
174
|
+
const legacy = result(options, paths, await configuration(paths.localPath), owned);
|
|
175
|
+
return { ...result(options, paths, config), state: legacy.configured ? 'migration-required' : 'partial',
|
|
176
|
+
warnings: ['Codex loads linked-worktree hooks from the main checkout. Run learning connect again to migrate unchanged AgentRun hooks, then reopen the session.'] };
|
|
177
|
+
}
|
|
178
|
+
return result(options, paths, config, owned);
|
|
179
|
+
}
|
|
180
|
+
async function lock(directory, fn, filename = 'install.lock', waitMs = 0) {
|
|
181
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
182
|
+
const holdPath = join(directory, filename);
|
|
183
|
+
let token;
|
|
184
|
+
const deadline = Date.now() + waitMs;
|
|
185
|
+
while (!token) {
|
|
186
|
+
token = await takeHold(directory, { holdPath, timeoutMs: Infinity, recoverUnknownOwner: false });
|
|
187
|
+
if (!token) {
|
|
188
|
+
if (Date.now() >= deadline)
|
|
189
|
+
throw new Error(`AgentRun hook installation lock is held or its owner cannot be verified: ${holdPath}. Wait for the current installation to finish. For a legacy or malformed lock, stop all AgentRun connect/disconnect commands using this checkout and its linked worktrees, verify none remain, then remove only this lock and retry.`);
|
|
190
|
+
await new Promise(done => setTimeout(done, 20));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
try {
|
|
194
|
+
return await fn();
|
|
195
|
+
}
|
|
196
|
+
finally {
|
|
197
|
+
await releaseHold(directory, token, { holdPath });
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
function stripHandlers(config, owned, warnings, stableIndices) {
|
|
201
|
+
let changed = false;
|
|
202
|
+
for (const [event, handler] of Object.entries(owned.handlers)) {
|
|
203
|
+
const groups = config.hooks?.[event];
|
|
204
|
+
if (!groups)
|
|
205
|
+
continue;
|
|
206
|
+
// Never shift a surviving Codex group: its native trust key includes both array indices.
|
|
207
|
+
let lastKept = -1;
|
|
208
|
+
for (let i = 0; i < groups.length; i++) {
|
|
209
|
+
const group = groups[i];
|
|
210
|
+
if (!group.hooks.some((h) => isDeepStrictEqual(h, handler)) || group.hooks.some((h) => !isDeepStrictEqual(h, handler)))
|
|
211
|
+
lastKept = i;
|
|
212
|
+
}
|
|
213
|
+
const kept = [];
|
|
214
|
+
for (const [index, group] of groups.entries()) {
|
|
215
|
+
const hadOwn = group.hooks.some((h) => isDeepStrictEqual(h, handler));
|
|
216
|
+
for (const h of group.hooks)
|
|
217
|
+
if (object(h) && h.command === handler.command && !isDeepStrictEqual(h, handler)) {
|
|
218
|
+
warnings.push(`Left a modified ${event} hook in place; review it in /hooks.`);
|
|
219
|
+
}
|
|
220
|
+
if (stableIndices && hadOwn && group.hooks.some((h, i) => i > group.hooks.findIndex((value) => isDeepStrictEqual(value, handler)) && !isDeepStrictEqual(h, handler))) {
|
|
221
|
+
// Stop capture even if a user has edited this group. Separate project groups keep stable indices.
|
|
222
|
+
warnings.push(`Removed the AgentRun ${event} handler; this modified group's remaining hook trust keys changed. Review them in /hooks.`);
|
|
223
|
+
}
|
|
224
|
+
changed ||= hadOwn;
|
|
225
|
+
group.hooks = group.hooks.filter((h) => !isDeepStrictEqual(h, handler));
|
|
226
|
+
if (group.hooks.length || !hadOwn || (stableIndices && index <= lastKept))
|
|
227
|
+
kept.push(group);
|
|
228
|
+
}
|
|
229
|
+
config.hooks[event] = kept;
|
|
230
|
+
if (!kept.length && owned.createdEvents.includes(event))
|
|
231
|
+
delete config.hooks[event];
|
|
232
|
+
}
|
|
233
|
+
if (config.hooks && !Object.keys(config.hooks).length && !owned.hadHooks)
|
|
234
|
+
delete config.hooks;
|
|
235
|
+
return changed;
|
|
236
|
+
}
|
|
237
|
+
async function cleanLegacy(paths, owned, warnings) {
|
|
238
|
+
const config = await configuration(paths.localPath);
|
|
239
|
+
if (stripHandlers(config, owned, warnings, false))
|
|
240
|
+
await writeJson(paths.localPath, config);
|
|
241
|
+
}
|
|
242
|
+
async function sharedLock(paths, runtime, fn) {
|
|
243
|
+
// Main-checkout v1 installs/removals take this same lock as all linked worktrees.
|
|
244
|
+
return runtime === 'codex' ? lock(paths.scope, fn, '.agentrun-learning.lock', 5000) : fn();
|
|
245
|
+
}
|
|
246
|
+
async function unchangedLocation(options, expected) {
|
|
247
|
+
const current = await location(options);
|
|
248
|
+
if (current.project !== expected.project || current.configRoot !== expected.configRoot || current.linkedWorktree !== expected.linkedWorktree) {
|
|
249
|
+
throw new Error('Git project hook scope changed during installation; nothing was replaced.');
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
/** Additive, project-scoped install. The receipt owns exact handlers, not an entire settings file. */
|
|
253
|
+
export async function installCliLearning(options) {
|
|
254
|
+
const url = cliLearningUrl(options.url);
|
|
255
|
+
const paths = await location(options);
|
|
256
|
+
const command = options.command ?? [process.execPath, fileURLToPath(new URL('./entry.js', import.meta.url))];
|
|
257
|
+
if (!command.length || command.some((part) => !part || /[\0\r\n]/.test(part)))
|
|
258
|
+
throw new Error('Invalid hook executable arguments.');
|
|
259
|
+
const dataDir = resolve(options.dataDir);
|
|
260
|
+
const line = [...command, 'learning', 'hook', '--runtime', options.runtime, '--project', paths.project, '--data', dataDir, '--url', url].map(quote).join(' ');
|
|
261
|
+
const handlers = Object.fromEntries(eventsFor(options.runtime).map((event) => [event, { type: 'command', command: line, timeout: 5 }]));
|
|
262
|
+
// Validate before creating any project files.
|
|
263
|
+
await configuration(paths.configPath);
|
|
264
|
+
return lock(paths.receiptDir, async () => {
|
|
265
|
+
await unchangedLocation(options, paths);
|
|
266
|
+
return sharedLock(paths, options.runtime, async () => {
|
|
267
|
+
await unchangedLocation(options, paths);
|
|
268
|
+
const config = await configuration(paths.configPath);
|
|
269
|
+
const previous = await receipt(paths.receiptPath, paths.project, options.runtime, paths.configRoot);
|
|
270
|
+
const migrating = paths.linkedWorktree && previous?.version === 1;
|
|
271
|
+
if (previous && (previous.dataDir !== dataDir || previous.url !== url || !isDeepStrictEqual(previous.handlers, handlers))) {
|
|
272
|
+
throw new Error('AgentRun is already configured with another target; disconnect it before reconnecting.');
|
|
273
|
+
}
|
|
274
|
+
if (previous && !migrating) {
|
|
275
|
+
if (!result(options, paths, config, previous).configured)
|
|
276
|
+
throw new Error('AgentRun hooks were removed, disabled or modified; disconnect before reconnecting.');
|
|
277
|
+
if (previous.version === 2 && previous.legacy) {
|
|
278
|
+
await cleanLegacy(paths, previous.legacy, []);
|
|
279
|
+
delete previous.legacy;
|
|
280
|
+
await writeJson(paths.receiptPath, previous);
|
|
281
|
+
}
|
|
282
|
+
return result(options, paths, config, previous);
|
|
283
|
+
}
|
|
284
|
+
if (migrating && !result(options, paths, await configuration(paths.localPath), previous).configured) {
|
|
285
|
+
throw new Error('AgentRun legacy hooks were removed, disabled or modified; disconnect before reconnecting.');
|
|
286
|
+
}
|
|
287
|
+
const fields = { project: paths.project, runtime: options.runtime, dataDir, url, handlers,
|
|
288
|
+
hadHooks: config.hooks !== undefined, createdEvents: eventsFor(options.runtime).filter((event) => !Object.hasOwn(config.hooks ?? {}, event)) };
|
|
289
|
+
const next = paths.linkedWorktree
|
|
290
|
+
? { ...fields, version: 2, format: 'codex-shared-json', configRoot: paths.configRoot, ...(migrating ? { legacy: previous } : {}) }
|
|
291
|
+
: { ...fields, version: 1 };
|
|
292
|
+
config.hooks ??= {};
|
|
293
|
+
for (const [event, handler] of Object.entries(handlers))
|
|
294
|
+
(config.hooks[event] ??= []).push({ hooks: [handler] });
|
|
295
|
+
jsonText(config); // Refuse a shared file our bounded status/disconnect reader could no longer open.
|
|
296
|
+
await mkdir(paths.scope, { recursive: true, mode: 0o700 });
|
|
297
|
+
// Codex discovers a worktree project layer only if its local .codex directory exists.
|
|
298
|
+
await mkdir(paths.localScope, { recursive: true, mode: 0o700 });
|
|
299
|
+
paths.localAvailable = true;
|
|
300
|
+
await writeJson(paths.receiptPath, next); // Own both files before migration can be interrupted.
|
|
301
|
+
await writeJson(paths.configPath, config);
|
|
302
|
+
if (next.version === 2 && next.legacy) {
|
|
303
|
+
await cleanLegacy(paths, next.legacy, []);
|
|
304
|
+
delete next.legacy;
|
|
305
|
+
await writeJson(paths.receiptPath, next);
|
|
306
|
+
}
|
|
307
|
+
return result(options, paths, config, next);
|
|
308
|
+
});
|
|
309
|
+
});
|
|
310
|
+
}
|
|
311
|
+
/** Removes only unchanged handlers recorded by this installer; never restores a stale whole-file backup. */
|
|
312
|
+
export async function removeCliLearning(options) {
|
|
313
|
+
const paths = await location(options);
|
|
314
|
+
if (!await receipt(paths.receiptPath, paths.project, options.runtime, paths.configRoot))
|
|
315
|
+
return statusCliLearning(options);
|
|
316
|
+
return lock(paths.receiptDir, async () => {
|
|
317
|
+
await unchangedLocation(options, paths);
|
|
318
|
+
return sharedLock(paths, options.runtime, async () => {
|
|
319
|
+
await unchangedLocation(options, paths);
|
|
320
|
+
const owned = await receipt(paths.receiptPath, paths.project, options.runtime, paths.configRoot);
|
|
321
|
+
const config = await configuration(paths.configPath);
|
|
322
|
+
const warnings = [];
|
|
323
|
+
if (owned) {
|
|
324
|
+
if (owned.version === 1 && paths.linkedWorktree)
|
|
325
|
+
await cleanLegacy(paths, owned, warnings);
|
|
326
|
+
else if (stripHandlers(config, owned, warnings, options.runtime === 'codex'))
|
|
327
|
+
await writeJson(paths.configPath, config);
|
|
328
|
+
if (owned.version === 2 && owned.legacy)
|
|
329
|
+
await cleanLegacy(paths, owned.legacy, warnings);
|
|
330
|
+
await rm(paths.receiptPath);
|
|
331
|
+
}
|
|
332
|
+
return { ...result(options, paths, config), warnings };
|
|
333
|
+
});
|
|
334
|
+
});
|
|
335
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
export type CliLearningReadiness = "ready" | "setup_required" | "unknown" | "unsupported";
|
|
2
|
+
export type CliLearningObservationScope = {
|
|
3
|
+
connector_id: string;
|
|
4
|
+
source_id: string;
|
|
5
|
+
external_session_id: string;
|
|
6
|
+
runtime: "codex" | "claude-code";
|
|
7
|
+
connection_id: string;
|
|
8
|
+
readiness: CliLearningReadiness;
|
|
9
|
+
native_session_hash: string;
|
|
10
|
+
sequence: number;
|
|
11
|
+
};
|
|
12
|
+
/** Prove possession of the existing project/runtime credential without sending it with observation metadata.
|
|
13
|
+
* The source must first match its canonical project and server origin to the private connection record. */
|
|
14
|
+
export declare function cliLearningObservationProof(token: string, scope: CliLearningObservationScope): string;
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
/** Prove possession of the existing project/runtime credential without sending it with observation metadata.
|
|
3
|
+
* The source must first match its canonical project and server origin to the private connection record. */
|
|
4
|
+
export function cliLearningObservationProof(token, scope) {
|
|
5
|
+
return createHmac("sha256", token).update(JSON.stringify([
|
|
6
|
+
"agentrun-cli-learning-observation-v1",
|
|
7
|
+
scope.connector_id, scope.source_id, scope.external_session_id, scope.runtime,
|
|
8
|
+
scope.connection_id, scope.readiness, scope.native_session_hash, scope.sequence,
|
|
9
|
+
])).digest("hex");
|
|
10
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import { type NativeInstructionSnapshot } from '../native/instructions.js';
|
|
2
|
+
import type { TranscriptCursor } from './evidence.js';
|
|
3
|
+
import { type CliLearningRuntime } from './state.js';
|
|
4
|
+
export declare const CLI_POLICY_BYTES: number;
|
|
5
|
+
export declare const CLAUDE_IMPORTS_PENDING = "Claude standing instructions contain imports whose policy files were not captured.";
|
|
6
|
+
export declare const CLAUDE_SNAPSHOT_PENDING = "A current native Claude system-prompt snapshot has not been recorded.";
|
|
7
|
+
/** Read only policy metadata before enrollment, not historical dialogue. Cached append offsets make long sessions
|
|
8
|
+
* cheap after their first scan. A deadline checkpoint is incomplete until a later invocation reaches the boundary. */
|
|
9
|
+
export declare function readTranscriptPolicy(options: {
|
|
10
|
+
runtime: CliLearningRuntime;
|
|
11
|
+
cursor: TranscriptCursor | null;
|
|
12
|
+
sessionId?: string;
|
|
13
|
+
turnId?: string;
|
|
14
|
+
requireWire?: boolean;
|
|
15
|
+
cachePath?: string;
|
|
16
|
+
redact?: (text: string) => string;
|
|
17
|
+
budgetMs?: number;
|
|
18
|
+
}): Promise<{
|
|
19
|
+
text: string;
|
|
20
|
+
incomplete?: string;
|
|
21
|
+
instructionsCaptured?: boolean;
|
|
22
|
+
wireCaptured?: boolean;
|
|
23
|
+
scannedBytes?: number;
|
|
24
|
+
totalBytes?: number;
|
|
25
|
+
}>;
|
|
26
|
+
/** Existing native discovery checks imports/configuration coverage. The active transcript supplies the actual
|
|
27
|
+
* session policy, including CLI-only system overrides, without uploading config values or historical conversation. */
|
|
28
|
+
export declare function captureSourcePolicy(options: {
|
|
29
|
+
runtime: CliLearningRuntime;
|
|
30
|
+
project: string;
|
|
31
|
+
cursor: TranscriptCursor | null;
|
|
32
|
+
env: NodeJS.ProcessEnv;
|
|
33
|
+
redact: (text: string) => string;
|
|
34
|
+
sessionId?: string;
|
|
35
|
+
turnId?: string;
|
|
36
|
+
cachePath?: string;
|
|
37
|
+
pinnedStanding?: NativeInstructionSnapshot;
|
|
38
|
+
}): Promise<NativeInstructionSnapshot & {
|
|
39
|
+
sourceStanding: NativeInstructionSnapshot;
|
|
40
|
+
}>;
|
|
41
|
+
export declare function readCodexPolicy(cursor: TranscriptCursor | null): Promise<{
|
|
42
|
+
text: string;
|
|
43
|
+
incomplete?: string;
|
|
44
|
+
instructionsCaptured?: boolean;
|
|
45
|
+
wireCaptured?: boolean;
|
|
46
|
+
scannedBytes?: number;
|
|
47
|
+
totalBytes?: number;
|
|
48
|
+
}>;
|