pi-background-tasks 0.7.6 → 0.9.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.
@@ -0,0 +1,304 @@
1
+ import type { Usage } from '@earendil-works/pi-ai';
2
+ import type {
3
+ TokenBudgetByteClassBreakdown,
4
+ TokenBudgetDominantByteClass,
5
+ TokenBudgetFamily,
6
+ TokenBudgetRateSource,
7
+ } from '../context/token-budget.js';
8
+ import type {
9
+ ContextProjectionMapEntry,
10
+ OmittedEventRecord,
11
+ ProjectionAccounting,
12
+ ProjectionEntry,
13
+ } from '../context/visible-conversation-v2.js';
14
+
15
+ export const DELEGATE_SEED_SCHEMA_VERSION = 'pi-background-tasks.delegate-seed.v1' as const;
16
+ export const DELEGATE_LEDGER_SCHEMA_VERSION = 'pi-background-tasks.delegate-ledger.v1' as const;
17
+ export const DELEGATE_RESULT_PACKAGE_SCHEMA_VERSION =
18
+ 'pi-background-tasks.delegate-result.v1' as const;
19
+ export const DELEGATE_RECEIPT_SCHEMA_VERSION = 'pi-background-tasks.delegate-receipt.v1' as const;
20
+ export const DELEGATE_BUDGET_PLAN_SCHEMA_VERSION =
21
+ 'pi-background-tasks.delegate-budget-plan.v2' as const;
22
+ export const DELEGATE_MANIFEST_SCHEMA_VERSION = 'pi-background-tasks.delegate-manifest.v1' as const;
23
+
24
+ /**
25
+ * Delegate's own context policy id. It shares the frozen
26
+ * `visible-conversation-ledger-v2` transform with Fusion but is a distinct
27
+ * consumer identity, so a delegate artifact can never be mistaken for a Fusion
28
+ * artifact and neither can claim the other's provenance.
29
+ */
30
+ export const DELEGATE_CONTEXT_POLICY_ID = 'delegate-inspect-v1';
31
+ export const DELEGATE_BRANCH_FILTER_ID = 'exclude-active-delegate-batch-v1';
32
+ export const DELEGATE_TOOL_NAME = 'bg_delegate';
33
+ export const DELEGATE_RESULT_TOOL_NAME = 'bg_result';
34
+
35
+ export const DELEGATE_CAPABILITIES = ['inspect'] as const;
36
+ export type DelegateCapability = (typeof DELEGATE_CAPABILITIES)[number];
37
+
38
+ export const DELEGATE_AUTO_DELIVER_MODES = ['never', 'when_small', 'always'] as const;
39
+ export type DelegateAutoDeliverMode = (typeof DELEGATE_AUTO_DELIVER_MODES)[number];
40
+
41
+ export const DELEGATE_DELIVERY_MODES = ['inline', 'artifact'] as const;
42
+ export type DelegateDeliveryMode = (typeof DELEGATE_DELIVERY_MODES)[number];
43
+
44
+ export interface DelegateRoute {
45
+ provider: string;
46
+ model: string;
47
+ }
48
+
49
+ export interface DelegatePinnedRoute extends DelegateRoute {
50
+ qualified_id: string;
51
+ context_window_tokens: number;
52
+ thinking_level: string;
53
+ /** Whether the route came from the parent's current model or an explicit argument. */
54
+ origin: 'parent_current' | 'explicit';
55
+ }
56
+
57
+ export interface DelegateBudgetRouteSource {
58
+ family: TokenBudgetFamily;
59
+ rate_source: TokenBudgetRateSource;
60
+ }
61
+
62
+ export interface DelegateContextPolicyDescriptor {
63
+ id: typeof DELEGATE_CONTEXT_POLICY_ID;
64
+ transform: 'visible-conversation-ledger-v2';
65
+ version: 1;
66
+ receipt_format: 'omitted_activity.v2';
67
+ user_text: 'verbatim';
68
+ assistant_text: 'verbatim';
69
+ assistant_thinking: 'ledger_only';
70
+ tool_call_arguments: 'ledger_only';
71
+ tool_results: 'ledger_only';
72
+ tool_payload_preview_bytes: 0;
73
+ images: 'marker_or_ledger_only';
74
+ unknown_block_behavior: 'error';
75
+ }
76
+
77
+ export interface DelegateBranchFilterDescriptor {
78
+ id: typeof DELEGATE_BRANCH_FILTER_ID;
79
+ tool_name: typeof DELEGATE_TOOL_NAME;
80
+ tool_call_id: string | null;
81
+ active_tool_call_leaf_excluded: boolean;
82
+ }
83
+
84
+ export interface DelegateConversationProjection {
85
+ policy: DelegateContextPolicyDescriptor;
86
+ branch_filter: DelegateBranchFilterDescriptor;
87
+ entries: readonly ProjectionEntry[];
88
+ accounting: ProjectionAccounting;
89
+ }
90
+
91
+ export interface DelegateLedgerV1 {
92
+ schema_version: typeof DELEGATE_LEDGER_SCHEMA_VERSION;
93
+ policy_id: typeof DELEGATE_CONTEXT_POLICY_ID;
94
+ transform: 'visible-conversation-ledger-v2';
95
+ entries: readonly OmittedEventRecord[];
96
+ projection_map: readonly ContextProjectionMapEntry[];
97
+ root_sha256: string;
98
+ }
99
+
100
+ export interface DelegateTaskDirective {
101
+ /** Verbatim operator/agent prompt. Always authoritative over projected history. */
102
+ text: string;
103
+ sha256: string;
104
+ authority: 'explicit_text';
105
+ }
106
+
107
+ export interface DelegateSeedV1 {
108
+ schema_version: typeof DELEGATE_SEED_SCHEMA_VERSION;
109
+ task_id: string;
110
+ launch_nonce: string;
111
+ cwd: string;
112
+ capability: DelegateCapability;
113
+ route: DelegatePinnedRoute;
114
+ parent_system_prompt: string;
115
+ parent_leaf_id: string | null;
116
+ directive: DelegateTaskDirective;
117
+ conversation_projection: DelegateConversationProjection;
118
+ limits: DelegateLimits;
119
+ }
120
+
121
+ export interface DelegateLimits {
122
+ max_turns: number;
123
+ max_tool_calls: number;
124
+ timeout_seconds: number;
125
+ /** Per-tool-result transcript cap; larger results spill to hashed artifacts. */
126
+ max_tool_result_bytes: number;
127
+ /** Cumulative spilled+inline tool output across the whole run. */
128
+ max_total_tool_output_bytes: number;
129
+ /** Cap on the child's captured final answer. */
130
+ max_answer_bytes: number;
131
+ /** Usable input tokens for the pinned route after reserves. */
132
+ allowed_input_tokens: number;
133
+ }
134
+
135
+ export interface DelegateAnswerBlock {
136
+ kind: 'text';
137
+ byte_length: number;
138
+ sha256: string;
139
+ data_base64: string;
140
+ }
141
+
142
+ export interface DelegateRouteAttestation {
143
+ provider: string;
144
+ model: string;
145
+ stop_reason: string;
146
+ }
147
+
148
+ /**
149
+ * Usage that is explicitly absent is reported as absent.
150
+ *
151
+ * A child that never produced a usable usage record must not be reported as
152
+ * having cost zero, so the status is carried alongside the value.
153
+ */
154
+ export type DelegateUsageReport =
155
+ | { status: 'observed'; usage: Usage }
156
+ | { status: 'unavailable'; reason: string };
157
+
158
+ /**
159
+ * The single atomically-committed answer data plane.
160
+ *
161
+ * The child writes exactly this document to a temporary file, fsyncs it, and
162
+ * renames it into place. The rename is the commit point: a package that exists
163
+ * under its final name is complete, and one that does not exist means the child
164
+ * produced no accepted answer. There is no second channel to reconcile.
165
+ */
166
+ export interface DelegateResultPackageV1 {
167
+ schema_version: typeof DELEGATE_RESULT_PACKAGE_SCHEMA_VERSION;
168
+ task_id: string;
169
+ launch_nonce: string;
170
+ seed_sha256: string;
171
+ directive_sha256: string;
172
+ route: DelegateRoute;
173
+ route_attestations: readonly DelegateRouteAttestation[];
174
+ stop_reason: string;
175
+ turns: number;
176
+ tool_calls: number;
177
+ usage: DelegateUsageReport;
178
+ answer: {
179
+ encoding: 'utf-8';
180
+ byte_length: number;
181
+ sha256: string;
182
+ blocks: readonly DelegateAnswerBlock[];
183
+ };
184
+ spilled_artifacts: readonly DelegateSpillReceipt[];
185
+ }
186
+
187
+ export interface DelegateSpillReceipt {
188
+ schema_version: typeof DELEGATE_RECEIPT_SCHEMA_VERSION;
189
+ artifact: string;
190
+ tool_name: string;
191
+ tool_call_id: string;
192
+ turn_sequence: number;
193
+ source_call_index: number;
194
+ byte_length: number;
195
+ sha256: string;
196
+ }
197
+
198
+ export const DELEGATE_ERROR_CODES = [
199
+ // Admission failures. No child process exists in these states.
200
+ 'delegate_hook_contract_unsupported',
201
+ 'delegate_isolation_unsupported',
202
+ 'route_unresolved',
203
+ 'route_capacity_unknown',
204
+ 'seed_projection_failed',
205
+ 'seed_budget_exceeded',
206
+ 'seed_persist_failed',
207
+ 'invalid_arguments',
208
+ // Launch and execution.
209
+ 'child_spawn_failed',
210
+ 'child_startup_failed',
211
+ 'child_timeout',
212
+ 'child_cancelled',
213
+ 'child_turn_limit',
214
+ 'child_tool_call_limit',
215
+ 'child_exited_without_commit',
216
+ // Budget, split by which budget was exhausted.
217
+ 'provider_context_budget_exhausted',
218
+ 'aggregate_tool_output_cap',
219
+ 'child_model_output_limit',
220
+ 'child_capture_limit',
221
+ // Integrity.
222
+ 'child_result_invalid',
223
+ 'child_result_encoding_invalid',
224
+ 'route_attestation_missing',
225
+ 'route_mismatch',
226
+ 'seed_hash_mismatch',
227
+ 'answer_hash_mismatch',
228
+ 'artifact_spill_failed',
229
+ 'artifact_read_failed',
230
+ 'artifact_error',
231
+ // Retrieval states and outcomes.
232
+ 'result_not_ready',
233
+ 'result_unavailable',
234
+ 'result_too_large_for_inline',
235
+ 'task_unknown',
236
+ ] as const;
237
+
238
+ export type DelegateErrorCode = (typeof DELEGATE_ERROR_CODES)[number];
239
+
240
+ export interface DelegateBudgetErrorDetail {
241
+ measurement_kind: 'launch_admission' | 'runtime_context';
242
+ measured_utf8_bytes: number;
243
+ measured_input_tokens_upper_bound: number;
244
+ allowed_input_tokens: number;
245
+ rate_source: TokenBudgetRateSource;
246
+ backed: boolean;
247
+ dominant_byte_class: TokenBudgetDominantByteClass;
248
+ byte_class_breakdown: TokenBudgetByteClassBreakdown;
249
+ }
250
+
251
+ export interface DelegateErrorDetails {
252
+ code: DelegateErrorCode;
253
+ /** True only when an OS process was actually created. Admission failures are false. */
254
+ childCreated?: boolean;
255
+ taskId?: string;
256
+ artifactDir?: string;
257
+ budget?: DelegateBudgetErrorDetail;
258
+ /** What is preserved on disk despite the failure. */
259
+ preserved?: readonly string[];
260
+ /** Concrete operator actions. */
261
+ remediation?: readonly string[];
262
+ }
263
+
264
+ /**
265
+ * Typed delegate failure.
266
+ *
267
+ * Every instance states what happened, what was preserved, and what the operator
268
+ * can do. There is no untyped delegate failure path.
269
+ */
270
+ export class DelegateError extends Error {
271
+ readonly code: DelegateErrorCode;
272
+ readonly childCreated: boolean;
273
+ readonly taskId: string | undefined;
274
+ readonly artifactDir: string | undefined;
275
+ readonly budget: DelegateBudgetErrorDetail | undefined;
276
+ readonly preserved: readonly string[];
277
+ readonly remediation: readonly string[];
278
+
279
+ constructor(message: string, details: DelegateErrorDetails) {
280
+ super(message);
281
+ this.name = 'DelegateError';
282
+ this.code = details.code;
283
+ this.childCreated = details.childCreated ?? false;
284
+ this.taskId = details.taskId;
285
+ this.artifactDir = details.artifactDir;
286
+ this.budget = details.budget;
287
+ this.preserved = details.preserved ?? [];
288
+ this.remediation = details.remediation ?? [];
289
+ }
290
+
291
+ /** Operator-facing rendering: cause, preserved evidence, and next action. */
292
+ describe(): string {
293
+ const lines = [`[${this.code}] ${this.message}`];
294
+ lines.push(`Child process created: ${this.childCreated ? 'yes' : 'no'}`);
295
+ if (this.artifactDir !== undefined) lines.push(`Artifacts: ${this.artifactDir}`);
296
+ lines.push(
297
+ this.preserved.length > 0
298
+ ? `Preserved: ${this.preserved.join(', ')}`
299
+ : 'Preserved: nothing was written for this failure',
300
+ );
301
+ if (this.remediation.length > 0) lines.push(`Remediation: ${this.remediation.join(' ')}`);
302
+ return lines.join('\n');
303
+ }
304
+ }
@@ -13,7 +13,9 @@ import {
13
13
  type FusionArtifactRef,
14
14
  type FusionAttemptArtifactRecord,
15
15
  type FusionBudgetPlanV1,
16
+ type FusionCalibrationViolation,
16
17
  type FusionCandidateId,
18
+ type FusionCapability,
17
19
  type FusionContextOmissionLedgerV2,
18
20
  type FusionChildRunResult,
19
21
  type FusionModelConfigV1,
@@ -22,14 +24,21 @@ import {
22
24
  type FusionState,
23
25
  type FusionTerminalState,
24
26
  type FusionUsage,
27
+ type FusionWorkflowId,
25
28
  type ResolvedFusionModels,
26
29
  } from './types.js';
30
+ import { FUSION_BRAINSTORM_WORKFLOW, type FusionWorkflowProfile } from './workflows.js';
27
31
 
28
- const RUN_ID_PATTERN = /^f[0-9a-f]{32}$/;
32
+ /**
33
+ * Run ids are prefixed by workflow so an artifact directory is self-describing.
34
+ * The prefix set is closed: an unknown prefix must fail rather than be accepted.
35
+ */
36
+ const RUN_ID_PATTERN = /^[fv][0-9a-f]{32}$/;
29
37
 
30
38
  interface MutableFusionArtifactManifest {
31
39
  schema_version: typeof FUSION_MANIFEST_SCHEMA_VERSION;
32
40
  run_id: string;
41
+ workflow: FusionWorkflowId;
33
42
  source: FusionSource;
34
43
  state: FusionState;
35
44
  created_at: string;
@@ -42,6 +51,11 @@ interface MutableFusionArtifactManifest {
42
51
  merger: string;
43
52
  thinking_level: string;
44
53
  };
54
+ capabilities: {
55
+ candidate: FusionCapability;
56
+ evaluation: FusionCapability;
57
+ merge: FusionCapability;
58
+ };
45
59
  usage: FusionUsage;
46
60
  attempts: FusionAttemptArtifactRecord[];
47
61
  artifacts: Record<string, FusionArtifactRef>;
@@ -53,9 +67,15 @@ export interface CreateFusionArtifactStoreOptions {
53
67
  cwd: string;
54
68
  sessionId?: string | undefined;
55
69
  runId?: string | undefined;
70
+ profile?: FusionWorkflowProfile | undefined;
56
71
  source: FusionSource;
57
72
  config: FusionModelConfigV1;
58
73
  models: ResolvedFusionModels;
74
+ capabilities?: {
75
+ candidate: FusionCapability;
76
+ evaluation: FusionCapability;
77
+ merge: FusionCapability;
78
+ };
59
79
  now?: () => Date;
60
80
  }
61
81
 
@@ -82,8 +102,8 @@ export interface RecordFusionFailedAttemptInput {
82
102
  usage?: FusionUsage;
83
103
  }
84
104
 
85
- function makeRunId(): string {
86
- return `f${randomBytes(16).toString('hex')}`;
105
+ function makeRunId(profile: FusionWorkflowProfile): string {
106
+ return `${profile.runIdPrefix}${randomBytes(16).toString('hex')}`;
87
107
  }
88
108
 
89
109
  function modelsForManifest(models: ResolvedFusionModels): MutableFusionArtifactManifest['models'] {
@@ -148,6 +168,7 @@ function publicManifest(manifest: MutableFusionArtifactManifest): FusionArtifact
148
168
  const out: FusionArtifactManifest = {
149
169
  schema_version: manifest.schema_version,
150
170
  run_id: manifest.run_id,
171
+ workflow: manifest.workflow,
151
172
  source: manifest.source,
152
173
  state: manifest.state,
153
174
  created_at: manifest.created_at,
@@ -155,6 +176,7 @@ function publicManifest(manifest: MutableFusionArtifactManifest): FusionArtifact
155
176
  cwd: manifest.cwd,
156
177
  config: manifest.config,
157
178
  models: manifest.models,
179
+ capabilities: manifest.capabilities,
158
180
  usage: cloneFusionUsage(manifest.usage),
159
181
  attempts: [...manifest.attempts],
160
182
  artifacts: { ...manifest.artifacts },
@@ -178,6 +200,10 @@ function responseName(prefix: string, kind: 'md' | 'txt'): string {
178
200
  return `${prefix}.response.${kind}`;
179
201
  }
180
202
 
203
+ function calibrationViolationName(prefix: string): string {
204
+ return `${prefix}.calibration-violation.json`;
205
+ }
206
+
181
207
  export class FusionArtifactStore {
182
208
  private readonly runDirAbs: string;
183
209
  private readonly runDirDisplay: string;
@@ -198,8 +224,14 @@ export class FusionArtifactStore {
198
224
  }
199
225
 
200
226
  static async create(options: CreateFusionArtifactStoreOptions): Promise<FusionArtifactStore> {
201
- const runId = options.runId ?? makeRunId();
227
+ const profile = options.profile ?? FUSION_BRAINSTORM_WORKFLOW;
228
+ const runId = options.runId ?? makeRunId(profile);
202
229
  if (!RUN_ID_PATTERN.test(runId)) throw errorForArtifact(`invalid fusion run id: ${runId}`);
230
+ if (!runId.startsWith(profile.runIdPrefix)) {
231
+ throw errorForArtifact(
232
+ `fusion run id ${runId} does not carry the ${profile.id} workflow prefix ${profile.runIdPrefix}`,
233
+ );
234
+ }
203
235
  const sessionSegment = sanitizePathSegment(
204
236
  options.sessionId ?? `session-${String(process.pid)}`,
205
237
  );
@@ -212,6 +244,7 @@ export class FusionArtifactStore {
212
244
  const manifest: MutableFusionArtifactManifest = {
213
245
  schema_version: FUSION_MANIFEST_SCHEMA_VERSION,
214
246
  run_id: runId,
247
+ workflow: profile.id,
215
248
  source: options.source,
216
249
  state: 'initializing',
217
250
  created_at: timestamp,
@@ -219,6 +252,11 @@ export class FusionArtifactStore {
219
252
  cwd: options.cwd,
220
253
  config: options.config,
221
254
  models: modelsForManifest(options.models),
255
+ capabilities: options.capabilities ?? {
256
+ candidate: 'reason',
257
+ evaluation: 'reason',
258
+ merge: 'reason',
259
+ },
222
260
  usage: cloneFusionUsage(EMPTY_FUSION_USAGE),
223
261
  attempts: [],
224
262
  artifacts: {},
@@ -245,6 +283,10 @@ export class FusionArtifactStore {
245
283
  return this.runDirAbs;
246
284
  }
247
285
 
286
+ childToolCallLogPath(stage: FusionStage, slot: 1 | 2 | 3 | undefined, attempt: number): string {
287
+ return this.artifactPath(`${attemptPrefix(stage, slot, attempt)}.tool-calls.jsonl`);
288
+ }
289
+
248
290
  snapshot(): FusionArtifactManifest {
249
291
  return publicManifest(this.manifest);
250
292
  }
@@ -333,6 +375,10 @@ export class FusionArtifactStore {
333
375
  responseName(prefix, input.responseKind),
334
376
  input.result.text,
335
377
  );
378
+ const toolCallsRef =
379
+ input.result.toolCallTrace === undefined
380
+ ? undefined
381
+ : await this.writeArtifact(`${prefix}.tool-calls.jsonl`, input.result.toolCallTrace.bytes);
336
382
  await this.updateManifest((manifest) => {
337
383
  const record: FusionAttemptArtifactRecord = {
338
384
  stage: input.result.stage,
@@ -347,11 +393,25 @@ export class FusionArtifactStore {
347
393
  qualifiedId: input.result.qualifiedId,
348
394
  usage: cloneFusionUsage(input.result.usage),
349
395
  };
396
+ if (toolCallsRef !== undefined && input.result.toolCallTrace !== undefined) {
397
+ record.tool_calls_path = toolCallsRef.path;
398
+ record.tool_calls = { ...input.result.toolCallTrace.summary };
399
+ }
350
400
  if (input.result.slot !== undefined) record.slot = input.result.slot;
351
401
  manifest.attempts.push(record);
352
402
  });
353
403
  }
354
404
 
405
+ async recordCalibrationViolation(input: {
406
+ stage: FusionStage;
407
+ slot?: 1 | 2 | 3;
408
+ attempt: number;
409
+ violation: FusionCalibrationViolation;
410
+ }): Promise<FusionArtifactRef> {
411
+ const prefix = attemptPrefix(input.stage, input.slot, input.attempt);
412
+ return this.writeArtifact(calibrationViolationName(prefix), `${canonicalJson(input.violation)}\n`);
413
+ }
414
+
355
415
  async recordFailedAttempt(input: RecordFusionFailedAttemptInput): Promise<void> {
356
416
  const prefix = attemptPrefix(input.stage, input.slot, input.attempt);
357
417
  const promptRef = await this.writeArtifact(`${prefix}.prompt.txt`, input.prompt);