pi-better-server 0.6.0 → 0.7.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/package.json +4 -3
- package/scripts/measure-full-runtime/frontend.ts +10 -2
- package/scripts/measure-full-runtime.mjs +2 -0
- package/src/codex/return.ts +3 -2
- package/src/detach/extension.ts +20 -3
- package/src/event-log.ts +40 -12
- package/src/hosted-session.ts +11 -5
- package/src/remote-client/packages.ts +1 -4
- package/src/runtime/background-tools.ts +54 -8
- package/src/runtime/background.ts +16 -4
- package/src/runtime/domain/background/process.mjs +49 -11
- package/src/runtime/domain/background/supervisor/store.mjs +3 -3
- package/src/runtime/domain/background/supervisor/supervisor.mjs +9 -3
- package/src/runtime/domain/background-service/index.domain.mjs +19 -0
- package/src/runtime/domain/background-service/index.ts +19 -0
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +87 -5
- package/src/runtime/domain/background-service/managed-frontend.ts +76 -5
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +5 -0
- package/src/runtime/domain/background-service/navigator-provider.ts +4 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +203 -31
- package/src/runtime/domain/background-service/observed-waits.ts +168 -24
- package/src/runtime/domain/background-service/process.domain.mjs +49 -11
- package/src/runtime/domain/background-service/process.ts +45 -11
- package/src/runtime/domain/background-service/review-settings.domain.mjs +16 -0
- package/src/runtime/domain/background-service/review-settings.ts +18 -0
- package/src/runtime/domain/background-service/runtime.domain.mjs +8 -70
- package/src/runtime/domain/background-service/runtime.ts +8 -73
- package/src/runtime/domain/background-service/shared-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/background-service/shared-harness-settings.ts +2 -5
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +55 -28
- package/src/runtime/domain/background-service/shared-navigator.ts +47 -26
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +5 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +6 -0
- package/src/runtime/domain/background-service/shared-ssh-core/index.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-ssh-core/index.ts +1 -1
- package/src/runtime/domain/background-service/stall.domain.mjs +5 -3
- package/src/runtime/domain/background-service/stall.ts +7 -4
- package/src/runtime/domain/background-service/supervised-progress.domain.mjs +42 -0
- package/src/runtime/domain/background-service/supervised-progress.ts +43 -0
- package/src/runtime/domain/background-service/supervisor/README.md +1 -4
- package/src/runtime/domain/background-service/supervisor/emit-runner.mjs +1 -0
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +49 -11
- package/src/runtime/domain/background-service/supervisor/generated/runner.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/generated/store.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/generated/watch-fingerprint.mjs +69 -0
- package/src/runtime/domain/background-service/supervisor/runner.domain.mjs +47 -4
- package/src/runtime/domain/background-service/supervisor/runner.ts +38 -3
- package/src/runtime/domain/background-service/supervisor/store.domain.mjs +3 -3
- package/src/runtime/domain/background-service/supervisor/store.ts +3 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.domain.mjs +9 -3
- package/src/runtime/domain/background-service/supervisor/supervisor.ts +6 -3
- package/src/runtime/domain/background-service/tools.domain.mjs +22 -16
- package/src/runtime/domain/background-service/tools.ts +26 -16
- package/src/runtime/domain/background-service/types.ts +4 -2
- package/src/runtime/domain/background-service/watch-fingerprint.domain.mjs +67 -0
- package/src/runtime/domain/background-service/watch-fingerprint.ts +70 -0
- package/src/runtime/domain/catalog/catalog-preferences.mjs +1 -3
- package/src/runtime/domain/coordinator/src/outbox.mjs +7 -0
- package/src/runtime/domain/coordinator/src/store.mjs +5 -1
- package/src/runtime/domain/log-paths.mjs +8 -1
- package/src/runtime/domain/parse.mjs +9 -5
- package/src/runtime/domain/sandbox-policy/README.md +3 -3
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/shared-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/sandbox-policy/shared-harness-settings.ts +2 -5
- package/src/runtime/domain/session-store.mjs +7 -0
- package/src/runtime/domain/shared-harness-settings.mjs +2 -3
- package/src/runtime/domain/subagents/README.md +12 -10
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +2 -5
- package/src/runtime/domain/subagents/assignment-outcomes.ts +2 -5
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +22 -0
- package/src/runtime/domain/subagents/assignment-report.ts +20 -0
- package/src/runtime/domain/subagents/batch.mjs +13 -5
- package/src/runtime/domain/subagents/catalog-preferences.domain.mjs +1 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -5
- package/src/runtime/domain/subagents/cleanup.domain.mjs +11 -2
- package/src/runtime/domain/subagents/cleanup.ts +10 -2
- package/src/runtime/domain/subagents/config.domain.mjs +5 -0
- package/src/runtime/domain/subagents/config.ts +8 -2
- package/src/runtime/domain/subagents/continuation.domain.mjs +4 -2
- package/src/runtime/domain/subagents/continuation.ts +4 -2
- package/src/runtime/domain/subagents/extensions.mjs +1 -0
- package/src/runtime/domain/subagents/failures.domain.mjs +11 -2
- package/src/runtime/domain/subagents/failures.ts +10 -2
- package/src/runtime/domain/subagents/finalization.domain.mjs +39 -32
- package/src/runtime/domain/subagents/finalization.ts +37 -30
- package/src/runtime/domain/subagents/git-workspace.domain.mjs +51 -6
- package/src/runtime/domain/subagents/git-workspace.ts +48 -6
- package/src/runtime/domain/subagents/index.domain.mjs +208 -75
- package/src/runtime/domain/subagents/index.ts +213 -75
- package/src/runtime/domain/subagents/isolated-workspace.domain.mjs +508 -0
- package/src/runtime/domain/subagents/isolated-workspace.ts +551 -0
- package/src/runtime/domain/subagents/list.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +22 -5
- package/src/runtime/domain/subagents/managed-launch-client.ts +23 -6
- package/src/runtime/domain/subagents/output-payload.domain.mjs +24 -9
- package/src/runtime/domain/subagents/output-payload.ts +26 -12
- package/src/runtime/domain/subagents/package.json +4 -2
- package/src/runtime/domain/subagents/parse.domain.mjs +9 -5
- package/src/runtime/domain/subagents/parse.ts +10 -5
- package/src/runtime/domain/subagents/registry.domain.mjs +31 -25
- package/src/runtime/domain/subagents/registry.ts +31 -13
- package/src/runtime/domain/subagents/retained-result.domain.mjs +56 -0
- package/src/runtime/domain/subagents/retained-result.ts +65 -0
- package/src/runtime/domain/subagents/session-selection.domain.mjs +3 -1
- package/src/runtime/domain/subagents/session-selection.ts +2 -1
- package/src/runtime/domain/subagents/session-store.domain.mjs +7 -0
- package/src/runtime/domain/subagents/session-store.ts +9 -0
- package/src/runtime/domain/subagents/settings-page.domain.mjs +151 -107
- package/src/runtime/domain/subagents/settings-page.ts +147 -108
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +23 -7
- package/src/runtime/domain/subagents/shared-catalog.ts +23 -7
- package/src/runtime/domain/subagents/shared-harness-settings.domain.mjs +2 -3
- package/src/runtime/domain/subagents/shared-harness-settings.ts +2 -5
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +55 -28
- package/src/runtime/domain/subagents/shared-navigator.ts +47 -26
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.domain.mjs +7 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/outbox.ts +9 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +5 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +6 -0
- package/src/runtime/domain/subagents/task-guard.domain.mjs +14 -1
- package/src/runtime/domain/subagents/task-guard.ts +13 -1
- package/src/runtime/domain/subagents/task-policy.domain.mjs +2 -1
- package/src/runtime/domain/subagents/task-policy.ts +5 -1
- package/src/runtime/domain/subagents/tools.domain.mjs +4 -8
- package/src/runtime/domain/subagents/tools.ts +4 -7
- package/src/runtime/domain/subagents/work-observation.domain.mjs +25 -1
- package/src/runtime/domain/subagents/work-observation.ts +20 -1
- package/src/runtime/domain/subagents/workspace-files.domain.mjs +103 -0
- package/src/runtime/domain/subagents/workspace-files.ts +114 -0
- package/src/runtime/domain/subagents/workspace-prepare-worker.mjs +12 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.d.mts +38 -0
- package/src/runtime/domain/subagents/workspace-scope.domain.mjs +5 -0
- package/src/runtime/domain/subagents/workspace-scope.ts +6 -0
- package/src/runtime/domain/subagents/worktree-feedback.domain.mjs +55 -0
- package/src/runtime/domain/subagents/worktree-feedback.ts +77 -0
- package/src/runtime/read-model.ts +4 -2
- package/src/runtime/root.ts +5 -2
- package/src/shared-ssh-core/index.ts +1 -1
- package/src/version.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-better-server",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.1",
|
|
4
4
|
"description": "Daemon that hosts Pi agent sessions behind a local Unix socket with session-addressed Pi RPC.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"type": "module",
|
|
@@ -47,13 +47,15 @@
|
|
|
47
47
|
"verify": "npm run typecheck && npm test"
|
|
48
48
|
},
|
|
49
49
|
"peerDependencies": {
|
|
50
|
-
"@earendil-works/pi-coding-agent": ">=0.82.0"
|
|
50
|
+
"@earendil-works/pi-coding-agent": ">=0.82.0",
|
|
51
|
+
"typebox": "*"
|
|
51
52
|
},
|
|
52
53
|
"devDependencies": {
|
|
53
54
|
"@earendil-works/pi-ai": "^0.82.0",
|
|
54
55
|
"@earendil-works/pi-coding-agent": "^0.82.0",
|
|
55
56
|
"@types/node": "^25.0.0",
|
|
56
57
|
"tsx": "^4.22.3",
|
|
58
|
+
"typebox": "1.3.27",
|
|
57
59
|
"typescript": "^6.0.0"
|
|
58
60
|
},
|
|
59
61
|
"engines": {
|
|
@@ -66,7 +68,6 @@
|
|
|
66
68
|
"proper-lockfile": "^4.1.2",
|
|
67
69
|
"shell-quote": "1.12.0",
|
|
68
70
|
"smol-toml": "1.9.0",
|
|
69
|
-
"typebox": "1.3.27",
|
|
70
71
|
"yaml": "^2.9.1"
|
|
71
72
|
}
|
|
72
73
|
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { createAgentSession, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
1
|
+
import { createAgentSession, initTheme, DefaultResourceLoader, SessionManager, SettingsManager } from '@earendil-works/pi-coding-agent';
|
|
2
2
|
import subagents from '../../../pi-better-subagents/index.ts';
|
|
3
3
|
import background from '../../../pi-better-background-tasks/src/index.ts';
|
|
4
4
|
import { getObservedWaitHost } from '../../../pi-better-background-tasks/src/observed-waits.ts';
|
|
@@ -9,12 +9,20 @@ const settingsManager = SettingsManager.inMemory({});
|
|
|
9
9
|
const resourceLoader = new DefaultResourceLoader({ cwd, agentDir, settingsManager, noExtensions: true, noSkills: true, noContextFiles: true, noThemes: true, noPromptTemplates: true, extensionFactories: process.env.BACKGROUND_ONLY ? [capturedBackground] : [subagents, capturedBackground] });
|
|
10
10
|
await resourceLoader.reload();
|
|
11
11
|
const { session } = await createAgentSession({ cwd, agentDir, settingsManager, resourceLoader, sessionManager: process.env.BACKGROUND_SESSION_FILE ? SessionManager.open(process.env.BACKGROUND_SESSION_FILE) : SessionManager.inMemory(cwd), noTools: 'all' });
|
|
12
|
-
|
|
12
|
+
const testNavigator = process.env.BACKGROUND_TEST_NAVIGATOR === "1";
|
|
13
|
+
if (testNavigator) initTheme("dark", false);
|
|
14
|
+
await session.bindExtensions({ mode: testNavigator ? 'tui' : 'print',
|
|
15
|
+
...(testNavigator ? { uiContext: { ...session.extensionRunner.createContext().ui, setEditorComponent() {}, setWidget() {}, setStatus() {} } } : {}), onError: error => { throw new Error(String(error)); } });
|
|
13
16
|
process.send?.({ ready: true, pid: process.pid, sessionId: session.sessionId });
|
|
14
17
|
process.on('message', async (request: any) => {
|
|
15
18
|
try {
|
|
16
19
|
if (request.stop) { await session.extensionRunner.emit({ type: 'session_shutdown', reason: 'quit' }); session.dispose(); process.disconnect(); return; }
|
|
17
20
|
if(request.barrier){await getObservedWaitHost(backgroundApi)!.reconcileNow();process.send?.({id:request.id,result:{ready:true}});return;}
|
|
21
|
+
if (request.navigatorRows) {
|
|
22
|
+
const state = (globalThis as any)[Symbol.for("pi-better-harness.navigator.state")];
|
|
23
|
+
process.send?.({ id: request.id, result: state.providers.get("background-tasks").listRows(Date.now()) });
|
|
24
|
+
return;
|
|
25
|
+
}
|
|
18
26
|
if(request.entries){process.send?.({id:request.id,result:session.sessionManager.getBranch()});return;}
|
|
19
27
|
const tool = session.extensionRunner.getToolDefinition(request.tool);
|
|
20
28
|
if (!tool) throw new Error(`Missing real tool ${request.tool}`);
|
|
@@ -21,6 +21,8 @@ const probe = new URL('./measure-full-runtime/probe.mjs', import.meta.url).href;
|
|
|
21
21
|
const execPath = process.env.PI_TEST_PRIVATE_RUNTIME_NODE ?? process.execPath;
|
|
22
22
|
process.env.PI_RESOURCE_REPORT_DIR=samples;await import(probe);
|
|
23
23
|
const env = { ...process.env, PI_CODING_AGENT_DIR: agent, PI_SERVER_DIR: transport, TMPDIR: root, TMP: root, TEMP: root, PI_RESOURCE_REPORT_DIR: samples,
|
|
24
|
+
// The steady-state measurement needs silent commands to stay healthy for the entire run.
|
|
25
|
+
PI_BETTER_STALL_QUIET_MS: String(60 * 60_000), PI_BETTER_STALL_MS: String(2 * 60 * 60_000),
|
|
24
26
|
BACKGROUND_SESSION_FILE:sessionFile,NODE_OPTIONS: `--import ${probe}`, LAUNCH_WORKSPACE: cwd, LAUNCH_ENTERED: join(cwd, 'entered'), LAUNCH_RELEASE: join(cwd, 'release'), PI_OFFLINE: '1' };
|
|
25
27
|
mkdirSync(join(agent,'extensions'),{recursive:true});
|
|
26
28
|
writeFileSync(join(agent,'extensions','resource-hosted.ts'),`export { default } from ${JSON.stringify(fileURLToPath(new URL('./measure-full-runtime/hosted-extension.ts',import.meta.url)))};\n`);
|
package/src/codex/return.ts
CHANGED
|
@@ -11,6 +11,7 @@ import { DaemonClient } from "../client.ts";
|
|
|
11
11
|
import { moveSession, type MoveResult } from "../move/orchestrate.ts";
|
|
12
12
|
import { defaultServerDir, socketPathFor } from "../paths.ts";
|
|
13
13
|
import { resolveSession } from "../remote/sessions.ts";
|
|
14
|
+
import { shellQuote } from "../startup/runtime.ts";
|
|
14
15
|
import { preflightCodexProvider } from "./preflight.ts";
|
|
15
16
|
import { readRolloutMeta } from "./rollout.ts";
|
|
16
17
|
import { startCodexDaemon, type CodexDaemon } from "./daemon.ts";
|
|
@@ -74,8 +75,8 @@ async function localDaemon(serverDir: string, codex: CodexRuntimeOptions | undef
|
|
|
74
75
|
* plain `codex resume` works.
|
|
75
76
|
*/
|
|
76
77
|
export function resumeHint(cwd: string, sessionId: string, managed: boolean, serverDir: string): string {
|
|
77
|
-
if (!managed) return `cd ${cwd} && codex resume ${sessionId}`;
|
|
78
|
-
const env = serverDir === defaultServerDir() ? "" : `PI_SERVER_DIR=${serverDir} `;
|
|
78
|
+
if (!managed) return `cd ${shellQuote(cwd)} && codex resume ${sessionId}`;
|
|
79
|
+
const env = serverDir === defaultServerDir() ? "" : `PI_SERVER_DIR=${shellQuote(serverDir)} `;
|
|
79
80
|
return `${env}pi-remote attach ${sessionId} --agent codex (or: ${env}pi-remote steer ${sessionId} --agent codex "<message>")`;
|
|
80
81
|
}
|
|
81
82
|
|
package/src/detach/extension.ts
CHANGED
|
@@ -60,6 +60,7 @@ export function assertLocalSessionTransferSafe(sessionManager: unknown): void {
|
|
|
60
60
|
interface ManagerOwnershipGuard {
|
|
61
61
|
departed: Set<string>;
|
|
62
62
|
wrapped: boolean;
|
|
63
|
+
flushDropped?: () => boolean;
|
|
63
64
|
}
|
|
64
65
|
|
|
65
66
|
// Native replacement and separately loaded extension modules must share both gates and latches.
|
|
@@ -107,9 +108,15 @@ function createLocalOwnershipGuard() {
|
|
|
107
108
|
if (state.wrapped) return;
|
|
108
109
|
state.wrapped = true;
|
|
109
110
|
const rewrite = typeof manager._rewriteFile === "function" ? manager._rewriteFile : undefined;
|
|
110
|
-
//
|
|
111
|
-
//
|
|
111
|
+
// Entries withheld by the fence remain in memory. Rewriting restores parent links
|
|
112
|
+
// on rollback, or on the next append if the fence was lifted outside this handler.
|
|
112
113
|
let dropped = false;
|
|
114
|
+
state.flushDropped = () => {
|
|
115
|
+
if (!dropped || !rewrite || manager.flushed === false) return false;
|
|
116
|
+
rewrite.call(manager);
|
|
117
|
+
dropped = false;
|
|
118
|
+
return true;
|
|
119
|
+
};
|
|
113
120
|
for (const method of GATED_METHODS) {
|
|
114
121
|
const original = manager[method];
|
|
115
122
|
if (typeof original !== "function") continue;
|
|
@@ -119,8 +126,8 @@ function createLocalOwnershipGuard() {
|
|
|
119
126
|
return undefined;
|
|
120
127
|
}
|
|
121
128
|
if (dropped) {
|
|
129
|
+
if (state.flushDropped?.()) return undefined;
|
|
122
130
|
dropped = false;
|
|
123
|
-
if (rewrite && manager.flushed !== false) return rewrite.call(this);
|
|
124
131
|
}
|
|
125
132
|
return (original as (...a: unknown[]) => unknown).apply(this, args);
|
|
126
133
|
};
|
|
@@ -180,6 +187,7 @@ export function markLocalSessionDeparted(pi: ExtensionAPI, sessionId: string, ma
|
|
|
180
187
|
|
|
181
188
|
export interface DetachDeps {
|
|
182
189
|
resolveTarget: typeof resolveTarget;
|
|
190
|
+
waitMs?: number;
|
|
183
191
|
}
|
|
184
192
|
|
|
185
193
|
export function registerDetach(pi: ExtensionAPI, deps: DetachDeps = { resolveTarget }): void {
|
|
@@ -223,6 +231,7 @@ export function registerDetach(pi: ExtensionAPI, deps: DetachDeps = { resolveTar
|
|
|
223
231
|
return DaemonClient.connect(target.socketPath);
|
|
224
232
|
},
|
|
225
233
|
isBusy: () => !ctx.isIdle(),
|
|
234
|
+
...(deps.waitMs === undefined ? {} : { waitMs: deps.waitMs }),
|
|
226
235
|
...(parsed.toCwd ? { toCwd: parsed.toCwd } : {}),
|
|
227
236
|
onProgress: (message) => ctx.ui.notify(message, "info"),
|
|
228
237
|
});
|
|
@@ -231,6 +240,14 @@ export function registerDetach(pi: ExtensionAPI, deps: DetachDeps = { resolveTar
|
|
|
231
240
|
} catch (error) {
|
|
232
241
|
const message = error instanceof Error ? error.message : String(error);
|
|
233
242
|
const untouched = error instanceof PreflightError || (error instanceof MoveError && error.sourceUnfenced);
|
|
243
|
+
if (error instanceof MoveError && error.sourceUnfenced && manager.getSessionId() === sessionId) {
|
|
244
|
+
try {
|
|
245
|
+
if (!localOwnershipGuard(pi).blockedFor(manager)) managerOwnershipGuard(manager).flushDropped?.();
|
|
246
|
+
} catch (flushError) {
|
|
247
|
+
ctx.ui.notify(`${message}\nCould not persist entries buffered during the move: ${String(flushError)}`, "error");
|
|
248
|
+
return;
|
|
249
|
+
}
|
|
250
|
+
}
|
|
234
251
|
ctx.ui.notify(untouched ? `${message}\nThis session is unchanged.` : message, "error");
|
|
235
252
|
} finally {
|
|
236
253
|
await target?.close();
|
package/src/event-log.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { appendFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
-
import { dirname } from "node:path";
|
|
1
|
+
import { appendFileSync, existsSync, mkdirSync, mkdtempSync, readFileSync, renameSync, rmSync, truncateSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { dirname, join } from "node:path";
|
|
3
3
|
|
|
4
4
|
export interface LoggedEvent {
|
|
5
5
|
seq: number;
|
|
@@ -56,13 +56,14 @@ export class EventLog {
|
|
|
56
56
|
private pending: string[] = [];
|
|
57
57
|
private pendingBytes = 0;
|
|
58
58
|
private timer: ReturnType<typeof setTimeout> | undefined;
|
|
59
|
+
private committed: ((entry: LoggedEvent) => void) | undefined;
|
|
59
60
|
|
|
60
61
|
constructor(path: string, options: EventLogOptions = {}) {
|
|
61
62
|
this.path = path;
|
|
62
63
|
this.ringSize = options.ringSize ?? DEFAULT_RING;
|
|
63
64
|
this.maxEvents = options.maxEvents ?? DEFAULT_MAX_EVENTS;
|
|
64
65
|
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
65
|
-
const existing = this.readFile();
|
|
66
|
+
const existing = this.readFile(true);
|
|
66
67
|
this.fileEvents = existing.length;
|
|
67
68
|
this.lastSeq = existing.at(-1)?.seq ?? 0;
|
|
68
69
|
this.maxBytes = options.maxBytes ?? DEFAULT_MAX_BYTES;
|
|
@@ -77,17 +78,21 @@ export class EventLog {
|
|
|
77
78
|
return this.lastSeq;
|
|
78
79
|
}
|
|
79
80
|
|
|
80
|
-
|
|
81
|
-
|
|
81
|
+
onCommitted(listener: (entry: LoggedEvent) => void): void {
|
|
82
|
+
this.committed = listener;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
append(event: unknown, flushImmediately = false): LoggedEvent {
|
|
86
|
+
const logged: LoggedEvent = { seq: this.lastSeq + 1, event };
|
|
82
87
|
const line = `${JSON.stringify(logged)}\n`;
|
|
88
|
+
this.lastSeq = logged.seq;
|
|
83
89
|
const size = Buffer.byteLength(line);
|
|
84
|
-
this.pushRing(logged, size);
|
|
85
90
|
this.pending.push(line);
|
|
86
91
|
this.pendingBytes += size;
|
|
87
92
|
this.fileEvents++;
|
|
88
93
|
this.fileBytes += size;
|
|
89
94
|
// Small batches are written after a short delay; a big one (or a quiet gap in the stream) does not wait.
|
|
90
|
-
if (this.pendingBytes >= 256 * 1024) this.flush();
|
|
95
|
+
if (flushImmediately || this.pendingBytes >= 256 * 1024) this.flush();
|
|
91
96
|
else if (!this.timer) {
|
|
92
97
|
this.timer = setTimeout(() => this.flush(), this.flushMs);
|
|
93
98
|
this.timer.unref();
|
|
@@ -103,10 +108,18 @@ export class EventLog {
|
|
|
103
108
|
this.timer = undefined;
|
|
104
109
|
}
|
|
105
110
|
if (this.pending.length === 0) return;
|
|
106
|
-
const
|
|
111
|
+
const pending = this.pending;
|
|
112
|
+
appendFileSync(this.path, pending.join(""), { mode: 0o600 });
|
|
107
113
|
this.pending = [];
|
|
108
114
|
this.pendingBytes = 0;
|
|
109
|
-
|
|
115
|
+
// Deliver the recorded values. Pi may mutate a streaming message between
|
|
116
|
+
// append and flush, and a replay must agree with the original delivery.
|
|
117
|
+
const committed = pending.map(line => {
|
|
118
|
+
const entry = JSON.parse(line) as LoggedEvent;
|
|
119
|
+
this.pushRing(entry, Buffer.byteLength(line));
|
|
120
|
+
return entry;
|
|
121
|
+
});
|
|
122
|
+
for (const entry of committed) this.committed?.(entry);
|
|
110
123
|
}
|
|
111
124
|
|
|
112
125
|
private pushRing(entry: LoggedEvent, size: number): void {
|
|
@@ -122,6 +135,7 @@ export class EventLog {
|
|
|
122
135
|
|
|
123
136
|
/** Every retained event with `seq > sinceSeq`, in order. */
|
|
124
137
|
since(sinceSeq: number): Replay {
|
|
138
|
+
this.flush();
|
|
125
139
|
const ringFirst = this.ring[0]?.seq;
|
|
126
140
|
const source = ringFirst !== undefined && sinceSeq + 1 >= ringFirst ? this.ring : this.readFile();
|
|
127
141
|
const firstSeq = source[0]?.seq ?? 0;
|
|
@@ -141,16 +155,30 @@ export class EventLog {
|
|
|
141
155
|
// Drop the oldest until the file is at half its byte bound (the newest event always stays).
|
|
142
156
|
while (start < lines.length - 1 && bytes > this.maxBytes / 2) bytes -= Buffer.byteLength(lines[start++]!);
|
|
143
157
|
keep = keep.slice(start);
|
|
144
|
-
|
|
158
|
+
const staging = mkdtempSync(join(dirname(this.path), ".compact-events-"));
|
|
159
|
+
try {
|
|
160
|
+
const next = join(staging, "events.jsonl");
|
|
161
|
+
writeFileSync(next, lines.slice(start).join(""), { mode: 0o600 });
|
|
162
|
+
renameSync(next, this.path);
|
|
163
|
+
} finally {
|
|
164
|
+
rmSync(staging, { recursive: true, force: true });
|
|
165
|
+
}
|
|
145
166
|
this.fileEvents = keep.length;
|
|
146
167
|
this.fileBytes = bytes;
|
|
147
168
|
}
|
|
148
169
|
|
|
149
|
-
private readFile(): LoggedEvent[] {
|
|
170
|
+
private readFile(repairTail = false): LoggedEvent[] {
|
|
150
171
|
this.flush();
|
|
151
172
|
if (!existsSync(this.path)) return [];
|
|
152
173
|
const entries: LoggedEvent[] = [];
|
|
153
|
-
|
|
174
|
+
let text = readFileSync(this.path, "utf8");
|
|
175
|
+
if (repairTail && text && !text.endsWith("\n")) {
|
|
176
|
+
// A crash can leave a partial final line. Remove it before any new
|
|
177
|
+
// append, so a later committed event cannot land on the broken line.
|
|
178
|
+
text = text.slice(0, text.lastIndexOf("\n") + 1);
|
|
179
|
+
truncateSync(this.path, Buffer.byteLength(text));
|
|
180
|
+
}
|
|
181
|
+
for (const line of text.split("\n")) {
|
|
154
182
|
if (!line) continue;
|
|
155
183
|
try {
|
|
156
184
|
entries.push(JSON.parse(line) as LoggedEvent);
|
package/src/hosted-session.ts
CHANGED
|
@@ -104,6 +104,9 @@ export class HostedSession {
|
|
|
104
104
|
constructor(session: AgentSession, log: EventLog, onActivity: (kind?: "work" | "metadata") => void, activity?: SessionActivity) {
|
|
105
105
|
this.session = session;
|
|
106
106
|
this.log = log;
|
|
107
|
+
this.log.onCommitted(entry => {
|
|
108
|
+
for (const listener of this.listeners) listener(entry);
|
|
109
|
+
});
|
|
107
110
|
this.onActivity = onActivity;
|
|
108
111
|
this.activity = activity;
|
|
109
112
|
this.ui = new UiBridge((event) => {
|
|
@@ -125,7 +128,9 @@ export class HostedSession {
|
|
|
125
128
|
if (event.type === "message_end") this.activeMessage = undefined;
|
|
126
129
|
if (event.type === "tool_execution_start" || event.type === "tool_execution_update") this.activeTools.set(event.toolCallId, event);
|
|
127
130
|
if (event.type === "tool_execution_end") this.activeTools.delete(event.toolCallId);
|
|
128
|
-
|
|
131
|
+
// Clients use lifecycle events to decide when a turn is idle. Flush those
|
|
132
|
+
// boundaries together with any preceding token or tool updates.
|
|
133
|
+
this.publish(event, event.type !== "message_update" && event.type !== "tool_execution_update");
|
|
129
134
|
if (event.type === "agent_start") this.runIdle = session.waitForIdle().catch(() => undefined);
|
|
130
135
|
if (event.type === "agent_end") for (const release of [...this.releaseOnAgentEnd]) release();
|
|
131
136
|
this.onActivity("work");
|
|
@@ -228,6 +233,7 @@ export class HostedSession {
|
|
|
228
233
|
fence(): void { this.disposed = true; fenceHostedSession(this.session); this.activity?.revokeRuntime(); }
|
|
229
234
|
|
|
230
235
|
get lastSeq(): number {
|
|
236
|
+
this.log.flush();
|
|
231
237
|
return this.log.last;
|
|
232
238
|
}
|
|
233
239
|
|
|
@@ -243,11 +249,10 @@ export class HostedSession {
|
|
|
243
249
|
/** Activation notices share the normal sequence and replay log, including after commitStop. */
|
|
244
250
|
publishRuntimeEvent(event: unknown): void { this.publish(event); }
|
|
245
251
|
|
|
246
|
-
private publish(event: unknown): void {
|
|
252
|
+
private publish(event: unknown, flushImmediately = true): void {
|
|
247
253
|
this.progressAt = Date.now();
|
|
248
254
|
if (this.runtimeReleased) return;
|
|
249
|
-
|
|
250
|
-
for (const listener of this.listeners) listener(logged);
|
|
255
|
+
this.log.append(event, flushImmediately);
|
|
251
256
|
}
|
|
252
257
|
|
|
253
258
|
/**
|
|
@@ -255,6 +260,7 @@ export class HostedSession {
|
|
|
255
260
|
* The replay and the live registration happen in one synchronous step, so no event is lost or repeated.
|
|
256
261
|
*/
|
|
257
262
|
subscribe(sinceSeq: number | undefined, listener: Listener): { replay: Replay; unsubscribe: () => void } {
|
|
263
|
+
this.log.flush();
|
|
258
264
|
const replay = sinceSeq === undefined ? { events: [], firstSeq: 0, truncated: false } : this.log.since(sinceSeq);
|
|
259
265
|
return { replay, unsubscribe: this.addListener(listener) };
|
|
260
266
|
}
|
|
@@ -305,9 +311,9 @@ export class HostedSession {
|
|
|
305
311
|
this.ui.cancelAll();
|
|
306
312
|
await aborted;
|
|
307
313
|
this.unsubscribe();
|
|
314
|
+
this.log.flush();
|
|
308
315
|
this.listeners.clear();
|
|
309
316
|
this.runtimeReleased = true;
|
|
310
|
-
this.log.flush();
|
|
311
317
|
this.session.dispose();
|
|
312
318
|
}
|
|
313
319
|
|
|
@@ -6,6 +6,7 @@ import { delimiter, dirname, isAbsolute, join, resolve } from "node:path";
|
|
|
6
6
|
import { promisify } from "node:util";
|
|
7
7
|
import { fileURLToPath } from "node:url";
|
|
8
8
|
import { getAgentDir, ProjectTrustStore, SettingsManager } from "@earendil-works/pi-coding-agent";
|
|
9
|
+
import lockfile from "proper-lockfile";
|
|
9
10
|
|
|
10
11
|
export interface PackageSpec {
|
|
11
12
|
source: string;
|
|
@@ -34,10 +35,6 @@ const semver = piRequire("semver") as {
|
|
|
34
35
|
valid(value: string): string | null;
|
|
35
36
|
validRange(value: string): string | null;
|
|
36
37
|
};
|
|
37
|
-
const lockfile = piRequire("proper-lockfile") as {
|
|
38
|
-
lockSync(path: string, options: { realpath: boolean }): () => void;
|
|
39
|
-
lock(path: string, options: { realpath: boolean; retries: { retries: number; minTimeout: number; maxTimeout: number } }): Promise<() => Promise<void>>;
|
|
40
|
-
};
|
|
41
38
|
const run = promisify(execFile);
|
|
42
39
|
const resources = ["extensions", "skills", "prompts", "themes"] as const;
|
|
43
40
|
const commitPattern = /^[a-f0-9]{40}$/;
|
|
@@ -10,9 +10,9 @@ import { acquireMutationStore } from './mutation-store.ts';
|
|
|
10
10
|
export async function createBackgroundTools(root: string, instance: string, draining: () => boolean = () => false, observe?: (scope: Record<string, unknown>) => Promise<any>, verificationMs = 30000,
|
|
11
11
|
trace?: (slot: number, phase: 'queued' | 'executing' | 'recovery' | 'read-pending' | 'read-returned' | 'tool-pending' | 'tool-returned' | 'settled') => void) {
|
|
12
12
|
const load = (file: string) => import(`./domain/background-service/${file}.domain.mjs`);
|
|
13
|
-
const [{ createObservedWaitHost }, { registerTools }, { createBackgroundTaskRuntime }, sandbox, authority, permissions, registry, navigator, failures] = await Promise.all([
|
|
13
|
+
const [{ createObservedWaitHost }, { registerTools }, { createBackgroundTaskRuntime }, sandbox, authority, permissions, registry, navigator, failures, reviewSettings] = await Promise.all([
|
|
14
14
|
load('observed-waits'), load('tools'), load('runtime'), load('sandbox'), load('managed-authority'),
|
|
15
|
-
import(String('./domain/sandbox-policy/permission-settings.domain.mjs')), load('registry'), load('navigator-provider'), load('failures'),
|
|
15
|
+
import(String('./domain/sandbox-policy/permission-settings.domain.mjs')), load('registry'), load('navigator-provider'), load('failures'), load('review-settings'),
|
|
16
16
|
]);
|
|
17
17
|
const identity = await load('process-identity');
|
|
18
18
|
const lease = acquireMutationStore(root);
|
|
@@ -34,6 +34,12 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
34
34
|
traceSeen.add(line);
|
|
35
35
|
try { console.error('[background-handoff-server]', output); } catch { /* diagnostics never own delivery */ }
|
|
36
36
|
};
|
|
37
|
+
const isAttentionDelivery = (item: any) => {
|
|
38
|
+
const type = item.notification.event?.customType;
|
|
39
|
+
return type === 'background-task-stall' || type === 'background-wait-review';
|
|
40
|
+
};
|
|
41
|
+
const sameNativeHost = (item: any, record: any) => item.scope.pid === record.pid && item.scope.start === record.start;
|
|
42
|
+
const deliveryLeaseMs = 30000;
|
|
37
43
|
const ownerKey = (owner: any) => JSON.stringify([owner.workspace, owner.sessionId]);
|
|
38
44
|
const forgetView = (view: string) => { projections.delete(view); recoveryVersions.delete(view); };
|
|
39
45
|
const forgetOwner = (key: string) => {
|
|
@@ -193,7 +199,7 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
193
199
|
sessionManager: { getSessionId: () => record.owner.sessionId, getBranch: () => branch, getEntries: () => branch, getLeafId: () => record.branchIds.at(-1), getSessionFile: () => undefined } };
|
|
194
200
|
service.noteParentContext(ctx, { recover: false });
|
|
195
201
|
for (const [token, item] of deliveries)
|
|
196
|
-
if (Date.now() - item.createdAt
|
|
202
|
+
if (Date.now() - item.createdAt >= deliveryLeaseMs) {
|
|
197
203
|
item.delivery.defer('Native delivery lease expired');
|
|
198
204
|
forgetOwner(ownerKey(item.scope.owner));
|
|
199
205
|
deliveries.delete(token);
|
|
@@ -202,7 +208,7 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
202
208
|
const item = deliveries.get(record.params.token);
|
|
203
209
|
traceHandoff('receipt', { sessionId: record.owner.sessionId, taskId: item?.notification.taskId,
|
|
204
210
|
receiptId: item?.receiptId, found: Boolean(item), delivered: record.params.delivered === true });
|
|
205
|
-
if (!item || ownerKey(item.scope.owner) !== key)
|
|
211
|
+
if (!item || ownerKey(item.scope.owner) !== key || isAttentionDelivery(item) && !sameNativeHost(item, record))
|
|
206
212
|
throw new Error('delivery-receipt-refused');
|
|
207
213
|
if (record.params.delivered === true && !service.isParentOriginActive(item.notification.origin, item.notification.branchId))
|
|
208
214
|
throw new Error('delivery-recipient-inactive');
|
|
@@ -234,7 +240,9 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
234
240
|
trace?.(slot, 'read-returned');
|
|
235
241
|
if (snapshot.status !== 'ready')
|
|
236
242
|
throw new Error(snapshot.reason ?? 'Shared Background observation unverified');
|
|
237
|
-
|
|
243
|
+
// Callback pointers carry a delivery obligation but no navigator detail.
|
|
244
|
+
const visibleRows = snapshot.rows.filter(({ meta }: any) => !meta.callbackPending
|
|
245
|
+
&& (!meta.parentRecipient?.branchId || record.branchIds.includes(meta.parentRecipient.branchId)));
|
|
238
246
|
const revision = authority.backgroundDigest([snapshot.scopeRevision, record.branchIds]);
|
|
239
247
|
let projection = projections.get(viewKey);
|
|
240
248
|
if (projection?.revision !== revision) {
|
|
@@ -260,14 +268,52 @@ export async function createBackgroundTools(root: string, instance: string, drai
|
|
|
260
268
|
let task = service.readDurableTask({cwd: record.owner.workspace, sessionId: record.owner.sessionId}, id);
|
|
261
269
|
if (!task) {
|
|
262
270
|
const exact = await observe({background: true, cwd: record.owner.workspace, sessionId: record.owner.sessionId, id});
|
|
263
|
-
task = exact.rows.find((row: any) => row.meta.id === id)?.meta;
|
|
271
|
+
task = exact.rows.find((row: any) => row.meta.id === id && !row.meta.callbackPending)?.meta;
|
|
264
272
|
}
|
|
265
273
|
if (task && task.dismissedAt === undefined && (!task.parentRecipient?.branchId || record.branchIds.includes(task.parentRecipient.branchId))) { tasks.push(task); present.add(id); }
|
|
266
274
|
}
|
|
267
275
|
}
|
|
268
|
-
const
|
|
276
|
+
const origin = { cwd: record.owner.workspace, sessionId: record.owner.sessionId };
|
|
277
|
+
const liveAlerts = new Map<string, any>();
|
|
278
|
+
const reviewTasks = tasks.filter(task => task.active && task.progress && task.callback && task.owner.kind === 'parent-session');
|
|
279
|
+
let intervalMinutes = reviewSettings.DEFAULT_BACKGROUND_REVIEW_INTERVAL_MINUTES;
|
|
280
|
+
if (reviewTasks.some(task => task.waits.length)) {
|
|
281
|
+
try { intervalMinutes = reviewSettings.readBackgroundReviewInterval({ agentDir: () => root }); }
|
|
282
|
+
catch { /* An unreadable settings file must not interrupt Background delivery. */ }
|
|
283
|
+
}
|
|
284
|
+
let nextReviewAt = Infinity;
|
|
285
|
+
for (const task of reviewTasks) {
|
|
286
|
+
const stall = task.progress.alertDue ? service.pendingStallAlert(origin, task.id, task.waits) : undefined;
|
|
287
|
+
const review = task.waits.length ? service.backgroundWaitReview(origin, task.id, task.waits, intervalMinutes * 60_000) : undefined;
|
|
288
|
+
for (const alert of [stall, review?.alert]) {
|
|
289
|
+
if (!alert) continue;
|
|
290
|
+
liveAlerts.set(alert.delivery.receiptId, alert.notification);
|
|
291
|
+
notifyParent(alert.notification, alert.delivery);
|
|
292
|
+
}
|
|
293
|
+
if (review && !review.alert) nextReviewAt = Math.min(nextReviewAt, review.dueAt);
|
|
294
|
+
}
|
|
295
|
+
const outgoing = [];
|
|
296
|
+
let retryAfterMs = Number.isFinite(nextReviewAt) ? Math.max(1, nextReviewAt - Date.now()) : undefined;
|
|
297
|
+
if (liveAlerts.size && deliveries.size >= 256) retryAfterMs = Math.min(retryAfterMs ?? 1000, 1000);
|
|
298
|
+
for (const [token, item] of deliveries) {
|
|
299
|
+
if (ownerKey(item.scope.owner) !== key) continue;
|
|
300
|
+
let notification = item.notification;
|
|
301
|
+
if (isAttentionDelivery(item)) {
|
|
302
|
+
if (item.notification.branchId && !record.branchIds.includes(item.notification.branchId)) continue;
|
|
303
|
+
notification = liveAlerts.get(item.receiptId);
|
|
304
|
+
if (!notification) { deliveries.delete(token); continue; }
|
|
305
|
+
// Two frontends can share a session and branch. Only the holder may hand off
|
|
306
|
+
// each alert. A survivor polls again at lease expiry if no receipt arrives.
|
|
307
|
+
if (!sameNativeHost(item, record)) {
|
|
308
|
+
const remaining = Math.max(1, item.createdAt + deliveryLeaseMs - Date.now());
|
|
309
|
+
retryAfterMs = Math.min(retryAfterMs ?? remaining, remaining);
|
|
310
|
+
continue;
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
outgoing.push({ token, notification, receiptId: item.receiptId });
|
|
314
|
+
}
|
|
269
315
|
traceHandoff('poll-return', { sessionId: record.owner.sessionId, total: outgoing.length, deliveries: outgoing.slice(0, 8).map(item => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
|
|
270
|
-
return { ...projection, tasks, recoveryPending: service.hasPendingParentCallbackRecovery(), deliveries: outgoing };
|
|
316
|
+
return { ...projection, tasks, retryAfterMs, recoveryPending: service.hasPendingParentCallbackRecovery(), deliveries: outgoing };
|
|
271
317
|
}
|
|
272
318
|
const origin = { cwd: record.owner.workspace, sessionId: record.owner.sessionId };
|
|
273
319
|
if (record.tool === '__background_detail' || record.tool === '__background_action') {
|
|
@@ -7,6 +7,8 @@ import { tmpdir } from "node:os";
|
|
|
7
7
|
import { snapshot } from "./domain/background/snapshot.mjs";
|
|
8
8
|
// @ts-expect-error Generated canonical registry queries.
|
|
9
9
|
import { observeMetasForOrigin, observeRecentMetasForOrigin, recentMetaDeadline, observationRevisionForOrigin, belongsToOrigin, readMeta, getRegistryIoMetrics } from "./domain/background/registry.mjs";
|
|
10
|
+
// @ts-expect-error Generated canonical progress policy.
|
|
11
|
+
import { supervisedProgress } from "./domain/background-service/supervised-progress.domain.mjs";
|
|
10
12
|
import { BackgroundHistory } from "./background-history.ts";
|
|
11
13
|
import type { WorkScope } from "./read-model.ts";
|
|
12
14
|
import { ENTITY_BUDGET } from "./work-budget.ts";
|
|
@@ -141,6 +143,8 @@ export class BackgroundObservation {
|
|
|
141
143
|
try {
|
|
142
144
|
const watcher = watch(directory, { recursive: true }, (_event, file) => {
|
|
143
145
|
if (this.closed) return;
|
|
146
|
+
// Progress changes only the active overlay. Historical rows and wait inputs stay cached.
|
|
147
|
+
if (file && /^tasks[/\\][^/\\]+[/\\]progress\.json$/.test(String(file))) { this.schedule(); return; }
|
|
144
148
|
const match = file && /^(?:observed[/\\]([^/\\]+)\.json|tasks[/\\]([^/\\]+)[/\\](?:launch|claim|command|result|lost|stop|cleanup)\.json)$/.exec(String(file));
|
|
145
149
|
if (match) {
|
|
146
150
|
const op = this.db?.prepare("SELECT operation_id FROM operations WHERE task_id=? AND observer_kind='local-supervisor'").get(match[1] ?? match[2]);
|
|
@@ -310,10 +314,14 @@ export class BackgroundObservation {
|
|
|
310
314
|
this.dirtyOperations.clear();
|
|
311
315
|
if (this.inbox.metrics.more || this.inbox.metrics.pending) this.schedule();
|
|
312
316
|
if (this.expiry) clearTimeout(this.expiry);
|
|
313
|
-
const deadlines = [...this.recent.map(op => op.terminal_at + 30000), ...[...this.legacy.values()].flatMap(entry => [
|
|
317
|
+
const deadlines = [...rows.flatMap(row => row.progress?.nextDeadline ?? []), ...this.recent.map(op => op.terminal_at + 30000), ...[...this.legacy.values()].flatMap(entry => [
|
|
314
318
|
...entry.recent.map(row => row.endedAt + 30000), ...recentMetaDeadline(entry.origin),
|
|
315
319
|
...(entry.origin.sessionId ? recentMetaDeadline({ cwd: entry.origin.cwd }) : [])])].filter(Number.isFinite);
|
|
316
|
-
if (deadlines.length) {
|
|
320
|
+
if (deadlines.length) {
|
|
321
|
+
const delay = Math.max(1, Math.min(2_147_483_647, Math.min(...deadlines) - Date.now()));
|
|
322
|
+
this.expiry = setTimeout(() => this.schedule(), delay);
|
|
323
|
+
this.expiry.unref();
|
|
324
|
+
}
|
|
317
325
|
observation?.commit();
|
|
318
326
|
return changed;
|
|
319
327
|
} catch (error) {
|
|
@@ -404,7 +412,7 @@ export class BackgroundObservation {
|
|
|
404
412
|
const terminal = inspection?.terminal === true || op.terminal_revision > 0;
|
|
405
413
|
const status = inspection?.terminal ? inspection.status : op.terminal_revision > 0 ? op.terminal_outcome : inspection?.status ?? "running";
|
|
406
414
|
const row = { ...parent, durable: true, id: op.task_id, operationId: op.operation_id, kind: context.kind ?? inspection?.kind ?? "process",
|
|
407
|
-
status, active: !terminal, terminal, attention: terminal && status !== "succeeded", waits,
|
|
415
|
+
callback: Boolean(context.kind && context.callback !== false), status, active: !terminal, terminal, attention: terminal && status !== "succeeded", waits,
|
|
408
416
|
terminalRevision: op.terminal_revision, terminalOutcome: op.terminal_outcome,
|
|
409
417
|
owner: { kind: op.owner_kind, sessionId: op.owner_session_id, workspace: op.owner_workspace, branchId: op.owner_branch_id ?? null },
|
|
410
418
|
startedAt: inspection?.result?.startedAt ?? inspection?.launch.createdAt ?? op.created_at,
|
|
@@ -417,7 +425,11 @@ export class BackgroundObservation {
|
|
|
417
425
|
if (this.terminalProjections.size > 4096) this.terminalProjections.delete(this.terminalProjections.keys().next().value!);
|
|
418
426
|
return row;
|
|
419
427
|
} catch (error) { this.dirtyOperations.add(op.operation_id); throw error; }
|
|
420
|
-
}).filter(Boolean)
|
|
428
|
+
}).filter(Boolean).map(row => {
|
|
429
|
+
if (!row.active) return row;
|
|
430
|
+
const inspection = this.terminalProjections.get(row.operationId)?.inspection;
|
|
431
|
+
return { ...row, progress: supervisedProgress(inspection) };
|
|
432
|
+
});
|
|
421
433
|
}
|
|
422
434
|
private pendingRows(entry: BackgroundScope): any[] { return entry.pending; }
|
|
423
435
|
private refreshPending(entry: BackgroundScope, revision: number): void {
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { spawn, spawnSync } from "node:child_process";
|
|
2
|
-
import { appendFileSync, closeSync, existsSync, mkdirSync, openSync, writeSync } from "node:fs";
|
|
3
|
-
import {
|
|
2
|
+
import { accessSync, appendFileSync, closeSync, constants, existsSync, mkdirSync, openSync, readFileSync, writeSync } from "node:fs";
|
|
3
|
+
import { homedir } from "node:os";
|
|
4
|
+
import { dirname, join, win32 } from "node:path";
|
|
4
5
|
/** Known Git for Windows locations; `bash -lc` needs a real bash, not the WSL shim. */
|
|
5
6
|
const WINDOWS_BASH_CANDIDATES = [
|
|
6
7
|
"C:\\Program Files\\Git\\bin\\bash.exe",
|
|
@@ -13,7 +14,8 @@ const WINDOWS_BASH_CANDIDATES = [
|
|
|
13
14
|
* POSIX keeps `/bin/bash`. Windows has no `/bin/bash`, and the `bash.exe` found
|
|
14
15
|
* on PATH is usually the WSL launcher in System32 or the WindowsApps alias,
|
|
15
16
|
* either of which would run the command inside WSL instead of Windows. Prefer
|
|
16
|
-
* an explicit override, then Git for Windows,
|
|
17
|
+
* an explicit override, then Pi's shellPath, Git for Windows, and a non-WSL
|
|
18
|
+
* `bash.exe` on PATH.
|
|
17
19
|
*
|
|
18
20
|
* Resolved lazily at spawn time, not module load: env-injection extensions
|
|
19
21
|
* (e.g. pi-env) may apply settings.json `env` values after this module is
|
|
@@ -21,27 +23,62 @@ const WINDOWS_BASH_CANDIDATES = [
|
|
|
21
23
|
*
|
|
22
24
|
* Exposed for tests and reuse.
|
|
23
25
|
*/
|
|
24
|
-
export function resolveDefaultShell() {
|
|
26
|
+
export function resolveDefaultShell(shellPath) {
|
|
25
27
|
const fromEnv = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
26
28
|
if (fromEnv)
|
|
27
29
|
return fromEnv;
|
|
28
30
|
if (process.platform !== "win32")
|
|
29
31
|
return "/bin/bash";
|
|
30
|
-
|
|
32
|
+
const configured = shellPath ?? readWindowsShellSetting();
|
|
33
|
+
const tried = [];
|
|
34
|
+
if (configured?.trim()) {
|
|
35
|
+
const candidate = /^~[\\/]/.test(configured) ? win32.join(homedir(), configured.slice(2)) : configured;
|
|
36
|
+
tried.push(candidate);
|
|
37
|
+
try {
|
|
38
|
+
accessSync(candidate, constants.F_OK);
|
|
39
|
+
return candidate;
|
|
40
|
+
}
|
|
41
|
+
catch { /* An unavailable setting leaves standard Windows discovery enabled. */ }
|
|
42
|
+
}
|
|
43
|
+
const gitCandidates = [process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]
|
|
44
|
+
.filter((directory) => Boolean(directory))
|
|
45
|
+
.map(directory => win32.join(directory, "Git", "bin", "bash.exe"));
|
|
46
|
+
for (const candidate of new Set([...gitCandidates, ...WINDOWS_BASH_CANDIDATES])) {
|
|
47
|
+
tried.push(candidate);
|
|
31
48
|
if (existsSync(candidate))
|
|
32
49
|
return candidate;
|
|
33
50
|
}
|
|
34
|
-
for (const dir of (process.env.PATH ?? "").split(";")) {
|
|
51
|
+
for (const dir of (process.env.PATH ?? process.env.Path ?? "").split(";")) {
|
|
35
52
|
const trimmed = dir.trim();
|
|
36
53
|
if (!trimmed || /(^|[\\/])(system32|windowsapps)([\\/]|$)/i.test(trimmed))
|
|
37
54
|
continue;
|
|
38
|
-
const candidate = join(trimmed, "bash.exe");
|
|
55
|
+
const candidate = win32.join(trimmed, "bash.exe");
|
|
56
|
+
tried.push(candidate);
|
|
39
57
|
if (existsSync(candidate))
|
|
40
58
|
return candidate;
|
|
41
59
|
}
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
60
|
+
throw new Error("No Bash executable found for Windows Background tasks. Set Pi's shellPath in settings.json or "
|
|
61
|
+
+ "PI_BETTER_BACKGROUND_TASKS_SHELL to a working bash.exe. Searched:\n " + [...new Set(tried)].join("\n "));
|
|
62
|
+
}
|
|
63
|
+
function readWindowsShellSetting() {
|
|
64
|
+
const agentDir = process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent");
|
|
65
|
+
try {
|
|
66
|
+
const settings = JSON.parse(readFileSync(join(agentDir, "settings.json"), "utf8"));
|
|
67
|
+
return typeof settings?.shellPath === "string" ? settings.shellPath : undefined;
|
|
68
|
+
}
|
|
69
|
+
catch {
|
|
70
|
+
return undefined;
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** Capture effective session settings before dispatching a Windows launch. */
|
|
74
|
+
export function resolveWindowsLaunchShell(pi) {
|
|
75
|
+
if (process.platform !== "win32")
|
|
76
|
+
return undefined;
|
|
77
|
+
const override = process.env.PI_BETTER_BACKGROUND_TASKS_SHELL;
|
|
78
|
+
if (override)
|
|
79
|
+
return override;
|
|
80
|
+
const settings = pi.getSettings?.();
|
|
81
|
+
return resolveDefaultShell(typeof settings?.shellPath === "string" ? settings.shellPath : undefined);
|
|
45
82
|
}
|
|
46
83
|
/** How long a timed-out process group has to exit on SIGTERM before SIGKILL. */
|
|
47
84
|
const TERMINATION_GRACE_MS = 2_000;
|
|
@@ -494,7 +531,8 @@ export function commandExecution(spec) {
|
|
|
494
531
|
const [command, ...args] = spec.argv;
|
|
495
532
|
return { execPath: command, execArgs: args };
|
|
496
533
|
}
|
|
497
|
-
|
|
534
|
+
const resolved = process.platform === "win32" ? spec.resolvedWindowsShell : undefined;
|
|
535
|
+
return { execPath: resolved ?? resolveDefaultShell(), execArgs: [spec.loginShell === false ? "-c" : "-lc", spec.command] };
|
|
498
536
|
}
|
|
499
537
|
function spawnArgs(spec, detached, stdio) {
|
|
500
538
|
const env = { ...process.env, ...spec.env };
|
|
@@ -325,13 +325,13 @@ function readText(path) {
|
|
|
325
325
|
catch (error) {
|
|
326
326
|
if (error.code === "ENOENT")
|
|
327
327
|
return { missing: true };
|
|
328
|
-
return { missing:
|
|
328
|
+
return { missing: false, error: error instanceof Error ? error.message : String(error) };
|
|
329
329
|
}
|
|
330
330
|
}
|
|
331
331
|
function readJsonRecord(path, problem) {
|
|
332
332
|
const read = readText(path);
|
|
333
|
-
if (read.
|
|
334
|
-
return { missing:
|
|
333
|
+
if (read.value === undefined)
|
|
334
|
+
return { missing: read.missing, error: read.error };
|
|
335
335
|
let parsed;
|
|
336
336
|
try {
|
|
337
337
|
parsed = JSON.parse(read.value);
|