@xingular/harness 1.3.1-unstable.4 → 1.3.1-unstable.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +74 -0
- package/README.md +14 -9
- package/dist/cli.js +1734 -796
- package/dist/sdk/accounts/choices.d.ts +18 -0
- package/dist/sdk/accounts/choices.js +27 -0
- package/dist/sdk/cli.js +4 -0
- package/dist/sdk/commands/extensionOwners.d.ts +4 -0
- package/dist/sdk/commands/extensionOwners.js +17 -0
- package/dist/sdk/commands/list.js +15 -2
- package/dist/sdk/commands/promptLoader.d.ts +5 -0
- package/dist/sdk/commands/promptLoader.js +76 -0
- package/dist/sdk/commands/promptRoutes.d.ts +13 -0
- package/dist/sdk/commands/promptRoutes.js +46 -0
- package/dist/sdk/commands/registry.d.ts +14 -0
- package/dist/sdk/commands/registry.js +2 -0
- package/dist/sdk/commands/runtimeRouter.d.ts +4 -0
- package/dist/sdk/commands/runtimeRouter.js +48 -0
- package/dist/sdk/computer/boundary.d.ts +40 -0
- package/dist/sdk/computer/boundary.js +79 -0
- package/dist/sdk/computer/contracts.d.ts +127 -0
- package/dist/sdk/computer/contracts.js +13 -0
- package/dist/sdk/computer/control.d.ts +34 -0
- package/dist/sdk/computer/control.js +112 -0
- package/dist/sdk/computer/terminalCapture.d.ts +26 -0
- package/dist/sdk/computer/terminalCapture.js +64 -0
- package/dist/sdk/computer/volatileImages.d.ts +9 -0
- package/dist/sdk/computer/volatileImages.js +50 -0
- package/dist/sdk/context/runDetails.d.ts +16 -0
- package/dist/sdk/context/runDetails.js +22 -0
- package/dist/sdk/doctor/checks.js +3 -0
- package/dist/sdk/doctor/probe.js +8 -6
- package/dist/sdk/harness.d.ts +8 -0
- package/dist/sdk/harness.js +7 -4
- package/dist/sdk/history/trajectory.js +2 -0
- package/dist/sdk/hub/hub.js +1 -1
- package/dist/sdk/hub/schema.d.ts +2 -2
- package/dist/sdk/plugins/manifest.d.ts +2 -0
- package/dist/sdk/plugins/manifest.js +1 -0
- package/dist/sdk/prompt/compile.d.ts +3 -1
- package/dist/sdk/prompt/compile.js +10 -7
- package/dist/sdk/refine/host.d.ts +9 -1
- package/dist/sdk/refine/host.js +29 -0
- package/dist/sdk/refine/prompts.d.ts +15 -0
- package/dist/sdk/refine/prompts.js +44 -0
- package/dist/sdk/refine/recursion.js +4 -4
- package/dist/sdk/refine/runner.d.ts +2 -0
- package/dist/sdk/refine/runner.js +2 -1
- package/dist/sdk/refine/serverMethods.js +4 -1
- package/dist/sdk/refine/service.d.ts +31 -0
- package/dist/sdk/refine/service.js +119 -4
- package/dist/sdk/refine/trajectory.js +7 -2
- package/dist/sdk/refine/types.d.ts +16 -0
- package/dist/sdk/remote/webClient.js +7 -3
- package/dist/sdk/server/methods.js +31 -1
- package/dist/sdk/sessions/compactionCheckpoint.d.ts +6 -1
- package/dist/sdk/sessions/compactionCheckpoint.js +34 -35
- package/dist/sdk/sessions/contracts.d.ts +141 -2
- package/dist/sdk/sessions/contracts.js +115 -3
- package/dist/sdk/sessions/planMode.d.ts +1 -1
- package/dist/sdk/sessions/planMode.js +7 -4
- package/dist/sdk/sessions/registry.d.ts +6 -2
- package/dist/sdk/sessions/registry.js +16 -13
- package/dist/sdk/sessions/runStore.d.ts +3 -1
- package/dist/sdk/sessions/runStore.js +26 -8
- package/dist/sdk/sessions/runner.d.ts +5 -5
- package/dist/sdk/sessions/runner.js +78 -15
- package/dist/sdk/sessions/sessions.js +35 -21
- package/dist/sdk/sessions/workSlice.d.ts +2 -0
- package/dist/sdk/sessions/workSlice.js +4 -3
- package/dist/sdk/terminal/client.d.ts +3 -0
- package/dist/sdk/terminal/client.js +13 -0
- package/dist/sdk/terminal/controller.d.ts +2 -0
- package/dist/sdk/terminal/controller.js +12 -6
- package/dist/sdk/terminal/opentui/theme.d.ts +2 -0
- package/dist/sdk/terminal/opentui/theme.js +4 -0
- package/dist/sdk/terminal/piExtension.js +73 -13
- package/dist/sdk/terminal/standalone.d.ts +6 -1
- package/dist/sdk/terminal/standalone.js +30 -3
- package/dist/sdk/terminal/terminals.d.ts +11 -1
- package/dist/sdk/terminal/terminals.js +58 -5
- package/dist/sdk/terminal/trajectory.js +2 -2
- package/dist/sdk/terminal/tui/commandPages.d.ts +1 -1
- package/dist/sdk/terminal/tui/commandPages.js +4 -2
- package/dist/sdk/terminal/tui/commands.js +29 -65
- package/dist/sdk/terminal/tui/modeChoices.d.ts +18 -0
- package/dist/sdk/terminal/tui/modeChoices.js +26 -1
- package/dist/sdk/terminal/tui/pages/contextPage.d.ts +30 -1
- package/dist/sdk/terminal/tui/pages/contextPage.js +109 -8
- package/dist/sdk/terminal/tui/pages/textPage.d.ts +17 -0
- package/dist/sdk/terminal/tui/pages/textPage.js +52 -0
- package/dist/sdk/terminal/tui/pages/trajectoryPage.d.ts +1 -0
- package/dist/sdk/terminal/tui/pages/trajectoryPage.js +12 -3
- package/dist/sdk/terminal/tui/runtime.js +60 -3
- package/dist/sdk/terminal/tui/sideQuestion.d.ts +3 -0
- package/dist/sdk/terminal/tui/sideQuestion.js +7 -1
- package/dist/sdk/terminal/tui/status.d.ts +0 -6
- package/dist/sdk/terminal/tui/status.js +1 -15
- package/dist/sdk/terminal/tui/variantCommands.d.ts +32 -0
- package/dist/sdk/terminal/tui/variantCommands.js +359 -0
- package/dist/sdk/terminal/variantControl.d.ts +24 -0
- package/dist/sdk/terminal/variantControl.js +145 -0
- package/dist/sdk/tools/definitions.js +1 -1
- package/dist/sdk/tools/dispatch.d.ts +1 -1
- package/dist/sdk/tools/dispatch.js +17 -3
- package/dist/sdk/variant/store.d.ts +33 -1
- package/dist/sdk/variant/store.js +108 -3
- package/dist/sdk/worktrees/git.d.ts +2 -0
- package/dist/sdk/worktrees/git.js +8 -0
- package/dist/sdk/worktrees/snapshot.d.ts +16 -0
- package/dist/sdk/worktrees/snapshot.js +83 -0
- package/dist/sdk/world/actions.js +1 -1
- package/dist/terminal-opentui.js +1643 -451
- package/dist/terminal-pi.js +179 -56
- package/docs/architecture/02-sessions-and-runs.md +33 -13
- package/docs/architecture/03-variants.md +24 -3
- package/docs/architecture/04-prompt.md +22 -11
- package/docs/architecture/05-refinement.md +32 -5
- package/docs/architecture/06-plugins-and-capabilities.md +13 -2
- package/docs/architecture/07-tools-and-gate.md +14 -0
- package/docs/architecture/08-memory-and-history.md +7 -3
- package/docs/architecture/09-accounts-and-connectors.md +13 -3
- package/docs/architecture/10-server-protocol.md +26 -3
- package/docs/architecture/11-terminal.md +50 -19
- package/docs/architecture/12-storage.md +12 -4
- package/docs/architecture/13-world-tools.md +19 -0
- package/docs/architecture/14-surfaces-and-parity.md +3 -3
- package/docs/architecture/README.md +2 -0
- package/docs/architecture/proposals/PROP-0049-context-attribution.md +7 -1
- package/docs/architecture/proposals/PROP-0050-run-stop-codes-and-refusals.md +30 -0
- package/docs/architecture/proposals/PROP-0051-unfinished-run-handoff.md +110 -0
- package/docs/architecture/proposals/PROP-0052-terminal-refine-and-variant-switch.md +111 -0
- package/docs/architecture/proposals/README.md +2 -0
- package/docs/decisions/ADR-0032-compaction-run-checkpoints.md +3 -1
- package/docs/decisions/ADR-0059-run-diagnostic-evidence.md +35 -0
- package/docs/decisions/ADR-0060-approvals-are-controls.md +40 -0
- package/docs/decisions/ADR-0061-strict-plugin-command-namespaces.md +41 -0
- package/docs/decisions/ADR-0062-shared-account-state.md +67 -0
- package/docs/decisions/ADR-0063-unfinished-work-handoffs.md +32 -0
- package/docs/decisions/ADR-0064-account-model-fallback-on-resume.md +79 -0
- package/docs/decisions/ADR-0065-variant-switch-at-turn-boundaries.md +31 -0
- package/docs/decisions/ADR-0066-guided-refinement-from-turn-snapshots.md +37 -0
- package/docs/decisions/ADR-0067-cache-stable-compaction-checkpoint.md +54 -0
- package/docs/doctor.md +2 -0
- package/docs/parity.md +18 -7
- package/docs/releases/1.3.1-unstable.5.md +53 -0
- package/docs/releases/1.3.1-unstable.6.md +31 -0
- package/docs/releases/1.3.1-unstable.7.md +17 -0
- package/docs/releases/1.3.1-unstable.8.md +19 -0
- package/docs/terminal-tui.md +48 -16
- package/package.json +1 -1
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
import { randomUUID } from 'node:crypto';
|
|
4
4
|
import { log } from "../core/bus.js";
|
|
5
5
|
import { HarnessError } from "../core/errors.js";
|
|
6
|
-
import { isActiveStatus, questionSketchError, runEventSchema } from "./contracts.js";
|
|
6
|
+
import { isActiveStatus, questionAnswerProblem, questionSketchError, runEventSchema } from "./contracts.js";
|
|
7
7
|
import { findRun, persistEvent, readEvents, runFamily } from "./runStore.js";
|
|
8
8
|
function validateQuestionRecommendations(input) {
|
|
9
9
|
if (!Array.isArray(input.options) || input.options.length === 0) {
|
|
@@ -176,7 +176,7 @@ export class RunRegistry {
|
|
|
176
176
|
emit('status.changed', { status: 'waiting_for_input' });
|
|
177
177
|
return Promise.all(answers);
|
|
178
178
|
},
|
|
179
|
-
finish: (outcome, failure, reason) => {
|
|
179
|
+
finish: (outcome, failure, reason, code) => {
|
|
180
180
|
if (finished || finishing)
|
|
181
181
|
return;
|
|
182
182
|
finishing = true;
|
|
@@ -190,7 +190,7 @@ export class RunRegistry {
|
|
|
190
190
|
if (outcome === 'failed')
|
|
191
191
|
emit('failed', failure ?? { code: 'failed', message: 'The run failed.' });
|
|
192
192
|
else if (outcome === 'interrupted')
|
|
193
|
-
emit('status.changed', { status: 'interrupted', ...(reason ? { reason } : {}) });
|
|
193
|
+
emit('status.changed', { status: 'interrupted', ...(reason ? { reason } : {}), ...(code ? { code } : {}) });
|
|
194
194
|
else
|
|
195
195
|
emit('completed', {});
|
|
196
196
|
finished = true;
|
|
@@ -213,7 +213,7 @@ export class RunRegistry {
|
|
|
213
213
|
},
|
|
214
214
|
interrupt: async () => {
|
|
215
215
|
// Release approvals/questions before SDK abort waits for their blocked tools.
|
|
216
|
-
run.finish('interrupted');
|
|
216
|
+
run.finish('interrupted', undefined, undefined, 'user_abort');
|
|
217
217
|
for (const handler of interruptHandlers) {
|
|
218
218
|
try {
|
|
219
219
|
await handler();
|
|
@@ -229,7 +229,7 @@ export class RunRegistry {
|
|
|
229
229
|
emit('status.changed', { status: 'running' });
|
|
230
230
|
const record = findRun(this.options.root(), runId);
|
|
231
231
|
if (record?.parentRunId && this.hasStoppedAncestor(record.parentRunId))
|
|
232
|
-
run.finish('interrupted');
|
|
232
|
+
run.finish('interrupted', undefined, undefined, 'parent_stopped');
|
|
233
233
|
return run;
|
|
234
234
|
}
|
|
235
235
|
hasStoppedAncestor(runId) {
|
|
@@ -350,7 +350,6 @@ export class RunRegistry {
|
|
|
350
350
|
}
|
|
351
351
|
validateAnswer(input, answer) {
|
|
352
352
|
const selected = answer.selected;
|
|
353
|
-
const selectedLabels = new Set(selected);
|
|
354
353
|
const notes = {};
|
|
355
354
|
for (const [label, note] of Object.entries(answer.notes ?? {})) {
|
|
356
355
|
const normalized = typeof note === 'string' ? note.trim() : '';
|
|
@@ -358,13 +357,17 @@ export class RunRegistry {
|
|
|
358
357
|
notes[label] = normalized;
|
|
359
358
|
}
|
|
360
359
|
const text = answer.text?.trim();
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
(
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
360
|
+
const problem = questionAnswerProblem(input, { selected, ...(text ? { text } : {}), notes });
|
|
361
|
+
if (problem) {
|
|
362
|
+
// Shape only: the answer content is the person's, and never belongs in a diagnostic log.
|
|
363
|
+
log('a question answer was refused', {
|
|
364
|
+
summary: input.summary ?? null,
|
|
365
|
+
field: problem.field,
|
|
366
|
+
selected: selected.length,
|
|
367
|
+
notes: Object.keys(notes).length,
|
|
368
|
+
textLength: text?.length ?? 0
|
|
369
|
+
});
|
|
370
|
+
throw new HarnessError('invalid_answer', problem.message);
|
|
368
371
|
}
|
|
369
372
|
return { selected, ...(text ? { text } : {}), ...(Object.keys(notes).length ? { notes } : {}) };
|
|
370
373
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type RunEvent, type RunRecord, type UsagePayload } from "./contracts.js";
|
|
1
|
+
import { type RunEvent, type RunRecord, type RunStopCode, type UsagePayload } from "./contracts.js";
|
|
2
2
|
export declare function runDir(root: string, runId: string): string;
|
|
3
3
|
export declare function saveRun(root: string, record: RunRecord): void;
|
|
4
4
|
export declare function loadRun(root: string, runId: string): RunRecord;
|
|
@@ -9,6 +9,8 @@ export declare function recordedSubagents(root: string, parentRunId: string): st
|
|
|
9
9
|
/** Changes a run's record. A settled run keeps its outcome whatever the change says. */
|
|
10
10
|
export declare function updateRun(root: string, runId: string, update: (record: RunRecord) => void): void;
|
|
11
11
|
export declare function terminalStatus(event: Pick<RunEvent, 'type' | 'payload'>): 'completed' | 'failed' | 'interrupted' | null;
|
|
12
|
+
/** The stop code a terminal event carries; null for an interruption written without one. */
|
|
13
|
+
export declare function stopCodeOfEvent(event: Pick<RunEvent, 'type' | 'payload'>): RunStopCode | null;
|
|
12
14
|
export declare function appendEvent(root: string, event: RunEvent): void;
|
|
13
15
|
/** A torn final line (a crash mid-write) is skipped rather than failing the whole log. */
|
|
14
16
|
export declare function readEvents(root: string, runId: string): RunEvent[];
|
|
@@ -7,7 +7,7 @@ import { join } from 'node:path';
|
|
|
7
7
|
import { notFound } from "../core/errors.js";
|
|
8
8
|
import { newId, now, readJson, readJsonOr, safeId, writeJson } from "../core/fs.js";
|
|
9
9
|
import { compareText, lines } from "../core/text.js";
|
|
10
|
-
import { isActiveStatus, runEventSchema, runRecordSchema, upgradeRunRecord, usagePayloadSchema } from "./contracts.js";
|
|
10
|
+
import { isActiveStatus, runEventSchema, runRecordSchema, stopCodeOf, upgradeRunRecord, usagePayloadSchema } from "./contracts.js";
|
|
11
11
|
import { readAllRuns, recordRun, runsForSession } from "./runIndex.js";
|
|
12
12
|
export function runDir(root, runId) {
|
|
13
13
|
return join(root, 'runs', safeId(runId));
|
|
@@ -20,9 +20,11 @@ function ordered(record) {
|
|
|
20
20
|
parentRunId: record.parentRunId,
|
|
21
21
|
relation: record.relation,
|
|
22
22
|
terminalReason: record.terminalReason,
|
|
23
|
+
...(record.terminalCode !== undefined ? { terminalCode: record.terminalCode } : {}),
|
|
23
24
|
id: record.id,
|
|
24
25
|
projectId: record.projectId,
|
|
25
26
|
mode: record.mode,
|
|
27
|
+
...(record.effectiveMode !== undefined ? { effectiveMode: record.effectiveMode } : {}),
|
|
26
28
|
harness: record.harness,
|
|
27
29
|
sessionType: record.sessionType,
|
|
28
30
|
sessionId: record.sessionId,
|
|
@@ -45,7 +47,10 @@ function ordered(record) {
|
|
|
45
47
|
...(record.profile ? { profile: record.profile } : {}),
|
|
46
48
|
...(record.title ? { title: record.title } : {}),
|
|
47
49
|
...(record.model ? { model: record.model } : {}),
|
|
48
|
-
...(record.effort ? { effort: record.effort } : {})
|
|
50
|
+
...(record.effort ? { effort: record.effort } : {}),
|
|
51
|
+
...(record.loadedSkills !== undefined ? { loadedSkills: record.loadedSkills } : {}),
|
|
52
|
+
...(record.activatedPlugins !== undefined ? { activatedPlugins: record.activatedPlugins } : {}),
|
|
53
|
+
...(record.workspaceSnapshot ? { workspaceSnapshot: record.workspaceSnapshot } : {})
|
|
49
54
|
};
|
|
50
55
|
}
|
|
51
56
|
function write(root, record) {
|
|
@@ -116,10 +121,10 @@ export function updateRun(root, runId, update) {
|
|
|
116
121
|
const record = readRecord(recordPath(root, runId));
|
|
117
122
|
if (!record)
|
|
118
123
|
return;
|
|
119
|
-
const { status, endedAt, terminalReason } = record;
|
|
124
|
+
const { status, endedAt, terminalReason, terminalCode } = record;
|
|
120
125
|
update(record);
|
|
121
126
|
if (!isActiveStatus(status))
|
|
122
|
-
Object.assign(record, { status, endedAt, terminalReason });
|
|
127
|
+
Object.assign(record, { status, endedAt, terminalReason, terminalCode });
|
|
123
128
|
write(root, record);
|
|
124
129
|
}
|
|
125
130
|
export function terminalStatus(event) {
|
|
@@ -137,6 +142,15 @@ function reasonOf(event) {
|
|
|
137
142
|
const reason = payload?.reason ?? payload?.message;
|
|
138
143
|
return typeof reason === 'string' ? reason : null;
|
|
139
144
|
}
|
|
145
|
+
/** The stop code a terminal event carries; null for an interruption written without one. */
|
|
146
|
+
export function stopCodeOfEvent(event) {
|
|
147
|
+
const payload = event.payload;
|
|
148
|
+
if (event.type === 'completed')
|
|
149
|
+
return 'completed';
|
|
150
|
+
if (event.type === 'failed')
|
|
151
|
+
return stopCodeOf(typeof payload?.code === 'string' ? payload.code : 'failed');
|
|
152
|
+
return typeof payload?.code === 'string' ? stopCodeOf(payload.code) : null;
|
|
153
|
+
}
|
|
140
154
|
export function appendEvent(root, event) {
|
|
141
155
|
const directory = runDir(root, event.runId);
|
|
142
156
|
mkdirSync(directory, { recursive: true });
|
|
@@ -204,6 +218,7 @@ export function persistEvent(root, event) {
|
|
|
204
218
|
record.status = outcome;
|
|
205
219
|
record.endedAt = event.timestamp;
|
|
206
220
|
record.terminalReason = reasonOf(event);
|
|
221
|
+
record.terminalCode = stopCodeOfEvent(event);
|
|
207
222
|
changed = true;
|
|
208
223
|
}
|
|
209
224
|
else if (event.type === 'status.changed') {
|
|
@@ -233,11 +248,12 @@ export function markInterruptedRuns(root, reason = STOPPED) {
|
|
|
233
248
|
if (settled) {
|
|
234
249
|
const status = terminalStatus(settled);
|
|
235
250
|
const settledReason = reasonOf(settled);
|
|
236
|
-
|
|
251
|
+
const settledCode = stopCodeOfEvent(settled);
|
|
252
|
+
if (record.status !== status || record.endedAt !== settled.timestamp || record.terminalReason !== settledReason || (settledCode !== null && record.terminalCode !== settledCode)) {
|
|
237
253
|
const backup = `${path}.before-outcome-repair`;
|
|
238
254
|
if (!existsSync(backup))
|
|
239
255
|
copyFileSync(path, backup);
|
|
240
|
-
Object.assign(record, { status, endedAt: settled.timestamp, terminalReason: settledReason });
|
|
256
|
+
Object.assign(record, { status, endedAt: settled.timestamp, terminalReason: settledReason, ...(settledCode ? { terminalCode: settledCode } : {}) });
|
|
241
257
|
write(root, record);
|
|
242
258
|
}
|
|
243
259
|
}
|
|
@@ -248,9 +264,10 @@ export function markInterruptedRuns(root, reason = STOPPED) {
|
|
|
248
264
|
continue;
|
|
249
265
|
record.status = 'interrupted';
|
|
250
266
|
record.terminalReason = reason;
|
|
267
|
+
record.terminalCode = 'harness_restart';
|
|
251
268
|
record.endedAt ??= now();
|
|
252
269
|
const last = events.reduce((highest, event) => Math.max(highest, event.sequence), -1);
|
|
253
|
-
appendEvent(root, { id: newId(), runId: record.id, sessionId: record.sessionId, sequence: last + 1, timestamp: now(), type: 'status.changed', payload: { status: 'interrupted', reason } });
|
|
270
|
+
appendEvent(root, { id: newId(), runId: record.id, sessionId: record.sessionId, sequence: last + 1, timestamp: now(), type: 'status.changed', payload: { status: 'interrupted', reason, code: 'harness_restart' } });
|
|
254
271
|
write(root, record);
|
|
255
272
|
interrupted.push(record.id);
|
|
256
273
|
}
|
|
@@ -282,9 +299,10 @@ export function reconcileStaleRuns(root, at = Date.now(), options = {}) {
|
|
|
282
299
|
const reason = lastHeartbeat ? 'stalled' : 'owner_gone';
|
|
283
300
|
record.status = 'interrupted';
|
|
284
301
|
record.terminalReason = reason;
|
|
302
|
+
record.terminalCode = reason;
|
|
285
303
|
record.endedAt = now();
|
|
286
304
|
const sequence = events.reduce((highest, event) => Math.max(highest, event.sequence), -1) + 1;
|
|
287
|
-
appendEvent(root, { id: newId(), runId: record.id, sessionId: record.sessionId, sequence, timestamp: now(), type: 'status.changed', payload: { status: 'interrupted', reason } });
|
|
305
|
+
appendEvent(root, { id: newId(), runId: record.id, sessionId: record.sessionId, sequence, timestamp: now(), type: 'status.changed', payload: { status: 'interrupted', reason, code: reason } });
|
|
288
306
|
write(root, record);
|
|
289
307
|
stalled.push(record.id);
|
|
290
308
|
}
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import type { Refusal } from "./contracts.js";
|
|
1
2
|
import type { BashOperations, ModelRuntime, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
2
3
|
import { EFFORTS, type Effort } from "../core/effort.js";
|
|
3
4
|
import type { AccountContext } from "../accounts/env.js";
|
|
@@ -42,6 +43,7 @@ export interface TurnParams {
|
|
|
42
43
|
initialBashAvailable?: boolean;
|
|
43
44
|
/** The same gate used for model-issued tools. */
|
|
44
45
|
gate?: ToolGate;
|
|
46
|
+
onRefusal?: (toolCallId: string, name: string, refusal: Refusal) => void;
|
|
45
47
|
images?: {
|
|
46
48
|
mediaType: string;
|
|
47
49
|
data: string;
|
|
@@ -68,6 +70,7 @@ export interface TurnParams {
|
|
|
68
70
|
loading(): Promise<Loading>;
|
|
69
71
|
loaded(extensions: Registered[]): void;
|
|
70
72
|
};
|
|
73
|
+
activatedPlugins?: (ids: string[]) => void;
|
|
71
74
|
/** The harness's own switched-on extensions. They are code in this process, so they load in every kind of run. */
|
|
72
75
|
inline?: InlineExtension[];
|
|
73
76
|
/** The stable part of the compiled prompt: the only text added to Pi's own. */
|
|
@@ -225,6 +228,7 @@ export interface PiSessionLike {
|
|
|
225
228
|
export interface ToolGate {
|
|
226
229
|
/** Resolves to a block reason, or null to let the call run. */
|
|
227
230
|
check(toolName: string, input: unknown): Promise<string | null>;
|
|
231
|
+
checkDetailed?(toolName: string, input: unknown): Promise<Refusal | null>;
|
|
228
232
|
/** Requests one human-only approval before an explicit outside-workspace Bash call runs. */
|
|
229
233
|
requestWorkspaceWriteScope?(toolName: string, input: unknown, reason: string): Promise<boolean>;
|
|
230
234
|
/** Whether the explicit Full Permission switch bypasses the boundary for this Bash command. */
|
|
@@ -248,11 +252,7 @@ export declare function summarize(input: unknown, toolName?: string): string;
|
|
|
248
252
|
/** How much text a tool handed back to the model: what its result adds to every later request. */
|
|
249
253
|
export declare function resultSize(result: unknown): number | null;
|
|
250
254
|
export declare function runTurn(run: ActiveRun, session: PiSessionLike, params: TurnParams): Promise<void>;
|
|
251
|
-
|
|
252
|
-
* Loads what a session may use besides its tools: Pi's context files, the registry's skills and
|
|
253
|
-
* prompts, and what the harness found for it. `gate` is loaded after every extension on disk.
|
|
254
|
-
*/
|
|
255
|
-
export declare function loadResources(pi: typeof import('@earendil-works/pi-coding-agent'), params: Pick<TurnParams, 'cwd' | 'account' | 'automatic' | 'resources' | 'variantExtensions' | 'plugins' | 'system' | 'inline'>, gate: unknown, automaticSettings?: SettingsManager): Promise<import("@earendil-works/pi-coding-agent").DefaultResourceLoader>;
|
|
255
|
+
export declare function loadResources(pi: typeof import('@earendil-works/pi-coding-agent'), params: Pick<TurnParams, 'cwd' | 'account' | 'automatic' | 'resources' | 'variantExtensions' | 'plugins' | 'system' | 'inline' | 'activatedPlugins'>, gate: unknown, automaticSettings?: SettingsManager): Promise<import("@earendil-works/pi-coding-agent").DefaultResourceLoader>;
|
|
256
256
|
/** What each extension on disk registered when it was loaded. The harness's own gate is not one of them. */
|
|
257
257
|
export declare function registeredBy(loader: {
|
|
258
258
|
getExtensions(): {
|
|
@@ -15,7 +15,13 @@ import { completedReasoningSummary, REASONING_SUMMARY_APIS, requestDetailedReaso
|
|
|
15
15
|
import { extensionUi } from "./extensionUi.js";
|
|
16
16
|
import { inspectWorkspaceWrite } from "./workspaceBoundary.js";
|
|
17
17
|
import { parseInitialBashCommand } from "./initialBash.js";
|
|
18
|
-
import { observeResources, registrationHash } from "../plugins/runtime.js";
|
|
18
|
+
import { observeResources, registrationHash, runtimeOwner } from "../plugins/runtime.js";
|
|
19
|
+
import { wrapPromptLoader } from "../commands/promptLoader.js";
|
|
20
|
+
import { applyExtensionOwners } from "../commands/extensionOwners.js";
|
|
21
|
+
import { pluginCommandPrefix } from "../plugins/commandPrefix.js";
|
|
22
|
+
import { installPluginCommandRouter } from "../commands/runtimeRouter.js";
|
|
23
|
+
import { pluginIdOf } from "../plugins/identity.js";
|
|
24
|
+
import { OUTPUT_TRIM, BUDGET_GUARD } from "../plugins/firstParty.js";
|
|
19
25
|
export { EFFORTS };
|
|
20
26
|
/** A one-line description of a tool call, for an approval request or the activity list. */
|
|
21
27
|
export function summarize(input, toolName = '') {
|
|
@@ -172,6 +178,7 @@ export async function runTurn(run, session, params) {
|
|
|
172
178
|
let aborted = false;
|
|
173
179
|
const usage = { inputTokens: 0, outputTokens: 0, cacheReadTokens: 0, cacheWriteTokens: 0, costUsd: 0, requests: 0 };
|
|
174
180
|
let usageReported = false;
|
|
181
|
+
let lastContextTokens;
|
|
175
182
|
// Only some providers report a reasoning split; absent stays absent rather than zero.
|
|
176
183
|
let reasoningTokens;
|
|
177
184
|
// One model request runs from a turn's start to its assistant message's end.
|
|
@@ -317,6 +324,8 @@ export async function runTurn(run, session, params) {
|
|
|
317
324
|
...(message.stopReason ? { stopReason: message.stopReason } : {})
|
|
318
325
|
};
|
|
319
326
|
requestStartedAt = null;
|
|
327
|
+
if (reported)
|
|
328
|
+
lastContextTokens = (reported.input ?? 0) + (reported.cacheRead ?? 0) + (reported.cacheWrite ?? 0);
|
|
320
329
|
const contextWindow = session.model?.contextWindow;
|
|
321
330
|
const { costUsd, ...tokens } = usage;
|
|
322
331
|
run.emit('usage.updated', {
|
|
@@ -405,16 +414,18 @@ export async function runTurn(run, session, params) {
|
|
|
405
414
|
break;
|
|
406
415
|
}
|
|
407
416
|
case 'compaction_start': {
|
|
408
|
-
run.emit('compaction.started', { reason: stringField(event, 'reason', 'context limit') });
|
|
417
|
+
run.emit('compaction.started', { reason: stringField(event, 'reason', 'context limit'), ...(lastContextTokens === undefined ? {} : { contextTokens: lastContextTokens }), ...(session.model?.contextWindow ? { contextWindow: session.model.contextWindow } : {}) });
|
|
409
418
|
break;
|
|
410
419
|
}
|
|
411
420
|
case 'compaction_end': {
|
|
412
421
|
const compaction = event;
|
|
422
|
+
const result = compaction.result && typeof compaction.result === 'object' ? compaction.result : null;
|
|
413
423
|
const summary = evidenceText(compaction.result);
|
|
414
424
|
const boundedSummary = summary ? limitedText(summary) : null;
|
|
415
425
|
run.emit('compaction.ended', {
|
|
416
426
|
reason: stringField(compaction, 'reason', 'context limit'),
|
|
417
427
|
aborted: compaction.aborted === true,
|
|
428
|
+
...(typeof result?.tokensBefore === 'number' && Number.isFinite(result.tokensBefore) ? { tokensBefore: result.tokensBefore } : {}),
|
|
418
429
|
...(typeof compaction.willRetry === 'boolean' ? { willRetry: compaction.willRetry } : {}),
|
|
419
430
|
...(stringField(compaction, 'errorMessage') ? { error: stringField(compaction, 'errorMessage').slice(0, 1000) } : {}),
|
|
420
431
|
...(boundedSummary ? { summary: boundedSummary.text, ...(boundedSummary.truncated ? { summaryTruncated: true } : {}) } : {})
|
|
@@ -431,7 +442,7 @@ export async function runTurn(run, session, params) {
|
|
|
431
442
|
if (notice)
|
|
432
443
|
run.emit('extension.notice', { kind: 'notify', level: 'info', text: notice });
|
|
433
444
|
if (aborted)
|
|
434
|
-
run.finish('interrupted');
|
|
445
|
+
run.finish('interrupted', undefined, undefined, 'user_abort');
|
|
435
446
|
else
|
|
436
447
|
run.finish('completed');
|
|
437
448
|
return;
|
|
@@ -443,8 +454,7 @@ export async function runTurn(run, session, params) {
|
|
|
443
454
|
await session.sendCustomMessage({ customType: CONTEXT_MESSAGE_TYPE, content: params.update.content, display: false, details: { [CONTEXT_SNAPSHOT_KEY]: params.update.snapshot } }, { triggerTurn: false });
|
|
444
455
|
}
|
|
445
456
|
const command = /^\/(\S+)/.exec(params.text)?.[1];
|
|
446
|
-
|
|
447
|
-
if (params.preamble && extensionCommand) {
|
|
457
|
+
if (params.preamble && command) {
|
|
448
458
|
if (!session.sendCustomMessage)
|
|
449
459
|
throw new HarnessError('provider_error', 'The Pi session cannot receive the command context.');
|
|
450
460
|
await session.sendCustomMessage({ customType: 'xingular-preamble', content: params.preamble, display: false, details: {} }, { triggerTurn: false });
|
|
@@ -485,9 +495,17 @@ export async function runTurn(run, session, params) {
|
|
|
485
495
|
: !params.gate
|
|
486
496
|
? 'This run has no Bash policy gate.'
|
|
487
497
|
: null;
|
|
498
|
+
if (refusal && !params.initialBashAvailable && command)
|
|
499
|
+
params.onRefusal?.(toolCallId, 'bash', { code: 'capability', reason: refusal });
|
|
488
500
|
if (!refusal) {
|
|
489
501
|
try {
|
|
490
|
-
|
|
502
|
+
const blocked = params.gate.checkDetailed ? await params.gate.checkDetailed('bash', args) : null;
|
|
503
|
+
if (!params.gate.checkDetailed)
|
|
504
|
+
refusal = await params.gate.check('bash', args);
|
|
505
|
+
if (blocked) {
|
|
506
|
+
params.onRefusal?.(toolCallId, 'bash', blocked);
|
|
507
|
+
refusal = blocked.reason;
|
|
508
|
+
}
|
|
491
509
|
}
|
|
492
510
|
catch (error) {
|
|
493
511
|
refusal = error instanceof Error ? error.message : 'The Bash policy could not be checked.';
|
|
@@ -525,7 +543,7 @@ export async function runTurn(run, session, params) {
|
|
|
525
543
|
await session.sendCustomMessage({ customType: 'xingular-initial-bash', content: initialBashInstruction, display: false, details: {} }, { triggerTurn: false });
|
|
526
544
|
initialBashInstruction = undefined;
|
|
527
545
|
}
|
|
528
|
-
const prompt = params.preamble && !
|
|
546
|
+
const prompt = params.preamble && !command ? `${params.preamble}\n\n${params.text}` : params.text;
|
|
529
547
|
const images = (params.images ?? []).map((image) => ({ type: 'image', mimeType: image.mediaType, data: image.data }));
|
|
530
548
|
accepting = true;
|
|
531
549
|
try {
|
|
@@ -558,11 +576,11 @@ export async function runTurn(run, session, params) {
|
|
|
558
576
|
// The model stopped because its slice was over. Keep the state it did not write itself.
|
|
559
577
|
if (!slice.checkpointWritten)
|
|
560
578
|
run.emit('checkpoint', derivedCheckpoint(slice, ledger));
|
|
561
|
-
run.finish('interrupted', undefined, 'slice_complete');
|
|
579
|
+
run.finish('interrupted', undefined, 'slice_complete', slice.endedBy === 'budget' ? 'slice_budget' : 'compaction_thrash');
|
|
562
580
|
return;
|
|
563
581
|
}
|
|
564
582
|
if (aborted)
|
|
565
|
-
run.finish('interrupted');
|
|
583
|
+
run.finish('interrupted', undefined, undefined, 'user_abort');
|
|
566
584
|
else if (lastError)
|
|
567
585
|
run.finish('failed', { code: 'provider_error', message: lastError });
|
|
568
586
|
else
|
|
@@ -570,7 +588,7 @@ export async function runTurn(run, session, params) {
|
|
|
570
588
|
}
|
|
571
589
|
catch (error) {
|
|
572
590
|
if (aborted)
|
|
573
|
-
run.finish('interrupted');
|
|
591
|
+
run.finish('interrupted', undefined, undefined, 'user_abort');
|
|
574
592
|
else
|
|
575
593
|
run.finish('failed', { code: 'provider_error', message: error instanceof Error ? error.message : String(error) });
|
|
576
594
|
}
|
|
@@ -608,6 +626,7 @@ async function runCommand(session, command) {
|
|
|
608
626
|
* Loads what a session may use besides its tools: Pi's context files, the registry's skills and
|
|
609
627
|
* prompts, and what the harness found for it. `gate` is loaded after every extension on disk.
|
|
610
628
|
*/
|
|
629
|
+
const promptRouting = new WeakMap();
|
|
611
630
|
export async function loadResources(pi, params, gate, automaticSettings) {
|
|
612
631
|
const loading = params.automatic ? null : ((await params.plugins?.loading()) ?? null);
|
|
613
632
|
const resourceLoader = new pi.DefaultResourceLoader({
|
|
@@ -629,11 +648,44 @@ export async function loadResources(pi, params, gate, automaticSettings) {
|
|
|
629
648
|
});
|
|
630
649
|
await resourceLoader.reload();
|
|
631
650
|
if (loading) {
|
|
651
|
+
applyExtensionOwners(resourceLoader, loading.found);
|
|
652
|
+
const extensions = () => registeredBy(resourceLoader).flatMap(record => {
|
|
653
|
+
const owner = runtimeOwner(loading, record.path);
|
|
654
|
+
const prefix = pluginCommandPrefix(owner?.packageRoot ? { path: record.path, origin: 'package', baseDir: owner.packageRoot } : { path: record.path });
|
|
655
|
+
return record.commands.map(name => ({ prefix, name, owner: owner?.packageRoot ? `package:${owner.packageRoot}` : `extension:${record.path}`, path: record.path }));
|
|
656
|
+
});
|
|
632
657
|
const records = registeredBy(resourceLoader).map((record) => ({ ...record, hash: registrationHash(loading, record.path) }));
|
|
633
658
|
const publish = () => params.plugins?.loaded(records);
|
|
634
659
|
observeResources(pi, resourceLoader, loading, records, publish);
|
|
660
|
+
const bare = await wrapPromptLoader(pi, resourceLoader, loading.found, loading.promptPaths, params.cwd, params.account.configDir, extensions);
|
|
661
|
+
promptRouting.set(resourceLoader, { loading, bare });
|
|
635
662
|
publish();
|
|
636
663
|
}
|
|
664
|
+
if (loading || params.automatic) {
|
|
665
|
+
const extensions = resourceLoader.getExtensions().extensions;
|
|
666
|
+
const ids = [];
|
|
667
|
+
let known = true;
|
|
668
|
+
for (const extension of extensions) {
|
|
669
|
+
const path = extension.resolvedPath || extension.path;
|
|
670
|
+
if (extension.hidden) {
|
|
671
|
+
for (const id of [OUTPUT_TRIM, BUDGET_GUARD])
|
|
672
|
+
if (path === `<inline:${id}>`)
|
|
673
|
+
ids.push(id);
|
|
674
|
+
}
|
|
675
|
+
else if (params.variantExtensions?.some((entry) => path === entry || path.startsWith(`${entry}/`))) {
|
|
676
|
+
ids.push('variant');
|
|
677
|
+
}
|
|
678
|
+
else {
|
|
679
|
+
const owner = loading && runtimeOwner(loading, path);
|
|
680
|
+
if (owner)
|
|
681
|
+
ids.push(pluginIdOf(owner));
|
|
682
|
+
else
|
|
683
|
+
known = false;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
if (known)
|
|
687
|
+
params.activatedPlugins?.([...new Set(ids)]);
|
|
688
|
+
}
|
|
637
689
|
return resourceLoader;
|
|
638
690
|
}
|
|
639
691
|
/** What each extension on disk registered when it was loaded. The harness's own gate is not one of them. */
|
|
@@ -687,12 +739,21 @@ export const piSessionFactory = async ({ params, allow, gate, tools, runtime: lo
|
|
|
687
739
|
};
|
|
688
740
|
}
|
|
689
741
|
catch (error) {
|
|
690
|
-
|
|
742
|
+
const reason = error instanceof Error ? error.message : 'The active project workspace could not be verified.';
|
|
743
|
+
params.onRefusal?.(event.toolCallId, event.toolName, { code: 'workspace', reason });
|
|
744
|
+
return { block: true, reason };
|
|
691
745
|
}
|
|
692
746
|
}
|
|
693
|
-
const
|
|
694
|
-
if (
|
|
695
|
-
|
|
747
|
+
const refusal = gate.checkDetailed ? await gate.checkDetailed(event.toolName, event.input) : null;
|
|
748
|
+
if (!gate.checkDetailed) {
|
|
749
|
+
const reason = await gate.check(event.toolName, event.input);
|
|
750
|
+
if (reason)
|
|
751
|
+
return { block: true, reason };
|
|
752
|
+
}
|
|
753
|
+
if (refusal) {
|
|
754
|
+
params.onRefusal?.(event.toolCallId, event.toolName, refusal);
|
|
755
|
+
return { block: true, reason: refusal.reason };
|
|
756
|
+
}
|
|
696
757
|
if (authorization) {
|
|
697
758
|
authorization.authorized = true;
|
|
698
759
|
writeAuthorizations.set(event.toolCallId, authorization);
|
|
@@ -749,7 +810,9 @@ export const piSessionFactory = async ({ params, allow, gate, tools, runtime: lo
|
|
|
749
810
|
});
|
|
750
811
|
}
|
|
751
812
|
const piSession = session;
|
|
752
|
-
|
|
813
|
+
const routing = promptRouting.get(resourceLoader);
|
|
814
|
+
const routes = installPluginCommandRouter(session, routing?.loading.found ?? [], routing?.bare ?? new Set());
|
|
815
|
+
piSession.extensionCommands = routes();
|
|
753
816
|
supportsImageInput = piSession.model?.input.includes('image') ?? false;
|
|
754
817
|
const streamAgent = piSession.agent;
|
|
755
818
|
const originalStream = streamAgent.streamFunction;
|
|
@@ -17,6 +17,7 @@ import * as attachments from "../plugins/attachments.js";
|
|
|
17
17
|
import { FIRST_PARTY_PLUGINS, firstPartyExtensions } from "../plugins/firstParty.js";
|
|
18
18
|
import { imagePruning } from "../world/images.js";
|
|
19
19
|
import { materialise } from "../variant/materialise.js";
|
|
20
|
+
import { snapshotWorkingTree } from "../worktrees/snapshot.js";
|
|
20
21
|
import { ASK_USER } from "../tools/askUser.js";
|
|
21
22
|
import { defaultSkillPaths } from "../tools/defaultSkills.js";
|
|
22
23
|
import { TODO_WRITE } from "../tools/todo.js";
|
|
@@ -24,7 +25,7 @@ import { CHECKPOINT_WRITE, checkpointOf } from "../tools/checkpoint.js";
|
|
|
24
25
|
import { SESSION_NAME, deriveSessionName, sessionNameTool } from "../tools/sessionName.js";
|
|
25
26
|
import { DEFAULT_TOOL_NAMES } from "../tools/definitions.js";
|
|
26
27
|
import { GET_CAPABILITIES, getCapabilitiesTool } from "../tools/getCapabilities.js";
|
|
27
|
-
import { isActiveStatus } from "./contracts.js";
|
|
28
|
+
import { isActiveStatus, stopCodeOf } from "./contracts.js";
|
|
28
29
|
import { SPAWN_SUBAGENT, WAIT_SUBAGENTS, subagentDepth, subagentHistory, subagentNesting } from "./subagents.js";
|
|
29
30
|
import { selectHistory } from "./history.js";
|
|
30
31
|
import { runLineageJoin } from "./lineageJoin.js";
|
|
@@ -128,12 +129,13 @@ export class Sessions {
|
|
|
128
129
|
}
|
|
129
130
|
gate(run, caller, gated, diagnostic = false, automatic = false) {
|
|
130
131
|
const { policy } = this.options;
|
|
131
|
-
|
|
132
|
+
const gate = {
|
|
133
|
+
check: async (name, input) => (await gate.checkDetailed(name, input))?.reason ?? null,
|
|
132
134
|
ask: (names) => {
|
|
133
135
|
for (const name of names)
|
|
134
136
|
gated.add(name);
|
|
135
137
|
},
|
|
136
|
-
|
|
138
|
+
checkDetailed: async (tool, args) => {
|
|
137
139
|
let record;
|
|
138
140
|
let inspection;
|
|
139
141
|
try {
|
|
@@ -141,28 +143,30 @@ export class Sessions {
|
|
|
141
143
|
inspection = inspectRunWorkspaceWrite(record, tool, args);
|
|
142
144
|
}
|
|
143
145
|
catch (error) {
|
|
144
|
-
return error instanceof Error ? error.message : 'The active project workspace could not be verified.';
|
|
146
|
+
return { code: 'workspace', reason: error instanceof Error ? error.message : 'The active project workspace could not be verified.' };
|
|
145
147
|
}
|
|
146
148
|
const call = { run: record, caller, tool, args: inspection.input };
|
|
147
149
|
const hostScope = (await policy.scope?.(call)) ?? { allowed: true };
|
|
148
150
|
const scope = combineWorkspaceScope(hostScope, inspection);
|
|
149
151
|
if (!scope.allowed && (scope.automatic || (automatic && inspection.outside) || !scope.requiresApproval))
|
|
150
|
-
return scope.reason ?? 'Outside the approved work scope.';
|
|
152
|
+
return { code: inspection.outside ? 'workspace' : 'scope', reason: scope.reason ?? 'Outside the approved work scope.' };
|
|
151
153
|
try {
|
|
152
154
|
await policy.authorize?.(call);
|
|
153
155
|
}
|
|
154
156
|
catch (error) {
|
|
155
|
-
return error instanceof Error ? error.message : 'Tool unavailable in the app settings.';
|
|
157
|
+
return { code: 'policy', reason: error instanceof Error ? error.message : 'Tool unavailable in the app settings.' };
|
|
156
158
|
}
|
|
157
159
|
if (scope.allowed && !scope.humanOnly && (scope.automatic || !gated.has(tool)))
|
|
158
160
|
return null;
|
|
159
161
|
if (diagnostic)
|
|
160
|
-
return 'This diagnostic call requires a separate per-call approval.';
|
|
162
|
+
return { code: 'unattended', reason: 'This diagnostic call requires a separate per-call approval.' };
|
|
161
163
|
// Refinement and reflection runs have nobody to ask: what would need a person is refused, never queued.
|
|
162
164
|
if (call.run.trigger === 'probe' || call.run.trigger === 'improver')
|
|
163
|
-
return scope.reason ? `Refused in a refinement run: ${scope.reason}` : 'Refused in a refinement run: this call needs a person to approve it.';
|
|
165
|
+
return { code: 'unattended', reason: scope.reason ? `Refused in a refinement run: ${scope.reason}` : 'Refused in a refinement run: this call needs a person to approve it.' };
|
|
164
166
|
if (call.run.trigger === 'reflection')
|
|
165
|
-
return scope.reason ? `Refused in a reflection run: ${scope.reason}` : 'Refused in a reflection run: this call needs a person to approve it.';
|
|
167
|
+
return { code: 'unattended', reason: scope.reason ? `Refused in a reflection run: ${scope.reason}` : 'Refused in a reflection run: this call needs a person to approve it.' };
|
|
168
|
+
if (automatic)
|
|
169
|
+
return { code: 'unattended', reason: scope.reason ?? 'Refused in an unattended run: this call needs a person to approve it.' };
|
|
166
170
|
const boundaryAction = inspection.outside ? `${inspection.reason} ${summarize(call.args, tool)}` : summarize(call.args);
|
|
167
171
|
const decision = await run.requestApproval({
|
|
168
172
|
target: tool,
|
|
@@ -172,12 +176,12 @@ export class Sessions {
|
|
|
172
176
|
standing: scope.humanOnly ? (scope.allowGlobalApproval ? 'switch' : 'none') : undefined
|
|
173
177
|
});
|
|
174
178
|
if (decision !== 'approved')
|
|
175
|
-
return 'The user denied this action.
|
|
179
|
+
return { code: 'approval_denied', reason: 'The user denied this action. Do not repeat it or ask for permission in a message; choose another approach or report what is blocked.' };
|
|
176
180
|
try {
|
|
177
181
|
await policy.authorize?.(call);
|
|
178
182
|
}
|
|
179
183
|
catch (error) {
|
|
180
|
-
return error instanceof Error ? error.message : 'Tool was disabled while waiting.';
|
|
184
|
+
return { code: 'policy', reason: error instanceof Error ? error.message : 'Tool was disabled while waiting.' };
|
|
181
185
|
}
|
|
182
186
|
return null;
|
|
183
187
|
},
|
|
@@ -245,6 +249,7 @@ export class Sessions {
|
|
|
245
249
|
}
|
|
246
250
|
}
|
|
247
251
|
};
|
|
252
|
+
return gate;
|
|
248
253
|
}
|
|
249
254
|
/** Compatibility alias for the shared native service. */
|
|
250
255
|
spawnSubagent(request) {
|
|
@@ -434,6 +439,7 @@ export class Sessions {
|
|
|
434
439
|
id: runId,
|
|
435
440
|
projectId: input.run.projectId ?? caller.projectId ?? null,
|
|
436
441
|
mode: input.run.mode ?? 'chat',
|
|
442
|
+
effectiveMode: input.plan ? 'plan' : 'normal',
|
|
437
443
|
harness: input.run.harness ?? 'pi',
|
|
438
444
|
sessionType: input.run.sessionType ?? 'structured',
|
|
439
445
|
sessionId: input.run.sessionId,
|
|
@@ -446,6 +452,7 @@ export class Sessions {
|
|
|
446
452
|
startedAt: now(),
|
|
447
453
|
endedAt: null,
|
|
448
454
|
status: 'queued',
|
|
455
|
+
loadedSkills: [],
|
|
449
456
|
exitCode: null,
|
|
450
457
|
handoffId: input.run.handoffId ?? null,
|
|
451
458
|
accountId: account.id,
|
|
@@ -467,7 +474,7 @@ export class Sessions {
|
|
|
467
474
|
}
|
|
468
475
|
const fail = (error, code = 'provider_unavailable') => {
|
|
469
476
|
const message = error instanceof Error ? error.message : String(error);
|
|
470
|
-
updateRun(root, runId, (record) => Object.assign(record, { status: 'failed', endedAt: now(), terminalReason: message }));
|
|
477
|
+
updateRun(root, runId, (record) => Object.assign(record, { status: 'failed', endedAt: now(), terminalReason: message, terminalCode: stopCodeOf(code) }));
|
|
471
478
|
log(`session ${runId} did not start: ${message}`, code);
|
|
472
479
|
};
|
|
473
480
|
// Plugins are resolved once per run: for the profiles the prompt lists, then for what Pi loads.
|
|
@@ -483,6 +490,12 @@ export class Sessions {
|
|
|
483
490
|
&& (input.depth ?? 0) === 0
|
|
484
491
|
&& !input.automatic
|
|
485
492
|
&& (input.run.trigger == null || input.run.trigger === 'user');
|
|
493
|
+
// The working tree as the person's turn found it, so refinement can replay the request later.
|
|
494
|
+
if (stateEligible) {
|
|
495
|
+
const snapshot = await snapshotWorkingTree(input.cwd);
|
|
496
|
+
if (snapshot)
|
|
497
|
+
updateRun(root, runId, (record) => { record.workspaceSnapshot = snapshot; });
|
|
498
|
+
}
|
|
486
499
|
const existingName = stateEligible ? latestSessionName(historyFile) : null;
|
|
487
500
|
const sessionState = stateEligible
|
|
488
501
|
? {
|
|
@@ -595,21 +608,20 @@ export class Sessions {
|
|
|
595
608
|
planModeSafety.set(tool.name, tool.planModeSafe);
|
|
596
609
|
const gate = (() => {
|
|
597
610
|
const baseGate = this.gate(run, caller, new Set((input.tools.gated ?? []).filter((name) => capabilities.tools.includes(name))), false, input.automatic === true);
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
const refusal = input.plan ? planRefusal(name, readOnly, args, planModeSafety.get(name)) : null;
|
|
604
|
-
return refusal ? Promise.resolve(refusal) : baseGate.check(name, args);
|
|
605
|
-
}
|
|
611
|
+
const checkDetailed = (name, args) => {
|
|
612
|
+
if (input.run.relation === 'subagent' && !capabilities.tools.includes(name))
|
|
613
|
+
return Promise.resolve({ code: 'capability', reason: 'This tool is outside the child capability snapshot.' });
|
|
614
|
+
const refusal = input.plan ? planRefusal(name, readOnly, args, planModeSafety.get(name)) : null;
|
|
615
|
+
return refusal ? Promise.resolve({ code: 'plan_mode', reason: refusal }) : baseGate.checkDetailed(name, args);
|
|
606
616
|
};
|
|
617
|
+
return { ...baseGate, checkDetailed, check: async (name, args) => (await checkDetailed(name, args))?.reason ?? null };
|
|
607
618
|
})();
|
|
608
619
|
const params = {
|
|
609
620
|
runId,
|
|
610
621
|
...(input.initialBashCommand !== undefined && input.initialBashCommand !== null ? { initialBashCommand: input.initialBashCommand, initialBashAvailable: capabilities.tools.includes('bash') } : {}),
|
|
611
622
|
...(input.initialBashContext !== undefined && input.initialBashContext !== null ? { initialBashContext: input.initialBashContext } : {}),
|
|
612
623
|
gate,
|
|
624
|
+
onRefusal: (toolCallId, name, refusal) => run.emit('tool.refused', { toolCallId, name, ...refusal, reason: refusal.reason.slice(0, 2000) }),
|
|
613
625
|
restrictTools: input.run.relation === 'subagent',
|
|
614
626
|
...(input.plan ? { plan: true } : {}),
|
|
615
627
|
...(stateEligible && input.plan ? { repairPlan: true } : {}),
|
|
@@ -633,9 +645,11 @@ export class Sessions {
|
|
|
633
645
|
this.options.subagents.extension(runId),
|
|
634
646
|
{ name: 'image-pruning', factory: imagePruning() },
|
|
635
647
|
{ name: COMPACTION_CHECKPOINT_EXTENSION, factory: compactionCheckpoint({ initialTodo: continuation?.todo, planInstructions: checkpointPlanInstructions }) },
|
|
636
|
-
...(sliceEnabled ? [{ name: WORK_SLICE_EXTENSION, factory: workSliceGuard({ policy: slicePolicy, state: sliceState, checkpointAvailable
|
|
648
|
+
...(sliceEnabled ? [{ name: WORK_SLICE_EXTENSION, factory: workSliceGuard({ policy: slicePolicy, state: sliceState, checkpointAvailable, onRefuse: (event, reason) => { if (typeof event.toolCallId === 'string')
|
|
649
|
+
run.emit('tool.refused', { toolCallId: event.toolCallId, name: event.toolName, code: 'work_slice', reason: reason.slice(0, 2000) }); } }) }] : [])
|
|
637
650
|
],
|
|
638
651
|
...(plugins && loadPlugins ? { plugins: { loading: loadPlugins, loaded: (extensions) => plugins.loaded(extensions) } } : {}),
|
|
652
|
+
activatedPlugins: (ids) => updateRun(root, runId, (record) => { record.activatedPlugins = ids; }),
|
|
639
653
|
system,
|
|
640
654
|
...(sliceEnabled ? { slice: { state: sliceState, maxToolCalls: slicePolicy.maxToolCalls } } : {}),
|
|
641
655
|
// A command sends no request of its own, so the context update waits for the next turn.
|
|
@@ -55,6 +55,7 @@ export declare function resetSliceState(state: SliceState, now?: number): void;
|
|
|
55
55
|
/** The first limit this reply has passed, named as a person would say it. */
|
|
56
56
|
export declare function sliceLimitReached(policy: SlicePolicy, state: SliceState, now?: number): string | null;
|
|
57
57
|
interface ToolCall {
|
|
58
|
+
toolCallId: string;
|
|
58
59
|
toolName: string;
|
|
59
60
|
}
|
|
60
61
|
interface ToolResult {
|
|
@@ -85,6 +86,7 @@ export interface WorkSliceGuardOptions {
|
|
|
85
86
|
checkpointAvailable?: boolean | (() => boolean);
|
|
86
87
|
/** Called when a triggering call terminates the reply; the runner ends it. */
|
|
87
88
|
onEnd?: (end: SliceEnd, limit: string) => void;
|
|
89
|
+
onRefuse?: (event: ToolCall, reason: string) => void;
|
|
88
90
|
}
|
|
89
91
|
/**
|
|
90
92
|
* Bounds one reply. A call past the budget is refused, with one wrap-up request when a checkpoint
|