praxis-agent 0.59.1 → 0.60.1
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/README.md +9 -3
- package/dist/application/background-bash-manager.d.ts +4 -0
- package/dist/application/background-bash-manager.js +95 -3
- package/dist/application/managed-worktree.d.ts +10 -0
- package/dist/application/managed-worktree.js +556 -6
- package/dist/application/workflow-worktree.js +6 -4
- package/dist/cli/interactive.js +3 -0
- package/dist/cli/protocol.d.ts +1 -0
- package/dist/cli/protocol.js +52 -7
- package/dist/cli-runtime.d.ts +1 -0
- package/dist/cli-runtime.js +48 -7
- package/dist/core/runtime.d.ts +6 -0
- package/dist/persistence/managed-worktree-store.d.ts +41 -0
- package/dist/persistence/managed-worktree-store.js +341 -0
- package/package.json +1 -1
|
@@ -1,17 +1,567 @@
|
|
|
1
1
|
import { execFile } from 'node:child_process';
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { constants } from 'node:fs';
|
|
4
|
+
import { lstat, mkdir, open, realpath } from 'node:fs/promises';
|
|
5
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
6
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
4
7
|
import { promisify } from 'node:util';
|
|
8
|
+
import { ManagedWorktreeStore, } from '../persistence/managed-worktree-store.js';
|
|
9
|
+
import { resolveProjectIdentity } from '../platform/project-identity.js';
|
|
10
|
+
import { writeFileAtomically } from '../platform/atomic-write.js';
|
|
11
|
+
import { ExclusiveFileLease, } from '../platform/exclusive-file-lease.js';
|
|
5
12
|
const execFileAsync = promisify(execFile);
|
|
13
|
+
async function gitRaw(cwd, args) {
|
|
14
|
+
return (await execFileAsync('git', ['-C', cwd, ...args], { encoding: 'utf8' })).stdout;
|
|
15
|
+
}
|
|
6
16
|
async function git(cwd, args) {
|
|
7
|
-
return (await
|
|
17
|
+
return (await gitRaw(cwd, args)).trim();
|
|
18
|
+
}
|
|
19
|
+
async function gitOptional(cwd, args) {
|
|
20
|
+
try {
|
|
21
|
+
return await git(cwd, args);
|
|
22
|
+
}
|
|
23
|
+
catch (error) {
|
|
24
|
+
if (error.code === 1)
|
|
25
|
+
return null;
|
|
26
|
+
throw error;
|
|
27
|
+
}
|
|
8
28
|
}
|
|
9
29
|
async function registeredWorktrees(root) {
|
|
10
|
-
const output = await
|
|
30
|
+
const output = await gitRaw(root, ['worktree', 'list', '--porcelain', '-z']);
|
|
11
31
|
return new Set(output
|
|
12
|
-
.split('\
|
|
32
|
+
.split('\0')
|
|
13
33
|
.filter((line) => line.startsWith('worktree '))
|
|
14
|
-
.map((line) => resolve(line.slice('worktree '.length))));
|
|
34
|
+
.map((line) => resolve(root, line.slice('worktree '.length))));
|
|
35
|
+
}
|
|
36
|
+
const COMPONENT_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._-]{0,191}$/u;
|
|
37
|
+
const MARKER_FIELDS = new Set(['version', 'worktreeId', 'repositoryRoot']);
|
|
38
|
+
const LOCAL_EXCLUDE_PATTERN = '/.praxis/worktrees/';
|
|
39
|
+
function managedWorktreeId(repositoryRoot, kind, ownerId) {
|
|
40
|
+
return createHash('sha256')
|
|
41
|
+
.update(`${repositoryRoot}\0${kind}\0${ownerId}`)
|
|
42
|
+
.digest('hex');
|
|
43
|
+
}
|
|
44
|
+
function validOwnerId(ownerId) {
|
|
45
|
+
return (ownerId.length > 0 &&
|
|
46
|
+
ownerId.length <= 256 &&
|
|
47
|
+
!Array.from(ownerId).some((character) => {
|
|
48
|
+
const code = character.codePointAt(0) ?? 0;
|
|
49
|
+
return code <= 0x1f || code === 0x7f;
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
function worktreeError(options, message) {
|
|
53
|
+
return new Error(`${options.label} worktree ${message}`);
|
|
54
|
+
}
|
|
55
|
+
async function assertRealDirectory(path, description) {
|
|
56
|
+
let current = resolve(path);
|
|
57
|
+
const parts = [];
|
|
58
|
+
while (true) {
|
|
59
|
+
parts.unshift(current);
|
|
60
|
+
const parent = resolve(current, '..');
|
|
61
|
+
if (parent === current)
|
|
62
|
+
break;
|
|
63
|
+
current = parent;
|
|
64
|
+
}
|
|
65
|
+
for (const part of parts) {
|
|
66
|
+
try {
|
|
67
|
+
const entry = await lstat(part);
|
|
68
|
+
if (entry.isSymbolicLink())
|
|
69
|
+
throw new Error(`${description} must not be a symlink`);
|
|
70
|
+
if (!entry.isDirectory())
|
|
71
|
+
throw new Error(`${description} must be a directory`);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (error.code === 'ENOENT')
|
|
75
|
+
continue;
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
async function acquireLease(lease, description) {
|
|
81
|
+
for (let attempt = 0; attempt < 400; attempt += 1) {
|
|
82
|
+
const handle = await lease.tryAcquire();
|
|
83
|
+
if (handle)
|
|
84
|
+
return handle;
|
|
85
|
+
await sleep(5);
|
|
86
|
+
}
|
|
87
|
+
throw new Error(`Timed out acquiring ${description}`);
|
|
88
|
+
}
|
|
89
|
+
async function readRegularFile(path, description) {
|
|
90
|
+
let handle;
|
|
91
|
+
try {
|
|
92
|
+
handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
93
|
+
}
|
|
94
|
+
catch (error) {
|
|
95
|
+
if (error.code === 'ELOOP') {
|
|
96
|
+
throw new Error(`${description} must be a regular file`);
|
|
97
|
+
}
|
|
98
|
+
throw error;
|
|
99
|
+
}
|
|
100
|
+
try {
|
|
101
|
+
if (!(await handle.stat()).isFile()) {
|
|
102
|
+
throw new Error(`${description} must be a regular file`);
|
|
103
|
+
}
|
|
104
|
+
return await handle.readFile({ encoding: 'utf8' });
|
|
105
|
+
}
|
|
106
|
+
finally {
|
|
107
|
+
await handle.close();
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
async function ensureManagedRootIgnored(repositoryRoot) {
|
|
111
|
+
const commonValue = await git(repositoryRoot, [
|
|
112
|
+
'rev-parse',
|
|
113
|
+
'--git-common-dir',
|
|
114
|
+
]);
|
|
115
|
+
const commonDirectory = await realpath(isAbsolute(commonValue)
|
|
116
|
+
? commonValue
|
|
117
|
+
: resolve(repositoryRoot, commonValue));
|
|
118
|
+
const infoDirectory = join(commonDirectory, 'info');
|
|
119
|
+
await assertRealDirectory(commonDirectory, 'Git common directory');
|
|
120
|
+
await assertRealDirectory(infoDirectory, 'Git info directory');
|
|
121
|
+
await mkdir(infoDirectory, { recursive: true, mode: 0o700 });
|
|
122
|
+
await assertRealDirectory(infoDirectory, 'Git info directory');
|
|
123
|
+
const excludePath = join(infoDirectory, 'exclude');
|
|
124
|
+
const lease = await acquireLease(new ExclusiveFileLease(`${excludePath}.praxis.lock`), 'managed worktree ignore lock');
|
|
125
|
+
try {
|
|
126
|
+
let source = '';
|
|
127
|
+
try {
|
|
128
|
+
source = await readRegularFile(excludePath, 'Git info exclude');
|
|
129
|
+
}
|
|
130
|
+
catch (error) {
|
|
131
|
+
if (error.code !== 'ENOENT')
|
|
132
|
+
throw error;
|
|
133
|
+
}
|
|
134
|
+
const lines = source.split(/\r?\n/u);
|
|
135
|
+
if (lines.includes(LOCAL_EXCLUDE_PATTERN))
|
|
136
|
+
return;
|
|
137
|
+
const prefix = source.length > 0 && !source.endsWith('\n') ? '\n' : '';
|
|
138
|
+
const next = `${source}${prefix}${LOCAL_EXCLUDE_PATTERN}\n`;
|
|
139
|
+
const committed = await writeFileAtomically(excludePath, next, {
|
|
140
|
+
mode: 0o600,
|
|
141
|
+
beforeCommit: async () => {
|
|
142
|
+
try {
|
|
143
|
+
return ((await readRegularFile(excludePath, 'Git info exclude')) === source);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
return error.code === 'ENOENT' && !source;
|
|
147
|
+
}
|
|
148
|
+
},
|
|
149
|
+
});
|
|
150
|
+
if (!committed) {
|
|
151
|
+
throw new Error('Git info exclude changed during managed worktree setup');
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
finally {
|
|
155
|
+
await lease.release();
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
async function linkedGitDirectory(worktreePath) {
|
|
159
|
+
const value = await git(worktreePath, ['rev-parse', '--git-dir']);
|
|
160
|
+
return realpath(isAbsolute(value) ? value : resolve(worktreePath, value));
|
|
161
|
+
}
|
|
162
|
+
async function writeMarker(path, record) {
|
|
163
|
+
const gitDirectory = await linkedGitDirectory(path);
|
|
164
|
+
const marker = join(gitDirectory, 'PRAXIS_WORKTREE');
|
|
165
|
+
try {
|
|
166
|
+
await lstat(marker);
|
|
167
|
+
throw new Error('Managed worktree marker already exists');
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
if (error.code !== 'ENOENT')
|
|
171
|
+
throw error;
|
|
172
|
+
}
|
|
173
|
+
const committed = await writeFileAtomically(marker, `${JSON.stringify({ version: 1, worktreeId: record.worktreeId, repositoryRoot: record.repositoryRoot })}\n`, {
|
|
174
|
+
mode: 0o600,
|
|
175
|
+
beforeCommit: async () => {
|
|
176
|
+
try {
|
|
177
|
+
await lstat(marker);
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
catch (error) {
|
|
181
|
+
return error.code === 'ENOENT';
|
|
182
|
+
}
|
|
183
|
+
},
|
|
184
|
+
});
|
|
185
|
+
if (!committed)
|
|
186
|
+
throw new Error('Managed worktree marker already exists');
|
|
187
|
+
}
|
|
188
|
+
async function readMarker(worktreePath, record) {
|
|
189
|
+
const markerPath = join(await linkedGitDirectory(worktreePath), 'PRAXIS_WORKTREE');
|
|
190
|
+
let marker;
|
|
191
|
+
try {
|
|
192
|
+
marker = JSON.parse(await readRegularFile(markerPath, 'worktree marker'));
|
|
193
|
+
}
|
|
194
|
+
catch {
|
|
195
|
+
throw new Error('worktree marker is invalid');
|
|
196
|
+
}
|
|
197
|
+
if (typeof marker !== 'object' ||
|
|
198
|
+
marker === null ||
|
|
199
|
+
Array.isArray(marker) ||
|
|
200
|
+
Object.keys(marker).length !== MARKER_FIELDS.size ||
|
|
201
|
+
Object.keys(marker).some((key) => !MARKER_FIELDS.has(key)) ||
|
|
202
|
+
marker.version !== 1 ||
|
|
203
|
+
marker.worktreeId !== record.worktreeId ||
|
|
204
|
+
marker.repositoryRoot !== record.repositoryRoot) {
|
|
205
|
+
throw new Error('worktree marker does not match ownership record');
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
async function inspectOwnedCheckout(record, registered) {
|
|
209
|
+
const registrations = registered ?? (await registeredWorktrees(record.repositoryRoot));
|
|
210
|
+
const pathEntry = await lstat(record.worktreePath);
|
|
211
|
+
if (pathEntry.isSymbolicLink() || !pathEntry.isDirectory()) {
|
|
212
|
+
throw new Error('worktree path is not a real directory');
|
|
213
|
+
}
|
|
214
|
+
await assertRealDirectory(record.worktreePath, 'managed worktree path');
|
|
215
|
+
if ((await realpath(record.worktreePath)) !== resolve(record.worktreePath)) {
|
|
216
|
+
throw new Error('worktree path is not canonical');
|
|
217
|
+
}
|
|
218
|
+
if (!registrations.has(resolve(record.worktreePath))) {
|
|
219
|
+
throw new Error('worktree is not registered');
|
|
220
|
+
}
|
|
221
|
+
const [status, head, topLevel] = await Promise.all([
|
|
222
|
+
git(record.worktreePath, ['status', '--porcelain']),
|
|
223
|
+
git(record.worktreePath, ['rev-parse', 'HEAD']),
|
|
224
|
+
git(record.worktreePath, ['rev-parse', '--show-toplevel']),
|
|
225
|
+
]);
|
|
226
|
+
const worktreeRoot = await realpath(resolve(record.worktreePath, topLevel));
|
|
227
|
+
if (worktreeRoot !== resolve(record.worktreePath)) {
|
|
228
|
+
throw new Error('registered worktree root does not match');
|
|
229
|
+
}
|
|
230
|
+
const root = await resolveProjectIdentity(record.worktreePath);
|
|
231
|
+
if (root !== record.repositoryRoot) {
|
|
232
|
+
throw new Error('repository identity does not match');
|
|
233
|
+
}
|
|
234
|
+
await readMarker(record.worktreePath, record);
|
|
235
|
+
const branch = await gitOptional(record.worktreePath, [
|
|
236
|
+
'symbolic-ref',
|
|
237
|
+
'--quiet',
|
|
238
|
+
'--short',
|
|
239
|
+
'HEAD',
|
|
240
|
+
]);
|
|
241
|
+
if (branch)
|
|
242
|
+
throw new Error('worktree is not detached');
|
|
243
|
+
return { status, head };
|
|
244
|
+
}
|
|
245
|
+
function sameOwnership(left, right) {
|
|
246
|
+
return (left.worktreeId === right.worktreeId &&
|
|
247
|
+
left.kind === right.kind &&
|
|
248
|
+
left.policy === right.policy &&
|
|
249
|
+
left.ownerId === right.ownerId &&
|
|
250
|
+
left.repositoryRoot === right.repositoryRoot &&
|
|
251
|
+
left.worktreePath === right.worktreePath &&
|
|
252
|
+
left.branch === right.branch &&
|
|
253
|
+
left.baseCommit === right.baseCommit &&
|
|
254
|
+
left.createdAt === right.createdAt);
|
|
255
|
+
}
|
|
256
|
+
function nextRecord(record, state, retentionReason) {
|
|
257
|
+
const base = { ...record };
|
|
258
|
+
delete base.retentionReason;
|
|
259
|
+
return {
|
|
260
|
+
...base,
|
|
261
|
+
state,
|
|
262
|
+
updatedAt: new Date().toISOString(),
|
|
263
|
+
...(retentionReason === undefined ? {} : { retentionReason }),
|
|
264
|
+
};
|
|
265
|
+
}
|
|
266
|
+
async function retain(store, record, reason) {
|
|
267
|
+
try {
|
|
268
|
+
await store.update(nextRecord(record, 'retained', reason));
|
|
269
|
+
return { retained: true, reason };
|
|
270
|
+
}
|
|
271
|
+
catch (error) {
|
|
272
|
+
return {
|
|
273
|
+
retained: true,
|
|
274
|
+
reason: `${reason}; could not persist retention state: ${error instanceof Error ? error.message : String(error)}`,
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
export async function createOwnedManagedWorktree(options) {
|
|
279
|
+
if (!COMPONENT_PATTERN.test(options.directoryName)) {
|
|
280
|
+
throw worktreeError(options, 'name is invalid');
|
|
281
|
+
}
|
|
282
|
+
if (!validOwnerId(options.ownerId)) {
|
|
283
|
+
throw worktreeError(options, 'owner ID is invalid');
|
|
284
|
+
}
|
|
285
|
+
if (!['workflow', 'agent', 'team'].includes(options.kind)) {
|
|
286
|
+
throw worktreeError(options, 'kind is invalid');
|
|
287
|
+
}
|
|
288
|
+
let repositoryRoot;
|
|
289
|
+
let baseCommit;
|
|
290
|
+
try {
|
|
291
|
+
;
|
|
292
|
+
[repositoryRoot, baseCommit] = await Promise.all([
|
|
293
|
+
resolveProjectIdentity(options.cwd),
|
|
294
|
+
git(options.cwd, ['rev-parse', 'HEAD']),
|
|
295
|
+
]);
|
|
296
|
+
}
|
|
297
|
+
catch {
|
|
298
|
+
throw worktreeError(options, 'isolation requires a Git repository');
|
|
299
|
+
}
|
|
300
|
+
const kindRoot = join(repositoryRoot, '.praxis', 'worktrees', options.kind);
|
|
301
|
+
const worktreePath = join(kindRoot, options.directoryName);
|
|
302
|
+
const rootRelative = relative(kindRoot, worktreePath);
|
|
303
|
+
if (!rootRelative ||
|
|
304
|
+
rootRelative === '..' ||
|
|
305
|
+
rootRelative.startsWith(`..${sep}`) ||
|
|
306
|
+
isAbsolute(rootRelative)) {
|
|
307
|
+
throw worktreeError(options, 'path escapes its kind root');
|
|
308
|
+
}
|
|
309
|
+
await assertRealDirectory(join(repositoryRoot, '.praxis'), 'managed worktree parent');
|
|
310
|
+
await assertRealDirectory(join(repositoryRoot, '.praxis', 'worktrees'), 'managed worktree parent');
|
|
311
|
+
await assertRealDirectory(kindRoot, 'managed worktree kind root');
|
|
312
|
+
await ensureManagedRootIgnored(repositoryRoot);
|
|
313
|
+
const worktreeId = managedWorktreeId(repositoryRoot, options.kind, options.ownerId);
|
|
314
|
+
const store = new ManagedWorktreeStore(options.stateRoot, repositoryRoot, worktreeId);
|
|
315
|
+
const lease = await store.acquireLease();
|
|
316
|
+
if (!lease)
|
|
317
|
+
throw worktreeError(options, `is already owned: ${worktreePath}`);
|
|
318
|
+
const now = new Date().toISOString();
|
|
319
|
+
const record = {
|
|
320
|
+
version: 1,
|
|
321
|
+
worktreeId,
|
|
322
|
+
kind: options.kind,
|
|
323
|
+
policy: options.policy,
|
|
324
|
+
ownerId: options.ownerId,
|
|
325
|
+
repositoryRoot,
|
|
326
|
+
worktreePath,
|
|
327
|
+
branch: null,
|
|
328
|
+
baseCommit,
|
|
329
|
+
state: 'creating',
|
|
330
|
+
createdAt: now,
|
|
331
|
+
updatedAt: now,
|
|
332
|
+
};
|
|
333
|
+
let recordCreated = false;
|
|
334
|
+
let gitCreated = false;
|
|
335
|
+
let markerCreated = false;
|
|
336
|
+
let created = false;
|
|
337
|
+
try {
|
|
338
|
+
await store.create(record);
|
|
339
|
+
recordCreated = true;
|
|
340
|
+
try {
|
|
341
|
+
const entry = await lstat(worktreePath);
|
|
342
|
+
if (entry.isSymbolicLink()) {
|
|
343
|
+
throw worktreeError(options, 'path must not be a symlink');
|
|
344
|
+
}
|
|
345
|
+
throw worktreeError(options, `path already exists: ${worktreePath}`);
|
|
346
|
+
}
|
|
347
|
+
catch (error) {
|
|
348
|
+
if (error.code !== 'ENOENT')
|
|
349
|
+
throw error;
|
|
350
|
+
}
|
|
351
|
+
await mkdir(kindRoot, { recursive: true });
|
|
352
|
+
await assertRealDirectory(kindRoot, 'managed worktree kind root');
|
|
353
|
+
await git(repositoryRoot, [
|
|
354
|
+
'worktree',
|
|
355
|
+
'add',
|
|
356
|
+
'--detach',
|
|
357
|
+
worktreePath,
|
|
358
|
+
baseCommit,
|
|
359
|
+
]);
|
|
360
|
+
gitCreated = true;
|
|
361
|
+
await writeMarker(worktreePath, record);
|
|
362
|
+
markerCreated = true;
|
|
363
|
+
await store.update(nextRecord(record, 'active'));
|
|
364
|
+
created = true;
|
|
365
|
+
}
|
|
366
|
+
catch (error) {
|
|
367
|
+
let rollbackError;
|
|
368
|
+
let uncertainArtifact = false;
|
|
369
|
+
if (gitCreated) {
|
|
370
|
+
try {
|
|
371
|
+
if (!markerCreated) {
|
|
372
|
+
throw new Error('ownership marker was not published');
|
|
373
|
+
}
|
|
374
|
+
const inspection = await inspectOwnedCheckout(record);
|
|
375
|
+
if (inspection.status.length > 0) {
|
|
376
|
+
throw new Error('created worktree is no longer clean');
|
|
377
|
+
}
|
|
378
|
+
if (inspection.head !== record.baseCommit) {
|
|
379
|
+
throw new Error('created worktree HEAD no longer matches its base');
|
|
380
|
+
}
|
|
381
|
+
await git(repositoryRoot, ['worktree', 'remove', worktreePath]);
|
|
382
|
+
}
|
|
383
|
+
catch (removeError) {
|
|
384
|
+
rollbackError = removeError;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
else {
|
|
388
|
+
try {
|
|
389
|
+
const registered = await registeredWorktrees(repositoryRoot);
|
|
390
|
+
const pathExists = await lstat(worktreePath)
|
|
391
|
+
.then(() => true)
|
|
392
|
+
.catch((pathError) => {
|
|
393
|
+
if (pathError.code === 'ENOENT') {
|
|
394
|
+
return false;
|
|
395
|
+
}
|
|
396
|
+
throw pathError;
|
|
397
|
+
});
|
|
398
|
+
uncertainArtifact = pathExists || registered.has(resolve(worktreePath));
|
|
399
|
+
}
|
|
400
|
+
catch {
|
|
401
|
+
uncertainArtifact = true;
|
|
402
|
+
}
|
|
403
|
+
}
|
|
404
|
+
if (recordCreated) {
|
|
405
|
+
try {
|
|
406
|
+
const retentionReason = rollbackError
|
|
407
|
+
? `Could not roll back ${worktreePath}: ${rollbackError.message}`
|
|
408
|
+
: uncertainArtifact
|
|
409
|
+
? `Creation failed with an unverified artifact at ${worktreePath}`
|
|
410
|
+
: undefined;
|
|
411
|
+
const failed = retentionReason
|
|
412
|
+
? nextRecord(record, 'retained', retentionReason)
|
|
413
|
+
: nextRecord(record, 'released');
|
|
414
|
+
await store.update(failed);
|
|
415
|
+
}
|
|
416
|
+
catch (stateError) {
|
|
417
|
+
rollbackError ??= stateError;
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
const primary = error instanceof Error ? error.message : String(error);
|
|
421
|
+
throw worktreeError(options, `could not be created: ${primary}${rollbackError ? `; cleanup warning: ${rollbackError.message}` : ''}`);
|
|
422
|
+
}
|
|
423
|
+
finally {
|
|
424
|
+
if (!created)
|
|
425
|
+
await lease.release();
|
|
426
|
+
}
|
|
427
|
+
let executionLease = lease;
|
|
428
|
+
let removedResult;
|
|
429
|
+
let cleanupInFlight;
|
|
430
|
+
return {
|
|
431
|
+
cwd: worktreePath,
|
|
432
|
+
cleanup: async () => {
|
|
433
|
+
if (removedResult)
|
|
434
|
+
return removedResult;
|
|
435
|
+
if (cleanupInFlight)
|
|
436
|
+
return cleanupInFlight;
|
|
437
|
+
const heldLease = executionLease;
|
|
438
|
+
executionLease = undefined;
|
|
439
|
+
cleanupInFlight = cleanupOwnedManagedWorktree(store, options, record, heldLease);
|
|
440
|
+
try {
|
|
441
|
+
const result = await cleanupInFlight;
|
|
442
|
+
if (!result.retained)
|
|
443
|
+
removedResult = result;
|
|
444
|
+
return result;
|
|
445
|
+
}
|
|
446
|
+
finally {
|
|
447
|
+
cleanupInFlight = undefined;
|
|
448
|
+
}
|
|
449
|
+
},
|
|
450
|
+
};
|
|
451
|
+
}
|
|
452
|
+
async function cleanupOwnedManagedWorktree(store, options, original, heldLease) {
|
|
453
|
+
const lease = heldLease ?? (await store.acquireLease());
|
|
454
|
+
if (!lease)
|
|
455
|
+
return {
|
|
456
|
+
retained: true,
|
|
457
|
+
reason: `${options.label} worktree cleanup is already in progress`,
|
|
458
|
+
};
|
|
459
|
+
try {
|
|
460
|
+
let record;
|
|
461
|
+
try {
|
|
462
|
+
record = await store.read();
|
|
463
|
+
}
|
|
464
|
+
catch (error) {
|
|
465
|
+
return {
|
|
466
|
+
retained: true,
|
|
467
|
+
reason: `Could not inspect ${options.label.toLowerCase()} worktree record: ${error.message}`,
|
|
468
|
+
};
|
|
469
|
+
}
|
|
470
|
+
if (!sameOwnership(record, original)) {
|
|
471
|
+
return {
|
|
472
|
+
retained: true,
|
|
473
|
+
reason: `${options.label} worktree ownership record does not match`,
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
if (record.state === 'released')
|
|
477
|
+
return { retained: false };
|
|
478
|
+
if (record.state !== 'active' &&
|
|
479
|
+
record.state !== 'retained' &&
|
|
480
|
+
record.state !== 'releasing') {
|
|
481
|
+
return {
|
|
482
|
+
retained: true,
|
|
483
|
+
reason: `${options.label} worktree is not releasable`,
|
|
484
|
+
};
|
|
485
|
+
}
|
|
486
|
+
if (record.policy === 'durable') {
|
|
487
|
+
return retain(store, record, `${options.label} worktree uses durable retention policy`);
|
|
488
|
+
}
|
|
489
|
+
const releasing = nextRecord(record, 'releasing');
|
|
490
|
+
try {
|
|
491
|
+
await store.update(releasing);
|
|
492
|
+
}
|
|
493
|
+
catch (error) {
|
|
494
|
+
return {
|
|
495
|
+
retained: true,
|
|
496
|
+
reason: `Could not update ${options.label.toLowerCase()} worktree record: ${error.message}`,
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
const registered = await registeredWorktrees(record.repositoryRoot).catch(() => null);
|
|
500
|
+
if (!registered) {
|
|
501
|
+
return retain(store, releasing, `Could not inspect registered ${options.label.toLowerCase()} worktrees`);
|
|
502
|
+
}
|
|
503
|
+
try {
|
|
504
|
+
await lstat(record.worktreePath);
|
|
505
|
+
}
|
|
506
|
+
catch (error) {
|
|
507
|
+
if (error.code !== 'ENOENT') {
|
|
508
|
+
return retain(store, releasing, `Could not inspect ${options.label.toLowerCase()} worktree path: ${error instanceof Error ? error.message : String(error)}`);
|
|
509
|
+
}
|
|
510
|
+
if (registered.has(resolve(record.worktreePath))) {
|
|
511
|
+
return retain(store, releasing, `${options.label} worktree is missing but remains registered at ${record.worktreePath}`);
|
|
512
|
+
}
|
|
513
|
+
try {
|
|
514
|
+
await store.update(nextRecord(releasing, 'released'));
|
|
515
|
+
return { retained: false };
|
|
516
|
+
}
|
|
517
|
+
catch (stateError) {
|
|
518
|
+
return {
|
|
519
|
+
retained: false,
|
|
520
|
+
reason: `${options.label} worktree is already absent but release state could not be persisted: ${stateError instanceof Error ? stateError.message : String(stateError)}`,
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
let inspection;
|
|
525
|
+
try {
|
|
526
|
+
inspection = await inspectOwnedCheckout(record, registered);
|
|
527
|
+
}
|
|
528
|
+
catch (error) {
|
|
529
|
+
const reason = `Could not verify ${options.label.toLowerCase()} worktree ${record.worktreePath}: ${error.message}`;
|
|
530
|
+
return retain(store, releasing, reason);
|
|
531
|
+
}
|
|
532
|
+
if (inspection.status.length > 0) {
|
|
533
|
+
const reason = `${options.label} worktree has uncommitted changes and was retained at ${record.worktreePath}`;
|
|
534
|
+
return retain(store, releasing, reason);
|
|
535
|
+
}
|
|
536
|
+
if (inspection.head !== record.baseCommit) {
|
|
537
|
+
const reason = `${options.label} worktree has commits and was retained at ${record.worktreePath}`;
|
|
538
|
+
return retain(store, releasing, reason);
|
|
539
|
+
}
|
|
540
|
+
try {
|
|
541
|
+
await git(record.repositoryRoot, [
|
|
542
|
+
'worktree',
|
|
543
|
+
'remove',
|
|
544
|
+
record.worktreePath,
|
|
545
|
+
]);
|
|
546
|
+
}
|
|
547
|
+
catch (error) {
|
|
548
|
+
const reason = `Could not remove ${options.label.toLowerCase()} worktree ${record.worktreePath}: ${error.message}`;
|
|
549
|
+
return retain(store, releasing, reason);
|
|
550
|
+
}
|
|
551
|
+
try {
|
|
552
|
+
await store.update(nextRecord(releasing, 'released'));
|
|
553
|
+
}
|
|
554
|
+
catch (error) {
|
|
555
|
+
return {
|
|
556
|
+
retained: false,
|
|
557
|
+
reason: `Could not update ${options.label.toLowerCase()} worktree record after removal: ${error.message}`,
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
return { retained: false };
|
|
561
|
+
}
|
|
562
|
+
finally {
|
|
563
|
+
await lease.release();
|
|
564
|
+
}
|
|
15
565
|
}
|
|
16
566
|
export async function createManagedWorktree(options) {
|
|
17
567
|
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,191}$/u.test(options.directoryName)) {
|
|
@@ -1,11 +1,13 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { createManagedWorktree, } from './managed-worktree.js';
|
|
1
|
+
import { createOwnedManagedWorktree, } from './managed-worktree.js';
|
|
3
2
|
export async function createWorkflowWorktree(options) {
|
|
4
|
-
return
|
|
3
|
+
return createOwnedManagedWorktree({
|
|
5
4
|
cwd: options.cwd,
|
|
6
|
-
|
|
5
|
+
stateRoot: options.praxisRoot,
|
|
7
6
|
directoryName: `${options.runId}-${options.agentId}`,
|
|
7
|
+
ownerId: `workflow:${options.runId}:${options.agentId}`,
|
|
8
8
|
label: 'Workflow',
|
|
9
|
+
kind: 'workflow',
|
|
10
|
+
policy: 'ephemeral',
|
|
9
11
|
});
|
|
10
12
|
}
|
|
11
13
|
//# sourceMappingURL=workflow-worktree.js.map
|
package/dist/cli/interactive.js
CHANGED
|
@@ -1968,6 +1968,9 @@ export function InteractiveApp({ dataPlane = resolveDataPlane(), configRoot: sup
|
|
|
1968
1968
|
},
|
|
1969
1969
|
});
|
|
1970
1970
|
break;
|
|
1971
|
+
case 'task-input-waiting':
|
|
1972
|
+
append({ kind: 'warning', text: event.summary });
|
|
1973
|
+
break;
|
|
1971
1974
|
case 'compact-boundary':
|
|
1972
1975
|
append({
|
|
1973
1976
|
kind: 'notice',
|
package/dist/cli/protocol.d.ts
CHANGED
|
@@ -243,6 +243,7 @@ export interface ProtocolTimingProjection {
|
|
|
243
243
|
}
|
|
244
244
|
export declare function projectProtocolTimings(startedAt: number, requestAt?: number, outputAt?: number): ProtocolTimingProjection;
|
|
245
245
|
export declare function createSuccessResult(result: ProtocolResult, info: CliRuntimeInfo, startedAt: number, modelTurns: number, context?: ProtocolSuccessProjectionContext): Record<string, unknown>;
|
|
246
|
+
export declare function formatPrintTextError(message: string, context?: ProtocolErrorProjectionContext): string;
|
|
246
247
|
export declare function createErrorResult(message: string, sessionId: string, startedAt: number, modelTurns: number, context?: ProtocolErrorProjectionContext): Record<string, unknown>;
|
|
247
248
|
/**
|
|
248
249
|
* Returns the argument text of a headless `/color` prompt, or undefined when
|
package/dist/cli/protocol.js
CHANGED
|
@@ -94,14 +94,44 @@ export function createSuccessResult(result, info, startedAt, modelTurns, context
|
|
|
94
94
|
uuid: randomUUID(),
|
|
95
95
|
};
|
|
96
96
|
}
|
|
97
|
+
function classifyErrorResult(message) {
|
|
98
|
+
const maxBudget = /Maximum budget of \$([0-9]+(?:\.[0-9]+)?) exceeded/iu.exec(message);
|
|
99
|
+
if (maxBudget || /maximum budget|budget .* exceeded/iu.test(message)) {
|
|
100
|
+
return {
|
|
101
|
+
subtype: 'error_max_budget_usd',
|
|
102
|
+
...(maxBudget?.[1] === undefined ? {} : { maxBudgetUsd: maxBudget[1] }),
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
const maxTurns = /Maximum model turns of (\d+) exceeded/iu.exec(message);
|
|
106
|
+
if (maxTurns || /maximum model turns|model turn limit/iu.test(message)) {
|
|
107
|
+
return {
|
|
108
|
+
subtype: 'error_max_turns',
|
|
109
|
+
...(maxTurns?.[1] === undefined ? {} : { maxTurns: maxTurns[1] }),
|
|
110
|
+
};
|
|
111
|
+
}
|
|
112
|
+
if (/StructuredOutput/iu.test(message)) {
|
|
113
|
+
return { subtype: 'error_max_structured_output_retries' };
|
|
114
|
+
}
|
|
115
|
+
return { subtype: 'error_during_execution' };
|
|
116
|
+
}
|
|
97
117
|
function errorResultSubtype(message) {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
118
|
+
return classifyErrorResult(message).subtype;
|
|
119
|
+
}
|
|
120
|
+
export function formatPrintTextError(message, context = {}) {
|
|
121
|
+
if (context.providerApiError === true) {
|
|
122
|
+
const normalized = typeof context.apiErrorStatus === 'number'
|
|
123
|
+
? normalizeApiError(message, context.apiErrorStatus)
|
|
124
|
+
: message;
|
|
125
|
+
return `${normalized}\n`;
|
|
126
|
+
}
|
|
127
|
+
const classification = classifyErrorResult(message);
|
|
128
|
+
if (classification.maxTurns !== undefined)
|
|
129
|
+
return `Error: Reached max turns (${classification.maxTurns})`;
|
|
130
|
+
if (classification.maxBudgetUsd !== undefined)
|
|
131
|
+
return `Error: Exceeded USD budget (${classification.maxBudgetUsd})`;
|
|
132
|
+
if (classification.subtype === 'error_max_structured_output_retries')
|
|
133
|
+
return 'Error: Failed to provide valid structured output after maximum retries';
|
|
134
|
+
return 'Execution error';
|
|
105
135
|
}
|
|
106
136
|
export function createErrorResult(message, sessionId, startedAt, modelTurns, context = {}) {
|
|
107
137
|
const duration = Date.now() - startedAt;
|
|
@@ -2206,6 +2236,21 @@ export class StreamJsonOutput {
|
|
|
2206
2236
|
});
|
|
2207
2237
|
return;
|
|
2208
2238
|
}
|
|
2239
|
+
if (event.type === 'task-input-waiting') {
|
|
2240
|
+
this.write({
|
|
2241
|
+
type: 'system',
|
|
2242
|
+
subtype: 'task_notification',
|
|
2243
|
+
task_id: event.taskId,
|
|
2244
|
+
...(event.toolUseId === undefined
|
|
2245
|
+
? {}
|
|
2246
|
+
: { tool_use_id: event.toolUseId }),
|
|
2247
|
+
output_file: event.outputFile,
|
|
2248
|
+
summary: event.summary,
|
|
2249
|
+
uuid: randomUUID(),
|
|
2250
|
+
session_id: this.sessionId,
|
|
2251
|
+
});
|
|
2252
|
+
return;
|
|
2253
|
+
}
|
|
2209
2254
|
if (event.type === 'session-state-changed') {
|
|
2210
2255
|
this.writeSessionState(event.state);
|
|
2211
2256
|
return;
|
package/dist/cli-runtime.d.ts
CHANGED
|
@@ -34,6 +34,7 @@ export interface CliIO {
|
|
|
34
34
|
stdout(message: string | Uint8Array): void;
|
|
35
35
|
stderr(message: string): void;
|
|
36
36
|
isTTY?: boolean;
|
|
37
|
+
stdinIsTTY?: boolean;
|
|
37
38
|
readStdinLines?: () => AsyncIterable<string | Uint8Array>;
|
|
38
39
|
readSecret?: (prompt: string, signal?: AbortSignal) => Promise<string>;
|
|
39
40
|
}
|