pi-better-server 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +4 -1
- package/scripts/copy-pi-test-providers.mjs +10 -0
- package/scripts/event-publication/README.md +26 -0
- package/scripts/event-publication/commit.mjs +21 -0
- package/scripts/event-publication/measure.mjs +37 -5
- package/scripts/event-publication/writer.mjs +3 -8
- package/scripts/measure-full-runtime/probe.mjs +4 -2
- package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
- package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
- package/scripts/measure-shared-reads.mjs +2 -1
- package/scripts/private-runtime/package-lock.json +18 -0
- package/scripts/private-runtime/package.json +4 -1
- package/scripts/source-provenance.mjs +2 -2
- package/scripts/test-on-pi.sh +2 -9
- package/src/handshake.ts +1 -1
- package/src/hosted-session.ts +32 -4
- package/src/maintenance.ts +35 -7
- package/src/registry.ts +28 -4
- package/src/runtime/attempt-invalidation.ts +54 -0
- package/src/runtime/background-history.ts +151 -45
- package/src/runtime/background-policy.ts +9 -4
- package/src/runtime/background-tools.ts +131 -23
- package/src/runtime/background.ts +351 -68
- package/src/runtime/cancellation.ts +28 -7
- package/src/runtime/catalog-sources.ts +199 -0
- package/src/runtime/catalog.ts +53 -21
- package/src/runtime/client.ts +22 -2
- package/src/runtime/domain/assignment-inbox.mjs +119 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +43 -35
- package/src/runtime/domain/background/process-identity.mjs +20 -2
- package/src/runtime/domain/background/process.mjs +3 -3
- package/src/runtime/domain/background/registry.mjs +61 -3
- package/src/runtime/domain/background/types.mjs +1 -0
- package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
- package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
- package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
- package/src/runtime/domain/background-service/goal-provider.ts +31 -16
- package/src/runtime/domain/background-service/index.domain.mjs +6 -9
- package/src/runtime/domain/background-service/index.ts +6 -9
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
- package/src/runtime/domain/background-service/managed-authority.ts +5 -3
- package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
- package/src/runtime/domain/background-service/managed-client.ts +20 -7
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
- package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
- package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
- package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
- package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
- package/src/runtime/domain/background-service/observed-waits.ts +154 -30
- package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
- package/src/runtime/domain/background-service/process-identity.ts +18 -2
- package/src/runtime/domain/background-service/process.domain.mjs +3 -3
- package/src/runtime/domain/background-service/process.ts +3 -3
- package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
- package/src/runtime/domain/background-service/registry.ts +53 -5
- package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
- package/src/runtime/domain/background-service/runtime.ts +19 -9
- package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
- package/src/runtime/domain/background-service/sandbox.ts +14 -11
- package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
- package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
- package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
- package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
- package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
- package/src/runtime/domain/background-service/tools.ts +41 -38
- package/src/runtime/domain/background-service/types.domain.mjs +1 -0
- package/src/runtime/domain/background-service/types.ts +3 -1
- package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
- package/src/runtime/domain/background-service/work-observation.ts +46 -19
- package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
- package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
- package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
- package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
- package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
- package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
- package/src/runtime/domain/coordinator/src/store.mjs +21 -3
- package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
- package/src/runtime/domain/coordinator/src/types.mjs +1 -1
- package/src/runtime/domain/health-observation.d.mts +3 -1
- package/src/runtime/domain/health-observation.mjs +189 -190
- package/src/runtime/domain/log-cursor.d.mts +2 -0
- package/src/runtime/domain/log-cursor.mjs +85 -16
- package/src/runtime/domain/parse.d.mts +4 -1
- package/src/runtime/domain/parse.mjs +50 -5
- package/src/runtime/domain/sandbox-policy/README.md +61 -63
- package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
- package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
- package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
- package/src/runtime/domain/sandbox-policy/index.ts +52 -9
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
- package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
- package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
- package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
- package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
- package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
- package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/README.md +1 -1
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
- package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
- package/src/runtime/domain/subagents/assignment-report.ts +83 -19
- package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
- package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
- package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
- package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
- package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
- package/src/runtime/domain/subagents/catalog-store.ts +27 -20
- package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
- package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
- package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
- package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
- package/src/runtime/domain/subagents/child-operations.ts +80 -1
- package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
- package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
- package/src/runtime/domain/subagents/child-process-list.ts +8 -0
- package/src/runtime/domain/subagents/config.domain.mjs +49 -2
- package/src/runtime/domain/subagents/config.ts +46 -2
- package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
- package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
- package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
- package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
- package/src/runtime/domain/subagents/extensions.mjs +11 -13
- package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
- package/src/runtime/domain/subagents/finalization.ts +15 -0
- package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
- package/src/runtime/domain/subagents/goal-provider.ts +44 -2
- package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
- package/src/runtime/domain/subagents/health-observation.ts +43 -48
- package/src/runtime/domain/subagents/index.domain.mjs +296 -123
- package/src/runtime/domain/subagents/index.ts +257 -98
- package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
- package/src/runtime/domain/subagents/launch-context.ts +23 -0
- package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
- package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
- package/src/runtime/domain/subagents/log-cursor.ts +91 -15
- package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
- package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
- package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
- package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
- package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
- package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
- package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
- package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
- package/src/runtime/domain/subagents/owned-exit.ts +12 -0
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
- package/src/runtime/domain/subagents/parse.ts +48 -6
- package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
- package/src/runtime/domain/subagents/permission-policy.ts +41 -8
- package/src/runtime/domain/subagents/process-identity.mjs +33 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
- package/src/runtime/domain/subagents/registry.ts +54 -33
- package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
- package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
- package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
- package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
- package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
- package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
- package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
- package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
- package/src/runtime/domain/subagents/task-policy.ts +3 -1
- package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
- package/src/runtime/domain/subagents/timing.ts +10 -1
- package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
- package/src/runtime/domain/subagents/work-observation.ts +71 -16
- package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
- package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
- package/src/runtime/domain/subagents/worker-waits.ts +93 -34
- package/src/runtime/health-config.ts +27 -11
- package/src/runtime/log-checkpoints.ts +117 -0
- package/src/runtime/mutation-store.ts +5 -4
- package/src/runtime/queries.ts +25 -2
- package/src/runtime/query-executor.ts +149 -28
- package/src/runtime/query-worker.mjs +106 -21
- package/src/runtime/read-model.ts +846 -120
- package/src/runtime/read-watchdog-probe.ts +4 -0
- package/src/runtime/result-supervision.ts +188 -16
- package/src/runtime/source-watch.ts +175 -0
- package/src/runtime/subagent-launch.ts +11 -4
- package/src/runtime/work-budget.ts +130 -0
- package/src/runtime/work-client.d.mts +8 -0
- package/src/runtime/work-client.mjs +150 -7
- package/src/server.ts +104 -23
- package/src/session-activity.ts +26 -4
- package/src/version.ts +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { createHash, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
import { lstatSync, readFileSync, realpathSync } from 'node:fs';
|
|
3
3
|
import { join } from 'node:path';
|
|
4
|
-
import { readProcessStartTokenFresh } from './process-identity.js';
|
|
4
|
+
import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
|
|
5
5
|
const ordered = (value: any): any => value === null || typeof value !== 'object' ? value : Array.isArray(value) ? value.map(ordered) : Object.fromEntries(Object.keys(value).sort().map(key => [key, ordered(value[key])]));
|
|
6
6
|
export const backgroundDigest = (value: unknown) => createHash('sha256').update(JSON.stringify(ordered(value))).digest('hex');
|
|
7
7
|
export function readBackgroundAuthority(root: string, instance: string, authority: any, requireLive = true): any {
|
|
@@ -13,14 +13,16 @@ export function readBackgroundAuthority(root: string, instance: string, authorit
|
|
|
13
13
|
|| !stat.isFile() || stat.isSymbolicLink() || stat.uid !== dir.uid || (stat.mode & 0o077) || stat.size > 1024 * 1024)
|
|
14
14
|
throw new Error('background-authority-refused');
|
|
15
15
|
const record = JSON.parse(readFileSync(path, 'utf8')), digest = createHash('sha256').update(authority.secret).digest('hex');
|
|
16
|
-
if (record.version !== 1 || record.instanceId !== instance || record.id !== authority.id || typeof record.secretHash !== 'string'
|
|
16
|
+
if ((record.version !== 1 && record.version !== 2) || record.instanceId !== instance || record.id !== authority.id || typeof record.secretHash !== 'string'
|
|
17
17
|
|| record.secretHash.length !== digest.length || !timingSafeEqual(Buffer.from(record.secretHash), Buffer.from(digest))
|
|
18
18
|
|| typeof record.key !== 'string' || !record.key || typeof record.tool !== 'string' || !record.owner?.sessionId
|
|
19
19
|
|| record.owner.workspace !== realpathSync(record.owner.workspace) || !Number.isSafeInteger(record.pid) || !record.start
|
|
20
20
|
|| !Array.isArray(record.branchIds) || record.branchIds.some((id: unknown) => typeof id !== 'string'))
|
|
21
21
|
throw new Error('background-authority-refused');
|
|
22
22
|
if (requireLive) {
|
|
23
|
-
|
|
23
|
+
const start = record.version === 2 ? readAdmissionStartToken(record.pid) : readProcessStartTokenFresh(record.pid);
|
|
24
|
+
if (!start) throw new Error('background-authority-refused: cannot verify host start time');
|
|
25
|
+
if (start !== record.start)
|
|
24
26
|
throw new Error('background-authority-refused: host identity changed');
|
|
25
27
|
process.kill(record.pid, 0);
|
|
26
28
|
}
|
|
@@ -4,25 +4,37 @@ import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, w
|
|
|
4
4
|
import { join } from 'node:path';
|
|
5
5
|
import { getAgentDir } from '@earendil-works/pi-coding-agent';
|
|
6
6
|
import { backgroundDigest } from "./managed-authority.domain.mjs";
|
|
7
|
-
import { readProcessStartTokenFresh } from "./process-identity.domain.mjs";
|
|
7
|
+
import { readAdmissionStartToken, readProcessStartTokenFresh } from "./process-identity.domain.mjs";
|
|
8
8
|
import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from "./sandbox.domain.mjs";
|
|
9
|
-
import { backgroundObservation } from "./work-observation.domain.mjs";
|
|
9
|
+
import { backgroundListNeedsHistory, backgroundObservation } from "./work-observation.domain.mjs";
|
|
10
10
|
/** Native host proof carries scope and captured policy, never a transcript or module path. */
|
|
11
11
|
export async function requestBackgroundTool(pi, ctx, key, tool, params, parameters, signal) {
|
|
12
12
|
if (signal?.aborted)
|
|
13
13
|
throw new Error('Background request cancelled before admission');
|
|
14
|
-
|
|
14
|
+
const input = params && typeof params === 'object' ? params : {};
|
|
15
|
+
const list = tool === 'bg_task_list' || (tool === 'bg_task' && input.action === 'list');
|
|
16
|
+
if (list && backgroundListNeedsHistory(input)) {
|
|
17
|
+
// The root history index is shared. Wait on its read plane before acquiring
|
|
18
|
+
// a grant or entering the serialized tool queue, even for an all-session list.
|
|
19
|
+
const snapshot = await backgroundObservation(pi, ctx, true, false, { limit: 1 }, { timeoutMs: 60000, signal });
|
|
20
|
+
if (snapshot.status !== 'ready')
|
|
21
|
+
throw new Error(snapshot.reason ?? `Background history is ${snapshot.status}`);
|
|
22
|
+
}
|
|
23
|
+
else {
|
|
24
|
+
await backgroundObservation(pi, ctx);
|
|
25
|
+
}
|
|
26
|
+
signal?.throwIfAborted();
|
|
15
27
|
const root = realpathSync(getAgentDir()), registration = JSON.parse(readFileSync(join(root, 'server-registration-v1.json'), 'utf8'));
|
|
16
28
|
if (registration.version !== 1 || registration.agentDir !== root)
|
|
17
29
|
throw new Error('Invalid runtime registration');
|
|
18
30
|
const module = new URL('./shared-work-client.mjs', import.meta.url).href;
|
|
19
|
-
const {
|
|
31
|
+
const { connectWorkClient } = await import(module);
|
|
20
32
|
const directory = join(root, 'background-tool-admission');
|
|
21
33
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
22
34
|
const stat = lstatSync(directory);
|
|
23
35
|
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
|
|
24
36
|
throw new Error('Unsafe Background admission directory');
|
|
25
|
-
const client =
|
|
37
|
+
const client = await connectWorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1'], { signal });
|
|
26
38
|
const id = randomUUID(), secret = randomBytes(32).toString('hex'), path = join(directory, `${id}.json`);
|
|
27
39
|
let off;
|
|
28
40
|
const abort = () => client.close();
|
|
@@ -34,9 +46,11 @@ export async function requestBackgroundTool(pi, ctx, key, tool, params, paramete
|
|
|
34
46
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
35
47
|
if (!sessionId)
|
|
36
48
|
throw new Error('Background tools require a native session identity');
|
|
37
|
-
const
|
|
49
|
+
const version = hello.capabilities?.includes("runtime-background-admission-v2") ? 2 : 1;
|
|
50
|
+
const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
|
|
51
|
+
const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
|
|
38
52
|
owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
|
|
39
|
-
pid: process.pid, start
|
|
53
|
+
pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
|
|
40
54
|
const staged = `${path}.tmp`;
|
|
41
55
|
writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
|
|
42
56
|
renameSync(staged, path);
|
|
@@ -3,25 +3,36 @@ import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, w
|
|
|
3
3
|
import { join } from 'node:path';
|
|
4
4
|
import { getAgentDir, type ExtensionAPI, type ExtensionContext } from '@earendil-works/pi-coding-agent';
|
|
5
5
|
import { backgroundDigest } from './managed-authority.js';
|
|
6
|
-
import { readProcessStartTokenFresh } from './process-identity.js';
|
|
6
|
+
import { readAdmissionStartToken, readProcessStartTokenFresh } from './process-identity.js';
|
|
7
7
|
import { currentForegroundSandboxPolicy, FOREGROUND_SANDBOX_POLICY_CHANNEL } from './sandbox.js';
|
|
8
|
-
import { backgroundObservation } from './work-observation.js';
|
|
8
|
+
import { backgroundListNeedsHistory, backgroundObservation } from './work-observation.js';
|
|
9
9
|
/** Native host proof carries scope and captured policy, never a transcript or module path. */
|
|
10
10
|
export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionContext, key: string, tool: string, params: unknown, parameters?: unknown, signal?: AbortSignal): Promise<any> {
|
|
11
11
|
if (signal?.aborted)
|
|
12
12
|
throw new Error('Background request cancelled before admission');
|
|
13
|
-
|
|
13
|
+
const input = params && typeof params === 'object' ? params as Record<string, unknown> : {};
|
|
14
|
+
const list = tool === 'bg_task_list' || (tool === 'bg_task' && input.action === 'list');
|
|
15
|
+
if (list && backgroundListNeedsHistory(input)) {
|
|
16
|
+
// The root history index is shared. Wait on its read plane before acquiring
|
|
17
|
+
// a grant or entering the serialized tool queue, even for an all-session list.
|
|
18
|
+
const snapshot = await backgroundObservation(pi, ctx, true, false, { limit: 1 }, { timeoutMs: 60000, signal });
|
|
19
|
+
if (snapshot.status !== 'ready')
|
|
20
|
+
throw new Error(snapshot.reason ?? `Background history is ${snapshot.status}`);
|
|
21
|
+
} else {
|
|
22
|
+
await backgroundObservation(pi, ctx);
|
|
23
|
+
}
|
|
24
|
+
signal?.throwIfAborted();
|
|
14
25
|
const root = realpathSync(getAgentDir()), registration = JSON.parse(readFileSync(join(root, 'server-registration-v1.json'), 'utf8'));
|
|
15
26
|
if (registration.version !== 1 || registration.agentDir !== root)
|
|
16
27
|
throw new Error('Invalid runtime registration');
|
|
17
28
|
const module = new URL('./shared-work-client.mjs', import.meta.url).href;
|
|
18
|
-
const {
|
|
29
|
+
const { connectWorkClient } = await import(module);
|
|
19
30
|
const directory = join(root, 'background-tool-admission');
|
|
20
31
|
mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
21
32
|
const stat = lstatSync(directory);
|
|
22
33
|
if (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid?.() || (stat.mode & 0o077))
|
|
23
34
|
throw new Error('Unsafe Background admission directory');
|
|
24
|
-
const client =
|
|
35
|
+
const client = await connectWorkClient(join(registration.serverDir, 'pi-server.sock'), root, ['runtime-background-execution-v1'], { signal });
|
|
25
36
|
const id = randomUUID(), secret = randomBytes(32).toString('hex'), path = join(directory, `${id}.json`);
|
|
26
37
|
let off: unknown;
|
|
27
38
|
const abort = () => client.close();
|
|
@@ -33,9 +44,11 @@ export async function requestBackgroundTool(pi: ExtensionAPI, ctx: ExtensionCont
|
|
|
33
44
|
const sessionId = ctx.sessionManager.getSessionId();
|
|
34
45
|
if (!sessionId)
|
|
35
46
|
throw new Error('Background tools require a native session identity');
|
|
36
|
-
const
|
|
47
|
+
const version = hello.capabilities?.includes("runtime-background-admission-v2") ? 2 : 1;
|
|
48
|
+
const start = version === 2 ? readAdmissionStartToken(process.pid) : readProcessStartTokenFresh(process.pid);
|
|
49
|
+
const record = { version, id, secretHash: createHash('sha256').update(secret).digest('hex'), instanceId: hello.instanceId,
|
|
37
50
|
owner: { kind: 'parent-session', sessionId, workspace: realpathSync(ctx.cwd) }, branchIds, projectTrusted: ctx.isProjectTrusted(),
|
|
38
|
-
pid: process.pid, start
|
|
51
|
+
pid: process.pid, start, key, tool, params, parametersDigest: parameters === undefined ? undefined : backgroundDigest(parameters), policy };
|
|
39
52
|
const staged = `${path}.tmp`;
|
|
40
53
|
writeFileSync(staged, JSON.stringify(record), { flag: 'wx', mode: 0o600 });
|
|
41
54
|
renameSync(staged, path);
|
|
@@ -3,12 +3,16 @@ import { randomUUID } from 'node:crypto';
|
|
|
3
3
|
import { requestBackgroundTool } from "./managed-client.domain.mjs";
|
|
4
4
|
import { onBackgroundObservation } from "./work-observation.domain.mjs";
|
|
5
5
|
import { getCallbackBatcher } from "./shared-callback-batcher.domain.mjs";
|
|
6
|
-
import { registerObservedWaitClient } from "./observed-
|
|
6
|
+
import { registerObservedWaitClient } from "./observed-wait-client.domain.mjs";
|
|
7
|
+
import { observeNavigatorLaunch } from "./shared-navigator.domain.mjs";
|
|
7
8
|
/** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
|
|
8
9
|
export function createManagedBackgroundFrontend(pi) {
|
|
9
10
|
let ctx, generation = 0, refresh, dirty = false;
|
|
10
11
|
let rows = [], legacyRows = [], details = new Map(), logs = new Map();
|
|
12
|
+
const retainedTasks = new Map();
|
|
13
|
+
const cachedTask = (id) => rows.find(row => row.id === id) ?? retainedTasks.get(id);
|
|
11
14
|
let adoptedScope;
|
|
15
|
+
let observing = false;
|
|
12
16
|
const scopeOf = (context) => JSON.stringify([context.cwd, context.sessionManager.getSessionId()]);
|
|
13
17
|
const ownership = new Map();
|
|
14
18
|
const adoptContext = (context) => {
|
|
@@ -18,6 +22,7 @@ export function createManagedBackgroundFrontend(pi) {
|
|
|
18
22
|
legacyRows = [];
|
|
19
23
|
details.clear();
|
|
20
24
|
logs.clear();
|
|
25
|
+
retainedTasks.clear();
|
|
21
26
|
generation++;
|
|
22
27
|
}
|
|
23
28
|
ctx = context;
|
|
@@ -34,6 +39,21 @@ export function createManagedBackgroundFrontend(pi) {
|
|
|
34
39
|
ownership.delete(ownership.keys().next().value);
|
|
35
40
|
};
|
|
36
41
|
const queued = new Set(), listeners = new Set();
|
|
42
|
+
const traceSeen = new Set();
|
|
43
|
+
const trace = (stage, facts = {}) => {
|
|
44
|
+
if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== '1')
|
|
45
|
+
return;
|
|
46
|
+
const full = JSON.stringify({ stage, sessionId: ctx?.sessionManager.getSessionId(), ...facts });
|
|
47
|
+
const line = full.length <= 4096 ? full : JSON.stringify({ stage, truncated: true });
|
|
48
|
+
if (traceSeen.has(line) || traceSeen.size >= 128)
|
|
49
|
+
return;
|
|
50
|
+
const output = traceSeen.size === 127 ? JSON.stringify({ stage: 'capture-limit', limit: 128 }) : line;
|
|
51
|
+
traceSeen.add(line);
|
|
52
|
+
try {
|
|
53
|
+
console.error('[background-handoff-frontend]', output);
|
|
54
|
+
}
|
|
55
|
+
catch { /* diagnostics never own delivery */ }
|
|
56
|
+
};
|
|
37
57
|
const active = (origin, branch) => Boolean(ctx && origin.cwd === ctx.cwd && origin.sessionId === ctx.sessionManager.getSessionId()
|
|
38
58
|
&& (!branch || ctx.sessionManager.getBranch().some(entry => entry.id === branch)));
|
|
39
59
|
const request = (tool, params) => {
|
|
@@ -55,21 +75,38 @@ export function createManagedBackgroundFrontend(pi) {
|
|
|
55
75
|
dirty = false;
|
|
56
76
|
const captured = ctx, version = generation;
|
|
57
77
|
refresh = (async () => {
|
|
58
|
-
|
|
78
|
+
trace('poll-start');
|
|
79
|
+
const snapshot = await request('__background_poll', { knownActiveIds: rows.filter(row => row.active).map(row => row.id).slice(0, 200) });
|
|
80
|
+
trace('poll-received', { stale: version !== generation, total: snapshot.deliveries?.length ?? 0, deliveries: (snapshot.deliveries ?? []).slice(0, 8).map((item) => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
|
|
59
81
|
if (version !== generation)
|
|
60
82
|
return;
|
|
61
83
|
if (snapshot.recoveryPending === true)
|
|
62
84
|
dirty = true;
|
|
63
|
-
|
|
64
|
-
|
|
85
|
+
// A rebuilding snapshot is not evidence that visible tasks vanished.
|
|
86
|
+
if (snapshot.status !== 'rebuilding' && snapshot.status !== 'degraded') {
|
|
87
|
+
rows = snapshot.tasks ?? [];
|
|
88
|
+
// Detail remains inspectable while Navigator retains a terminal row.
|
|
89
|
+
for (const task of rows) {
|
|
90
|
+
retainedTasks.delete(task.id);
|
|
91
|
+
retainedTasks.set(task.id, task);
|
|
92
|
+
if (retainedTasks.size > 256)
|
|
93
|
+
retainedTasks.delete(retainedTasks.keys().next().value);
|
|
94
|
+
}
|
|
95
|
+
legacyRows = snapshot.legacyRows ?? [];
|
|
96
|
+
}
|
|
65
97
|
notify();
|
|
66
98
|
for (const item of snapshot.deliveries ?? []) {
|
|
67
99
|
if (queued.has(item.token))
|
|
68
100
|
continue;
|
|
69
101
|
queued.add(item.token);
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
102
|
+
const facts = { taskId: item.notification.taskId, receiptId: item.receiptId };
|
|
103
|
+
const receipt = (delivered, reason) => {
|
|
104
|
+
trace('handoff', { ...facts, delivered, reason: reason?.slice(0, 256) });
|
|
105
|
+
void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
|
|
106
|
+
.then(() => trace('receipt-return', facts), error => trace('receipt-error', { ...facts, error: String(error).slice(0, 256) }))
|
|
107
|
+
.finally(() => { queued.delete(item.token); if (ctx === captured)
|
|
108
|
+
void reconcile().catch(() => undefined); });
|
|
109
|
+
};
|
|
73
110
|
const proof = captured.sessionManager.getBranch().some((entry) => {
|
|
74
111
|
const message = entry.type === 'custom_message' ? entry : entry.message;
|
|
75
112
|
return item.notification.urgent ? message?.customType === item.notification.event.customType && message.details?.urgentEventId === item.receiptId : message?.customType === 'background-completion-batch' && message.details?.completionEventIds?.includes(item.receiptId);
|
|
@@ -79,6 +116,7 @@ export function createManagedBackgroundFrontend(pi) {
|
|
|
79
116
|
continue;
|
|
80
117
|
}
|
|
81
118
|
const n = item.notification;
|
|
119
|
+
trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
|
|
82
120
|
if (n.urgent) {
|
|
83
121
|
void getCallbackBatcher(pi).deliverUrgent({ ...n.event, receiptId: item.receiptId, getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active', onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
|
|
84
122
|
continue;
|
|
@@ -88,22 +126,37 @@ export function createManagedBackgroundFrontend(pi) {
|
|
|
88
126
|
getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
|
|
89
127
|
onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
|
|
90
128
|
}
|
|
91
|
-
})().
|
|
129
|
+
})().catch(error => { trace('poll-error', { error: String(error).slice(0, 256) }); throw error; })
|
|
130
|
+
.finally(() => { refresh = undefined; if (dirty && ctx)
|
|
92
131
|
void reconcile().catch(() => undefined); });
|
|
93
132
|
return refresh;
|
|
94
133
|
};
|
|
134
|
+
const activate = () => {
|
|
135
|
+
if (observing || !ctx)
|
|
136
|
+
return;
|
|
137
|
+
observing = true;
|
|
138
|
+
const version = generation;
|
|
139
|
+
void reconcile().catch(() => { if (generation === version)
|
|
140
|
+
observing = false; });
|
|
141
|
+
};
|
|
95
142
|
const host = {
|
|
96
143
|
async reconcileNow() { await reconcile(); while (refresh)
|
|
97
144
|
await refresh; },
|
|
98
|
-
start(context
|
|
145
|
+
start(context, restore = true) {
|
|
146
|
+
adoptContext(context);
|
|
147
|
+
generation++;
|
|
148
|
+
observing = false;
|
|
149
|
+
if (restore)
|
|
150
|
+
activate();
|
|
151
|
+
},
|
|
99
152
|
noteParentContext(context) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
|
|
100
|
-
close() { ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); queued.clear(); ownership.clear(); },
|
|
153
|
+
close() { observing = false; ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); queued.clear(); ownership.clear(); },
|
|
101
154
|
isParentOriginActive: active,
|
|
102
155
|
onDurableTaskChange(listener) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
103
|
-
listDurableTasks(origin,
|
|
104
|
-
readDurableTask(origin, id) { return active(origin) ?
|
|
156
|
+
listDurableTasks(origin, _options = {}) { return active(origin) ? rows : []; },
|
|
157
|
+
readDurableTask(origin, id) { const task = cachedTask(id); return active(origin, task?.parentRecipient?.branchId) ? task : undefined; },
|
|
105
158
|
ownsDurableTask(id) { if (!ctx || adoptedScope !== scopeOf(ctx))
|
|
106
|
-
return false; return ownership.has(id) || rows.some(row => row.id === id); },
|
|
159
|
+
return false; return ownership.has(id) || rows.some(row => row.id === id && !row.readOnly); },
|
|
107
160
|
readDurableTaskLog(origin, id, lines = 40) {
|
|
108
161
|
if (!active(origin))
|
|
109
162
|
return;
|
|
@@ -135,7 +188,10 @@ export function createManagedBackgroundFrontend(pi) {
|
|
|
135
188
|
throw new Error('Native Background context unavailable');
|
|
136
189
|
adoptContext(context);
|
|
137
190
|
const capturedGeneration = generation, capturedScope = adoptedScope;
|
|
138
|
-
const
|
|
191
|
+
const launch = () => requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
|
|
192
|
+
const spawning = ['bg_task_spawn', 'bg_task_spawn_batch', 'bg_task_watch'].includes(definition.name)
|
|
193
|
+
|| definition.name === 'bg_task' && ['spawn', 'watch'].includes(params?.action);
|
|
194
|
+
const result = spawning ? await observeNavigatorLaunch(context, 'background-tasks', id, params?.name || 'Background task launch', launch) : await launch();
|
|
139
195
|
if (ctx === context && generation === capturedGeneration && adoptedScope === capturedScope)
|
|
140
196
|
rememberOwnership(result.details?.backgroundOwnership, context);
|
|
141
197
|
await host.reconcileNow().catch(() => undefined);
|
|
@@ -146,10 +202,11 @@ export function createManagedBackgroundFrontend(pi) {
|
|
|
146
202
|
} });
|
|
147
203
|
registerObservedWaitClient(proxy, host);
|
|
148
204
|
const ui = {
|
|
149
|
-
|
|
205
|
+
onOpen: activate,
|
|
206
|
+
rows: () => legacyRows,
|
|
150
207
|
prepareDetail(id, options) {
|
|
151
208
|
const lines = options?.logTailLines ?? 40, key = `${id}:${lines}`;
|
|
152
|
-
const durable =
|
|
209
|
+
const durable = Boolean(cachedTask(id)), cache = durable ? logs : details;
|
|
153
210
|
const version = generation;
|
|
154
211
|
if (cache.has(key))
|
|
155
212
|
return;
|
|
@@ -161,7 +218,8 @@ export function createManagedBackgroundFrontend(pi) {
|
|
|
161
218
|
cache.delete(key); });
|
|
162
219
|
},
|
|
163
220
|
detail(id, now, options) { return details.get(`${id}:${options?.logTailLines ?? 40}`) ?? null; },
|
|
164
|
-
close(id) {
|
|
221
|
+
close(id) { if (cachedTask(id)?.readOnly)
|
|
222
|
+
return { action: 'not-closable', providerId: 'background-tasks', id }; void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
|
|
165
223
|
};
|
|
166
224
|
return { host, proxy, ui };
|
|
167
225
|
}
|
|
@@ -4,17 +4,22 @@ import type { ExtensionAPI, ExtensionContext } from '@earendil-works/pi-coding-a
|
|
|
4
4
|
import { requestBackgroundTool } from './managed-client.js';
|
|
5
5
|
import { onBackgroundObservation } from './work-observation.js';
|
|
6
6
|
import { getCallbackBatcher } from './shared-callback-batcher.js';
|
|
7
|
-
import { registerObservedWaitClient
|
|
7
|
+
import { registerObservedWaitClient } from "./observed-wait-client.js";
|
|
8
|
+
import type { ObservedWaitHost } from "./observed-waits.js";
|
|
9
|
+
import { observeNavigatorLaunch } from './shared-navigator.ts';
|
|
8
10
|
/** Native transcript delivery and cached UI projections; no coordinator or supervisor. */
|
|
9
11
|
export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
10
12
|
let ctx: ExtensionContext | undefined, generation = 0, refresh: Promise<void> | undefined, dirty=false;
|
|
11
13
|
let rows: any[] = [], legacyRows: any[] = [], details = new Map<string, any>(), logs = new Map<string, any>();
|
|
14
|
+
const retainedTasks = new Map<string, any>();
|
|
15
|
+
const cachedTask = (id: string) => rows.find(row => row.id === id) ?? retainedTasks.get(id);
|
|
12
16
|
let adoptedScope: string | undefined;
|
|
17
|
+
let observing = false;
|
|
13
18
|
const scopeOf = (context: ExtensionContext) => JSON.stringify([context.cwd, context.sessionManager.getSessionId()]);
|
|
14
19
|
const ownership = new Map<string, { operationId: string; owner: { kind: string; sessionId: string; workspace: string } }>();
|
|
15
20
|
const adoptContext = (context: ExtensionContext) => {
|
|
16
21
|
if (adoptedScope !== undefined && adoptedScope !== scopeOf(context)) {
|
|
17
|
-
ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); generation++;
|
|
22
|
+
ownership.clear(); rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); generation++;
|
|
18
23
|
}
|
|
19
24
|
ctx = context; adoptedScope = scopeOf(context);
|
|
20
25
|
};
|
|
@@ -26,6 +31,16 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
26
31
|
if (ownership.size > 256) ownership.delete(ownership.keys().next().value!);
|
|
27
32
|
};
|
|
28
33
|
const queued = new Set<string>(), listeners = new Set<(change: any) => void>();
|
|
34
|
+
const traceSeen = new Set<string>();
|
|
35
|
+
const trace = (stage: string, facts: Record<string, unknown> = {}) => {
|
|
36
|
+
if (process.env.PI_BG_OBSERVED_WAITS_DEBUG !== '1') return;
|
|
37
|
+
const full = JSON.stringify({ stage, sessionId: ctx?.sessionManager.getSessionId(), ...facts });
|
|
38
|
+
const line = full.length <= 4096 ? full : JSON.stringify({ stage, truncated: true });
|
|
39
|
+
if (traceSeen.has(line) || traceSeen.size >= 128) return;
|
|
40
|
+
const output = traceSeen.size === 127 ? JSON.stringify({ stage: 'capture-limit', limit: 128 }) : line;
|
|
41
|
+
traceSeen.add(line);
|
|
42
|
+
try { console.error('[background-handoff-frontend]', output); } catch { /* diagnostics never own delivery */ }
|
|
43
|
+
};
|
|
29
44
|
const active = (origin: any, branch?: string | null) => Boolean(ctx && origin.cwd === ctx.cwd && origin.sessionId === ctx.sessionManager.getSessionId()
|
|
30
45
|
&& (!branch || ctx.sessionManager.getBranch().some(entry => entry.id === branch)));
|
|
31
46
|
const request = (tool: string, params: any) => {
|
|
@@ -42,19 +57,34 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
42
57
|
dirty=false;
|
|
43
58
|
const captured = ctx, version = generation;
|
|
44
59
|
refresh = (async () => {
|
|
45
|
-
|
|
60
|
+
trace('poll-start');
|
|
61
|
+
const snapshot = await request('__background_poll', { knownActiveIds: rows.filter(row => row.active).map(row => row.id).slice(0, 200) });
|
|
62
|
+
trace('poll-received', { stale: version !== generation, total: snapshot.deliveries?.length ?? 0, deliveries: (snapshot.deliveries ?? []).slice(0, 8).map((item: any) => ({ taskId: item.notification.taskId, receiptId: item.receiptId })) });
|
|
46
63
|
if (version !== generation)
|
|
47
64
|
return;
|
|
48
65
|
if (snapshot.recoveryPending === true) dirty = true;
|
|
49
|
-
|
|
50
|
-
|
|
66
|
+
// A rebuilding snapshot is not evidence that visible tasks vanished.
|
|
67
|
+
if (snapshot.status !== 'rebuilding' && snapshot.status !== 'degraded') {
|
|
68
|
+
rows = snapshot.tasks ?? [];
|
|
69
|
+
// Detail remains inspectable while Navigator retains a terminal row.
|
|
70
|
+
for (const task of rows) {
|
|
71
|
+
retainedTasks.delete(task.id); retainedTasks.set(task.id, task);
|
|
72
|
+
if (retainedTasks.size > 256) retainedTasks.delete(retainedTasks.keys().next().value!);
|
|
73
|
+
}
|
|
74
|
+
legacyRows = snapshot.legacyRows ?? [];
|
|
75
|
+
}
|
|
51
76
|
notify();
|
|
52
77
|
for (const item of snapshot.deliveries ?? []) {
|
|
53
78
|
if (queued.has(item.token))
|
|
54
79
|
continue;
|
|
55
80
|
queued.add(item.token);
|
|
56
|
-
const
|
|
57
|
-
|
|
81
|
+
const facts = { taskId: item.notification.taskId, receiptId: item.receiptId };
|
|
82
|
+
const receipt = (delivered: boolean, reason?: string) => {
|
|
83
|
+
trace('handoff', { ...facts, delivered, reason: reason?.slice(0, 256) });
|
|
84
|
+
void requestBackgroundTool(pi, captured, randomUUID(), '__background_receipt', { token: item.token, delivered, reason })
|
|
85
|
+
.then(() => trace('receipt-return', facts), error => trace('receipt-error', { ...facts, error: String(error).slice(0, 256) }))
|
|
86
|
+
.finally(() => {queued.delete(item.token);if(ctx===captured)void reconcile().catch(()=>undefined);});
|
|
87
|
+
};
|
|
58
88
|
const proof = captured.sessionManager.getBranch().some((entry: any) => {
|
|
59
89
|
const message = entry.type === 'custom_message' ? entry : entry.message;
|
|
60
90
|
return item.notification.urgent ? message?.customType===item.notification.event.customType&&message.details?.urgentEventId===item.receiptId : message?.customType === 'background-completion-batch' && message.details?.completionEventIds?.includes(item.receiptId);
|
|
@@ -64,25 +94,36 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
64
94
|
continue;
|
|
65
95
|
}
|
|
66
96
|
const n = item.notification;
|
|
97
|
+
trace('queue', { ...facts, urgent: n.urgent === true, recipientActive: active(n.origin, n.branchId) });
|
|
67
98
|
if(n.urgent){void getCallbackBatcher(pi).deliverUrgent({...n.event,receiptId:item.receiptId,getSuppressionReason:()=>active(n.origin,n.branchId)?undefined:'The originating session or branch is no longer active',onDelivered:()=>receipt(true),onSuppressed:(reason)=>receipt(false,reason)});continue;}
|
|
68
99
|
getCallbackBatcher(pi).enqueue({ ...n.event, source: 'background-task', id: n.taskId, label: n.taskId, status: n.waitId ? `${n.status}; wait ${n.waitId} ready` : n.status,
|
|
69
100
|
detailTool: 'bg_task_status', outcome: n.outcome, callback: true, receiptId: item.receiptId,
|
|
70
101
|
getSuppressionReason: () => active(n.origin, n.branchId) ? undefined : 'The originating session or branch is no longer active',
|
|
71
102
|
onDelivered: () => receipt(true), onSuppressed: (reason) => receipt(false, reason) });
|
|
72
103
|
}
|
|
73
|
-
})().
|
|
104
|
+
})().catch(error => { trace('poll-error', { error: String(error).slice(0, 256) }); throw error; })
|
|
105
|
+
.finally(() => { refresh = undefined;if(dirty&&ctx)void reconcile().catch(()=>undefined); });
|
|
74
106
|
return refresh;
|
|
75
107
|
};
|
|
108
|
+
const activate = () => {
|
|
109
|
+
if (observing || !ctx) return;
|
|
110
|
+
observing = true;
|
|
111
|
+
const version = generation;
|
|
112
|
+
void reconcile().catch(() => { if (generation === version) observing = false; });
|
|
113
|
+
};
|
|
76
114
|
const host = {
|
|
77
115
|
async reconcileNow() { await reconcile(); while (refresh) await refresh; },
|
|
78
|
-
start(context: ExtensionContext
|
|
116
|
+
start(context: ExtensionContext, restore = true) {
|
|
117
|
+
adoptContext(context); generation++; observing = false;
|
|
118
|
+
if (restore) activate();
|
|
119
|
+
},
|
|
79
120
|
noteParentContext(context: ExtensionContext) { adoptContext(context); generation++; void reconcile().catch(() => undefined); },
|
|
80
|
-
close() { ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); queued.clear(); ownership.clear(); },
|
|
121
|
+
close() { observing = false; ctx = undefined; adoptedScope = undefined; generation++; rows = []; legacyRows = []; details.clear(); logs.clear(); retainedTasks.clear(); queued.clear(); ownership.clear(); },
|
|
81
122
|
isParentOriginActive: active,
|
|
82
123
|
onDurableTaskChange(listener: (change: any) => void) { listeners.add(listener); return () => listeners.delete(listener); },
|
|
83
|
-
listDurableTasks(origin: any,
|
|
84
|
-
readDurableTask(origin: any, id: string) { return active(origin) ?
|
|
85
|
-
ownsDurableTask(id: string) { if (!ctx || adoptedScope !== scopeOf(ctx)) return false; return ownership.has(id) || rows.some(row => row.id === id); },
|
|
124
|
+
listDurableTasks(origin: any, _options: any = {}) { return active(origin) ? rows : []; },
|
|
125
|
+
readDurableTask(origin: any, id: string) { const task = cachedTask(id); return active(origin, task?.parentRecipient?.branchId) ? task : undefined; },
|
|
126
|
+
ownsDurableTask(id: string) { if (!ctx || adoptedScope !== scopeOf(ctx)) return false; return ownership.has(id) || rows.some(row => row.id === id && !row.readOnly); },
|
|
86
127
|
readDurableTaskLog(origin: any, id: string, lines = 40) {
|
|
87
128
|
if (!active(origin))
|
|
88
129
|
return;
|
|
@@ -104,7 +145,10 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
104
145
|
throw new Error('Native Background context unavailable');
|
|
105
146
|
adoptContext(context);
|
|
106
147
|
const capturedGeneration = generation, capturedScope = adoptedScope;
|
|
107
|
-
const
|
|
148
|
+
const launch = () => requestBackgroundTool(pi, context, id, definition.name, params, definition.parameters, signal);
|
|
149
|
+
const spawning = ['bg_task_spawn', 'bg_task_spawn_batch', 'bg_task_watch'].includes(definition.name)
|
|
150
|
+
|| definition.name === 'bg_task' && ['spawn', 'watch'].includes(params?.action);
|
|
151
|
+
const result = spawning ? await observeNavigatorLaunch(context, 'background-tasks', id, params?.name || 'Background task launch', launch) : await launch();
|
|
108
152
|
if (ctx === context && generation === capturedGeneration && adoptedScope === capturedScope) rememberOwnership(result.details?.backgroundOwnership, context);
|
|
109
153
|
await host.reconcileNow().catch(() => undefined);
|
|
110
154
|
return result;
|
|
@@ -114,10 +158,11 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
114
158
|
} });
|
|
115
159
|
registerObservedWaitClient(proxy, host as unknown as ObservedWaitHost);
|
|
116
160
|
const ui: ManagedBackgroundNavigator = {
|
|
117
|
-
|
|
161
|
+
onOpen: activate,
|
|
162
|
+
rows: () => legacyRows,
|
|
118
163
|
prepareDetail(id, options) {
|
|
119
164
|
const lines = options?.logTailLines ?? 40, key = `${id}:${lines}`;
|
|
120
|
-
const durable =
|
|
165
|
+
const durable = Boolean(cachedTask(id)), cache = durable ? logs : details;
|
|
121
166
|
const version=generation;
|
|
122
167
|
if (cache.has(key))
|
|
123
168
|
return;
|
|
@@ -125,7 +170,7 @@ export function createManagedBackgroundFrontend(pi: ExtensionAPI) {
|
|
|
125
170
|
void request(durable ? '__background_log' : '__background_detail', { id, lines }).then(value => { if(version===generation){cache.set(key, value); notify();} }, () => {if(version===generation)cache.delete(key);});
|
|
126
171
|
},
|
|
127
172
|
detail(id, now, options) { return details.get(`${id}:${options?.logTailLines ?? 40}`) ?? null; },
|
|
128
|
-
close(id) { void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
|
|
173
|
+
close(id) { if (cachedTask(id)?.readOnly) return {action: 'not-closable', providerId: 'background-tasks', id}; void request('__background_action', { id, action: rows.find(row => row.id === id)?.active || legacyRows.find(row => row.id === id)?.status === 'running' ? 'stop' : 'dismiss' }).then(() => reconcile()).catch(() => undefined); return { action: 'requested', providerId: 'background-tasks', id }; }
|
|
129
174
|
};
|
|
130
175
|
return { host, proxy, ui };
|
|
131
176
|
}
|
|
@@ -6,13 +6,12 @@ import { actionableFailures, failureLabel, readFailureState } from "./shared-fai
|
|
|
6
6
|
import { failurePath, failureView } from "./failures.domain.mjs";
|
|
7
7
|
import { readLog } from "./logs.domain.mjs";
|
|
8
8
|
import { listMetasForOrigin, onMetaChanged, readMeta, writeMeta } from "./registry.domain.mjs";
|
|
9
|
-
import { getObservedWaitHost } from "./observed-
|
|
10
|
-
import { stopTask } from "./runtime.domain.mjs";
|
|
9
|
+
import { getObservedWaitHost } from "./observed-wait-client.domain.mjs";
|
|
11
10
|
import { formatBackgroundTaskStall, observeBackgroundTaskStall } from "./stall.domain.mjs";
|
|
12
11
|
const TERMINAL_NAVIGATOR_RETENTION_MS = 30_000;
|
|
13
12
|
const DURABLE_ROW_CACHE_MS = 1_000;
|
|
14
13
|
let durableRowCache;
|
|
15
|
-
export function createBackgroundTasksNavigator(runtime
|
|
14
|
+
export function createBackgroundTasksNavigator(runtime, managed) {
|
|
16
15
|
const owner = Symbol("background-tasks navigator factory");
|
|
17
16
|
let unregister;
|
|
18
17
|
let navigatorContext;
|
|
@@ -74,6 +73,7 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
|
|
|
74
73
|
id: "background-tasks",
|
|
75
74
|
label: "Background Tasks",
|
|
76
75
|
priority: 20,
|
|
76
|
+
onOpen: managed?.onOpen,
|
|
77
77
|
visibleCount: () => {
|
|
78
78
|
const now = Date.now();
|
|
79
79
|
return (managed ? managed.rows().filter(row => row.status === "running").length : visibleMetas(now).filter((meta) => meta.status === "running").length)
|
|
@@ -92,9 +92,13 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
|
|
|
92
92
|
},
|
|
93
93
|
armCloseLabel: (row) => row.status === "running" || row.status === "starting" ? "x again to stop" : "x again to dismiss",
|
|
94
94
|
close: (id) => {
|
|
95
|
+
if (durableTask(id)?.readOnly)
|
|
96
|
+
return { action: "not-closable", providerId: "background-tasks", id };
|
|
95
97
|
if (managed)
|
|
96
98
|
return managed.close(id);
|
|
97
99
|
const durable = durableTask(id);
|
|
100
|
+
if (durable?.readOnly)
|
|
101
|
+
return { action: "not-closable", providerId: "background-tasks", id };
|
|
98
102
|
if (durable) {
|
|
99
103
|
const host = navigatorHost();
|
|
100
104
|
const origin = activeNavigatorOrigin;
|
|
@@ -113,7 +117,11 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
|
|
|
113
117
|
if (!meta)
|
|
114
118
|
return { action: "missing", providerId: "background-tasks", id };
|
|
115
119
|
if (meta.status === "running") {
|
|
116
|
-
|
|
120
|
+
const pi = piRef;
|
|
121
|
+
if (runtime)
|
|
122
|
+
void runtime.stopTask(pi, id);
|
|
123
|
+
else
|
|
124
|
+
void import("./runtime.domain.mjs").then(({ stopTask }) => stopTask(pi, id));
|
|
117
125
|
return { action: "stopped", providerId: "background-tasks", id, status: "stopping" };
|
|
118
126
|
}
|
|
119
127
|
meta.dismissedAt = Date.now();
|
|
@@ -180,6 +188,8 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
|
|
|
180
188
|
return {
|
|
181
189
|
providerId: "background-tasks",
|
|
182
190
|
id: task.id,
|
|
191
|
+
parentAgentId: task.parentAgentId,
|
|
192
|
+
readOnly: task.readOnly,
|
|
183
193
|
name: task.name,
|
|
184
194
|
status: task.status,
|
|
185
195
|
statusTone: toneForDurableStatus(task.status),
|
|
@@ -204,6 +214,7 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
|
|
|
204
214
|
const metadata = [
|
|
205
215
|
{ label: "provider", value: "Background Tasks (durable)" },
|
|
206
216
|
{ label: "kind", value: task.kind },
|
|
217
|
+
...(task.parentAgentId ? [{ label: "agent", value: task.parentAgentId }] : []),
|
|
207
218
|
{ label: "operation", value: task.operationId },
|
|
208
219
|
{ label: "status", value: `${task.status}${task.terminalOutcome ? ` (${task.terminalOutcome})` : ""}` },
|
|
209
220
|
{ label: "started", value: new Date(task.startedAt).toISOString() },
|
|
@@ -242,7 +253,7 @@ export function createBackgroundTasksNavigator(runtime = { stopTask }, managed)
|
|
|
242
253
|
label: log?.truncated ? "log tail" : "log",
|
|
243
254
|
text: evidenceText,
|
|
244
255
|
},
|
|
245
|
-
footerActions: [task.active ? "x stop" : "x dismiss"],
|
|
256
|
+
footerActions: task.readOnly ? ["Managed by owning agent"] : [task.active ? "x stop" : "x dismiss"],
|
|
246
257
|
};
|
|
247
258
|
}
|
|
248
259
|
function durableCommandLabel(task) {
|