pi-background-tasks 2.5.0 → 2.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/BACKGROUND-TASKS-INSTRUCTIONS.md +1 -1
- package/README.md +70 -25
- package/TESTING.md +42 -2
- package/TEST_PLAN.md +7 -4
- package/dist/extensions/anthropic-attribution-child.js +4 -0
- package/dist/extensions/anthropic-attribution-child.js.map +1 -0
- package/dist/extensions/anthropic-attribution.js +107 -0
- package/dist/extensions/anthropic-attribution.js.map +1 -0
- package/dist/extensions/background-tasks.js +2 -0
- package/dist/extensions/background-tasks.js.map +1 -0
- package/dist/extensions/delegate-child.js +2 -0
- package/dist/extensions/delegate-child.js.map +1 -0
- package/dist/extensions/fusion-child.js +2 -0
- package/dist/extensions/fusion-child.js.map +1 -0
- package/dist/package.json +5 -0
- package/dist/src/core/anthropic-attribution-path.js +24 -0
- package/dist/src/core/anthropic-attribution-path.js.map +1 -0
- package/dist/src/core/anthropic-attribution.js +2247 -0
- package/dist/src/core/anthropic-attribution.js.map +1 -0
- package/dist/src/core/attested-pi-contract.js +5 -0
- package/dist/src/core/attested-pi-contract.js.map +1 -0
- package/dist/src/core/attested-pi-run.js +749 -0
- package/dist/src/core/attested-pi-run.js.map +1 -0
- package/dist/src/core/canonical-json.js +19 -0
- package/dist/src/core/canonical-json.js.map +1 -0
- package/dist/src/core/common.js +787 -0
- package/dist/src/core/common.js.map +1 -0
- package/dist/src/core/config.js +78 -0
- package/dist/src/core/config.js.map +1 -0
- package/dist/src/core/context/parent-snapshot.js +75 -0
- package/dist/src/core/context/parent-snapshot.js.map +1 -0
- package/dist/src/core/context/token-budget.js +631 -0
- package/dist/src/core/context/token-budget.js.map +1 -0
- package/dist/src/core/context/visible-conversation-v2.js +390 -0
- package/dist/src/core/context/visible-conversation-v2.js.map +1 -0
- package/dist/src/core/delegate/artifacts.js +357 -0
- package/dist/src/core/delegate/artifacts.js.map +1 -0
- package/dist/src/core/delegate/budget.js +266 -0
- package/dist/src/core/delegate/budget.js.map +1 -0
- package/dist/src/core/delegate/facade-contract.js +7 -0
- package/dist/src/core/delegate/facade-contract.js.map +1 -0
- package/dist/src/core/delegate/hook-contract-evidence.json +18 -0
- package/dist/src/core/delegate/hook-contract.js +124 -0
- package/dist/src/core/delegate/hook-contract.js.map +1 -0
- package/dist/src/core/delegate/launch.js +366 -0
- package/dist/src/core/delegate/launch.js.map +1 -0
- package/dist/src/core/delegate/result-package.js +293 -0
- package/dist/src/core/delegate/result-package.js.map +1 -0
- package/dist/src/core/delegate/runner.js +398 -0
- package/dist/src/core/delegate/runner.js.map +1 -0
- package/dist/src/core/delegate/seed.js +334 -0
- package/dist/src/core/delegate/seed.js.map +1 -0
- package/dist/src/core/delegate/types.js +103 -0
- package/dist/src/core/delegate/types.js.map +1 -0
- package/dist/src/core/durable-fs.js +372 -0
- package/dist/src/core/durable-fs.js.map +1 -0
- package/dist/src/core/extension-api.js +382 -0
- package/dist/src/core/extension-api.js.map +1 -0
- package/dist/src/core/fusion/artifacts.js +654 -0
- package/dist/src/core/fusion/artifacts.js.map +1 -0
- package/dist/src/core/fusion/budget.js +949 -0
- package/dist/src/core/fusion/budget.js.map +1 -0
- package/dist/src/core/fusion/child-protocol.js +176 -0
- package/dist/src/core/fusion/child-protocol.js.map +1 -0
- package/dist/src/core/fusion/claude-cache.js +156 -0
- package/dist/src/core/fusion/claude-cache.js.map +1 -0
- package/dist/src/core/fusion/clean-context.js +64 -0
- package/dist/src/core/fusion/clean-context.js.map +1 -0
- package/dist/src/core/fusion/config.js +349 -0
- package/dist/src/core/fusion/config.js.map +1 -0
- package/dist/src/core/fusion/context.js +184 -0
- package/dist/src/core/fusion/context.js.map +1 -0
- package/dist/src/core/fusion/evaluation.js +696 -0
- package/dist/src/core/fusion/evaluation.js.map +1 -0
- package/dist/src/core/fusion/facade-contract.js +3 -0
- package/dist/src/core/fusion/facade-contract.js.map +1 -0
- package/dist/src/core/fusion/orchestrator.js +867 -0
- package/dist/src/core/fusion/orchestrator.js.map +1 -0
- package/dist/src/core/fusion/output-contract.js +27 -0
- package/dist/src/core/fusion/output-contract.js.map +1 -0
- package/dist/src/core/fusion/pi-child.js +1741 -0
- package/dist/src/core/fusion/pi-child.js.map +1 -0
- package/dist/src/core/fusion/prompts.js +260 -0
- package/dist/src/core/fusion/prompts.js.map +1 -0
- package/dist/src/core/fusion/result-package.js +857 -0
- package/dist/src/core/fusion/result-package.js.map +1 -0
- package/dist/src/core/fusion/source-policy.js +259 -0
- package/dist/src/core/fusion/source-policy.js.map +1 -0
- package/dist/src/core/fusion/types.js +207 -0
- package/dist/src/core/fusion/types.js.map +1 -0
- package/dist/src/core/fusion/web-fetch.js +777 -0
- package/dist/src/core/fusion/web-fetch.js.map +1 -0
- package/dist/src/core/fusion/workflows.js +126 -0
- package/dist/src/core/fusion/workflows.js.map +1 -0
- package/dist/src/core/lazy-module.js +181 -0
- package/dist/src/core/lazy-module.js.map +1 -0
- package/dist/src/core/pi-launch.js +431 -0
- package/dist/src/core/pi-launch.js.map +1 -0
- package/dist/src/core/registry.js +3331 -0
- package/dist/src/core/registry.js.map +1 -0
- package/dist/src/core/reload-shell-owner.js +1396 -0
- package/dist/src/core/reload-shell-owner.js.map +1 -0
- package/dist/src/core/shell-policy.js +80 -0
- package/dist/src/core/shell-policy.js.map +1 -0
- package/dist/src/core/task-durable.js +51 -0
- package/dist/src/core/task-durable.js.map +1 -0
- package/dist/src/core/update-check.js +92 -0
- package/dist/src/core/update-check.js.map +1 -0
- package/dist/src/core/windows-taskkill.js +185 -0
- package/dist/src/core/windows-taskkill.js.map +1 -0
- package/dist/src/delegate-child-extension.js +776 -0
- package/dist/src/delegate-child-extension.js.map +1 -0
- package/dist/src/delegate-extension.js +746 -0
- package/dist/src/delegate-extension.js.map +1 -0
- package/dist/src/extension.js +953 -0
- package/dist/src/extension.js.map +1 -0
- package/dist/src/fusion-child-extension.js +760 -0
- package/dist/src/fusion-child-extension.js.map +1 -0
- package/dist/src/fusion-extension.js +1030 -0
- package/dist/src/fusion-extension.js.map +1 -0
- package/dist/src/ui/background-tasks-manager.js +689 -0
- package/dist/src/ui/background-tasks-manager.js.map +1 -0
- package/dist/src/ui/fusion-model-selector.js +277 -0
- package/dist/src/ui/fusion-model-selector.js.map +1 -0
- package/docs/INDEX.md +35 -33
- package/docs/api/eventbus-v1.md +21 -5
- package/docs/choose-a-workflow.md +2 -0
- package/docs/commands/bg-clear.md +3 -3
- package/docs/commands/bg-update.md +3 -3
- package/docs/commands/bg.md +18 -6
- package/docs/commands/claude-cache.md +4 -4
- package/docs/commands/fusion-models.md +49 -4
- package/docs/commands/fusion.md +3 -3
- package/docs/commands/jobs.md +3 -3
- package/docs/commands/kill.md +3 -3
- package/docs/commands/logs.md +3 -3
- package/docs/commands/task-manager.md +5 -5
- package/docs/concepts/completion-delivery.md +6 -2
- package/docs/getting-started.md +7 -1
- package/docs/manifest.json +228 -42
- package/docs/operations/configuration.md +58 -5
- package/docs/operations/releasing.md +4 -2
- package/docs/operations/testing.md +22 -0
- package/docs/operations/troubleshooting.md +6 -2
- package/docs/read-before-edit.md +44 -31
- package/docs/reference/runtime-contracts.md +87 -51
- package/docs/reference/shortcuts-and-dock.md +28 -14
- package/docs/subsystems/anthropic-attribution.md +23 -11
- package/docs/subsystems/attested-pi-runs.md +12 -7
- package/docs/subsystems/background-task-runtime.md +53 -11
- package/docs/subsystems/child-launch-durability-and-safety.md +28 -9
- package/docs/subsystems/delegation.md +16 -3
- package/docs/subsystems/docs-freshness-gate.md +14 -7
- package/docs/subsystems/fusion.md +36 -11
- package/docs/subsystems/host-ui-and-telemetry.md +22 -9
- package/docs/tools/bg_delegate.md +3 -1
- package/docs/tools/bg_kill.md +3 -1
- package/docs/tools/bg_logs.md +3 -1
- package/docs/tools/bg_result.md +5 -3
- package/docs/tools/bg_run.md +31 -5
- package/docs/tools/bg_run_pi_attested.md +3 -1
- package/docs/tools/bg_status.md +3 -1
- package/docs/tools/fusion_investigate.md +3 -1
- package/docs/tools/fusion_reason.md +3 -1
- package/docs/tools/fusion_research.md +3 -1
- package/docs/tools/fusion_validate.md +3 -1
- package/extensions/anthropic-attribution-child.ts +3 -0
- package/extensions/anthropic-attribution.ts +166 -1
- package/package.json +12 -10
- package/src/core/anthropic-attribution-path.ts +5 -4
- package/src/core/anthropic-attribution.ts +293 -113
- package/src/core/attested-pi-contract.ts +4 -0
- package/src/core/attested-pi-run.ts +468 -81
- package/src/core/canonical-json.ts +21 -0
- package/src/core/common.ts +450 -40
- package/src/core/config.ts +121 -0
- package/src/core/context/visible-conversation-v2.ts +3 -6
- package/src/core/delegate/artifacts.ts +13 -9
- package/src/core/delegate/budget.ts +13 -6
- package/src/core/delegate/facade-contract.ts +6 -0
- package/src/core/delegate/result-package.ts +32 -14
- package/src/core/delegate/runner.ts +129 -58
- package/src/core/delegate/seed.ts +5 -7
- package/src/core/durable-fs.ts +178 -30
- package/src/core/extension-api.ts +36 -8
- package/src/core/fusion/artifacts.ts +17 -16
- package/src/core/fusion/clean-context.ts +8 -5
- package/src/core/fusion/config.ts +2 -1
- package/src/core/fusion/context.ts +2 -6
- package/src/core/fusion/facade-contract.ts +2 -0
- package/src/core/fusion/orchestrator.ts +3 -3
- package/src/core/fusion/prompts.ts +1 -1
- package/src/core/fusion/result-package.ts +259 -72
- package/src/core/fusion/source-policy.ts +43 -17
- package/src/core/lazy-module.ts +215 -0
- package/src/core/pi-launch.ts +390 -65
- package/src/core/registry.ts +2010 -381
- package/src/core/reload-shell-owner.ts +1662 -0
- package/src/core/shell-policy.ts +134 -0
- package/src/core/task-durable.ts +67 -0
- package/src/delegate-extension.ts +404 -144
- package/src/extension.ts +387 -114
- package/src/fusion-extension.ts +202 -96
|
@@ -0,0 +1,749 @@
|
|
|
1
|
+
import { spawn as nodeSpawn } from 'node:child_process';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { readFile, realpath, stat } from 'node:fs/promises';
|
|
4
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
5
|
+
import { isJsonObject, parseJsonText } from './common.js';
|
|
6
|
+
import { canonicalJson, sha256Buffer } from './canonical-json.js';
|
|
7
|
+
import { ATTESTED_GIT_KILL_GRACE_MS, ATTESTED_GIT_MAX_OUTPUT_BYTES, ATTESTED_GIT_TIMEOUT_MS, } from './attested-pi-contract.js';
|
|
8
|
+
export { canonicalJson, sha256Buffer } from './canonical-json.js';
|
|
9
|
+
export { ATTESTED_GIT_KILL_GRACE_MS, ATTESTED_GIT_MAX_OUTPUT_BYTES, ATTESTED_GIT_TIMEOUT_MS, ATTESTED_TASK_ID_PATTERN, } from './attested-pi-contract.js';
|
|
10
|
+
export { closeAndFsyncOutputStream, writeFileFsynced, writeJsonAtomic } from './task-durable.js';
|
|
11
|
+
import { runWindowsTaskkill, } from './windows-taskkill.js';
|
|
12
|
+
import { assertWindowsCommandLineWithinLimit, piLaunchArgv, resolvePiLaunch, } from './pi-launch.js';
|
|
13
|
+
export const PI_TASK_ATTESTATION_SCHEMA_VERSION = 'phase2.pi_task_attestation.v1';
|
|
14
|
+
export class AttestedGitCommandError extends Error {
|
|
15
|
+
code = 'attested_git_failed';
|
|
16
|
+
constructor(message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'AttestedGitCommandError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class AttestedGitTimeoutError extends Error {
|
|
22
|
+
code = 'attested_git_timeout';
|
|
23
|
+
constructor(args) {
|
|
24
|
+
super(`git ${args.join(' ')} timed out during attested Pi preflight`);
|
|
25
|
+
this.name = 'AttestedGitTimeoutError';
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
export class AttestedGitOutputLimitError extends Error {
|
|
29
|
+
code = 'attested_git_output_limit';
|
|
30
|
+
constructor(args, maxBytes) {
|
|
31
|
+
super(`git ${args.join(' ')} output exceeded the explicit ${String(maxBytes)} bytes per-stream limit`);
|
|
32
|
+
this.name = 'AttestedGitOutputLimitError';
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
class AttestedGitCleanupError extends Error {
|
|
36
|
+
code = 'attested_git_cleanup_failed';
|
|
37
|
+
primaryError;
|
|
38
|
+
cleanupErrors;
|
|
39
|
+
constructor(primaryError, cleanupErrors) {
|
|
40
|
+
super(`${primaryError.message}; Git process-tree cleanup failed: ${cleanupErrors.join('; ')}`);
|
|
41
|
+
this.name = 'AttestedGitCleanupError';
|
|
42
|
+
this.primaryError = primaryError;
|
|
43
|
+
this.cleanupErrors = [...cleanupErrors];
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
export function makeAttestedTaskId() {
|
|
47
|
+
return `b${randomBytes(16).toString('hex')}`;
|
|
48
|
+
}
|
|
49
|
+
export function validateStructuredPiLaunchRequest(input) {
|
|
50
|
+
if (!input.name.trim())
|
|
51
|
+
throw new Error('Attested Pi task requires a concise name');
|
|
52
|
+
if (!input.provider.trim())
|
|
53
|
+
throw new Error('Attested Pi task requires provider');
|
|
54
|
+
if (!input.model.trim())
|
|
55
|
+
throw new Error('Attested Pi task requires model');
|
|
56
|
+
if (!input.prompt)
|
|
57
|
+
throw new Error('Attested Pi task requires prompt text');
|
|
58
|
+
if (!input.reportPath.trim())
|
|
59
|
+
throw new Error('Attested Pi task requires a report path');
|
|
60
|
+
const args = input.extraPiArgs ?? [];
|
|
61
|
+
for (const arg of args) {
|
|
62
|
+
if (arg === '--api-key' || arg.startsWith('--api-key=')) {
|
|
63
|
+
throw new Error('Attested Pi tasks forbid direct --api-key launch arguments');
|
|
64
|
+
}
|
|
65
|
+
if (arg === '--auth-file' || arg.startsWith('--auth-file=')) {
|
|
66
|
+
throw new Error('Attested Pi tasks forbid alternate auth-file launch arguments');
|
|
67
|
+
}
|
|
68
|
+
if (arg === '-p' || arg === '--print' || arg === '--mode' || arg.startsWith('--mode=')) {
|
|
69
|
+
throw new Error('Attested Pi tasks own print/json mode arguments');
|
|
70
|
+
}
|
|
71
|
+
if (arg === '--provider' ||
|
|
72
|
+
arg.startsWith('--provider=') ||
|
|
73
|
+
arg === '--model' ||
|
|
74
|
+
arg.startsWith('--model=')) {
|
|
75
|
+
throw new Error('Use structured provider/model fields, not duplicate Pi args');
|
|
76
|
+
}
|
|
77
|
+
if (arg === '--thinking' || arg.startsWith('--thinking=')) {
|
|
78
|
+
throw new Error('Use the structured thinking field, not duplicate Pi args');
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
const ATTESTED_PI_REMOVED_ENV_KEYS = [
|
|
83
|
+
'OPENROUTER_API_KEY',
|
|
84
|
+
'OPENROUTER_BASE_URL',
|
|
85
|
+
'OPENAI_API_KEY',
|
|
86
|
+
'OPENAI_BASE_URL',
|
|
87
|
+
'ANTHROPIC_API_KEY',
|
|
88
|
+
'ANTHROPIC_BASE_URL',
|
|
89
|
+
'PI_API_KEY',
|
|
90
|
+
'PI_API_BASE_URL',
|
|
91
|
+
'PI_AUTH_FILE',
|
|
92
|
+
];
|
|
93
|
+
export function attestedPiChildEnv(env) {
|
|
94
|
+
const out = { ...env };
|
|
95
|
+
for (const key of ATTESTED_PI_REMOVED_ENV_KEYS)
|
|
96
|
+
Reflect.deleteProperty(out, key);
|
|
97
|
+
return out;
|
|
98
|
+
}
|
|
99
|
+
export function buildAttestedPiArgv(input, attributionExtensionPath) {
|
|
100
|
+
validateStructuredPiLaunchRequest(input);
|
|
101
|
+
const args = ['pi', '--mode', 'json', '--provider', input.provider, '--model', input.model];
|
|
102
|
+
if (input.provider === 'anthropic') {
|
|
103
|
+
if (!attributionExtensionPath?.trim()) {
|
|
104
|
+
throw new Error('Anthropic attested Pi tasks require the package attribution extension');
|
|
105
|
+
}
|
|
106
|
+
args.push('--extension', attributionExtensionPath);
|
|
107
|
+
}
|
|
108
|
+
if (input.thinking?.trim())
|
|
109
|
+
args.push('--thinking', input.thinking.trim());
|
|
110
|
+
args.push(...(input.extraPiArgs ?? []), input.prompt);
|
|
111
|
+
return args;
|
|
112
|
+
}
|
|
113
|
+
export async function resolveReportPath(cwd, reportPath) {
|
|
114
|
+
if (isAbsolute(reportPath))
|
|
115
|
+
throw new Error('Attested Pi report path must be relative to task cwd');
|
|
116
|
+
const resolved = resolve(cwd, reportPath);
|
|
117
|
+
const relativePath = relative(cwd, resolved);
|
|
118
|
+
if (relativePath === '' || relativePath.startsWith('..') || isAbsolute(relativePath)) {
|
|
119
|
+
throw new Error('Attested Pi report path must stay inside task cwd');
|
|
120
|
+
}
|
|
121
|
+
const parts = relativePath.split(sep);
|
|
122
|
+
if (parts[0] === '.git' || (parts[0] === '.pi' && parts[1] === 'tasks')) {
|
|
123
|
+
throw new Error('Attested Pi report path cannot target Git metadata or the fixed task store');
|
|
124
|
+
}
|
|
125
|
+
return resolved;
|
|
126
|
+
}
|
|
127
|
+
function positiveInteger(value, fallback, label) {
|
|
128
|
+
const candidate = value ?? fallback;
|
|
129
|
+
if (!Number.isFinite(candidate) || candidate <= 0) {
|
|
130
|
+
throw new Error(`${label} must be a positive finite number`);
|
|
131
|
+
}
|
|
132
|
+
return Math.max(1, Math.floor(candidate));
|
|
133
|
+
}
|
|
134
|
+
function errorCode(error) {
|
|
135
|
+
if (typeof error !== 'object' || error === null)
|
|
136
|
+
return undefined;
|
|
137
|
+
const code = Reflect.get(error, 'code');
|
|
138
|
+
return typeof code === 'string' ? code : undefined;
|
|
139
|
+
}
|
|
140
|
+
function errorMessage(error) {
|
|
141
|
+
return error instanceof Error ? error.message : String(error);
|
|
142
|
+
}
|
|
143
|
+
function signalError(signal) {
|
|
144
|
+
return signal.reason instanceof Error
|
|
145
|
+
? signal.reason
|
|
146
|
+
: new Error(`Attested Git preflight cancelled${signal.reason === undefined ? '' : `: ${String(signal.reason)}`}`);
|
|
147
|
+
}
|
|
148
|
+
function gitDeadline(options) {
|
|
149
|
+
const configured = options.deadlineAt;
|
|
150
|
+
return typeof configured === 'number' && Number.isFinite(configured)
|
|
151
|
+
? configured
|
|
152
|
+
: Date.now() + ATTESTED_GIT_TIMEOUT_MS;
|
|
153
|
+
}
|
|
154
|
+
function assertGitBoundary(options, args) {
|
|
155
|
+
if (options.signal?.aborted === true)
|
|
156
|
+
throw signalError(options.signal);
|
|
157
|
+
if (Date.now() >= gitDeadline(options))
|
|
158
|
+
throw new AttestedGitTimeoutError(args);
|
|
159
|
+
}
|
|
160
|
+
class BoundedGitCapture {
|
|
161
|
+
maxBytes;
|
|
162
|
+
chunks = [];
|
|
163
|
+
bytes = 0;
|
|
164
|
+
exceeded = false;
|
|
165
|
+
constructor(maxBytes) {
|
|
166
|
+
this.maxBytes = maxBytes;
|
|
167
|
+
}
|
|
168
|
+
append(data) {
|
|
169
|
+
const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data, 'utf8');
|
|
170
|
+
const remaining = this.maxBytes - this.bytes;
|
|
171
|
+
if (remaining > 0) {
|
|
172
|
+
const kept = buffer.length <= remaining ? buffer : buffer.subarray(0, remaining);
|
|
173
|
+
this.chunks.push(kept);
|
|
174
|
+
this.bytes += kept.length;
|
|
175
|
+
}
|
|
176
|
+
if (buffer.length > Math.max(0, remaining))
|
|
177
|
+
this.exceeded = true;
|
|
178
|
+
return this.exceeded;
|
|
179
|
+
}
|
|
180
|
+
text() {
|
|
181
|
+
return Buffer.concat(this.chunks, this.bytes).toString('utf8');
|
|
182
|
+
}
|
|
183
|
+
diagnostic() {
|
|
184
|
+
const text = this.text().trim();
|
|
185
|
+
return this.exceeded
|
|
186
|
+
? `${text}${text.length > 0 ? ' ' : ''}[output exceeded ${String(this.maxBytes)} bytes]`
|
|
187
|
+
: text;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
function delay(ms) {
|
|
191
|
+
return new Promise((resolvePromise) => {
|
|
192
|
+
setTimeout(resolvePromise, ms);
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
function posixTreeSignal(child, pid, signal, killProcess) {
|
|
196
|
+
const errors = [];
|
|
197
|
+
if (pid !== undefined) {
|
|
198
|
+
try {
|
|
199
|
+
if (killProcess(-pid, signal))
|
|
200
|
+
return errors;
|
|
201
|
+
errors.push(`process group ${signal} returned false`);
|
|
202
|
+
}
|
|
203
|
+
catch (error) {
|
|
204
|
+
if (errorCode(error) === 'ESRCH')
|
|
205
|
+
return [];
|
|
206
|
+
errors.push(`process group ${signal} failed: ${errorMessage(error)}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
try {
|
|
210
|
+
if (child.kill(signal))
|
|
211
|
+
return errors;
|
|
212
|
+
errors.push(`child ${signal} returned false`);
|
|
213
|
+
}
|
|
214
|
+
catch (error) {
|
|
215
|
+
if (errorCode(error) === 'ESRCH')
|
|
216
|
+
return errors;
|
|
217
|
+
errors.push(`child ${signal} failed: ${errorMessage(error)}`);
|
|
218
|
+
}
|
|
219
|
+
return errors;
|
|
220
|
+
}
|
|
221
|
+
function windowsTaskkillSucceeded(outcome) {
|
|
222
|
+
return outcome.exitCode === 0 || outcome.exitCode === 128;
|
|
223
|
+
}
|
|
224
|
+
function describeTaskkill(phase, outcome) {
|
|
225
|
+
const stderr = outcome.stderr.trim();
|
|
226
|
+
const stdout = outcome.stdout.trim();
|
|
227
|
+
const detail = stderr || stdout;
|
|
228
|
+
const truncated = outcome.stderrTruncated || outcome.stdoutTruncated ? ' (output truncated)' : '';
|
|
229
|
+
return `taskkill ${phase} exited ${String(outcome.exitCode)}${detail ? `: ${detail}` : ''}${truncated}`;
|
|
230
|
+
}
|
|
231
|
+
async function terminateGitProcessTree(child, options, killGraceMs, isClosed) {
|
|
232
|
+
const pid = child.pid;
|
|
233
|
+
if (options.platform !== 'win32') {
|
|
234
|
+
const errors = posixTreeSignal(child, pid, 'SIGTERM', options.killProcess);
|
|
235
|
+
// Keep the grace timer referenced and always probe/force the process group
|
|
236
|
+
// once. The direct Git process can exit before a descendant that ignored
|
|
237
|
+
// TERM; forcing the detached group closes that tree-shaped race.
|
|
238
|
+
await delay(killGraceMs);
|
|
239
|
+
errors.push(...posixTreeSignal(child, pid, 'SIGKILL', options.killProcess));
|
|
240
|
+
return errors;
|
|
241
|
+
}
|
|
242
|
+
if (pid === undefined)
|
|
243
|
+
return ['Git process has no pid for Windows tree termination'];
|
|
244
|
+
const softController = new AbortController();
|
|
245
|
+
let softOutcome;
|
|
246
|
+
let softError;
|
|
247
|
+
let softSettled = false;
|
|
248
|
+
const soft = Promise.resolve()
|
|
249
|
+
.then(() => options.killTree(pid, 'terminate', softController.signal))
|
|
250
|
+
.then((outcome) => {
|
|
251
|
+
softOutcome = outcome;
|
|
252
|
+
softSettled = true;
|
|
253
|
+
}, (error) => {
|
|
254
|
+
softError = error;
|
|
255
|
+
softSettled = true;
|
|
256
|
+
});
|
|
257
|
+
await delay(killGraceMs);
|
|
258
|
+
const softSucceeded = softOutcome !== undefined && windowsTaskkillSucceeded(softOutcome);
|
|
259
|
+
const needsForce = !softSettled || !softSucceeded || !isClosed();
|
|
260
|
+
if (!softSettled)
|
|
261
|
+
softController.abort();
|
|
262
|
+
await soft;
|
|
263
|
+
const errors = [];
|
|
264
|
+
if (softError !== undefined)
|
|
265
|
+
errors.push(`taskkill terminate failed: ${errorMessage(softError)}`);
|
|
266
|
+
else if (softOutcome !== undefined && !windowsTaskkillSucceeded(softOutcome))
|
|
267
|
+
errors.push(describeTaskkill('terminate', softOutcome));
|
|
268
|
+
if (!needsForce)
|
|
269
|
+
return errors;
|
|
270
|
+
try {
|
|
271
|
+
const forceOutcome = await options.killTree(pid, 'force');
|
|
272
|
+
if (!windowsTaskkillSucceeded(forceOutcome))
|
|
273
|
+
errors.push(describeTaskkill('force', forceOutcome));
|
|
274
|
+
}
|
|
275
|
+
catch (error) {
|
|
276
|
+
errors.push(`taskkill force failed: ${errorMessage(error)}`);
|
|
277
|
+
}
|
|
278
|
+
return errors;
|
|
279
|
+
}
|
|
280
|
+
function defaultGitSpawn(command, args, options) {
|
|
281
|
+
return nodeSpawn(command, args, options);
|
|
282
|
+
}
|
|
283
|
+
export async function runGitCommand(cwd, args, options = {}) {
|
|
284
|
+
const deadlineAt = gitDeadline(options);
|
|
285
|
+
const boundedOptions = { ...options, deadlineAt };
|
|
286
|
+
assertGitBoundary(boundedOptions, args);
|
|
287
|
+
const platform = options.platform ?? process.platform;
|
|
288
|
+
const env = options.env ?? process.env;
|
|
289
|
+
const spawn = options.spawn ?? defaultGitSpawn;
|
|
290
|
+
const killProcess = options.killProcess ?? process.kill.bind(process);
|
|
291
|
+
const killTree = options.killTree ??
|
|
292
|
+
((pid, phase, signal) => {
|
|
293
|
+
const taskkillOptions = signal === undefined ? { env } : { env, signal };
|
|
294
|
+
return runWindowsTaskkill(pid, phase, taskkillOptions);
|
|
295
|
+
});
|
|
296
|
+
const killGraceMs = positiveInteger(options.killGraceMs, ATTESTED_GIT_KILL_GRACE_MS, 'killGraceMs');
|
|
297
|
+
const maxOutputBytes = positiveInteger(options.maxOutputBytes, ATTESTED_GIT_MAX_OUTPUT_BYTES, 'maxOutputBytes');
|
|
298
|
+
let child;
|
|
299
|
+
try {
|
|
300
|
+
child = spawn('git', args, {
|
|
301
|
+
cwd,
|
|
302
|
+
detached: platform !== 'win32',
|
|
303
|
+
env,
|
|
304
|
+
shell: false,
|
|
305
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
306
|
+
windowsHide: true,
|
|
307
|
+
});
|
|
308
|
+
}
|
|
309
|
+
catch (error) {
|
|
310
|
+
throw new AttestedGitCommandError(`git ${args.join(' ')} failed to spawn: ${errorMessage(error)}`);
|
|
311
|
+
}
|
|
312
|
+
const admissionSignal = options.signal;
|
|
313
|
+
const stdout = new BoundedGitCapture(maxOutputBytes);
|
|
314
|
+
const stderr = new BoundedGitCapture(maxOutputBytes);
|
|
315
|
+
let closed = false;
|
|
316
|
+
let closeRecord;
|
|
317
|
+
let resolveClose;
|
|
318
|
+
const closePromise = new Promise((resolvePromise) => {
|
|
319
|
+
resolveClose = resolvePromise;
|
|
320
|
+
});
|
|
321
|
+
let primaryError;
|
|
322
|
+
let processError;
|
|
323
|
+
let termination;
|
|
324
|
+
let deadlineTimer;
|
|
325
|
+
const requestTermination = (error) => {
|
|
326
|
+
if (closed)
|
|
327
|
+
return;
|
|
328
|
+
primaryError ??= error;
|
|
329
|
+
termination ??= terminateGitProcessTree(child, { platform, killProcess, killTree }, killGraceMs, () => closed);
|
|
330
|
+
};
|
|
331
|
+
const stdoutListener = (data) => {
|
|
332
|
+
if (stdout.append(data))
|
|
333
|
+
requestTermination(new AttestedGitOutputLimitError(args, maxOutputBytes));
|
|
334
|
+
};
|
|
335
|
+
const stderrListener = (data) => {
|
|
336
|
+
if (stderr.append(data))
|
|
337
|
+
requestTermination(new AttestedGitOutputLimitError(args, maxOutputBytes));
|
|
338
|
+
};
|
|
339
|
+
const errorListener = (error) => {
|
|
340
|
+
processError = error;
|
|
341
|
+
const wrapped = new AttestedGitCommandError(`git ${args.join(' ')} process error: ${error.message}`);
|
|
342
|
+
if (child.pid === undefined) {
|
|
343
|
+
primaryError ??= wrapped;
|
|
344
|
+
closed = true;
|
|
345
|
+
closeRecord = { code: null, signal: null };
|
|
346
|
+
resolveClose?.();
|
|
347
|
+
return;
|
|
348
|
+
}
|
|
349
|
+
requestTermination(wrapped);
|
|
350
|
+
};
|
|
351
|
+
const closeListener = (code, signal) => {
|
|
352
|
+
if (closed)
|
|
353
|
+
return;
|
|
354
|
+
closed = true;
|
|
355
|
+
closeRecord = { code, signal };
|
|
356
|
+
if (deadlineTimer !== undefined) {
|
|
357
|
+
clearTimeout(deadlineTimer);
|
|
358
|
+
deadlineTimer = undefined;
|
|
359
|
+
}
|
|
360
|
+
resolveClose?.();
|
|
361
|
+
};
|
|
362
|
+
const abortListener = () => {
|
|
363
|
+
if (admissionSignal !== undefined)
|
|
364
|
+
requestTermination(signalError(admissionSignal));
|
|
365
|
+
};
|
|
366
|
+
child.stdout?.on('data', stdoutListener);
|
|
367
|
+
child.stderr?.on('data', stderrListener);
|
|
368
|
+
child.on('error', errorListener);
|
|
369
|
+
child.on('close', closeListener);
|
|
370
|
+
admissionSignal?.addEventListener('abort', abortListener, { once: true });
|
|
371
|
+
const remainingMs = Math.max(0, deadlineAt - Date.now());
|
|
372
|
+
deadlineTimer = setTimeout(() => {
|
|
373
|
+
requestTermination(new AttestedGitTimeoutError(args));
|
|
374
|
+
}, remainingMs);
|
|
375
|
+
if (admissionSignal?.aborted === true)
|
|
376
|
+
abortListener();
|
|
377
|
+
try {
|
|
378
|
+
await closePromise;
|
|
379
|
+
const cleanupErrors = termination === undefined ? [] : await termination;
|
|
380
|
+
if (primaryError !== undefined) {
|
|
381
|
+
if (cleanupErrors.length > 0)
|
|
382
|
+
throw new AttestedGitCleanupError(primaryError, cleanupErrors);
|
|
383
|
+
throw primaryError;
|
|
384
|
+
}
|
|
385
|
+
if (processError !== undefined) {
|
|
386
|
+
throw new AttestedGitCommandError(`git ${args.join(' ')} process error: ${processError.message}`);
|
|
387
|
+
}
|
|
388
|
+
const close = closeRecord;
|
|
389
|
+
if (close?.code === 0)
|
|
390
|
+
return stdout.text().trim();
|
|
391
|
+
const exit = close?.code === null || close === undefined ? 'null' : String(close.code);
|
|
392
|
+
const signal = close?.signal ? ` (${close.signal})` : '';
|
|
393
|
+
throw new AttestedGitCommandError(`git ${args.join(' ')} failed with exit ${exit}${signal}: ${stderr.diagnostic()}`);
|
|
394
|
+
}
|
|
395
|
+
finally {
|
|
396
|
+
if (deadlineTimer !== undefined)
|
|
397
|
+
clearTimeout(deadlineTimer);
|
|
398
|
+
admissionSignal?.removeEventListener('abort', abortListener);
|
|
399
|
+
child.stdout?.off('data', stdoutListener);
|
|
400
|
+
child.stderr?.off('data', stderrListener);
|
|
401
|
+
child.off('error', errorListener);
|
|
402
|
+
child.off('close', closeListener);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
function withDefaultGitDeadline(options) {
|
|
406
|
+
return options.deadlineAt === undefined
|
|
407
|
+
? { ...options, deadlineAt: Date.now() + ATTESTED_GIT_TIMEOUT_MS }
|
|
408
|
+
: options;
|
|
409
|
+
}
|
|
410
|
+
export async function gitAuthoritySnapshot(cwd, options = {}) {
|
|
411
|
+
const bounded = withDefaultGitDeadline(options);
|
|
412
|
+
const commit = await runGitCommand(cwd, ['rev-parse', 'HEAD'], bounded);
|
|
413
|
+
const tree = await runGitCommand(cwd, ['rev-parse', 'HEAD^{tree}'], bounded);
|
|
414
|
+
const status = await runGitCommand(cwd, ['status', '--porcelain=v1', '--untracked-files=all'], bounded);
|
|
415
|
+
return { commit, tree, clean: status.length === 0 };
|
|
416
|
+
}
|
|
417
|
+
export async function gitRepoRoot(cwd, options = {}) {
|
|
418
|
+
const bounded = withDefaultGitDeadline(options);
|
|
419
|
+
const root = await runGitCommand(cwd, ['rev-parse', '--show-toplevel'], bounded);
|
|
420
|
+
assertGitBoundary(bounded, ['rev-parse', '--show-toplevel']);
|
|
421
|
+
const resolved = await realpath(root);
|
|
422
|
+
assertGitBoundary(bounded, ['rev-parse', '--show-toplevel']);
|
|
423
|
+
return resolved;
|
|
424
|
+
}
|
|
425
|
+
export function observePiOAuth(ctx, provider, modelId) {
|
|
426
|
+
const registry = ctx.modelRegistry;
|
|
427
|
+
const selected = registry.find?.(provider, modelId);
|
|
428
|
+
if (!selected)
|
|
429
|
+
throw new Error(`Pi model not found in ModelRegistry: ${provider}/${modelId}`);
|
|
430
|
+
if (!registry.isUsingOAuth)
|
|
431
|
+
throw new Error('ModelRegistry OAuth observation is unavailable');
|
|
432
|
+
if (!registry.isUsingOAuth(selected)) {
|
|
433
|
+
throw new Error(`Attested Pi task requires OAuth credentials for ${provider}/${modelId}`);
|
|
434
|
+
}
|
|
435
|
+
const channel = provider === 'openai-codex'
|
|
436
|
+
? 'subscription-codex'
|
|
437
|
+
: provider === 'anthropic'
|
|
438
|
+
? 'subscription-anthropic'
|
|
439
|
+
: undefined;
|
|
440
|
+
const authClass = provider === 'openai-codex'
|
|
441
|
+
? 'pi-codex-oauth'
|
|
442
|
+
: provider === 'anthropic'
|
|
443
|
+
? 'pi-anthropic-oauth'
|
|
444
|
+
: undefined;
|
|
445
|
+
if (!channel || !authClass)
|
|
446
|
+
throw new Error(`Unsupported attested Pi OAuth provider: ${provider}`);
|
|
447
|
+
return {
|
|
448
|
+
apiIdentity: selected.api,
|
|
449
|
+
authClass,
|
|
450
|
+
credentialKind: 'oauth',
|
|
451
|
+
routeClass: 'subscription-agent',
|
|
452
|
+
channel,
|
|
453
|
+
directApiKey: false,
|
|
454
|
+
selectedModel: selected,
|
|
455
|
+
};
|
|
456
|
+
}
|
|
457
|
+
function readString(record, key) {
|
|
458
|
+
const value = record[key];
|
|
459
|
+
return typeof value === 'string' ? value : undefined;
|
|
460
|
+
}
|
|
461
|
+
function readNumber(record, key) {
|
|
462
|
+
const value = record[key];
|
|
463
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
464
|
+
}
|
|
465
|
+
function nonNegativeInteger(value) {
|
|
466
|
+
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : 0;
|
|
467
|
+
}
|
|
468
|
+
function normalizeUsage(value) {
|
|
469
|
+
if (!isJsonObject(value))
|
|
470
|
+
return { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, totalTokens: 0 };
|
|
471
|
+
const input = nonNegativeInteger(value['input']);
|
|
472
|
+
const output = nonNegativeInteger(value['output']);
|
|
473
|
+
const cacheRead = nonNegativeInteger(value['cacheRead']);
|
|
474
|
+
const cacheWrite = nonNegativeInteger(value['cacheWrite']);
|
|
475
|
+
const totalTokens = nonNegativeInteger(value['totalTokens']) || input + output + cacheRead + cacheWrite;
|
|
476
|
+
const cost = isJsonObject(value['cost']) ? readNumber(value['cost'], 'total') : undefined;
|
|
477
|
+
const usage = { input, output, cacheRead, cacheWrite, totalTokens };
|
|
478
|
+
if (cost !== undefined && cost >= 0)
|
|
479
|
+
usage.costTotal = cost;
|
|
480
|
+
return usage;
|
|
481
|
+
}
|
|
482
|
+
function appendUsage(target, delta) {
|
|
483
|
+
target.input += delta.input;
|
|
484
|
+
target.output += delta.output;
|
|
485
|
+
target.cacheRead += delta.cacheRead;
|
|
486
|
+
target.cacheWrite += delta.cacheWrite;
|
|
487
|
+
target.totalTokens += delta.totalTokens;
|
|
488
|
+
if (delta.costTotal !== undefined)
|
|
489
|
+
target.costTotal = (target.costTotal ?? 0) + delta.costTotal;
|
|
490
|
+
}
|
|
491
|
+
function textFromAssistantMessage(message) {
|
|
492
|
+
const content = message['content'];
|
|
493
|
+
if (!Array.isArray(content))
|
|
494
|
+
return [];
|
|
495
|
+
return content.flatMap((part) => {
|
|
496
|
+
if (!isJsonObject(part))
|
|
497
|
+
return [];
|
|
498
|
+
if (part['type'] === 'text' && typeof part['text'] === 'string')
|
|
499
|
+
return [part['text']];
|
|
500
|
+
return [];
|
|
501
|
+
});
|
|
502
|
+
}
|
|
503
|
+
function countToolCalls(message, tools) {
|
|
504
|
+
const content = message['content'];
|
|
505
|
+
if (!Array.isArray(content))
|
|
506
|
+
return;
|
|
507
|
+
for (const part of content) {
|
|
508
|
+
if (!isJsonObject(part) || part['type'] !== 'toolCall')
|
|
509
|
+
continue;
|
|
510
|
+
const name = typeof part['name'] === 'string' && part['name'] ? part['name'] : 'tool';
|
|
511
|
+
tools.total += 1;
|
|
512
|
+
tools.byName[name] = (tools.byName[name] ?? 0) + 1;
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
export function parsePiJsonEvents(raw) {
|
|
516
|
+
const text = raw.toString('utf8');
|
|
517
|
+
if (!text.endsWith('\n'))
|
|
518
|
+
throw new Error('Pi JSON event stream is not newline-terminated');
|
|
519
|
+
let sessionId;
|
|
520
|
+
let sessionCwd;
|
|
521
|
+
let sessionCount = 0;
|
|
522
|
+
let agentStartCount = 0;
|
|
523
|
+
let agentEndCount = 0;
|
|
524
|
+
let provider;
|
|
525
|
+
let model;
|
|
526
|
+
let finalStopReason;
|
|
527
|
+
let assistantCount = 0;
|
|
528
|
+
const usage = {
|
|
529
|
+
input: 0,
|
|
530
|
+
output: 0,
|
|
531
|
+
cacheRead: 0,
|
|
532
|
+
cacheWrite: 0,
|
|
533
|
+
totalTokens: 0,
|
|
534
|
+
};
|
|
535
|
+
const tools = { total: 0, failed: 0, byName: {} };
|
|
536
|
+
const transcript = [];
|
|
537
|
+
for (const line of text.split('\n')) {
|
|
538
|
+
if (!line)
|
|
539
|
+
continue;
|
|
540
|
+
const parsed = parseJsonText(line);
|
|
541
|
+
if (!isJsonObject(parsed))
|
|
542
|
+
throw new Error('Pi JSON event line is not an object');
|
|
543
|
+
const eventType = parsed['type'];
|
|
544
|
+
if (eventType === 'session') {
|
|
545
|
+
sessionCount += 1;
|
|
546
|
+
sessionId = readString(parsed, 'id');
|
|
547
|
+
sessionCwd = readString(parsed, 'cwd');
|
|
548
|
+
continue;
|
|
549
|
+
}
|
|
550
|
+
if (eventType === 'agent_start')
|
|
551
|
+
agentStartCount += 1;
|
|
552
|
+
if (eventType === 'agent_end')
|
|
553
|
+
agentEndCount += 1;
|
|
554
|
+
if (eventType === 'tool_execution_start') {
|
|
555
|
+
const name = readString(parsed, 'toolName') ?? readString(parsed, 'tool_name') ?? 'tool';
|
|
556
|
+
tools.total += 1;
|
|
557
|
+
tools.byName[name] = (tools.byName[name] ?? 0) + 1;
|
|
558
|
+
transcript.push(`→ ${name}`);
|
|
559
|
+
continue;
|
|
560
|
+
}
|
|
561
|
+
if (eventType === 'tool_execution_end') {
|
|
562
|
+
if (parsed['isError'] === true) {
|
|
563
|
+
tools.failed += 1;
|
|
564
|
+
const name = readString(parsed, 'toolName') ?? readString(parsed, 'tool_name') ?? 'tool';
|
|
565
|
+
transcript.push(`✗ ${name} failed`);
|
|
566
|
+
}
|
|
567
|
+
continue;
|
|
568
|
+
}
|
|
569
|
+
if (eventType !== 'message_end' || !isJsonObject(parsed['message']))
|
|
570
|
+
continue;
|
|
571
|
+
const message = parsed['message'];
|
|
572
|
+
if (message['role'] !== 'assistant')
|
|
573
|
+
continue;
|
|
574
|
+
assistantCount += 1;
|
|
575
|
+
const messageProvider = readString(message, 'provider');
|
|
576
|
+
const messageModel = readString(message, 'model');
|
|
577
|
+
if (!messageProvider || !messageModel) {
|
|
578
|
+
throw new Error('Assistant message lacks provider/model in Pi JSON events');
|
|
579
|
+
}
|
|
580
|
+
if (provider !== undefined && provider !== messageProvider)
|
|
581
|
+
throw new Error('Pi assistant provider changed during task');
|
|
582
|
+
if (model !== undefined && model !== messageModel)
|
|
583
|
+
throw new Error('Pi assistant model changed during task');
|
|
584
|
+
provider = messageProvider;
|
|
585
|
+
model = messageModel;
|
|
586
|
+
appendUsage(usage, normalizeUsage(message['usage']));
|
|
587
|
+
countToolCalls(message, tools);
|
|
588
|
+
transcript.push(...textFromAssistantMessage(message));
|
|
589
|
+
if (message['error'] !== undefined && message['error'] !== null)
|
|
590
|
+
throw new Error('Assistant message reported an error');
|
|
591
|
+
const stopReason = readString(message, 'stopReason');
|
|
592
|
+
if (stopReason)
|
|
593
|
+
finalStopReason = stopReason;
|
|
594
|
+
}
|
|
595
|
+
if (sessionCount !== 1 || !sessionId || !sessionCwd)
|
|
596
|
+
throw new Error('Pi JSON events must contain exactly one session header');
|
|
597
|
+
if (agentStartCount !== 1)
|
|
598
|
+
throw new Error('Pi JSON events must contain exactly one agent_start');
|
|
599
|
+
if (agentEndCount !== 1)
|
|
600
|
+
throw new Error('Pi JSON events must contain exactly one agent_end');
|
|
601
|
+
if (assistantCount < 1 || !provider || !model)
|
|
602
|
+
throw new Error('Pi JSON events contain no assistant message');
|
|
603
|
+
if (finalStopReason !== 'stop')
|
|
604
|
+
throw new Error(`Pi final stop reason is not stop: ${finalStopReason ?? 'missing'}`);
|
|
605
|
+
return {
|
|
606
|
+
piSessionId: sessionId,
|
|
607
|
+
piCwd: sessionCwd,
|
|
608
|
+
provider,
|
|
609
|
+
model,
|
|
610
|
+
providerScopedModelId: `${provider}/${model}`,
|
|
611
|
+
finalStopReason,
|
|
612
|
+
tokenUsage: usage,
|
|
613
|
+
assistantCount,
|
|
614
|
+
toolUsage: tools,
|
|
615
|
+
humanTranscript: transcript.filter((line) => line.trim()).join('\n') + '\n',
|
|
616
|
+
};
|
|
617
|
+
}
|
|
618
|
+
export async function sha256File(path) {
|
|
619
|
+
const bytes = await readFile(path);
|
|
620
|
+
return { byteLength: bytes.length, sha256: sha256Buffer(bytes) };
|
|
621
|
+
}
|
|
622
|
+
export function spawnAndCapturePi(spawnImpl, argv, options, platform = process.platform, launchOverride) {
|
|
623
|
+
const stdoutChunks = [];
|
|
624
|
+
const stderrChunks = [];
|
|
625
|
+
const logicalExecutable = argv[0];
|
|
626
|
+
if (logicalExecutable !== 'pi')
|
|
627
|
+
throw new Error('Attested Pi argv must start with pi');
|
|
628
|
+
const piArgs = argv.slice(1);
|
|
629
|
+
const launch = launchOverride ?? resolvePiLaunch({ platform });
|
|
630
|
+
assertWindowsCommandLineWithinLimit(launch, piArgs, platform, 'attested-pi-run');
|
|
631
|
+
const child = spawnImpl(launch.executable, piLaunchArgv(launch, piArgs), options);
|
|
632
|
+
child.stdout?.on('data', (chunk) => {
|
|
633
|
+
stdoutChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf8'));
|
|
634
|
+
});
|
|
635
|
+
child.stderr?.on('data', (chunk) => {
|
|
636
|
+
stderrChunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk, 'utf8'));
|
|
637
|
+
});
|
|
638
|
+
return { child, stdoutChunks, stderrChunks };
|
|
639
|
+
}
|
|
640
|
+
export async function buildPiTaskAttestation(input) {
|
|
641
|
+
if (input.startAuthority.commit !== input.finishAuthority.commit ||
|
|
642
|
+
input.startAuthority.tree !== input.finishAuthority.tree) {
|
|
643
|
+
throw new Error('Git authority changed during attested Pi task');
|
|
644
|
+
}
|
|
645
|
+
if (!input.startAuthority.clean || !input.finishAuthority.clean) {
|
|
646
|
+
throw new Error('Git worktree must be clean at attested Pi task start and finish');
|
|
647
|
+
}
|
|
648
|
+
if (input.parsedEvents.provider !== input.auth.selectedModel.provider ||
|
|
649
|
+
input.parsedEvents.model !== input.auth.selectedModel.id) {
|
|
650
|
+
throw new Error('Observed Pi provider/model do not match selected ModelRegistry model');
|
|
651
|
+
}
|
|
652
|
+
const metadata = await sha256File(input.paths.metadataAbsPath);
|
|
653
|
+
const output = await sha256File(input.paths.outputAbsPath);
|
|
654
|
+
const events = await sha256File(input.paths.eventsAbsPath);
|
|
655
|
+
const stderr = await sha256File(input.paths.stderrAbsPath);
|
|
656
|
+
const wrapper = await sha256File(input.paths.wrapperAbsPath);
|
|
657
|
+
const report = await sha256File(input.reportAbsPath);
|
|
658
|
+
const promptHash = sha256Buffer(input.prompt);
|
|
659
|
+
const attestation = {
|
|
660
|
+
schema_version: PI_TASK_ATTESTATION_SCHEMA_VERSION,
|
|
661
|
+
locator: {
|
|
662
|
+
session_dir: input.sessionDir,
|
|
663
|
+
task_id: input.task.id,
|
|
664
|
+
metadata_ref: input.paths.metadataPath,
|
|
665
|
+
output_ref: input.paths.outputPath,
|
|
666
|
+
events_ref: input.paths.eventsPath,
|
|
667
|
+
stderr_ref: input.paths.stderrPath,
|
|
668
|
+
wrapper_ref: input.paths.wrapperPath,
|
|
669
|
+
},
|
|
670
|
+
source_hashes: {
|
|
671
|
+
metadata_sha256: metadata.sha256,
|
|
672
|
+
output_sha256: output.sha256,
|
|
673
|
+
events_sha256: events.sha256,
|
|
674
|
+
stderr_sha256: stderr.sha256,
|
|
675
|
+
wrapper_sha256: wrapper.sha256,
|
|
676
|
+
},
|
|
677
|
+
lifecycle: {
|
|
678
|
+
status: input.task.status,
|
|
679
|
+
is_agent: input.task.isAgent,
|
|
680
|
+
start_time_ms: input.task.startTime,
|
|
681
|
+
end_time_ms: input.task.endTime ?? input.task.startTime,
|
|
682
|
+
exit_code: input.task.exitCode ?? null,
|
|
683
|
+
signal: input.task.signal ?? null,
|
|
684
|
+
bytes_written: input.task.bytesWritten,
|
|
685
|
+
},
|
|
686
|
+
invocation: {
|
|
687
|
+
pi_session_id: input.parsedEvents.piSessionId,
|
|
688
|
+
argv: input.argv,
|
|
689
|
+
cwd_realpath: input.cwdRealpath,
|
|
690
|
+
provider: input.parsedEvents.provider,
|
|
691
|
+
model_id: input.parsedEvents.model,
|
|
692
|
+
provider_scoped_model_id: input.parsedEvents.providerScopedModelId,
|
|
693
|
+
api_identity: input.auth.apiIdentity,
|
|
694
|
+
auth_class: input.auth.authClass,
|
|
695
|
+
credential_kind: input.auth.credentialKind,
|
|
696
|
+
route_class: input.auth.routeClass,
|
|
697
|
+
channel: input.auth.channel,
|
|
698
|
+
direct_api_key: input.auth.directApiKey,
|
|
699
|
+
final_stop_reason: input.parsedEvents.finalStopReason,
|
|
700
|
+
},
|
|
701
|
+
authority: {
|
|
702
|
+
repo_root_realpath: input.repoRootRealpath,
|
|
703
|
+
start_commit_oid: input.startAuthority.commit,
|
|
704
|
+
start_tree_oid: input.startAuthority.tree,
|
|
705
|
+
finish_commit_oid: input.finishAuthority.commit,
|
|
706
|
+
finish_tree_oid: input.finishAuthority.tree,
|
|
707
|
+
start_worktree_clean: input.startAuthority.clean,
|
|
708
|
+
finish_worktree_clean: input.finishAuthority.clean,
|
|
709
|
+
},
|
|
710
|
+
artifacts: {
|
|
711
|
+
prompt: { byte_length: input.prompt.length, sha256: promptHash },
|
|
712
|
+
task_output: { byte_length: output.byteLength, sha256: output.sha256 },
|
|
713
|
+
stderr: { byte_length: stderr.byteLength, sha256: stderr.sha256 },
|
|
714
|
+
transcript: { byte_length: events.byteLength, sha256: events.sha256 },
|
|
715
|
+
report: { byte_length: report.byteLength, sha256: report.sha256 },
|
|
716
|
+
},
|
|
717
|
+
attestation_sha256: '',
|
|
718
|
+
};
|
|
719
|
+
const withoutSelf = { ...attestation, attestation_sha256: undefined };
|
|
720
|
+
Reflect.deleteProperty(withoutSelf, 'attestation_sha256');
|
|
721
|
+
attestation['attestation_sha256'] = sha256Buffer(Buffer.from(canonicalJson(withoutSelf), 'utf8'));
|
|
722
|
+
return attestation;
|
|
723
|
+
}
|
|
724
|
+
export function makeAttestedTaskPaths(runtimeAbs, runtimeDisplay, id) {
|
|
725
|
+
return {
|
|
726
|
+
outputAbsPath: join(runtimeAbs, `${id}.output`),
|
|
727
|
+
metadataAbsPath: join(runtimeAbs, `${id}.json`),
|
|
728
|
+
eventsAbsPath: join(runtimeAbs, `${id}.pi-events.jsonl`),
|
|
729
|
+
stderrAbsPath: join(runtimeAbs, `${id}.stderr`),
|
|
730
|
+
wrapperAbsPath: join(runtimeAbs, `${id}.pi-telemetry-wrapper.cjs`),
|
|
731
|
+
attestationAbsPath: join(runtimeAbs, `${id}.attestation.json`),
|
|
732
|
+
outputPath: join(runtimeDisplay, `${id}.output`),
|
|
733
|
+
metadataPath: join(runtimeDisplay, `${id}.json`),
|
|
734
|
+
eventsPath: join(runtimeDisplay, `${id}.pi-events.jsonl`),
|
|
735
|
+
stderrPath: join(runtimeDisplay, `${id}.stderr`),
|
|
736
|
+
wrapperPath: join(runtimeDisplay, `${id}.pi-telemetry-wrapper.cjs`),
|
|
737
|
+
attestationPath: join(runtimeDisplay, `${id}.attestation.json`),
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
export function pathInside(parent, child) {
|
|
741
|
+
const rel = relative(parent, child);
|
|
742
|
+
return (rel === '' || (!rel.startsWith('..') && !isAbsolute(rel) && !rel.split(sep).includes('..')));
|
|
743
|
+
}
|
|
744
|
+
export async function assertRegularReadable(path) {
|
|
745
|
+
const stats = await stat(path);
|
|
746
|
+
if (!stats.isFile())
|
|
747
|
+
throw new Error(`Expected regular file: ${path}`);
|
|
748
|
+
}
|
|
749
|
+
//# sourceMappingURL=attested-pi-run.js.map
|