@dreamlake/dreamlake-cli 0.98.0 → 0.99.0
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/api/index.d.ts +212 -10
- package/dist/api/index.js +6 -0
- package/dist/api/native-experiments.d.ts +77 -0
- package/dist/api/native-experiments.js +31 -0
- package/dist/api/sessions.d.ts +240 -7
- package/dist/api/sessions.js +56 -1
- package/dist/api/skills.d.ts +122 -0
- package/dist/api/skills.js +220 -0
- package/dist/cli/experiments/index.js +2 -0
- package/dist/cli/experiments/native-commands.d.ts +13 -0
- package/dist/cli/experiments/native-commands.js +88 -0
- package/dist/cli/help-examples.generated.js +22 -5
- package/dist/cli/index.js +2 -0
- package/dist/cli/session-affiliation.js +3 -2
- package/dist/cli/sessions/affiliation.d.ts +12 -1
- package/dist/cli/sessions/affiliation.js +37 -0
- package/dist/cli/sessions/control.d.ts +11 -0
- package/dist/cli/sessions/control.js +49 -4
- package/dist/cli/sessions/index.js +70 -17
- package/dist/cli/sessions/live.d.ts +85 -0
- package/dist/cli/sessions/live.js +258 -0
- package/dist/cli/sessions/runner/exec.d.ts +118 -6
- package/dist/cli/sessions/runner/exec.js +298 -47
- package/dist/cli/sessions/runner/native.js +4 -1
- package/dist/cli/sessions/runner/serve.d.ts +37 -2
- package/dist/cli/sessions/runner/serve.js +273 -28
- package/dist/cli/sessions/wrap.d.ts +63 -0
- package/dist/cli/sessions/wrap.js +226 -0
- package/dist/cli/skill/index.d.ts +19 -1
- package/dist/cli/skill/index.js +65 -12
- package/dist/cli/skill/read.d.ts +25 -0
- package/dist/cli/skill/read.js +65 -0
- package/dist/cli/skill/registry.d.ts +95 -0
- package/dist/cli/skill/registry.js +284 -0
- package/dist/cli/skill/reminders.js +2 -1
- package/dist/cli/version.d.ts +1 -1
- package/dist/cli/version.js +1 -1
- package/package.json +9 -9
|
@@ -8,9 +8,11 @@
|
|
|
8
8
|
import { spawn } from 'node:child_process';
|
|
9
9
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
10
10
|
import { createHash, randomUUID } from 'node:crypto';
|
|
11
|
-
import { mkdirSync, existsSync, statSync } from 'node:fs';
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
11
|
+
import { mkdirSync, existsSync, readFileSync, realpathSync, statSync, writeFileSync } from 'node:fs';
|
|
12
|
+
import { homedir } from 'node:os';
|
|
13
|
+
import { basename, join, resolve, sep } from 'node:path';
|
|
14
|
+
import { claudePermissionMode, codexSandbox, defaultRoots, tmuxSessionName } from './native.js';
|
|
15
|
+
import { redactSessionText } from '../redaction.js';
|
|
14
16
|
const OUTPUT_LIMIT = 2 * 1024 * 1024;
|
|
15
17
|
/** Default process runner: own process group, bounded output and time, killable through `signal`. */
|
|
16
18
|
export const run = (command, args, options = {}) => new Promise(resolve => {
|
|
@@ -58,37 +60,80 @@ export const run = (command, args, options = {}) => new Promise(resolve => {
|
|
|
58
60
|
else
|
|
59
61
|
child.stdin.end();
|
|
60
62
|
});
|
|
63
|
+
/** `checkpoint` is what is known about a side effect; `detail` is why it failed (exit code, signal, bounded
|
|
64
|
+
* and redacted output tails), so a receipt carries the underlying error text and not only a code. */
|
|
61
65
|
export class RunnerError extends Error {
|
|
62
66
|
code;
|
|
63
67
|
uncertain;
|
|
64
68
|
checkpoint;
|
|
65
|
-
|
|
69
|
+
detail;
|
|
70
|
+
constructor(code, message, uncertain = false, checkpoint = {}, detail = {}) {
|
|
66
71
|
super(message ?? code);
|
|
67
72
|
this.code = code;
|
|
68
73
|
this.uncertain = uncertain;
|
|
69
74
|
this.checkpoint = checkpoint;
|
|
75
|
+
this.detail = detail;
|
|
70
76
|
}
|
|
71
77
|
}
|
|
78
|
+
const OUTPUT_TAIL = 2000;
|
|
79
|
+
/** Redaction runs over the whole (bounded) stream first and the tail is cut from the result: cut first,
|
|
80
|
+
* and a value longer than the tail loses the `password=` / `Authorization:` prefix that identifies it. */
|
|
81
|
+
const tail = (text) => { const trimmed = text.trim(); return trimmed ? redactSessionText(trimmed).slice(-OUTPUT_TAIL) : undefined; };
|
|
82
|
+
/** The most useful one-line text of a failed provider run: stderr, else the `result` of Claude's JSON answer, else stdout. */
|
|
83
|
+
const failureText = (result) => {
|
|
84
|
+
if (result.stderr.trim())
|
|
85
|
+
return result.stderr.trim();
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(result.stdout);
|
|
88
|
+
if (typeof parsed?.result === 'string' && parsed.result.trim())
|
|
89
|
+
return parsed.result.trim();
|
|
90
|
+
}
|
|
91
|
+
catch { /* not a JSON answer */ }
|
|
92
|
+
return result.stdout.trim();
|
|
93
|
+
};
|
|
72
94
|
/** A provider that ran at all may have edited files or written its transcript before failing:
|
|
73
95
|
* a nonzero exit is an uncertain effect. Only a process that never started is a plain failure. */
|
|
74
96
|
const failed = (result, code, checkpoint = {}) => {
|
|
75
97
|
// Only a process that never spawned is a plain failure; one killed by a signal still ran.
|
|
76
98
|
const neverRan = result.spawned === false || (result.spawned === undefined && result.code === null && !result.signal && !result.timedOut && !result.aborted);
|
|
77
|
-
|
|
99
|
+
const stderrTail = tail(result.stderr), stdoutTail = tail(result.stdout);
|
|
100
|
+
const detail = { exitCode: result.code, signal: result.signal ?? null, timedOut: result.timedOut, ...(stderrTail ? { stderrTail } : {}), ...(stdoutTail ? { stdoutTail } : {}) };
|
|
101
|
+
return new RunnerError(result.aborted ? 'cancelled' : result.timedOut ? 'provider_timeout' : neverRan ? 'provider_unavailable' : code, redactSessionText(failureText(result)).slice(0, 500), !neverRan, checkpoint, detail);
|
|
78
102
|
};
|
|
79
103
|
export async function hasTmux(exec) { return (await exec('tmux', ['-V'], { timeoutMs: 5000 })).code === 0; }
|
|
80
104
|
export async function tmuxAlive(exec, name) { return (await exec('tmux', ['has-session', '-t', `=${name}`], { timeoutMs: 5000 })).code === 0; }
|
|
81
105
|
/** The owner marker is written by this runner at creation; a session with another or no marker is not ours to type into or kill. */
|
|
82
106
|
export const ownerMarker = (runnerKey, nativeSessionId) => createHash('sha256').update(JSON.stringify(['dreamlake-runner', runnerKey, nativeSessionId])).digest('hex').slice(0, 32);
|
|
83
|
-
|
|
84
|
-
|
|
107
|
+
// Pane-target commands need the session separator: =name: resolves the current pane
|
|
108
|
+
// of that exact session; =name alone is only valid for target-session commands.
|
|
109
|
+
/** `policy` records the permission level the process was launched under (`@dreamlake_policy`), so a later
|
|
110
|
+
* resume or send can tell whether the live process still matches the authorized level. */
|
|
111
|
+
export async function markOwnership(exec, name, marker, policy) {
|
|
112
|
+
const set = await exec('tmux', ['set-option', '-t', `=${name}:`, '@dreamlake_runner', marker, ';', 'set-option', '-F', '-t', `=${name}:`, '@dreamlake_pane', '#{pane_id}:#{pane_pid}', ...(policy ? [';', 'set-option', '-t', `=${name}:`, '@dreamlake_policy', policy] : [])], { timeoutMs: 5000 });
|
|
85
113
|
if (set.code !== 0)
|
|
86
114
|
throw new RunnerError('tmux_mark_failed', set.stderr.trim(), true, { tmuxSession: name });
|
|
87
115
|
}
|
|
116
|
+
const LEVELS = ['read-only', 'workspace-write', 'full-access'];
|
|
117
|
+
/** The level an owned tmux session's process was launched under, or `null` when it was not recorded (a
|
|
118
|
+
* session launched by an older runner) — which is not proof of anything, and is treated as such. */
|
|
119
|
+
export async function livePolicy(exec, name) {
|
|
120
|
+
const shown = await exec('tmux', ['display-message', '-p', '-t', `=${name}:`, '#{@dreamlake_policy}'], { timeoutMs: 5000 });
|
|
121
|
+
const value = shown.stdout.trim();
|
|
122
|
+
return shown.code === 0 && LEVELS.includes(value) ? value : null;
|
|
123
|
+
}
|
|
124
|
+
/** Refuses to type into a live process whose launch level is not the authorized one. Equal: proceed.
|
|
125
|
+
* Different: the caller relaunches at the authorized level. Unknown: refused, a restart is the way out. */
|
|
126
|
+
export function assertLivePolicy(live, authorized) {
|
|
127
|
+
if (live === authorized)
|
|
128
|
+
return 'matches';
|
|
129
|
+
if (live === null)
|
|
130
|
+
throw new RunnerError('permission_unverified_restart_required', `The live session does not record the level its process was launched under, so it cannot be used at ${authorized}; run control restart --permission ${authorized} to relaunch it.`);
|
|
131
|
+
return 'relaunch';
|
|
132
|
+
}
|
|
88
133
|
export async function verifyOwnership(exec, name, marker) {
|
|
89
134
|
if (!await tmuxAlive(exec, name))
|
|
90
135
|
return 'absent';
|
|
91
|
-
const shown = await exec('tmux', ['display-message', '-p', '-t', `=${name}
|
|
136
|
+
const shown = await exec('tmux', ['display-message', '-p', '-t', `=${name}:`, '#{@dreamlake_runner}|#{pane_id}|#{pane_pid}|#{@dreamlake_pane}|#{session_windows}|#{window_panes}'], { timeoutMs: 5000 });
|
|
92
137
|
if (shown.code !== 0)
|
|
93
138
|
return 'foreign';
|
|
94
139
|
const [owner, pane, pid, bound, windows, panes] = shown.stdout.trim().split('|');
|
|
@@ -114,11 +159,11 @@ export async function tmuxSend(exec, name, marker, text, signal) {
|
|
|
114
159
|
if (loaded.code !== 0)
|
|
115
160
|
throw new RunnerError('tmux_send_failed', loaded.stderr.trim());
|
|
116
161
|
pasteAttempted = true;
|
|
117
|
-
const pasted = await exec('tmux', ['paste-buffer', '-p', '-d', '-b', buffer, '-t', `=${name}
|
|
162
|
+
const pasted = await exec('tmux', ['paste-buffer', '-p', '-d', '-b', buffer, '-t', `=${name}:`], { timeoutMs: 5000, signal });
|
|
118
163
|
checkCancelled();
|
|
119
164
|
if (pasted.code !== 0)
|
|
120
165
|
throw new RunnerError('tmux_send_failed', pasted.stderr.trim(), true, { pasteAttempted });
|
|
121
|
-
const result = await exec('tmux', ['send-keys', '-t', `=${name}
|
|
166
|
+
const result = await exec('tmux', ['send-keys', '-t', `=${name}:`, 'Enter'], { timeoutMs: 5000, signal });
|
|
122
167
|
submitted = result.code === 0;
|
|
123
168
|
checkCancelled();
|
|
124
169
|
if (result.code !== 0)
|
|
@@ -143,7 +188,10 @@ export async function tmuxStop(exec, name, marker) {
|
|
|
143
188
|
throw new RunnerError('tmux_stop_unverified', undefined, true);
|
|
144
189
|
return true;
|
|
145
190
|
}
|
|
146
|
-
/** A fresh worktree next to the user's other DreamLake worktrees, never inside the source checkout.
|
|
191
|
+
/** A fresh worktree next to the user's other DreamLake worktrees, never inside the source checkout.
|
|
192
|
+
* `prepared` receives the record (path, branch, whether the branch is new, its starting tip) just before
|
|
193
|
+
* `git worktree add`: an add that is cancelled or times out may already have registered the worktree and
|
|
194
|
+
* created the branch, and that record is what lets the caller reconcile such a partial creation. */
|
|
147
195
|
export async function createWorktree(exec, input) {
|
|
148
196
|
input.signal?.throwIfAborted();
|
|
149
197
|
const top = await exec('git', ['-C', input.repo, 'rev-parse', '--show-toplevel'], { timeoutMs: 10_000 });
|
|
@@ -155,29 +203,196 @@ export async function createWorktree(exec, input) {
|
|
|
155
203
|
if (existsSync(path))
|
|
156
204
|
throw new RunnerError('worktree_exists', path);
|
|
157
205
|
mkdirSync(join(input.home, '.dreamlake', 'worktrees'), { recursive: true });
|
|
158
|
-
input.checkpoint?.({ cwd: path, branch, root, phase: 'worktree-create' });
|
|
159
206
|
const exists = (await exec('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}`], { timeoutMs: 10_000 })).code === 0;
|
|
207
|
+
// Where the branch points before anything is created: an existing branch's tip, or the base a new one starts from.
|
|
208
|
+
const base = await exec('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `${exists ? `refs/heads/${branch}` : input.baseRef ?? 'HEAD'}^{commit}`], { timeoutMs: 10_000 });
|
|
209
|
+
const startOid = base.code === 0 && OID.test(base.stdout.trim()) ? base.stdout.trim() : null;
|
|
210
|
+
const identity = randomUUID();
|
|
211
|
+
const record = { path, branch, root, createdBranch: !exists, gitDir: null, branchOid: startOid, identity };
|
|
212
|
+
input.checkpoint?.({ cwd: path, branch, root, phase: 'worktree-create', branchOid: startOid, worktreeIdentity: identity });
|
|
213
|
+
input.prepared?.(record);
|
|
160
214
|
const args = exists ? ['-C', root, 'worktree', 'add', '--', path, branch] : ['-C', root, 'worktree', 'add', '-b', branch, '--', path, ...(input.baseRef ? [input.baseRef] : [])];
|
|
161
215
|
input.signal?.throwIfAborted();
|
|
162
216
|
const added = await exec('git', args, { timeoutMs: 120_000, signal: input.signal });
|
|
163
217
|
if (added.code !== 0)
|
|
164
|
-
throw new RunnerError('worktree_failed', added.stderr.trim().slice(0, 500), added.spawned !== false, { cwd: path, branch, root });
|
|
165
|
-
|
|
218
|
+
throw new RunnerError(added.aborted ? 'cancelled' : 'worktree_failed', added.stderr.trim().slice(0, 500), added.spawned !== false, { cwd: path, branch, root });
|
|
219
|
+
// This creation's identity goes into the worktree's own admin directory: cleanup removes a worktree only
|
|
220
|
+
// when it carries exactly this file, so neither a replacement nor a later re-creation at the same path
|
|
221
|
+
// (same admin directory, same branch, same tip) nor a half-made worktree can be mistaken for it.
|
|
222
|
+
const gitDir = gitdirPointer(path);
|
|
223
|
+
if (gitDir) {
|
|
224
|
+
try {
|
|
225
|
+
writeFileSync(join(gitDir, IDENTITY_FILE), `${identity}\n`, { mode: 0o600 });
|
|
226
|
+
}
|
|
227
|
+
catch { /* without the file, cleanup keeps the worktree and says so */ }
|
|
228
|
+
}
|
|
229
|
+
// The tip as git actually created it. The base resolved beforehand may have moved meanwhile (a fetch, a
|
|
230
|
+
// commit on HEAD); compared against that stale snapshot, an untouched orphan would look committed and be kept.
|
|
231
|
+
const tip = await exec('git', ['-C', root, 'rev-parse', '--verify', '--quiet', `refs/heads/${branch}^{commit}`], { timeoutMs: 10_000 });
|
|
232
|
+
return { ...record, gitDir, branchOid: tip.code === 0 && OID.test(tip.stdout.trim()) ? tip.stdout.trim() : startOid };
|
|
233
|
+
}
|
|
234
|
+
const OID = /^[a-f0-9]{40,64}$/;
|
|
235
|
+
const IDENTITY_FILE = 'dreamlake-session';
|
|
236
|
+
const gitdirPointer = (path) => { try {
|
|
237
|
+
const text = readFileSync(join(path, '.git'), 'utf8').trim();
|
|
238
|
+
return text.startsWith('gitdir:') ? text.slice('gitdir:'.length).trim() : null;
|
|
239
|
+
}
|
|
240
|
+
catch {
|
|
241
|
+
return null;
|
|
242
|
+
} };
|
|
243
|
+
/** The identity of the creation that made the worktree at `path`, or null when it carries none. */
|
|
244
|
+
export function worktreeIdentity(path) {
|
|
245
|
+
const gitDir = gitdirPointer(path);
|
|
246
|
+
if (!gitDir)
|
|
247
|
+
return null;
|
|
248
|
+
try {
|
|
249
|
+
return readFileSync(join(gitDir, IDENTITY_FILE), 'utf8').trim() || null;
|
|
250
|
+
}
|
|
251
|
+
catch {
|
|
252
|
+
return null;
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
const resolved = (path) => { try {
|
|
256
|
+
return realpathSync(path);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
return resolve(path);
|
|
260
|
+
} };
|
|
261
|
+
/** `git worktree list --porcelain`: one block per worktree (`worktree`, `HEAD`, `branch`/`detached`, …). */
|
|
262
|
+
async function listWorktrees(exec, root) {
|
|
263
|
+
const list = await exec('git', ['-C', root, 'worktree', 'list', '--porcelain'], { timeoutMs: 10_000 });
|
|
264
|
+
if (list.code !== 0)
|
|
265
|
+
return null;
|
|
266
|
+
return list.stdout.split(/\n\s*\n/).flatMap(block => {
|
|
267
|
+
const lines = block.split('\n'), path = lines.find(l => l.startsWith('worktree '))?.slice('worktree '.length);
|
|
268
|
+
return path ? [{ path, head: lines.find(l => l.startsWith('HEAD '))?.slice('HEAD '.length) ?? '', branch: lines.find(l => l.startsWith('branch '))?.slice('branch '.length) ?? null }] : [];
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
/** Remove a worktree this runner created for a start that never became a session, and the branch it
|
|
272
|
+
* created for it. Nothing is destroyed unless it is still exactly what this start made: the worktree at
|
|
273
|
+
* the path must carry this creation's identity file (a replacement, a re-creation at the same path or a
|
|
274
|
+
* worktree whose creation never completed does not, and is kept as `identity_missing`), be checked out
|
|
275
|
+
* on the branch, and the branch must still point at its initial tip (a provider that committed and then
|
|
276
|
+
* failed has made the branch worth keeping). Removal is never `--force` (edits keep it); the branch is
|
|
277
|
+
* deleted with `update-ref -d <old>`, which refuses a branch that moved, and never while any worktree
|
|
278
|
+
* has it checked out. A kept worktree or branch is reported with the reason. */
|
|
279
|
+
export async function removeWorktree(exec, where) {
|
|
280
|
+
const kept = (reason) => ({ removed: false, branchDeleted: false, reason });
|
|
281
|
+
const all = await listWorktrees(exec, where.root);
|
|
282
|
+
if (!all)
|
|
283
|
+
return kept('git worktree list failed');
|
|
284
|
+
const wanted = resolved(where.path), ref = `refs/heads/${where.branch}`;
|
|
285
|
+
const listed = all.find(w => resolved(w.path) === wanted) ?? null;
|
|
286
|
+
let removed = false;
|
|
287
|
+
if (listed) {
|
|
288
|
+
const identity = worktreeIdentity(where.path);
|
|
289
|
+
if (identity === null)
|
|
290
|
+
return kept('identity_missing: the worktree carries no DreamLake identity file (its creation did not complete, or it is not this runner\'s)');
|
|
291
|
+
if (identity !== where.identity)
|
|
292
|
+
return kept('the worktree at this path is not the one this start created');
|
|
293
|
+
if (listed.branch !== ref)
|
|
294
|
+
return kept(listed.branch ? `the worktree is on ${listed.branch}, not ${where.branch}` : 'the worktree is detached');
|
|
295
|
+
if (!where.branchOid)
|
|
296
|
+
return kept('the branch tip at creation is unknown');
|
|
297
|
+
if (listed.head !== where.branchOid)
|
|
298
|
+
return kept(`the branch has commits since the start (${listed.head.slice(0, 12)})`);
|
|
299
|
+
const result = await exec('git', ['-C', where.root, 'worktree', 'remove', '--', where.path], { timeoutMs: 60_000 });
|
|
300
|
+
if (result.code !== 0)
|
|
301
|
+
return kept((result.stderr || result.stdout).trim().slice(0, 300) || `git exited ${result.code}`);
|
|
302
|
+
removed = true;
|
|
303
|
+
}
|
|
304
|
+
else if (existsSync(where.path))
|
|
305
|
+
return kept('the directory is not a registered worktree');
|
|
306
|
+
const reason = removed ? {} : { reason: 'no worktree is registered at this path' };
|
|
307
|
+
if (!where.createdBranch)
|
|
308
|
+
return { removed, branchDeleted: false, ...reason };
|
|
309
|
+
if (!where.branchOid)
|
|
310
|
+
return { removed, branchDeleted: false, reason: 'the branch tip at creation is unknown' };
|
|
311
|
+
const elsewhere = all.find(w => w !== listed && w.branch === ref);
|
|
312
|
+
if (elsewhere)
|
|
313
|
+
return { removed, branchDeleted: false, reason: `the branch is checked out in ${elsewhere.path}` };
|
|
314
|
+
// An add cancelled before it ran, or one git undid itself on a signal, may have created no branch at all.
|
|
315
|
+
const current = await exec('git', ['-C', where.root, 'rev-parse', '--verify', '--quiet', ref], { timeoutMs: 10_000 });
|
|
316
|
+
if (current.code !== 0)
|
|
317
|
+
return { removed, branchDeleted: false, reason: removed ? 'the branch no longer exists' : 'nothing was created' };
|
|
318
|
+
// Deleted only if it still points where it did at creation; a branch that moved is left alone.
|
|
319
|
+
const deleted = await exec('git', ['-C', where.root, 'update-ref', '-d', ref, where.branchOid], { timeoutMs: 10_000 });
|
|
320
|
+
return { removed, branchDeleted: deleted.code === 0, ...(deleted.code === 0 ? reason : { reason: deleted.stderr.trim().slice(0, 300) }) };
|
|
166
321
|
}
|
|
167
322
|
const DEFAULT_PROMPT = 'You were started by the DreamLake built-in agent on behalf of its user. Reply with one line acknowledging the working directory, then wait for instructions.';
|
|
168
|
-
const
|
|
323
|
+
export const currentProfileOwner = () => ({ home: homedir(), uid: process.getuid?.() ?? null });
|
|
324
|
+
/** Claude Code keeps its login in `<config dir>/.claude.json`, and the default profile is `~/.claude.json`,
|
|
325
|
+
* not `~/.claude/.claude.json`. Exporting `CLAUDE_CONFIG_DIR=~/.claude` (what Nymph records for a default
|
|
326
|
+
* session) therefore makes Claude create an empty, logged-out profile and answer "Not logged in". The
|
|
327
|
+
* variable is exported only for a non-default directory that holds a logged-in profile; otherwise the
|
|
328
|
+
* process inherits the runner's own environment, which is how the user runs Claude.
|
|
329
|
+
*
|
|
330
|
+
* A session descriptor can name any readable path, so the directory is accepted only when it is this
|
|
331
|
+
* user's own — owned by the current uid, or inside the current home — and that is decided on the resolved
|
|
332
|
+
* path (symlinks followed first, so a link inside this home to a directory elsewhere is judged by where
|
|
333
|
+
* it points) before its profile is read; another Unix user's profile is not this user's login. A login
|
|
334
|
+
* means a non-empty `oauthAccount` object or a non-empty `primaryApiKey`; `{ "oauthAccount": {} }` is
|
|
335
|
+
* logged out. */
|
|
336
|
+
export function claudeConfigDecision(requested, defaultDir, owner = currentProfileOwner()) {
|
|
337
|
+
if (!requested)
|
|
338
|
+
return { dir: null, exported: false, reason: 'inherited' };
|
|
339
|
+
const decided = (reason) => ({ dir: requested, exported: reason === 'exported', reason });
|
|
340
|
+
let real;
|
|
341
|
+
try {
|
|
342
|
+
real = realpathSync(requested);
|
|
343
|
+
}
|
|
344
|
+
catch (error) {
|
|
345
|
+
return decided(['ENOENT', 'ENOTDIR', 'ELOOP'].includes(error.code ?? '') ? 'profile_missing' : 'profile_logged_out');
|
|
346
|
+
}
|
|
347
|
+
if (real === resolved(defaultDir))
|
|
348
|
+
return decided('default_config_dir');
|
|
349
|
+
let dir;
|
|
350
|
+
try {
|
|
351
|
+
dir = statSync(real);
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
return decided('profile_missing');
|
|
355
|
+
}
|
|
356
|
+
if (!dir.isDirectory())
|
|
357
|
+
return decided('profile_missing');
|
|
358
|
+
const home = resolved(owner.home);
|
|
359
|
+
const owned = owner.uid !== null && dir.uid === owner.uid, underHome = real === home || real.startsWith(home + sep);
|
|
360
|
+
if (!owned && !underHome)
|
|
361
|
+
return decided('profile_not_owned');
|
|
362
|
+
let profile = null;
|
|
363
|
+
try {
|
|
364
|
+
profile = JSON.parse(readFileSync(join(real, '.claude.json'), 'utf8'));
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
return decided(error.code === 'ENOENT' ? 'profile_missing' : 'profile_logged_out');
|
|
368
|
+
}
|
|
369
|
+
const account = profile?.oauthAccount, key = profile?.primaryApiKey;
|
|
370
|
+
const loggedIn = !!profile && typeof profile === 'object' && ((typeof account === 'object' && account !== null && Object.keys(account).length > 0) || (typeof key === 'string' && key.trim().length > 0));
|
|
371
|
+
return decided(loggedIn ? 'exported' : 'profile_logged_out');
|
|
372
|
+
}
|
|
373
|
+
const claudeConfig = (input) => claudeConfigDecision(input.claudeConfigDir, input.defaultClaudeConfigDir ?? defaultRoots(homedir()).claude);
|
|
374
|
+
const claudeEnv = (decision) => decision.exported ? { ...process.env, CLAUDE_CONFIG_DIR: decision.dir } : process.env;
|
|
375
|
+
const claudeEnvPrefix = (decision) => decision.exported ? ['env', `CLAUDE_CONFIG_DIR=${decision.dir}`] : [];
|
|
169
376
|
const PROVIDER_TIMEOUT = 15 * 60_000;
|
|
377
|
+
/** The exact command line of a headless turn (`claude -p` / `codex exec`); echoed in every receipt so the
|
|
378
|
+
* permission mode a process actually ran under is readable next to the level that was authorized. */
|
|
379
|
+
export function headlessArgv(input) {
|
|
380
|
+
if (input.provider === 'claude')
|
|
381
|
+
return ['claude', '-p', input.resume ? '--resume' : '--session-id', input.nativeSessionId ?? '', '--permission-mode', claudePermissionMode(input.permissionLevel), '--output-format', 'json'];
|
|
382
|
+
return input.resume ? ['codex', 'exec', '--sandbox', codexSandbox(input.permissionLevel), '--json', 'resume', input.nativeSessionId ?? '', '-'] : ['codex', 'exec', '-C', input.cwd ?? '.', '--sandbox', codexSandbox(input.permissionLevel), '--json', '-'];
|
|
383
|
+
}
|
|
170
384
|
/** Headless: one provider turn that creates the session; the prompt travels on stdin. */
|
|
171
385
|
export async function startHeadless(exec, launch) {
|
|
172
386
|
const prompt = launch.prompt ?? DEFAULT_PROMPT;
|
|
173
387
|
if (launch.provider === 'claude') {
|
|
174
|
-
const id = launch.nativeSessionId ?? randomUUID();
|
|
175
|
-
launch.checkpoint?.({ nativeSessionId: id, phase: 'provider-start' });
|
|
176
|
-
const
|
|
388
|
+
const id = launch.nativeSessionId ?? randomUUID(), decision = claudeConfig(launch);
|
|
389
|
+
launch.checkpoint?.({ nativeSessionId: id, phase: 'provider-start', claudeConfig: decision });
|
|
390
|
+
const argv = headlessArgv({ provider: 'claude', nativeSessionId: id, permissionLevel: launch.permissionLevel, resume: false });
|
|
391
|
+
const result = await exec(argv[0], argv.slice(1), { cwd: launch.cwd, timeoutMs: PROVIDER_TIMEOUT, env: claudeEnv(decision), input: prompt, signal: launch.signal });
|
|
177
392
|
// The id was chosen here, so even a failed turn leaves a reconcilable checkpoint.
|
|
178
393
|
if (result.code !== 0)
|
|
179
|
-
throw failed(result, 'claude_failed', { nativeSessionId: id });
|
|
180
|
-
return { nativeSessionId: id, reply: claudeReply(result.stdout) };
|
|
394
|
+
throw failed(result, 'claude_failed', { nativeSessionId: id, claudeConfig: decision });
|
|
395
|
+
return { nativeSessionId: id, reply: claudeReply(result.stdout), argv, claudeConfig: decision };
|
|
181
396
|
}
|
|
182
397
|
let stream = '', checkpointed = false;
|
|
183
398
|
launch.checkpoint?.({ phase: 'provider-start' });
|
|
@@ -186,7 +401,8 @@ export async function startHeadless(exec, launch) {
|
|
|
186
401
|
launch.checkpoint?.({ nativeSessionId: id, phase: 'provider-running' });
|
|
187
402
|
checkpointed = true;
|
|
188
403
|
} };
|
|
189
|
-
const
|
|
404
|
+
const argv = headlessArgv({ provider: 'codex', permissionLevel: launch.permissionLevel, resume: false, cwd: launch.cwd });
|
|
405
|
+
const result = await exec(argv[0], argv.slice(1), { cwd: launch.cwd, timeoutMs: PROVIDER_TIMEOUT, input: prompt, signal: launch.signal, onStdout });
|
|
190
406
|
// The identity comes from the launch's own JSON stream, never from scanning the rollout
|
|
191
407
|
// directory: a transcript that merely appeared nearby could belong to anyone.
|
|
192
408
|
const id = codexThreadId(result.stdout);
|
|
@@ -196,7 +412,7 @@ export async function startHeadless(exec, launch) {
|
|
|
196
412
|
throw failed(result, 'codex_failed', id ? { nativeSessionId: id } : {});
|
|
197
413
|
if (!id)
|
|
198
414
|
throw new RunnerError('codex_session_id_unknown', 'codex exec --json did not report a thread id', true);
|
|
199
|
-
return { nativeSessionId: id, reply: codexReply(result.stdout) };
|
|
415
|
+
return { nativeSessionId: id, reply: codexReply(result.stdout), argv };
|
|
200
416
|
}
|
|
201
417
|
/** Stamp a fresh launch identity atomically with session creation (tmux >= 3.2).
|
|
202
418
|
* Unlike the stable runner marker, this nonce cannot match a previous/concurrent launch. */
|
|
@@ -210,7 +426,7 @@ async function createTmux(exec, input, work = async () => { }) {
|
|
|
210
426
|
if (created.code !== 0)
|
|
211
427
|
throw new RunnerError('tmux_start_failed', created.stderr.trim(), true, checkpoint);
|
|
212
428
|
input.signal?.throwIfAborted();
|
|
213
|
-
await markOwnership(exec, input.name, input.marker);
|
|
429
|
+
await markOwnership(exec, input.name, input.marker, input.policy);
|
|
214
430
|
input.signal?.throwIfAborted();
|
|
215
431
|
await work();
|
|
216
432
|
input.signal?.throwIfAborted();
|
|
@@ -221,7 +437,7 @@ async function createTmux(exec, input, work = async () => { }) {
|
|
|
221
437
|
// session that replaced the deterministic name cannot be killed by cleanup.
|
|
222
438
|
let tornDown = false;
|
|
223
439
|
try {
|
|
224
|
-
const found = await exec('tmux', ['display-message', '-p', '-t', `=${input.name}
|
|
440
|
+
const found = await exec('tmux', ['display-message', '-p', '-t', `=${input.name}:`, '#{session_id}|#{DREAMLAKE_LAUNCH_NONCE}'], { timeoutMs: 5000 });
|
|
225
441
|
const [id, actual] = found.stdout.trim().split('|');
|
|
226
442
|
if (found.code === 0 && /^\$[0-9]+$/.test(id) && actual === nonce) {
|
|
227
443
|
const killed = await exec('tmux', ['if-shell', '-F', '-t', id, `#{==:#{DREAMLAKE_LAUNCH_NONCE},${nonce}}`, `kill-session -t '${id}'`], { timeoutMs: 5000 });
|
|
@@ -230,25 +446,27 @@ async function createTmux(exec, input, work = async () => { }) {
|
|
|
230
446
|
}
|
|
231
447
|
}
|
|
232
448
|
catch { /* uncertain cleanup is included in the receipt */ }
|
|
233
|
-
throw new RunnerError(input.signal?.aborted ? 'cancelled' : error instanceof RunnerError ? error.code : 'tmux_start_failed', error instanceof Error ? error.message : undefined, true, { ...(error instanceof RunnerError ? error.checkpoint : {}), ...checkpoint, tornDown });
|
|
449
|
+
throw new RunnerError(input.signal?.aborted ? 'cancelled' : error instanceof RunnerError ? error.code : 'tmux_start_failed', error instanceof Error ? error.message : undefined, true, { ...(error instanceof RunnerError ? error.checkpoint : {}), ...checkpoint, tornDown }, error instanceof RunnerError ? error.detail : {});
|
|
234
450
|
}
|
|
235
451
|
}
|
|
236
|
-
/** Interactive: a detached, owner-marked tmux session. Prompts sit behind `--`.
|
|
452
|
+
/** Interactive: a detached, owner-marked tmux session. Prompts sit behind `--`. `argv` is the program the
|
|
453
|
+
* tmux session runs (with an `env CLAUDE_CONFIG_DIR=…` prefix when one was exported). */
|
|
237
454
|
export async function startTmux(exec, launch) {
|
|
238
455
|
if (launch.signal?.aborted)
|
|
239
456
|
throw new RunnerError('cancelled');
|
|
240
457
|
if (launch.provider === 'claude') {
|
|
241
|
-
const id = launch.nativeSessionId ?? randomUUID(), name = tmuxSessionName('claude', launch.cwd, id, launch.claudeConfigDir);
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
458
|
+
const id = launch.nativeSessionId ?? randomUUID(), name = tmuxSessionName('claude', launch.cwd, id, launch.claudeConfigDir), decision = claudeConfig(launch);
|
|
459
|
+
launch.checkpoint?.({ claudeConfig: decision });
|
|
460
|
+
const program = [...claudeEnvPrefix(decision), 'claude', '--session-id', id, '--permission-mode', claudePermissionMode(launch.permissionLevel), ...(launch.prompt ? ['--', launch.prompt] : [])];
|
|
461
|
+
await createTmux(exec, { name, cwd: launch.cwd, marker: launch.marker(id), nativeSessionId: id, policy: launch.permissionLevel, signal: launch.signal, checkpoint: launch.checkpoint, program });
|
|
462
|
+
return { nativeSessionId: id, tmuxSession: name, argv: program, claudeConfig: decision };
|
|
245
463
|
}
|
|
246
464
|
// The launch's own JSON stream identifies Codex; then resume that exact thread in tmux.
|
|
247
465
|
const { nativeSessionId: id } = await startHeadless(exec, launch);
|
|
248
466
|
const name = tmuxSessionName('codex', launch.cwd, id);
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
return { nativeSessionId: id, tmuxSession: name };
|
|
467
|
+
const program = ['codex', '-C', launch.cwd, '--sandbox', codexSandbox(launch.permissionLevel), 'resume', id];
|
|
468
|
+
await createTmux(exec, { name, cwd: launch.cwd, marker: launch.marker(id), nativeSessionId: id, policy: launch.permissionLevel, signal: launch.signal, checkpoint: launch.checkpoint, program });
|
|
469
|
+
return { nativeSessionId: id, tmuxSession: name, argv: program };
|
|
252
470
|
}
|
|
253
471
|
/** Resume in tmux, re-applying the session's permission ceiling; a live session receives the prompt instead.
|
|
254
472
|
* Cancellation is honoured before and during the launch; a launch cancelled mid-way is torn down. */
|
|
@@ -259,40 +477,73 @@ export async function resumeTmux(exec, input) {
|
|
|
259
477
|
if (owned === 'foreign')
|
|
260
478
|
throw new RunnerError('pane_ownership_unverified');
|
|
261
479
|
input.signal?.throwIfAborted();
|
|
480
|
+
let relaunched;
|
|
262
481
|
if (owned === 'owned') {
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
482
|
+
// A live process is only typed into when it was launched under the level that is authorized now. The
|
|
483
|
+
// record may have moved since (PATCH …/permission): then the process is stopped and relaunched under
|
|
484
|
+
// the authorized level; a process whose launch level is unknown is never trusted.
|
|
485
|
+
const live = await livePolicy(exec, name);
|
|
486
|
+
if (assertLivePolicy(live, input.permissionLevel) === 'matches') {
|
|
487
|
+
// A live session keeps its process (and its permission mode): no new command line, `argv: null`.
|
|
488
|
+
if (input.prompt)
|
|
489
|
+
await tmuxSend(exec, name, input.marker, input.prompt, input.signal);
|
|
490
|
+
return { tmuxSession: name, created: false, delivered: !!input.prompt, argv: null, processLevel: live };
|
|
491
|
+
}
|
|
492
|
+
input.signal?.throwIfAborted();
|
|
493
|
+
await tmuxStop(exec, name, input.marker);
|
|
494
|
+
relaunched = { relaunched: true, previousProcessLevel: live };
|
|
495
|
+
input.checkpoint?.({ tmuxSession: name, phase: 'relaunch-stopped', previousProcessLevel: live });
|
|
266
496
|
}
|
|
497
|
+
const decision = input.provider === 'claude' ? claudeConfig(input) : undefined;
|
|
498
|
+
if (decision)
|
|
499
|
+
input.checkpoint?.({ claudeConfig: decision });
|
|
267
500
|
const program = input.provider === 'codex' ? ['codex', '-C', input.cwd, '--sandbox', codexSandbox(input.permissionLevel), 'resume', input.nativeSessionId]
|
|
268
|
-
: [...(
|
|
269
|
-
await createTmux(exec, { name, cwd: input.cwd, program, marker: input.marker, nativeSessionId: input.nativeSessionId, signal: input.signal, checkpoint: input.checkpoint }, async () => {
|
|
501
|
+
: [...claudeEnvPrefix(decision), 'claude', '--resume', input.nativeSessionId, '--permission-mode', claudePermissionMode(input.permissionLevel)];
|
|
502
|
+
await createTmux(exec, { name, cwd: input.cwd, program, marker: input.marker, nativeSessionId: input.nativeSessionId, policy: input.permissionLevel, signal: input.signal, checkpoint: input.checkpoint }, async () => {
|
|
270
503
|
if (input.prompt) {
|
|
271
504
|
await delay(3000, undefined, { signal: input.signal });
|
|
272
505
|
await tmuxSend(exec, name, input.marker, input.prompt, input.signal);
|
|
273
506
|
}
|
|
274
507
|
});
|
|
275
|
-
return { tmuxSession: name, created: true, delivered: !!input.prompt };
|
|
508
|
+
return { tmuxSession: name, created: true, delivered: !!input.prompt, argv: program, processLevel: input.permissionLevel, ...(relaunched ?? {}), ...(decision ? { claudeConfig: decision } : {}) };
|
|
276
509
|
}
|
|
277
510
|
/** Headless message: one resumed turn under the session's permission ceiling; the text travels on stdin. */
|
|
278
511
|
export async function sendHeadless(exec, input) {
|
|
512
|
+
const argv = headlessArgv({ provider: input.provider, nativeSessionId: input.nativeSessionId, permissionLevel: input.permissionLevel, resume: true });
|
|
279
513
|
if (input.provider === 'claude') {
|
|
280
|
-
const
|
|
514
|
+
const decision = claudeConfig(input);
|
|
515
|
+
const result = await exec(argv[0], argv.slice(1), { cwd: input.cwd, timeoutMs: PROVIDER_TIMEOUT, env: claudeEnv(decision), input: input.text, signal: input.signal });
|
|
281
516
|
if (result.code !== 0)
|
|
282
|
-
throw failed(result, 'claude_failed');
|
|
283
|
-
return { reply: claudeReply(result.stdout) };
|
|
517
|
+
throw failed(result, 'claude_failed', { claudeConfig: decision });
|
|
518
|
+
return { reply: claudeReply(result.stdout), argv, claudeConfig: decision };
|
|
284
519
|
}
|
|
285
|
-
const result = await exec(
|
|
520
|
+
const result = await exec(argv[0], argv.slice(1), { cwd: input.cwd, timeoutMs: PROVIDER_TIMEOUT, input: input.text, signal: input.signal });
|
|
286
521
|
if (result.code !== 0)
|
|
287
522
|
throw failed(result, 'codex_failed');
|
|
288
|
-
return { reply: codexReply(result.stdout) };
|
|
523
|
+
return { reply: codexReply(result.stdout), argv };
|
|
524
|
+
}
|
|
525
|
+
export function transcriptMark(transcriptPath) {
|
|
526
|
+
if (!transcriptPath)
|
|
527
|
+
return null;
|
|
528
|
+
try {
|
|
529
|
+
const stat = statSync(transcriptPath);
|
|
530
|
+
return { mtimeMs: stat.mtimeMs, size: stat.size };
|
|
531
|
+
}
|
|
532
|
+
catch {
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
289
535
|
}
|
|
290
|
-
/** Someone (a person, another runner) is writing this conversation right now.
|
|
291
|
-
|
|
536
|
+
/** Someone (a person, another runner) is writing this conversation right now. A transcript that still
|
|
537
|
+
* reads exactly as this runner's own last turn left it was not written by anyone else, however recent;
|
|
538
|
+
* the runner identifies its own writes by that recorded state, never by how long ago they happened. */
|
|
539
|
+
export function nativeWriterBusy(transcriptPath, now = Date.now(), windowMs = 60_000, own) {
|
|
292
540
|
if (!transcriptPath)
|
|
293
541
|
return false;
|
|
294
542
|
try {
|
|
295
|
-
|
|
543
|
+
const stat = statSync(transcriptPath);
|
|
544
|
+
if (own && own.mtimeMs === stat.mtimeMs && own.size === stat.size)
|
|
545
|
+
return false;
|
|
546
|
+
return now - stat.mtimeMs < windowMs;
|
|
296
547
|
}
|
|
297
548
|
catch {
|
|
298
549
|
return false;
|
|
@@ -44,6 +44,7 @@ export function findCodexRollout(root, id, since) {
|
|
|
44
44
|
return file;
|
|
45
45
|
return null;
|
|
46
46
|
}
|
|
47
|
+
const MTIME_SLACK_MS = 2_000;
|
|
47
48
|
export function listCodexRollouts(root, since) {
|
|
48
49
|
const out = [];
|
|
49
50
|
const walk = (dir, depth) => {
|
|
@@ -65,7 +66,9 @@ export function listCodexRollouts(root, since) {
|
|
|
65
66
|
}
|
|
66
67
|
if (stat.isDirectory() && depth < 3)
|
|
67
68
|
walk(path, depth + 1);
|
|
68
|
-
|
|
69
|
+
// mtime is only a coarse pre-filter: Linux stamps files from a tick-granular clock that can trail
|
|
70
|
+
// Date.now() by a few ms, so allow slack here; the rollout's own `createdAt` is the strict `since` check.
|
|
71
|
+
else if (stat.isFile() && entry.startsWith('rollout-') && entry.endsWith('.jsonl') && (since === undefined || stat.mtimeMs >= since - MTIME_SLACK_MS))
|
|
69
72
|
out.push(path);
|
|
70
73
|
}
|
|
71
74
|
};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Pods, type PodConfig } from './pod.js';
|
|
2
2
|
import { RunnerJournal } from './journal.js';
|
|
3
|
-
import type { ClaimedCommand, CommandReceipt, DreamLakeClient, PermissionLevel, SessionsApi } from '../../../api/index.js';
|
|
3
|
+
import type { ClaimedCommand, CommandReceipt, DreamLakeClient, LiveCurrent, LiveState, PermissionLevel, SessionsApi } from '../../../api/index.js';
|
|
4
4
|
import { type NativeRoots } from './native.js';
|
|
5
5
|
import { type Run } from './exec.js';
|
|
6
6
|
export interface RunnerOptions {
|
|
@@ -14,12 +14,17 @@ export interface RunnerOptions {
|
|
|
14
14
|
/** Persisted runner key location; defaults to ~/.dreamlake/session-runner.json */
|
|
15
15
|
trustedRepositories?: string[];
|
|
16
16
|
maxAgentPermission?: PermissionLevel;
|
|
17
|
+
/** Advertised as `capabilities.humanPermissionCap`: the highest level a person may raise a session to
|
|
18
|
+
* through `restart` / `PATCH …/permission` on this runner. Absent: the start level stays a hard ceiling. */
|
|
19
|
+
maxHumanPermission?: PermissionLevel;
|
|
17
20
|
podConfig?: PodConfig;
|
|
18
21
|
stateFile?: string;
|
|
19
22
|
once?: boolean;
|
|
20
23
|
signal?: AbortSignal;
|
|
21
24
|
pollSeconds?: number;
|
|
22
25
|
concurrency?: number;
|
|
26
|
+
/** Runner heartbeat cadence while a turn runs (default 10 s; tests shorten it). */
|
|
27
|
+
heartbeatMs?: number;
|
|
23
28
|
}
|
|
24
29
|
/** Stable per machine + Unix user; a random key, not a credential (the owner's token authenticates). */
|
|
25
30
|
export declare function runnerKey(stateFile: string): string;
|
|
@@ -45,6 +50,27 @@ export declare class Semaphore {
|
|
|
45
50
|
acquire(signal?: AbortSignal): Promise<void>;
|
|
46
51
|
release(): void;
|
|
47
52
|
}
|
|
53
|
+
/** The runner's own live-state reports (`source: runner`, every 10 s while a provider turn of a session
|
|
54
|
+
* runs, then the outcome). Best effort and bounded: a beat never fails or delays the command it describes;
|
|
55
|
+
* a session the server will not let this runner speak for (not bound to it, `409 session_runner_mismatch`;
|
|
56
|
+
* unknown, 404) is logged once and dropped until a resume or restart of it completes here. Without a
|
|
57
|
+
* runner id (tests, dry runs) nothing is sent. */
|
|
58
|
+
export declare class LiveBeats {
|
|
59
|
+
private readonly api;
|
|
60
|
+
private readonly runnerId;
|
|
61
|
+
private readonly log;
|
|
62
|
+
readonly intervalMs: number;
|
|
63
|
+
private readonly muted;
|
|
64
|
+
readonly pending: Set<Promise<unknown>>;
|
|
65
|
+
constructor(api: Pick<SessionsApi, 'heartbeat'>, runnerId: string | undefined, log?: (line: string) => void, intervalMs?: number);
|
|
66
|
+
beat(sessionId: string, liveState: LiveState, current?: LiveCurrent): Promise<boolean>;
|
|
67
|
+
/** The receipt of a resume / restart binds the session to this runner: its beats are welcome again. */
|
|
68
|
+
allow(sessionId: string): void;
|
|
69
|
+
/** `running` now and every interval while `work` runs, then the outcome: `waiting-for-user` after a
|
|
70
|
+
* completed turn (the reply awaits a person), `stopped` when the turn was cancelled, `uncertain` when the
|
|
71
|
+
* provider failed. The outcome beat is not awaited: the receipt never waits on it. */
|
|
72
|
+
during<T>(sessionId: string, work: () => Promise<T>): Promise<T>;
|
|
73
|
+
}
|
|
48
74
|
export interface Executors {
|
|
49
75
|
execute(command: ClaimedCommand, signal: AbortSignal): Promise<Record<string, unknown>>;
|
|
50
76
|
}
|
|
@@ -61,13 +87,20 @@ export declare function commandExecutors(input: {
|
|
|
61
87
|
quarantined?: Set<string>;
|
|
62
88
|
trustedRepositories?: string[];
|
|
63
89
|
maxAgentPermission?: PermissionLevel;
|
|
90
|
+
maxHumanPermission?: PermissionLevel;
|
|
64
91
|
pods?: Pods;
|
|
92
|
+
beats?: LiveBeats;
|
|
65
93
|
}): Executors;
|
|
94
|
+
/** `error` stays the stable code (what callers branch on); `result.error` carries the underlying text:
|
|
95
|
+
* the runner's message, and for a provider failure its exit code, signal and redacted output tails. */
|
|
66
96
|
export declare function receiptFor(leaseToken: string, outcome: {
|
|
67
97
|
result?: Record<string, unknown>;
|
|
68
98
|
error?: unknown;
|
|
69
99
|
}, aborted: boolean): CommandReceipt;
|
|
70
100
|
/** One command end to end: lease renewal with a local deadline, execution, one receipt. Exported for tests. */
|
|
101
|
+
/** How often a running command asks the server whether its owner cancelled it. Independent of lease renewal,
|
|
102
|
+
* so a slow or hanging renewal never delays the interruption of a provider turn. */
|
|
103
|
+
export declare const CANCEL_CHECK_MS = 2000;
|
|
71
104
|
export declare function handleCommand(input: {
|
|
72
105
|
api: SessionsApi;
|
|
73
106
|
runnerId: string;
|
|
@@ -77,8 +110,10 @@ export declare function handleCommand(input: {
|
|
|
77
110
|
now?: () => number;
|
|
78
111
|
shutdown?: AbortSignal;
|
|
79
112
|
tickMs?: number;
|
|
113
|
+
renewMs?: number;
|
|
114
|
+
cancelCheckMs?: number;
|
|
80
115
|
journal?: RunnerJournal;
|
|
81
|
-
}): Promise<import("../../../api/sessions.js").Command<"start" | "stop" | "status" | "resume" | "send" | "sync" | "subagents"> | null>;
|
|
116
|
+
}): Promise<import("../../../api/sessions.js").Command<"start" | "stop" | "restart" | "status" | "resume" | "send" | "sync" | "subagents"> | null>;
|
|
82
117
|
export declare function serve(options: RunnerOptions): Promise<{
|
|
83
118
|
runnerId: string;
|
|
84
119
|
handled: number;
|