@koalaauto/agentchannel 3.45.2 → 3.45.3
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/dist/src/adapters/codex.js +4 -0
- package/dist/src/args.d.ts +1 -1
- package/dist/src/args.js +7 -60
- package/dist/src/cli-admin.d.ts +3 -0
- package/dist/src/cli-admin.js +307 -0
- package/dist/src/cli-memory.d.ts +3 -0
- package/dist/src/cli-memory.js +138 -0
- package/dist/src/cli-run.d.ts +28 -0
- package/dist/src/cli-run.js +429 -0
- package/dist/src/cli-shared.d.ts +73 -0
- package/dist/src/cli-shared.js +159 -0
- package/dist/src/cli.d.ts +9 -38
- package/dist/src/cli.js +21 -1181
- package/dist/src/client.d.ts +0 -22
- package/dist/src/client.js +0 -29
- package/dist/src/codexdaemon.d.ts +22 -0
- package/dist/src/codexdaemon.js +68 -0
- package/dist/src/invite_people.d.ts +31 -0
- package/dist/src/invite_people.js +238 -0
- package/dist/src/invite_person.d.ts +1 -1
- package/dist/src/invite_person.js +1 -1
- package/dist/src/mcp.d.ts +1 -1
- package/dist/src/mcp.js +7 -47
- package/dist/src/prompts.d.ts +2 -2
- package/dist/src/prompts.js +6 -17
- package/dist/src/runner/home.d.ts +45 -0
- package/dist/src/runner/home.js +150 -0
- package/dist/src/runner/runner.d.ts +3 -76
- package/dist/src/runner/runner.js +24 -326
- package/dist/src/runner/structured.d.ts +20 -0
- package/dist/src/runner/structured.js +64 -0
- package/dist/src/runner/traces.d.ts +29 -0
- package/dist/src/runner/traces.js +119 -0
- package/dist/src/sandboxcheck.d.ts +3 -0
- package/dist/src/sandboxcheck.js +16 -1
- package/dist/src/version.d.ts +1 -1
- package/dist/src/version.js +1 -1
- package/package.json +1 -1
- package/dist/src/import.d.ts +0 -244
- package/dist/src/import.js +0 -998
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { randomBytes } from 'node:crypto';
|
|
2
|
-
import { appendFileSync,
|
|
2
|
+
import { appendFileSync, mkdirSync, rmSync } from 'node:fs';
|
|
3
3
|
import { tmpdir } from 'node:os';
|
|
4
|
-
import {
|
|
4
|
+
import { join } from 'node:path';
|
|
5
5
|
import { fileURLToPath } from 'node:url';
|
|
6
6
|
import { gitCommonDir } from '../adapters/index.js';
|
|
7
7
|
import { memoryIndex, ownerMemoryDir, projectInstructions } from './context.js';
|
|
@@ -12,7 +12,7 @@ import { developerDir } from '../adapters/scope.js';
|
|
|
12
12
|
import { Client as HubClient, HubError, isTerminal } from '../client.js';
|
|
13
13
|
import { taskFiles } from '../attachments.js';
|
|
14
14
|
import { buildAgentEnv } from '../env.js';
|
|
15
|
-
import {
|
|
15
|
+
import { unlinkWindowsSandbox } from '../codexhome.js';
|
|
16
16
|
import { effectivePerm } from '../perm.js';
|
|
17
17
|
import { ANSWER_SCHEMA, buildAnswerPrompt, buildMentionPrompt, buildPreparePrompt, buildResumePrompt, buildTaskPrompt, postUrl, refOf, REMOTE_FAILED_PREFIX, taskUrl } from '../prompts.js';
|
|
18
18
|
import { RunnerState } from './state.js';
|
|
@@ -21,6 +21,20 @@ import { looksLikeLoginError, quotaProblem, summarizeRuntimeError } from '../env
|
|
|
21
21
|
import { redact } from '../redact.js';
|
|
22
22
|
import { TraceRecorder } from '../trace.js';
|
|
23
23
|
import { looksLikeSandboxError } from '../sandboxcheck.js';
|
|
24
|
+
import { prepareAgentHome, realHomeOf, secretPaths } from './home.js';
|
|
25
|
+
import { draftText, parsePrepared, parseStructured } from './structured.js';
|
|
26
|
+
import { TraceQueue } from './traces.js';
|
|
27
|
+
// moved out; still reachable from here for the code and tests that import them from runner.js
|
|
28
|
+
export * from './home.js';
|
|
29
|
+
export * from './structured.js';
|
|
30
|
+
/** How long the runner trusts its copy of the agent's record before reading it again. */
|
|
31
|
+
const ME_TTL_MS = 60_000;
|
|
32
|
+
/** How long a hub that has no GitHub App is left alone before a run asks it for a token again. */
|
|
33
|
+
const GITHUB_OFF_MS = 10 * 60_000;
|
|
34
|
+
/** The same after a failure that may pass (GitHub down, a setup being fixed). */
|
|
35
|
+
const GITHUB_RETRY_MS = 60_000;
|
|
36
|
+
/** How often a parked run (waiting for an answer) is looked at: an answer reaches it this much later at most. */
|
|
37
|
+
const PARKED_CHECK_MS = 12_000;
|
|
24
38
|
export function jobKey(j) {
|
|
25
39
|
if (j.kind === 'mention')
|
|
26
40
|
return `mention:${j.item.mention.id}`;
|
|
@@ -89,159 +103,6 @@ export function unseenReplies(messages, myId, seen) {
|
|
|
89
103
|
return messages.filter((m) => !seenSet.has(m.id) &&
|
|
90
104
|
(((m.kind === 'answer' || m.kind === 'decision') && ((m.reply_to && mine.has(m.reply_to)) || m.to_agent === myId)) || isHumanNoteTo(m, myId)));
|
|
91
105
|
}
|
|
92
|
-
/**
|
|
93
|
-
* Runner files a spawned agent must never read: the agent key (config.json), other
|
|
94
|
-
* runs' tokens (runs.json), session ids and logs. Not the whole home: the per-task
|
|
95
|
-
* worktrees live in <home>/work and must stay readable.
|
|
96
|
-
*/
|
|
97
|
-
export function secretPaths(home) {
|
|
98
|
-
return ['config.json', 'agent-key', 'admin-session', 'cf-secret', 'runs.json', 'sessions.json', 'logs'].map((f) => join(home, f));
|
|
99
|
-
}
|
|
100
|
-
/**
|
|
101
|
-
* Runtime config a spawned agent's CLI needs from the real home: linked into the
|
|
102
|
-
* scratch home. Claude only: its user settings, hooks and MCP servers are not
|
|
103
|
-
* loaded anyway (settingSources [], strictMcpConfig). Codex is NOT linked: it
|
|
104
|
-
* gets its own CODEX_HOME (see prepareCodexHome).
|
|
105
|
-
*/
|
|
106
|
-
export const RUNTIME_HOME_LINKS = ['.claude', '.claude.json'];
|
|
107
|
-
/**
|
|
108
|
-
* macOS (live test): Claude Code keeps its login in the login keychain, which
|
|
109
|
-
* `security` finds through $HOME/Library/Keychains. Without this link a worker
|
|
110
|
-
* with a scratch HOME reports "Not logged in". Only the folder is linked; the
|
|
111
|
-
* sandbox still denies the worker's tools every path under the real home.
|
|
112
|
-
*/
|
|
113
|
-
export function runtimeHomeLinks(platform = process.platform) {
|
|
114
|
-
return platform === 'darwin' ? [...RUNTIME_HOME_LINKS, 'Library/Keychains'] : RUNTIME_HOME_LINKS;
|
|
115
|
-
}
|
|
116
|
-
/** The config.toml of a worker's own CODEX_HOME: nothing from the user's global config (no mcp_servers, profiles, notify hooks). */
|
|
117
|
-
export const CODEX_WORKER_CONFIG = [
|
|
118
|
-
'# Written by agentchannel for background worker runs. The user\'s global Codex',
|
|
119
|
-
'# config (MCP servers, profiles, hooks, AGENTS.md) is deliberately not used here.',
|
|
120
|
-
'# Model and sandbox are set per run by the runner.',
|
|
121
|
-
'',
|
|
122
|
-
].join('\n');
|
|
123
|
-
/**
|
|
124
|
-
* Codex isolation (live test): a worker run must not load the user's global
|
|
125
|
-
* Codex config (~/.codex/config.toml: MCP servers with their own credentials,
|
|
126
|
-
* profiles, notify hooks, AGENTS.md). The run gets its own CODEX_HOME holding
|
|
127
|
-
* only a generated config.toml and a symlink to the login file (auth.json) of
|
|
128
|
-
* the user's Codex home. The login file is placed by path only: it is never
|
|
129
|
-
* opened or copied here. Codex rewrites it in place through the link, so a
|
|
130
|
-
* refreshed login stays the user's. Sessions of the run stay in this home, so
|
|
131
|
-
* a resumed run of the same task finds its thread.
|
|
132
|
-
*/
|
|
133
|
-
export function prepareCodexHome(home, realCodexHome, platform = process.platform) {
|
|
134
|
-
const dir = join(home, '.codex');
|
|
135
|
-
try {
|
|
136
|
-
// an older scratch home linked the whole ~/.codex: replace the link
|
|
137
|
-
if (lstatSync(dir).isSymbolicLink())
|
|
138
|
-
rmSync(dir);
|
|
139
|
-
}
|
|
140
|
-
catch {
|
|
141
|
-
/* not there */
|
|
142
|
-
}
|
|
143
|
-
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
144
|
-
// Windows: the elevated sandbox, once its one-time setup is done (codexhome.ts)
|
|
145
|
-
const elevated = platform === 'win32' && linkWindowsSandbox(dir, realCodexHome);
|
|
146
|
-
writeFileSync(join(dir, 'config.toml'), CODEX_WORKER_CONFIG + (elevated ? WINDOWS_ELEVATED_CONFIG : ''), { mode: 0o600 });
|
|
147
|
-
if (realCodexHome) {
|
|
148
|
-
const src = join(realCodexHome, 'auth.json');
|
|
149
|
-
const dst = join(dir, 'auth.json');
|
|
150
|
-
let have = false;
|
|
151
|
-
try {
|
|
152
|
-
lstatSync(dst);
|
|
153
|
-
have = true;
|
|
154
|
-
}
|
|
155
|
-
catch {
|
|
156
|
-
/* not there */
|
|
157
|
-
}
|
|
158
|
-
if (!have && existsSync(src)) {
|
|
159
|
-
try {
|
|
160
|
-
symlinkSync(src, dst);
|
|
161
|
-
}
|
|
162
|
-
catch {
|
|
163
|
-
// Windows makes file symlinks only with developer mode or admin; a hard link needs neither
|
|
164
|
-
if (platform === 'win32') {
|
|
165
|
-
try {
|
|
166
|
-
linkSync(src, dst);
|
|
167
|
-
}
|
|
168
|
-
catch {
|
|
169
|
-
/* best effort: codex then reports "not logged in" */
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
}
|
|
175
|
-
return dir;
|
|
176
|
-
}
|
|
177
|
-
/** The user's real home: HOME, or USERPROFILE on Windows, where HOME is usually not set. */
|
|
178
|
-
export function realHomeOf(env, platform = process.platform) {
|
|
179
|
-
return env.HOME || (platform === 'win32' ? env.USERPROFILE : undefined) || undefined;
|
|
180
|
-
}
|
|
181
|
-
/**
|
|
182
|
-
* B1: a per-task scratch HOME for spawned agents, so `~/.config/agentchannel`
|
|
183
|
-
* (agent key file, admin session, runner state) is not reachable through
|
|
184
|
-
* $HOME. Runtime config (.claude, .codex) is linked, the git identity
|
|
185
|
-
* (.gitconfig) copied; npm keeps the real cache via npm_config_cache.
|
|
186
|
-
*/
|
|
187
|
-
export function prepareAgentHome(root, agentName, key, realHome, realCodexHome, platform = process.platform) {
|
|
188
|
-
const safe = (x) => x.replace(/[^A-Za-z0-9_.-]/g, '_').slice(0, 80);
|
|
189
|
-
const home = join(root, safe(agentName), safe(key));
|
|
190
|
-
mkdirSync(home, { recursive: true, mode: 0o700 });
|
|
191
|
-
// the run's own temporary directory, the one place besides its task directory a sandboxed run writes: tools need one, and
|
|
192
|
-
// Claude Code keeps its sandbox's network bridge there (a sandbox that reads only its own paths cannot reach /tmp)
|
|
193
|
-
const tmp = join(home, 'tmp');
|
|
194
|
-
mkdirSync(tmp, { recursive: true, mode: 0o700 });
|
|
195
|
-
const env = { HOME: home, TMPDIR: tmp };
|
|
196
|
-
// Windows programs find the home in USERPROFILE and the temporary directory in TEMP/TMP
|
|
197
|
-
if (platform === 'win32')
|
|
198
|
-
Object.assign(env, { USERPROFILE: home, TEMP: tmp, TMP: tmp });
|
|
199
|
-
if (!realHome) {
|
|
200
|
-
env.CODEX_HOME = prepareCodexHome(home, realCodexHome, platform);
|
|
201
|
-
return { home, env };
|
|
202
|
-
}
|
|
203
|
-
for (const name of runtimeHomeLinks(platform)) {
|
|
204
|
-
const src = join(realHome, name);
|
|
205
|
-
const dst = join(home, name);
|
|
206
|
-
if (!existsSync(src))
|
|
207
|
-
continue;
|
|
208
|
-
try {
|
|
209
|
-
lstatSync(dst);
|
|
210
|
-
}
|
|
211
|
-
catch {
|
|
212
|
-
try {
|
|
213
|
-
mkdirSync(dirname(dst), { recursive: true, mode: 0o700 });
|
|
214
|
-
// a junction links a Windows directory without developer mode or admin
|
|
215
|
-
symlinkSync(src, dst, platform === 'win32' && lstatSync(src).isDirectory() ? 'junction' : undefined);
|
|
216
|
-
}
|
|
217
|
-
catch {
|
|
218
|
-
/* best effort */
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
}
|
|
222
|
-
const git = join(realHome, '.gitconfig');
|
|
223
|
-
if (existsSync(git)) {
|
|
224
|
-
try {
|
|
225
|
-
copyFileSync(git, join(home, '.gitconfig'));
|
|
226
|
-
}
|
|
227
|
-
catch {
|
|
228
|
-
/* best effort */
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
const npmCache = join(realHome, '.npm');
|
|
232
|
-
if (existsSync(npmCache))
|
|
233
|
-
env.npm_config_cache = npmCache;
|
|
234
|
-
env.CODEX_HOME = prepareCodexHome(home, realCodexHome || join(realHome, '.codex'), platform);
|
|
235
|
-
return { home, env };
|
|
236
|
-
}
|
|
237
|
-
/** How long the runner trusts its copy of the agent's record before reading it again. */
|
|
238
|
-
const ME_TTL_MS = 60_000;
|
|
239
|
-
/** How long a hub that has no GitHub App is left alone before a run asks it for a token again. */
|
|
240
|
-
const GITHUB_OFF_MS = 10 * 60_000;
|
|
241
|
-
/** The same after a failure that may pass (GitHub down, a setup being fixed). */
|
|
242
|
-
const GITHUB_RETRY_MS = 60_000;
|
|
243
|
-
/** How often a parked run (waiting for an answer) is looked at: an answer reaches it this much later at most. */
|
|
244
|
-
const PARKED_CHECK_MS = 12_000;
|
|
245
106
|
/** A task handed back this many times for an account limit then fails normally. */
|
|
246
107
|
const QUOTA_RELEASES = 3;
|
|
247
108
|
export function budgetBlocked(me) {
|
|
@@ -282,12 +143,12 @@ export class Runner {
|
|
|
282
143
|
sandboxReported;
|
|
283
144
|
sandboxRecheck = false;
|
|
284
145
|
/** Execution traces the hub has not taken yet (kept on disk too), and the last trace of each task (a commit joins it). */
|
|
285
|
-
|
|
286
|
-
lastTrace = new Map();
|
|
146
|
+
traces;
|
|
287
147
|
constructor(opts) {
|
|
288
148
|
this.o = { max: 2, perm: 'workdir', intervalMs: 3000, heartbeatMs: 30_000, idleMs: 60 * 60_000, ...opts };
|
|
289
149
|
this.state = new RunnerState(opts.home);
|
|
290
|
-
this.
|
|
150
|
+
this.traces = new TraceQueue({ home: this.o.home, client: this.o.client, secrets: this.o.secrets, log: (t, l) => this.taskLog(t, l), unauthorized: () => this.authFailed('trace') });
|
|
151
|
+
this.traces.load();
|
|
291
152
|
}
|
|
292
153
|
log(s) {
|
|
293
154
|
(this.o.log ?? ((x) => console.error(x)))(`[ach run] ${s}`);
|
|
@@ -361,7 +222,7 @@ export class Runner {
|
|
|
361
222
|
}
|
|
362
223
|
await this.checkActive();
|
|
363
224
|
await this.prune();
|
|
364
|
-
await this.
|
|
225
|
+
await this.traces.flush();
|
|
365
226
|
if (this.paused)
|
|
366
227
|
return; // heartbeats of parked runs went out in checkActive; nothing new is taken (it waits in the hub's inbox)
|
|
367
228
|
if (await this.sandboxBlocked())
|
|
@@ -1074,15 +935,7 @@ export class Runner {
|
|
|
1074
935
|
if (sha) {
|
|
1075
936
|
this.taskLog(rec.taskId, `runner committed ${sha}`);
|
|
1076
937
|
// the commit joins the run's trace, so the panel can name what the run produced
|
|
1077
|
-
|
|
1078
|
-
const q = id ? this.traceQueue.get(id) : undefined;
|
|
1079
|
-
if (id && q) {
|
|
1080
|
-
q.body.commit = sha;
|
|
1081
|
-
this.persistTrace(id);
|
|
1082
|
-
}
|
|
1083
|
-
else if (id && this.o.client.putTrace)
|
|
1084
|
-
await this.o.client.putTrace(rec.taskId, id, { commit: sha }).catch((e) => this.taskLog(rec.taskId, `trace commit: ${e?.message ?? e}`));
|
|
1085
|
-
await this.flushTraces();
|
|
938
|
+
await this.traces.addCommit(rec.taskId, sha);
|
|
1086
939
|
}
|
|
1087
940
|
}
|
|
1088
941
|
catch (e) {
|
|
@@ -1686,8 +1539,8 @@ export class Runner {
|
|
|
1686
1539
|
if (!this.fatal)
|
|
1687
1540
|
await usage(runCost, !!result.estimated, { model: result.model, effort: result.effort }).catch((e) => this.log(`usage ${taskId}: ${e?.message ?? e}`));
|
|
1688
1541
|
this.taskLog(taskId, `${mode} run end ok=${result.ok} cost=${result.costUsd ?? 0} model=${result.model ?? '?'} effort=${result.effort ?? '?'} err=${result.error ?? ''}`);
|
|
1689
|
-
if (mode !== 'mention')
|
|
1690
|
-
await this.
|
|
1542
|
+
if (mode !== 'mention' && !this.o.noTrace)
|
|
1543
|
+
await this.traces.add(taskId, rec.runId, mode, startedAt, result, recorder, !this.fatal);
|
|
1691
1544
|
return result;
|
|
1692
1545
|
}
|
|
1693
1546
|
/** decisions §34: the capabilities server of one run, or undefined when nothing is declared (or the run is in the cloud). */
|
|
@@ -1712,99 +1565,6 @@ export class Runner {
|
|
|
1712
1565
|
};
|
|
1713
1566
|
}
|
|
1714
1567
|
// ---- the execution trace -------------------------------------------------------------------------------------------------
|
|
1715
|
-
traceDir() {
|
|
1716
|
-
return join(this.o.home, 'traces');
|
|
1717
|
-
}
|
|
1718
|
-
/** Traces an earlier process could not upload are tried again. */
|
|
1719
|
-
loadPendingTraces() {
|
|
1720
|
-
try {
|
|
1721
|
-
for (const f of readdirSync(this.traceDir())) {
|
|
1722
|
-
if (!f.endsWith('.json'))
|
|
1723
|
-
continue;
|
|
1724
|
-
const j = JSON.parse(readFileSync(join(this.traceDir(), f), 'utf8'));
|
|
1725
|
-
if (j?.taskId && j?.traceId && j?.body)
|
|
1726
|
-
this.traceQueue.set(j.traceId, { taskId: j.taskId, body: j.body });
|
|
1727
|
-
}
|
|
1728
|
-
}
|
|
1729
|
-
catch {
|
|
1730
|
-
/* none */
|
|
1731
|
-
}
|
|
1732
|
-
}
|
|
1733
|
-
/** Build and send the trace of the run that just ended. Never throws; a failed upload is kept and retried. */
|
|
1734
|
-
async uploadTrace(taskId, runId, mode, startedAt, result, recorder, send) {
|
|
1735
|
-
if (!this.o.client.putTrace || this.o.noTrace)
|
|
1736
|
-
return;
|
|
1737
|
-
try {
|
|
1738
|
-
const { steps, omitted } = recorder.finish();
|
|
1739
|
-
if (!steps.length && result.ok)
|
|
1740
|
-
return; // nothing happened worth auditing
|
|
1741
|
-
const traceId = `tr_${randomBytes(9).toString('base64url')}`;
|
|
1742
|
-
const body = {
|
|
1743
|
-
run_id: runId, mode, started: startedAt.toISOString(), ended: new Date().toISOString(), ok: !!result.ok,
|
|
1744
|
-
...(result.error ? { error: redact(summarizeRuntimeError(result.error), [...(this.o.secrets ?? [])]).slice(0, 600) } : {}),
|
|
1745
|
-
steps, omitted,
|
|
1746
|
-
};
|
|
1747
|
-
this.lastTrace.set(taskId, traceId);
|
|
1748
|
-
this.traceQueue.set(traceId, { taskId, body });
|
|
1749
|
-
this.persistTrace(traceId);
|
|
1750
|
-
if (send)
|
|
1751
|
-
await this.flushTraces();
|
|
1752
|
-
}
|
|
1753
|
-
catch (e) {
|
|
1754
|
-
this.taskLog(taskId, `trace: ${e?.message ?? e}`);
|
|
1755
|
-
}
|
|
1756
|
-
}
|
|
1757
|
-
persistTrace(traceId) {
|
|
1758
|
-
const q = this.traceQueue.get(traceId);
|
|
1759
|
-
if (!q)
|
|
1760
|
-
return;
|
|
1761
|
-
try {
|
|
1762
|
-
mkdirSync(this.traceDir(), { recursive: true, mode: 0o700 });
|
|
1763
|
-
writeFileSync(join(this.traceDir(), `${traceId}.json`), JSON.stringify({ traceId, ...q }), { mode: 0o600 });
|
|
1764
|
-
}
|
|
1765
|
-
catch {
|
|
1766
|
-
/* kept in memory */
|
|
1767
|
-
}
|
|
1768
|
-
}
|
|
1769
|
-
/** Send what is waiting (a few at a time). A trace never holds up a task: failures are logged and tried again on the next poll. */
|
|
1770
|
-
async flushTraces() {
|
|
1771
|
-
const put = this.o.client.putTrace;
|
|
1772
|
-
if (!put || !this.traceQueue.size)
|
|
1773
|
-
return;
|
|
1774
|
-
let n = 0;
|
|
1775
|
-
for (const [id, q] of [...this.traceQueue]) {
|
|
1776
|
-
if (n++ >= 5)
|
|
1777
|
-
break;
|
|
1778
|
-
try {
|
|
1779
|
-
await put.call(this.o.client, q.taskId, id, q.body);
|
|
1780
|
-
this.traceQueue.delete(id);
|
|
1781
|
-
try {
|
|
1782
|
-
unlinkSync(join(this.traceDir(), `${id}.json`));
|
|
1783
|
-
}
|
|
1784
|
-
catch {
|
|
1785
|
-
/* already gone */
|
|
1786
|
-
}
|
|
1787
|
-
}
|
|
1788
|
-
catch (e) {
|
|
1789
|
-
const code = e instanceof HubError ? e.status : 0;
|
|
1790
|
-
if (is401(e))
|
|
1791
|
-
return this.authFailed('trace');
|
|
1792
|
-
// an older hub (404), a task that is gone or not ours (403/404/409): not worth keeping
|
|
1793
|
-
if (code === 404 || code === 403 || code === 409 || code === 400) {
|
|
1794
|
-
this.traceQueue.delete(id);
|
|
1795
|
-
try {
|
|
1796
|
-
unlinkSync(join(this.traceDir(), `${id}.json`));
|
|
1797
|
-
}
|
|
1798
|
-
catch {
|
|
1799
|
-
/* */
|
|
1800
|
-
}
|
|
1801
|
-
this.taskLog(q.taskId, `trace not taken (${code}): ${e?.message ?? e}`);
|
|
1802
|
-
}
|
|
1803
|
-
else
|
|
1804
|
-
this.taskLog(q.taskId, `trace upload failed, will retry: ${e?.message ?? e}`);
|
|
1805
|
-
}
|
|
1806
|
-
}
|
|
1807
|
-
}
|
|
1808
1568
|
/** Polls until stop() or a 401 (B7: resolves 'unauthorized' after aborting every job). */
|
|
1809
1569
|
async start() {
|
|
1810
1570
|
this.recover();
|
|
@@ -1896,65 +1656,3 @@ function promptFile(f) {
|
|
|
1896
1656
|
const { key: _key, ...rest } = f;
|
|
1897
1657
|
return rest;
|
|
1898
1658
|
}
|
|
1899
|
-
/**
|
|
1900
|
-
* The JSON object a structured run ended with. Codex returns it bare (outputSchema); a remote run's final message may
|
|
1901
|
-
* wrap it in a ```json fence or a sentence, so the last {...} in the text is taken. Throws when there is none.
|
|
1902
|
-
*/
|
|
1903
|
-
export function parseStructured(text) {
|
|
1904
|
-
const t = text.trim();
|
|
1905
|
-
try {
|
|
1906
|
-
return JSON.parse(t);
|
|
1907
|
-
}
|
|
1908
|
-
catch {
|
|
1909
|
-
/* not bare JSON */
|
|
1910
|
-
}
|
|
1911
|
-
const fenced = t.match(/```(?:json)?\s*([\s\S]*?)```/g);
|
|
1912
|
-
for (const f of (fenced ?? []).reverse()) {
|
|
1913
|
-
try {
|
|
1914
|
-
return JSON.parse(f.replace(/^```(?:json)?\s*/, '').replace(/```$/, '').trim());
|
|
1915
|
-
}
|
|
1916
|
-
catch {
|
|
1917
|
-
/* next */
|
|
1918
|
-
}
|
|
1919
|
-
}
|
|
1920
|
-
const start = t.lastIndexOf('{"action"');
|
|
1921
|
-
if (start >= 0) {
|
|
1922
|
-
const end = t.lastIndexOf('}');
|
|
1923
|
-
if (end > start)
|
|
1924
|
-
return JSON.parse(t.slice(start, end + 1));
|
|
1925
|
-
}
|
|
1926
|
-
throw new Error('no JSON object');
|
|
1927
|
-
}
|
|
1928
|
-
/** The read-ahead's final JSON object: the last one in its message (bare, fenced, or after a sentence). Throws when there is none. */
|
|
1929
|
-
export function parsePrepared(text) {
|
|
1930
|
-
const t = text.trim();
|
|
1931
|
-
const tries = [t];
|
|
1932
|
-
for (const f of (t.match(/```(?:json)?\s*([\s\S]*?)```/g) ?? []).reverse())
|
|
1933
|
-
tries.push(f.replace(/^```(?:json)?\s*/, '').replace(/```$/, '').trim());
|
|
1934
|
-
const start = t.lastIndexOf('{"code"');
|
|
1935
|
-
if (start >= 0)
|
|
1936
|
-
tries.push(t.slice(start, t.lastIndexOf('}') + 1));
|
|
1937
|
-
for (const x of tries) {
|
|
1938
|
-
let j;
|
|
1939
|
-
try {
|
|
1940
|
-
j = JSON.parse(x);
|
|
1941
|
-
}
|
|
1942
|
-
catch {
|
|
1943
|
-
continue;
|
|
1944
|
-
}
|
|
1945
|
-
if (!j || typeof j !== 'object' || typeof j.code !== 'boolean')
|
|
1946
|
-
continue;
|
|
1947
|
-
const list = (v) => (Array.isArray(v) ? v.map((s) => String(s).trim()).filter(Boolean) : []);
|
|
1948
|
-
return { code: j.code, files: list(j.files).slice(0, 200), plan: String(j.plan ?? '').trim(), questions: list(j.questions).slice(0, 20) };
|
|
1949
|
-
}
|
|
1950
|
-
throw new Error('no JSON object with "code"');
|
|
1951
|
-
}
|
|
1952
|
-
/** The draft as the owner reads it on the task: the plan, the files, the questions, and the small-job rule it fell inside. */
|
|
1953
|
-
export function draftText(o, rule) {
|
|
1954
|
-
return [
|
|
1955
|
-
o.plan || (o.code ? '(no plan given)' : 'No code change.'),
|
|
1956
|
-
...(o.files.length ? ['', 'Files:', ...o.files.map((f) => `- ${f}`)] : []),
|
|
1957
|
-
...(o.questions.length ? ['', 'Questions for the sender:', ...o.questions.map((q) => `- ${q}`)] : []),
|
|
1958
|
-
...(rule ? ['', `Small job (autorun.json): ${rule}`] : []),
|
|
1959
|
-
].join('\n');
|
|
1960
|
-
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The JSON object a structured run ended with. Codex returns it bare (outputSchema); a remote run's final message may
|
|
3
|
+
* wrap it in a ```json fence or a sentence, so the last {...} in the text is taken. Throws when there is none.
|
|
4
|
+
*/
|
|
5
|
+
export declare function parseStructured(text: string): {
|
|
6
|
+
action?: string;
|
|
7
|
+
text?: string;
|
|
8
|
+
evidence?: string;
|
|
9
|
+
};
|
|
10
|
+
/** What a read-ahead found (its final JSON object). */
|
|
11
|
+
export interface PrepareOut {
|
|
12
|
+
code: boolean;
|
|
13
|
+
files: string[];
|
|
14
|
+
plan: string;
|
|
15
|
+
questions: string[];
|
|
16
|
+
}
|
|
17
|
+
/** The read-ahead's final JSON object: the last one in its message (bare, fenced, or after a sentence). Throws when there is none. */
|
|
18
|
+
export declare function parsePrepared(text: string): PrepareOut;
|
|
19
|
+
/** The draft as the owner reads it on the task: the plan, the files, the questions, and the small-job rule it fell inside. */
|
|
20
|
+
export declare function draftText(o: PrepareOut, rule: string): string;
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
// What a structured run ends with: the JSON a read-only run answers in, and the draft a read-ahead writes for whoever does the
|
|
2
|
+
// work. Parsing only.
|
|
3
|
+
/**
|
|
4
|
+
* The JSON object a structured run ended with. Codex returns it bare (outputSchema); a remote run's final message may
|
|
5
|
+
* wrap it in a ```json fence or a sentence, so the last {...} in the text is taken. Throws when there is none.
|
|
6
|
+
*/
|
|
7
|
+
export function parseStructured(text) {
|
|
8
|
+
const t = text.trim();
|
|
9
|
+
try {
|
|
10
|
+
return JSON.parse(t);
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
/* not bare JSON */
|
|
14
|
+
}
|
|
15
|
+
const fenced = t.match(/```(?:json)?\s*([\s\S]*?)```/g);
|
|
16
|
+
for (const f of (fenced ?? []).reverse()) {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(f.replace(/^```(?:json)?\s*/, '').replace(/```$/, '').trim());
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
/* next */
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const start = t.lastIndexOf('{"action"');
|
|
25
|
+
if (start >= 0) {
|
|
26
|
+
const end = t.lastIndexOf('}');
|
|
27
|
+
if (end > start)
|
|
28
|
+
return JSON.parse(t.slice(start, end + 1));
|
|
29
|
+
}
|
|
30
|
+
throw new Error('no JSON object');
|
|
31
|
+
}
|
|
32
|
+
/** The read-ahead's final JSON object: the last one in its message (bare, fenced, or after a sentence). Throws when there is none. */
|
|
33
|
+
export function parsePrepared(text) {
|
|
34
|
+
const t = text.trim();
|
|
35
|
+
const tries = [t];
|
|
36
|
+
for (const f of (t.match(/```(?:json)?\s*([\s\S]*?)```/g) ?? []).reverse())
|
|
37
|
+
tries.push(f.replace(/^```(?:json)?\s*/, '').replace(/```$/, '').trim());
|
|
38
|
+
const start = t.lastIndexOf('{"code"');
|
|
39
|
+
if (start >= 0)
|
|
40
|
+
tries.push(t.slice(start, t.lastIndexOf('}') + 1));
|
|
41
|
+
for (const x of tries) {
|
|
42
|
+
let j;
|
|
43
|
+
try {
|
|
44
|
+
j = JSON.parse(x);
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
continue;
|
|
48
|
+
}
|
|
49
|
+
if (!j || typeof j !== 'object' || typeof j.code !== 'boolean')
|
|
50
|
+
continue;
|
|
51
|
+
const list = (v) => (Array.isArray(v) ? v.map((s) => String(s).trim()).filter(Boolean) : []);
|
|
52
|
+
return { code: j.code, files: list(j.files).slice(0, 200), plan: String(j.plan ?? '').trim(), questions: list(j.questions).slice(0, 20) };
|
|
53
|
+
}
|
|
54
|
+
throw new Error('no JSON object with "code"');
|
|
55
|
+
}
|
|
56
|
+
/** The draft as the owner reads it on the task: the plan, the files, the questions, and the small-job rule it fell inside. */
|
|
57
|
+
export function draftText(o, rule) {
|
|
58
|
+
return [
|
|
59
|
+
o.plan || (o.code ? '(no plan given)' : 'No code change.'),
|
|
60
|
+
...(o.files.length ? ['', 'Files:', ...o.files.map((f) => `- ${f}`)] : []),
|
|
61
|
+
...(o.questions.length ? ['', 'Questions for the sender:', ...o.questions.map((q) => `- ${q}`)] : []),
|
|
62
|
+
...(rule ? ['', `Small job (autorun.json): ${rule}`] : []),
|
|
63
|
+
].join('\n');
|
|
64
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { AdapterResult, RunMode } from '../adapters/types.js';
|
|
2
|
+
import { type Client } from '../client.js';
|
|
3
|
+
import type { TraceRecorder } from '../trace.js';
|
|
4
|
+
export declare class TraceQueue {
|
|
5
|
+
private o;
|
|
6
|
+
private queue;
|
|
7
|
+
/** The trace of each task's last run (a commit made after it is added to it). */
|
|
8
|
+
private last;
|
|
9
|
+
constructor(o: {
|
|
10
|
+
home: string;
|
|
11
|
+
client: Partial<Pick<Client, 'putTrace'>>;
|
|
12
|
+
secrets?: readonly string[];
|
|
13
|
+
/** a task's own log line */
|
|
14
|
+
log: (taskId: string, line: string) => void;
|
|
15
|
+
/** the hub refused the agent's key */
|
|
16
|
+
unauthorized: () => void;
|
|
17
|
+
});
|
|
18
|
+
private dir;
|
|
19
|
+
/** Traces an earlier process could not upload are tried again. */
|
|
20
|
+
load(): void;
|
|
21
|
+
/** Builds the trace of the run that just ended and queues it (sends it when `send`). Never throws. */
|
|
22
|
+
add(taskId: string, runId: string, mode: RunMode, startedAt: Date, result: AdapterResult, recorder: TraceRecorder, send: boolean): Promise<void>;
|
|
23
|
+
/** The commit a task's last run produced joins that run's trace, so the panel can name what the run made. */
|
|
24
|
+
addCommit(taskId: string, sha: string): Promise<void>;
|
|
25
|
+
private persist;
|
|
26
|
+
private drop;
|
|
27
|
+
/** Sends what is waiting (a few at a time). Failures are logged and tried again on the next poll. */
|
|
28
|
+
flush(): Promise<void>;
|
|
29
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
// The traces of runs (what each step did), queued for the hub: kept on disk so a run's trace survives a restart, sent a few at
|
|
2
|
+
// a time, and dropped when the hub will never take them. A trace never holds up a task.
|
|
3
|
+
import { randomBytes } from 'node:crypto';
|
|
4
|
+
import { mkdirSync, readdirSync, readFileSync, unlinkSync, writeFileSync } from 'node:fs';
|
|
5
|
+
import { join } from 'node:path';
|
|
6
|
+
import { HubError } from '../client.js';
|
|
7
|
+
import { summarizeRuntimeError } from '../envcheck.js';
|
|
8
|
+
import { redact } from '../redact.js';
|
|
9
|
+
export class TraceQueue {
|
|
10
|
+
o;
|
|
11
|
+
queue = new Map();
|
|
12
|
+
/** The trace of each task's last run (a commit made after it is added to it). */
|
|
13
|
+
last = new Map();
|
|
14
|
+
constructor(o) {
|
|
15
|
+
this.o = o;
|
|
16
|
+
}
|
|
17
|
+
dir() {
|
|
18
|
+
return join(this.o.home, 'traces');
|
|
19
|
+
}
|
|
20
|
+
/** Traces an earlier process could not upload are tried again. */
|
|
21
|
+
load() {
|
|
22
|
+
try {
|
|
23
|
+
for (const f of readdirSync(this.dir())) {
|
|
24
|
+
if (!f.endsWith('.json'))
|
|
25
|
+
continue;
|
|
26
|
+
const j = JSON.parse(readFileSync(join(this.dir(), f), 'utf8'));
|
|
27
|
+
if (j?.taskId && j?.traceId && j?.body)
|
|
28
|
+
this.queue.set(j.traceId, { taskId: j.taskId, body: j.body });
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
/* none */
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
/** Builds the trace of the run that just ended and queues it (sends it when `send`). Never throws. */
|
|
36
|
+
async add(taskId, runId, mode, startedAt, result, recorder, send) {
|
|
37
|
+
if (!this.o.client.putTrace)
|
|
38
|
+
return;
|
|
39
|
+
try {
|
|
40
|
+
const { steps, omitted } = recorder.finish();
|
|
41
|
+
if (!steps.length && result.ok)
|
|
42
|
+
return; // nothing happened worth auditing
|
|
43
|
+
const traceId = `tr_${randomBytes(9).toString('base64url')}`;
|
|
44
|
+
const body = {
|
|
45
|
+
run_id: runId, mode, started: startedAt.toISOString(), ended: new Date().toISOString(), ok: !!result.ok,
|
|
46
|
+
...(result.error ? { error: redact(summarizeRuntimeError(result.error), [...(this.o.secrets ?? [])]).slice(0, 600) } : {}),
|
|
47
|
+
steps, omitted,
|
|
48
|
+
};
|
|
49
|
+
this.last.set(taskId, traceId);
|
|
50
|
+
this.queue.set(traceId, { taskId, body });
|
|
51
|
+
this.persist(traceId);
|
|
52
|
+
if (send)
|
|
53
|
+
await this.flush();
|
|
54
|
+
}
|
|
55
|
+
catch (e) {
|
|
56
|
+
this.o.log(taskId, `trace: ${e?.message ?? e}`);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** The commit a task's last run produced joins that run's trace, so the panel can name what the run made. */
|
|
60
|
+
async addCommit(taskId, sha) {
|
|
61
|
+
const id = this.last.get(taskId);
|
|
62
|
+
const q = id ? this.queue.get(id) : undefined;
|
|
63
|
+
if (id && q) {
|
|
64
|
+
q.body.commit = sha;
|
|
65
|
+
this.persist(id);
|
|
66
|
+
}
|
|
67
|
+
else if (id && this.o.client.putTrace)
|
|
68
|
+
await this.o.client.putTrace(taskId, id, { commit: sha }).catch((e) => this.o.log(taskId, `trace commit: ${e?.message ?? e}`));
|
|
69
|
+
await this.flush();
|
|
70
|
+
}
|
|
71
|
+
persist(traceId) {
|
|
72
|
+
const q = this.queue.get(traceId);
|
|
73
|
+
if (!q)
|
|
74
|
+
return;
|
|
75
|
+
try {
|
|
76
|
+
mkdirSync(this.dir(), { recursive: true, mode: 0o700 });
|
|
77
|
+
writeFileSync(join(this.dir(), `${traceId}.json`), JSON.stringify({ traceId, ...q }), { mode: 0o600 });
|
|
78
|
+
}
|
|
79
|
+
catch {
|
|
80
|
+
/* kept in memory */
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
drop(id) {
|
|
84
|
+
this.queue.delete(id);
|
|
85
|
+
try {
|
|
86
|
+
unlinkSync(join(this.dir(), `${id}.json`));
|
|
87
|
+
}
|
|
88
|
+
catch {
|
|
89
|
+
/* already gone */
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
/** Sends what is waiting (a few at a time). Failures are logged and tried again on the next poll. */
|
|
93
|
+
async flush() {
|
|
94
|
+
const put = this.o.client.putTrace;
|
|
95
|
+
if (!put || !this.queue.size)
|
|
96
|
+
return;
|
|
97
|
+
let n = 0;
|
|
98
|
+
for (const [id, q] of [...this.queue]) {
|
|
99
|
+
if (n++ >= 5)
|
|
100
|
+
break;
|
|
101
|
+
try {
|
|
102
|
+
await put.call(this.o.client, q.taskId, id, q.body);
|
|
103
|
+
this.drop(id);
|
|
104
|
+
}
|
|
105
|
+
catch (e) {
|
|
106
|
+
const code = e instanceof HubError ? e.status : 0;
|
|
107
|
+
if (code === 401)
|
|
108
|
+
return this.o.unauthorized();
|
|
109
|
+
// an older hub (404), a task that is gone or not ours (403/404/409): not worth keeping
|
|
110
|
+
if (code === 404 || code === 403 || code === 409 || code === 400) {
|
|
111
|
+
this.drop(id);
|
|
112
|
+
this.o.log(q.taskId, `trace not taken (${code}): ${e?.message ?? e}`);
|
|
113
|
+
}
|
|
114
|
+
else
|
|
115
|
+
this.o.log(q.taskId, `trace upload failed, will retry: ${e?.message ?? e}`);
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { type CodexDaemonDir } from './codexdaemon.js';
|
|
1
2
|
/**
|
|
2
3
|
* decisions §27: does the agent tool's sandbox work on this machine?
|
|
3
4
|
*
|
|
@@ -113,6 +114,8 @@ export interface ProbeOptions {
|
|
|
113
114
|
runEnv?: NodeJS.ProcessEnv;
|
|
114
115
|
/** the user's own Codex home (default: CODEX_HOME, else ~/.codex): where Windows keeps the elevated sandbox setup */
|
|
115
116
|
codexHome?: string;
|
|
117
|
+
/** puts Codex's socket folder right first (codexdaemon.ts). Default: the real one, unless `run` is a stand-in */
|
|
118
|
+
codexDaemon?: () => CodexDaemonDir | null;
|
|
116
119
|
}
|
|
117
120
|
/** Probe `tool`'s sandbox on this machine. Never throws. */
|
|
118
121
|
export declare function probeSandbox(tool: SandboxTool, o?: ProbeOptions): Promise<SandboxStatus>;
|