@timmyjl12/pi-subagents 0.0.0-stage → 0.21.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/CHANGELOG.md +862 -0
- package/CONTRIBUTING.md +72 -0
- package/LICENSE +21 -0
- package/README.md +1125 -3
- package/SECURITY.md +97 -0
- package/dist/abortable.d.ts +12 -0
- package/dist/abortable.js +42 -0
- package/dist/active-agents-prompt.d.ts +40 -0
- package/dist/active-agents-prompt.js +98 -0
- package/dist/advisor-status.d.ts +16 -0
- package/dist/advisor-status.js +74 -0
- package/dist/agent-color.d.ts +35 -0
- package/dist/agent-color.js +131 -0
- package/dist/agent-file-toggle.d.ts +125 -0
- package/dist/agent-file-toggle.js +264 -0
- package/dist/agent-manager.d.ts +872 -0
- package/dist/agent-manager.js +2910 -0
- package/dist/agent-runner.d.ts +358 -0
- package/dist/agent-runner.js +1219 -0
- package/dist/agent-types.d.ts +142 -0
- package/dist/agent-types.js +315 -0
- package/dist/awaited-result.d.ts +37 -0
- package/dist/awaited-result.js +150 -0
- package/dist/child-context.d.ts +15 -0
- package/dist/child-context.js +181 -0
- package/dist/child-session-shutdown.d.ts +21 -0
- package/dist/child-session-shutdown.js +97 -0
- package/dist/cleanup-plans.d.ts +10 -0
- package/dist/cleanup-plans.js +112 -0
- package/dist/context.d.ts +12 -0
- package/dist/context.js +56 -0
- package/dist/cross-extension-rpc.d.ts +73 -0
- package/dist/cross-extension-rpc.js +192 -0
- package/dist/custom-agents.d.ts +79 -0
- package/dist/custom-agents.js +583 -0
- package/dist/default-agents.d.ts +7 -0
- package/dist/default-agents.js +125 -0
- package/dist/enabled-models.d.ts +49 -0
- package/dist/enabled-models.js +145 -0
- package/dist/env.d.ts +6 -0
- package/dist/env.js +28 -0
- package/dist/error-log.d.ts +64 -0
- package/dist/error-log.js +176 -0
- package/dist/force-main-model.d.ts +21 -0
- package/dist/force-main-model.js +28 -0
- package/dist/goal-bridge.d.ts +155 -0
- package/dist/goal-bridge.js +305 -0
- package/dist/group-join.d.ts +36 -0
- package/dist/group-join.js +161 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +6390 -0
- package/dist/invocation-config.d.ts +164 -0
- package/dist/invocation-config.js +158 -0
- package/dist/memory.d.ts +53 -0
- package/dist/memory.js +165 -0
- package/dist/mention-clone.d.ts +87 -0
- package/dist/mention-clone.js +178 -0
- package/dist/mention.d.ts +81 -0
- package/dist/mention.js +131 -0
- package/dist/model-resolver.d.ts +36 -0
- package/dist/model-resolver.js +95 -0
- package/dist/model-scope.d.ts +49 -0
- package/dist/model-scope.js +48 -0
- package/dist/nested-tools.d.ts +76 -0
- package/dist/nested-tools.js +393 -0
- package/dist/output-diagnostics.d.ts +11 -0
- package/dist/output-diagnostics.js +64 -0
- package/dist/output-file.d.ts +64 -0
- package/dist/output-file.js +351 -0
- package/dist/prompts.d.ts +61 -0
- package/dist/prompts.js +94 -0
- package/dist/recovery.d.ts +56 -0
- package/dist/recovery.js +341 -0
- package/dist/report-cleanup.d.ts +204 -0
- package/dist/report-cleanup.js +1632 -0
- package/dist/report-store.d.ts +738 -0
- package/dist/report-store.js +3612 -0
- package/dist/schedule-store.d.ts +52 -0
- package/dist/schedule-store.js +240 -0
- package/dist/schedule.d.ts +121 -0
- package/dist/schedule.js +420 -0
- package/dist/settings.d.ts +388 -0
- package/dist/settings.js +268 -0
- package/dist/skill-loader.d.ts +24 -0
- package/dist/skill-loader.js +93 -0
- package/dist/standalone-fallback.d.ts +30 -0
- package/dist/standalone-fallback.js +239 -0
- package/dist/status-note.d.ts +61 -0
- package/dist/status-note.js +85 -0
- package/dist/structured-output.d.ts +61 -0
- package/dist/structured-output.js +112 -0
- package/dist/terminal-progress.d.ts +115 -0
- package/dist/terminal-progress.js +206 -0
- package/dist/types.d.ts +411 -0
- package/dist/types.js +5 -0
- package/dist/ui/agent-mention.d.ts +82 -0
- package/dist/ui/agent-mention.js +187 -0
- package/dist/ui/agent-widget.d.ts +304 -0
- package/dist/ui/agent-widget.js +770 -0
- package/dist/ui/cleanup-preview.d.ts +59 -0
- package/dist/ui/cleanup-preview.js +466 -0
- package/dist/ui/conversation-viewer.d.ts +105 -0
- package/dist/ui/conversation-viewer.js +544 -0
- package/dist/ui/fleet-list.d.ts +183 -0
- package/dist/ui/fleet-list.js +494 -0
- package/dist/ui/fleet-overlay.d.ts +203 -0
- package/dist/ui/fleet-overlay.js +887 -0
- package/dist/ui/hub-feed.d.ts +52 -0
- package/dist/ui/hub-feed.js +148 -0
- package/dist/ui/native-transcript.d.ts +33 -0
- package/dist/ui/native-transcript.js +234 -0
- package/dist/ui/schedule-menu.d.ts +16 -0
- package/dist/ui/schedule-menu.js +94 -0
- package/dist/ui/select-item.d.ts +27 -0
- package/dist/ui/select-item.js +34 -0
- package/dist/ui/tool-progress.d.ts +22 -0
- package/dist/ui/tool-progress.js +56 -0
- package/dist/ui/viewer-keys.d.ts +20 -0
- package/dist/ui/viewer-keys.js +17 -0
- package/dist/ui/workflow-card.d.ts +175 -0
- package/dist/ui/workflow-card.js +332 -0
- package/dist/ui/workflow-dialog.d.ts +305 -0
- package/dist/ui/workflow-dialog.js +848 -0
- package/dist/ui/workflow-menu.d.ts +60 -0
- package/dist/ui/workflow-menu.js +147 -0
- package/dist/usage.d.ts +147 -0
- package/dist/usage.js +147 -0
- package/dist/workflow/collisions.d.ts +95 -0
- package/dist/workflow/collisions.js +88 -0
- package/dist/workflow/entry.d.ts +32 -0
- package/dist/workflow/entry.js +29 -0
- package/dist/workflow/host.d.ts +65 -0
- package/dist/workflow/host.js +477 -0
- package/dist/workflow/journal.d.ts +113 -0
- package/dist/workflow/journal.js +177 -0
- package/dist/workflow/json-schema.d.ts +51 -0
- package/dist/workflow/json-schema.js +111 -0
- package/dist/workflow/meta.d.ts +67 -0
- package/dist/workflow/meta.js +317 -0
- package/dist/workflow/progress.d.ts +224 -0
- package/dist/workflow/progress.js +361 -0
- package/dist/workflow/runtime.d.ts +373 -0
- package/dist/workflow/runtime.js +919 -0
- package/dist/workflow/saved.d.ts +90 -0
- package/dist/workflow/saved.js +203 -0
- package/dist/workflow/task.d.ts +145 -0
- package/dist/workflow/task.js +213 -0
- package/dist/workflow/tool-description.d.ts +43 -0
- package/dist/workflow/tool-description.js +204 -0
- package/dist/workflow/worker-source.d.ts +47 -0
- package/dist/workflow/worker-source.js +778 -0
- package/dist/worktree.d.ts +52 -0
- package/dist/worktree.js +164 -0
- package/dist/xml.d.ts +10 -0
- package/dist/xml.js +12 -0
- package/docs/DEVELOPMENT.md +40 -0
- package/docs/artifacts.md +93 -0
- package/docs/recovery.md +62 -0
- package/docs/rpc.md +252 -0
- package/docs/runtime-performance.md +53 -0
- package/docs/workflows.md +467 -0
- package/examples/agent-tool-description.md +43 -0
- package/examples/workflows/compose.js +51 -0
- package/examples/workflows/fan-out-audit.js +47 -0
- package/examples/workflows/gated-fix.js +60 -0
- package/examples/workflows/lib/count-child.js +27 -0
- package/examples/workflows/review-panel.js +66 -0
- package/examples/workflows/structured-findings.js +78 -0
- package/package.json +75 -6
- package/src/abortable.ts +43 -0
- package/src/active-agents-prompt.ts +115 -0
- package/src/advisor-status.ts +74 -0
- package/src/agent-color.ts +169 -0
- package/src/agent-file-toggle.ts +273 -0
- package/src/agent-manager.ts +3312 -0
- package/src/agent-runner.ts +1500 -0
- package/src/agent-types.ts +390 -0
- package/src/awaited-result.ts +187 -0
- package/src/child-context.ts +173 -0
- package/src/child-session-shutdown.ts +114 -0
- package/src/cleanup-plans.ts +112 -0
- package/src/context.ts +58 -0
- package/src/cross-extension-rpc.ts +257 -0
- package/src/custom-agents.ts +689 -0
- package/src/default-agents.ts +129 -0
- package/src/enabled-models.ts +180 -0
- package/src/env.ts +33 -0
- package/src/error-log.ts +202 -0
- package/src/force-main-model.ts +29 -0
- package/src/goal-bridge.ts +468 -0
- package/src/group-join.ts +188 -0
- package/src/index.ts +6856 -0
- package/src/invocation-config.ts +276 -0
- package/src/memory.ts +179 -0
- package/src/mention-clone.ts +221 -0
- package/src/mention.ts +141 -0
- package/src/model-resolver.ts +118 -0
- package/src/model-scope.ts +70 -0
- package/src/nested-tools.ts +553 -0
- package/src/output-diagnostics.ts +68 -0
- package/src/output-file.ts +380 -0
- package/src/prompts.ts +151 -0
- package/src/recovery.ts +320 -0
- package/src/report-cleanup.ts +2044 -0
- package/src/report-store.ts +4130 -0
- package/src/schedule-store.ts +244 -0
- package/src/schedule.ts +450 -0
- package/src/settings.ts +632 -0
- package/src/skill-loader.ts +102 -0
- package/src/standalone-fallback.ts +195 -0
- package/src/status-note.ts +90 -0
- package/src/structured-output.ts +130 -0
- package/src/terminal-progress.ts +215 -0
- package/src/types.ts +424 -0
- package/src/ui/agent-mention.ts +216 -0
- package/src/ui/agent-widget.ts +866 -0
- package/src/ui/cleanup-preview.ts +518 -0
- package/src/ui/conversation-viewer.ts +527 -0
- package/src/ui/fleet-list.ts +563 -0
- package/src/ui/fleet-overlay.ts +1048 -0
- package/src/ui/hub-feed.ts +179 -0
- package/src/ui/native-transcript.ts +224 -0
- package/src/ui/schedule-menu.ts +105 -0
- package/src/ui/select-item.ts +45 -0
- package/src/ui/tool-progress.ts +67 -0
- package/src/ui/viewer-keys.ts +39 -0
- package/src/ui/workflow-card.ts +470 -0
- package/src/ui/workflow-dialog.ts +1119 -0
- package/src/ui/workflow-menu.ts +193 -0
- package/src/usage.ts +217 -0
- package/src/workflow/collisions.ts +123 -0
- package/src/workflow/entry.ts +47 -0
- package/src/workflow/host.ts +524 -0
- package/src/workflow/journal.ts +221 -0
- package/src/workflow/json-schema.ts +128 -0
- package/src/workflow/meta.ts +325 -0
- package/src/workflow/progress.ts +550 -0
- package/src/workflow/runtime.ts +1342 -0
- package/src/workflow/saved.ts +217 -0
- package/src/workflow/task.ts +313 -0
- package/src/workflow/tool-description.ts +205 -0
- package/src/workflow/worker-source.ts +781 -0
- package/src/worktree.ts +205 -0
- package/src/xml.ts +13 -0
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import type { Model } from "@earendil-works/pi-ai";
|
|
2
|
+
import { type AgentSession, type ExtensionAPI, type ExtensionContext, type ToolDefinition } from "@earendil-works/pi-coding-agent";
|
|
3
|
+
import type { ReportLookup, ReportOwnerContext } from "./report-store.ts";
|
|
4
|
+
import type { AgentConfig, AgentInvocation, AgentRecord, IsolationMode, ThinkingLevel } from "./types.ts";
|
|
5
|
+
export declare function getMaxSubagentDepth(): number;
|
|
6
|
+
export declare function setMaxSubagentDepth(n: number): void;
|
|
7
|
+
/**
|
|
8
|
+
* Async, parent-scoped reader for durable completed reports.
|
|
9
|
+
*
|
|
10
|
+
* Injected explicitly from the surviving root manager through the runner into
|
|
11
|
+
* these tools. Only the owner that actually spawned an archived child may read
|
|
12
|
+
* it; the store enforces `parentAgentId === ownerId`, so a workflow row (which
|
|
13
|
+
* has `workflowId`, not a parent) and a sibling's child stay invisible.
|
|
14
|
+
*/
|
|
15
|
+
export interface ArchivedReportReader {
|
|
16
|
+
findOwned(ref: string, owner: ReportOwnerContext): Promise<ReportLookup>;
|
|
17
|
+
}
|
|
18
|
+
interface NestedSpawnOptions {
|
|
19
|
+
description: string;
|
|
20
|
+
model?: Model<any>;
|
|
21
|
+
maxTurns?: number;
|
|
22
|
+
isolated?: boolean;
|
|
23
|
+
inheritContext?: boolean;
|
|
24
|
+
thinkingLevel?: ThinkingLevel;
|
|
25
|
+
isBackground?: boolean;
|
|
26
|
+
isolation?: IsolationMode;
|
|
27
|
+
invocation?: AgentInvocation;
|
|
28
|
+
signal?: AbortSignal;
|
|
29
|
+
onAssistantUsage?: (usage: {
|
|
30
|
+
input: number;
|
|
31
|
+
output: number;
|
|
32
|
+
cacheWrite: number;
|
|
33
|
+
}) => void;
|
|
34
|
+
onSessionCreated?: (session: AgentSession) => void;
|
|
35
|
+
depth: number;
|
|
36
|
+
parentAgentId: string;
|
|
37
|
+
maxSubagentDepth: number;
|
|
38
|
+
configCwd?: string;
|
|
39
|
+
rootSessionId?: string;
|
|
40
|
+
/**
|
|
41
|
+
* The admitted definition, cloned from the branch's own scoped registry
|
|
42
|
+
* before any admission await. The runner derives prompt, tool policy and
|
|
43
|
+
* model/session/nesting defaults from this snapshot, so another root or
|
|
44
|
+
* process-wide reload cannot change what this queued child is allowed to do.
|
|
45
|
+
*/
|
|
46
|
+
agentDefinition?: AgentConfig;
|
|
47
|
+
}
|
|
48
|
+
export interface NestedAgentManager {
|
|
49
|
+
spawn(pi: ExtensionAPI, ctx: ExtensionContext, type: string, prompt: string, options: NestedSpawnOptions): string;
|
|
50
|
+
/** Resolves once the spawned agent is running; rejects on a startup failure. */
|
|
51
|
+
awaitStartup(id: string): Promise<void>;
|
|
52
|
+
spawnAndWait(pi: ExtensionAPI, ctx: ExtensionContext, type: string, prompt: string, options: Omit<NestedSpawnOptions, "isBackground">,
|
|
53
|
+
/** Fires synchronously after spawn, before the session exists — where the transcript is attached. */
|
|
54
|
+
onSpawned?: (id: string) => void): Promise<{
|
|
55
|
+
id: string;
|
|
56
|
+
record: AgentRecord;
|
|
57
|
+
}>;
|
|
58
|
+
getRecord(id: string): AgentRecord | undefined;
|
|
59
|
+
resume(id: string, prompt: string, signal?: AbortSignal): Promise<AgentRecord | undefined>;
|
|
60
|
+
}
|
|
61
|
+
export interface NestedToolContext {
|
|
62
|
+
manager: NestedAgentManager;
|
|
63
|
+
pi: ExtensionAPI;
|
|
64
|
+
parentAgentId: string;
|
|
65
|
+
depth: number;
|
|
66
|
+
maxSubagentDepth: number;
|
|
67
|
+
/** "all" = any enabled agent; string[] = only those types. Never empty. */
|
|
68
|
+
allowedSubagents: "all" | string[];
|
|
69
|
+
/** Root used for agent/config discovery; may differ from the agent's working directory. */
|
|
70
|
+
configCwd: string;
|
|
71
|
+
/** Optional durable-report reader; absent means archive-only reads are unavailable. */
|
|
72
|
+
archive?: ArchivedReportReader;
|
|
73
|
+
}
|
|
74
|
+
/** Build child-safe orchestration tools scoped to one parent agent instance. */
|
|
75
|
+
export declare function createNestedSubagentTools(context: NestedToolContext): ToolDefinition[];
|
|
76
|
+
export {};
|
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
import { defineTool, } from "@earendil-works/pi-coding-agent";
|
|
2
|
+
import { Type } from "@sinclair/typebox";
|
|
3
|
+
import { abortable } from "./abortable.js";
|
|
4
|
+
import { getAllowPerCallTurnLimits } from "./agent-runner.js";
|
|
5
|
+
import { buildAgentRegistry, cloneAgentDefinition, getAgentConfigIn, getAvailableTypesIn, resolveEnabledTypeIn, resolveTypeIn, } from "./agent-types.js";
|
|
6
|
+
import { loadCustomAgents, loadCustomAgentsAsync } from "./custom-agents.js";
|
|
7
|
+
import { isForceMainModel } from "./force-main-model.js";
|
|
8
|
+
import { isolationParam, maxTurnsParam, resolveAgentInvocationConfig } from "./invocation-config.js";
|
|
9
|
+
import { resolveModel } from "./model-resolver.js";
|
|
10
|
+
import { checkModelScope } from "./model-scope.js";
|
|
11
|
+
import { createOutputFilePath, getOutputTranscriptDefault, streamToOutputFile, writeInitialEntry, } from "./output-file.js";
|
|
12
|
+
import { getForegroundOutcomeNote, getStatusNote, partialOutputSuffix } from "./status-note.js";
|
|
13
|
+
import { addUsage } from "./usage.js";
|
|
14
|
+
import { isWorktreeIsolationEnabled } from "./worktree.js";
|
|
15
|
+
/**
|
|
16
|
+
* Hard ceiling on nesting for every branch: main session = 0, its subagents = 1,
|
|
17
|
+
* their children = 2. `0`/`1` disables nesting entirely. Set from
|
|
18
|
+
* `subagents.json` (`maxSubagentDepth`). Read when a subagent session is built,
|
|
19
|
+
* so a change applies to sessions started after it.
|
|
20
|
+
*/
|
|
21
|
+
let maxSubagentDepth = 2;
|
|
22
|
+
export function getMaxSubagentDepth() { return maxSubagentDepth; }
|
|
23
|
+
export function setMaxSubagentDepth(n) { maxSubagentDepth = Math.max(0, Math.floor(n)); }
|
|
24
|
+
const NESTED_TOOL_NAMES = ["Agent", "get_subagent_result", "steer_subagent"];
|
|
25
|
+
function textResult(text, isError = false) {
|
|
26
|
+
return { content: [{ type: "text", text }], isError, details: {} };
|
|
27
|
+
}
|
|
28
|
+
function ownsRecord(record, parentAgentId) {
|
|
29
|
+
return record?.parentAgentId === parentAgentId;
|
|
30
|
+
}
|
|
31
|
+
function formatRecord(record, position) {
|
|
32
|
+
if (record.status === "error") {
|
|
33
|
+
return `Agent failed: ${record.error ?? "unknown error"}${partialOutputSuffix(record)}`;
|
|
34
|
+
}
|
|
35
|
+
if (record.status === "queued" || record.status === "running") {
|
|
36
|
+
return `Agent ${record.id} is ${record.status}.`;
|
|
37
|
+
}
|
|
38
|
+
// A truncated run must not read as a finished one. The top-level path carries
|
|
39
|
+
// this in its result headline; a nested result has no headline, so the note
|
|
40
|
+
// leads — appended, it would look like part of the child's own output.
|
|
41
|
+
const text = record.result?.trim() || record.error?.trim() || "No output.";
|
|
42
|
+
const note = position === "inline"
|
|
43
|
+
? getForegroundOutcomeNote(record.status)
|
|
44
|
+
: getStatusNote(record.status);
|
|
45
|
+
return note ? `Nested agent${note}.\n\n${text}` : text;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* The durable-report shape of {@link formatRecord}. Same honesty rules: a
|
|
49
|
+
* failure keeps its error and the partial output before it, a non-normal
|
|
50
|
+
* status keeps its note, and missing metadata is never invented as zero.
|
|
51
|
+
*/
|
|
52
|
+
function formatArchivedReport(report, provenance) {
|
|
53
|
+
const recovered = `\n\n(Recovered from the ${provenance} saved report; no live session remains.)`;
|
|
54
|
+
if (report.status === "error") {
|
|
55
|
+
const partial = report.result?.trim();
|
|
56
|
+
return `Agent failed: ${report.error ?? "unknown error"}${partial ? `\n\nPartial output before the failure:\n${partial}` : ""}${recovered}`;
|
|
57
|
+
}
|
|
58
|
+
const text = report.result?.trim() || report.error?.trim() || "No output.";
|
|
59
|
+
const note = getStatusNote(report.status);
|
|
60
|
+
return `${note ? `Nested agent${note}.\n\n` : ""}${text}${recovered}`;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* The backend owner's contract is `parentAgentId` EXACT for nested reads;
|
|
64
|
+
* `ownerIds` is cleanup ancestry and must never widen read access. Enforce that
|
|
65
|
+
* here as well, so even a backend release that matched ancestors cannot expose
|
|
66
|
+
* a sibling/descendant row through this bridge.
|
|
67
|
+
*/
|
|
68
|
+
function exactParentLookup(lookup, parentAgentId, ref) {
|
|
69
|
+
if (lookup.status === "missing")
|
|
70
|
+
return lookup;
|
|
71
|
+
if (lookup.status === "ambiguous") {
|
|
72
|
+
return { status: "missing", ref, reason: "ambiguous archived owner match" };
|
|
73
|
+
}
|
|
74
|
+
const owned = lookup.status === "found"
|
|
75
|
+
? lookup.report.parentAgentId === parentAgentId
|
|
76
|
+
: lookup.entry.parentAgentId === parentAgentId;
|
|
77
|
+
return owned ? lookup : { status: "missing", ref, reason: "not owned by this parent" };
|
|
78
|
+
}
|
|
79
|
+
/** Honest wording for every non-found archived lookup; never a guessed result. */
|
|
80
|
+
function formatArchivedLookup(lookup, ref) {
|
|
81
|
+
switch (lookup.status) {
|
|
82
|
+
case "found":
|
|
83
|
+
return formatArchivedReport(lookup.report, lookup.provenance);
|
|
84
|
+
case "expired":
|
|
85
|
+
return `Nested agent ${lookup.entry.id} is no longer available: its saved report expired at ${new Date(lookup.expiredAt).toISOString()} (30-day retention).`;
|
|
86
|
+
case "deleted":
|
|
87
|
+
return `Nested agent ${lookup.entry.id}'s saved report was deliberately deleted${lookup.reason === undefined ? "" : ` (${lookup.reason})`} at ${new Date(lookup.deletedAt).toISOString()}. It will not be resurrected.`;
|
|
88
|
+
case "ambiguous":
|
|
89
|
+
return `Nested agent "${ref}" is ambiguous in the saved archive; no result was chosen.`;
|
|
90
|
+
case "missing":
|
|
91
|
+
return `Nested agent not found or not owned by this parent: "${ref}". ${lookup.reason}.`;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Build child-safe orchestration tools scoped to one parent agent instance. */
|
|
95
|
+
export function createNestedSubagentTools(context) {
|
|
96
|
+
// Agents resolve from a registry built for THIS branch's config root (under
|
|
97
|
+
// worktree isolation, the copy). Never via registerAgents — that is
|
|
98
|
+
// process-global state shared with the main session and every other agent.
|
|
99
|
+
const loadRegistry = () => buildAgentRegistry(loadCustomAgents(context.configCwd));
|
|
100
|
+
// Executes use the async twin so a slow definition directory yields instead
|
|
101
|
+
// of blocking the child's event loop. The synchronous form stays for the
|
|
102
|
+
// parameter schema below, which cannot await; it is read fresh, not cached
|
|
103
|
+
// for admission.
|
|
104
|
+
const loadRegistryAsync = async () => buildAgentRegistry(await loadCustomAgentsAsync(context.configCwd));
|
|
105
|
+
const allowedTypesIn = (registry) => context.allowedSubagents === "all"
|
|
106
|
+
? undefined
|
|
107
|
+
: new Set(context.allowedSubagents.map(name => resolveTypeIn(registry, name) ?? name));
|
|
108
|
+
const availableIn = (registry) => {
|
|
109
|
+
const allowed = allowedTypesIn(registry);
|
|
110
|
+
return getAvailableTypesIn(registry).filter(name => allowed === undefined || allowed.has(name));
|
|
111
|
+
};
|
|
112
|
+
const agentTool = defineTool({
|
|
113
|
+
name: NESTED_TOOL_NAMES[0],
|
|
114
|
+
label: "Agent",
|
|
115
|
+
description: "Launch a child-safe nested subagent for bounded delegated work. " +
|
|
116
|
+
"Only use agent types allowed by this parent agent; nesting is depth-limited.",
|
|
117
|
+
parameters: Type.Object({
|
|
118
|
+
prompt: Type.String({ description: "Self-contained task for the nested agent." }),
|
|
119
|
+
description: Type.String({ description: "Short 3-5 word task description." }),
|
|
120
|
+
subagent_type: Type.String({ description: `Allowed nested agent type. Available: ${availableIn(loadRegistry()).join(", ") || "none"}.` }),
|
|
121
|
+
model: Type.Optional(Type.String({ description: "Optional provider/model override." })),
|
|
122
|
+
thinking: Type.Optional(Type.String({ description: "Optional thinking level." })),
|
|
123
|
+
...maxTurnsParam(getAllowPerCallTurnLimits()),
|
|
124
|
+
run_in_background: Type.Optional(Type.Boolean({
|
|
125
|
+
description: "Defaults to false for nested spawns — the call blocks and returns the child's result inline. Set true only for work you will collect later with get_subagent_result; a detached child is stopped when you finish.",
|
|
126
|
+
})),
|
|
127
|
+
resume: Type.Optional(Type.String({ description: "Resume a nested agent owned by this parent." })),
|
|
128
|
+
isolated: Type.Optional(Type.Boolean()),
|
|
129
|
+
inherit_context: Type.Optional(Type.Boolean()),
|
|
130
|
+
...isolationParam(isWorktreeIsolationEnabled()),
|
|
131
|
+
}),
|
|
132
|
+
execute: async (_toolCallId, params, signal, _onUpdate, ctx) => {
|
|
133
|
+
if (params.resume) {
|
|
134
|
+
const existing = context.manager.getRecord(params.resume);
|
|
135
|
+
if (!ownsRecord(existing, context.parentAgentId)) {
|
|
136
|
+
return textResult(`Nested agent not found or not owned by this parent: "${params.resume}".`, true);
|
|
137
|
+
}
|
|
138
|
+
const resumed = await context.manager.resume(params.resume, params.prompt, signal);
|
|
139
|
+
return resumed
|
|
140
|
+
? textResult(formatRecord(resumed, "inline"), resumed.status === "error")
|
|
141
|
+
: textResult(`Failed to resume nested agent "${params.resume}".`, true);
|
|
142
|
+
}
|
|
143
|
+
if (context.depth >= context.maxSubagentDepth) {
|
|
144
|
+
return textResult(`Nested subagent call blocked (depth=${context.depth}, max=${context.maxSubagentDepth}). Complete the task directly.`, true);
|
|
145
|
+
}
|
|
146
|
+
// Reloaded per call so new agent files are picked up without a restart.
|
|
147
|
+
const registry = await loadRegistryAsync();
|
|
148
|
+
const rawType = params.subagent_type;
|
|
149
|
+
// Strict resolve, never the fallback policy: a project-level
|
|
150
|
+
// `fallbackSubagent` must not hand a nested caller an agent its allowlist
|
|
151
|
+
// never named. The list stays allowlist-filtered so a typo can't enumerate
|
|
152
|
+
// agents this parent may not reach.
|
|
153
|
+
const resolvedType = resolveEnabledTypeIn(registry, rawType);
|
|
154
|
+
if (resolvedType === undefined) {
|
|
155
|
+
return textResult(`Unknown or disabled nested agent type: "${rawType}". Allowed: ${availableIn(registry).join(", ") || "none"}.`, true);
|
|
156
|
+
}
|
|
157
|
+
const allowed = allowedTypesIn(registry);
|
|
158
|
+
if (allowed !== undefined && !allowed.has(resolvedType)) {
|
|
159
|
+
return textResult(`Nested agent type "${resolvedType}" is not allowed for this parent. Allowed: ${[...allowed].join(", ")}.`, true);
|
|
160
|
+
}
|
|
161
|
+
const config = getAgentConfigIn(registry, resolvedType);
|
|
162
|
+
// Pin what was admitted, not what the process-wide registry says later.
|
|
163
|
+
// The manager may queue, copy a worktree or otherwise suspend before the
|
|
164
|
+
// runner reads the definition; cloning now keeps prompt, tools/denylists,
|
|
165
|
+
// model and session/nesting policy on the values that passed admission.
|
|
166
|
+
const agentDefinition = config === undefined ? undefined : cloneAgentDefinition(config);
|
|
167
|
+
// Foreground regardless of `backgroundByDefault` — see the reasoning on
|
|
168
|
+
// ResolveOptions. An explicit `true` here still opts in.
|
|
169
|
+
const invocation = resolveAgentInvocationConfig(config, params, {
|
|
170
|
+
worktreeAllowed: isWorktreeIsolationEnabled(),
|
|
171
|
+
defaultRunInBackground: false,
|
|
172
|
+
allowPerCallTurnLimits: getAllowPerCallTurnLimits(),
|
|
173
|
+
});
|
|
174
|
+
// /subagents off: the nested spawn twins its parent's model (itself
|
|
175
|
+
// twinned), so caller/config model inputs and the scope check give way.
|
|
176
|
+
const twinForced = isForceMainModel();
|
|
177
|
+
let model = ctx.model;
|
|
178
|
+
if (!twinForced && invocation.modelInput) {
|
|
179
|
+
const resolvedModel = resolveModel(invocation.modelInput, ctx.modelRegistry);
|
|
180
|
+
if (typeof resolvedModel === "string") {
|
|
181
|
+
if (invocation.modelFromParams)
|
|
182
|
+
return textResult(resolvedModel, true);
|
|
183
|
+
}
|
|
184
|
+
else {
|
|
185
|
+
model = resolvedModel;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
// Same scopeModels policy as the top-level Agent tool — a nested spawn
|
|
189
|
+
// must not escape the allowlist. A "warn" verdict proceeds silently:
|
|
190
|
+
// child sessions have no UI surface to toast to.
|
|
191
|
+
if (!twinForced) {
|
|
192
|
+
const scopeVerdict = checkModelScope({
|
|
193
|
+
model,
|
|
194
|
+
cwd: context.configCwd,
|
|
195
|
+
modelRegistry: ctx.modelRegistry,
|
|
196
|
+
callerSupplied: invocation.modelFromParams,
|
|
197
|
+
agentLabel: config?.displayName ?? resolvedType,
|
|
198
|
+
modelInput: invocation.modelInput,
|
|
199
|
+
});
|
|
200
|
+
if (scopeVerdict.kind === "error")
|
|
201
|
+
return textResult(scopeVerdict.message, true);
|
|
202
|
+
}
|
|
203
|
+
// The whole branch shares the root session's transcript directory; read it
|
|
204
|
+
// off the owning parent rather than this child session's own id.
|
|
205
|
+
const rootSessionId = context.manager.getRecord(context.parentAgentId)?.rootSessionId;
|
|
206
|
+
const childDepth = context.depth + 1;
|
|
207
|
+
const options = {
|
|
208
|
+
description: params.description,
|
|
209
|
+
model,
|
|
210
|
+
maxTurns: invocation.maxTurns,
|
|
211
|
+
isolated: invocation.isolated,
|
|
212
|
+
inheritContext: invocation.inheritContext,
|
|
213
|
+
thinkingLevel: invocation.thinking,
|
|
214
|
+
isolation: invocation.isolation,
|
|
215
|
+
invocation: {
|
|
216
|
+
thinking: invocation.thinking,
|
|
217
|
+
maxTurns: invocation.maxTurns,
|
|
218
|
+
isolated: invocation.isolated,
|
|
219
|
+
inheritContext: invocation.inheritContext,
|
|
220
|
+
runInBackground: invocation.runInBackground,
|
|
221
|
+
isolation: invocation.isolation,
|
|
222
|
+
},
|
|
223
|
+
// Nested children are hidden from every reporting surface, so their spend
|
|
224
|
+
// would otherwise be unattributable. Fold it into every ancestor's record:
|
|
225
|
+
// the top-level one appears in lifecycle events, completion notifications,
|
|
226
|
+
// and `/agents`, and those all read `lifetimeUsage`. The whole chain is
|
|
227
|
+
// walked, not just the immediate parent — a spawn callback only fires for
|
|
228
|
+
// that child's OWN turns, so stopping at one level would hide a
|
|
229
|
+
// great-grandchild from the only record anyone can see. (The live
|
|
230
|
+
// widget/fleet counters read their own per-agent activity tracker, which
|
|
231
|
+
// still sees only the top-level agent's own turns.)
|
|
232
|
+
onAssistantUsage: (usage) => {
|
|
233
|
+
for (let id = context.parentAgentId; id !== undefined;) {
|
|
234
|
+
const ancestor = context.manager.getRecord(id);
|
|
235
|
+
if (!ancestor)
|
|
236
|
+
break;
|
|
237
|
+
addUsage(ancestor.lifetimeUsage, usage);
|
|
238
|
+
id = ancestor.parentAgentId;
|
|
239
|
+
}
|
|
240
|
+
},
|
|
241
|
+
depth: childDepth,
|
|
242
|
+
parentAgentId: context.parentAgentId,
|
|
243
|
+
maxSubagentDepth: context.maxSubagentDepth,
|
|
244
|
+
configCwd: context.configCwd,
|
|
245
|
+
rootSessionId,
|
|
246
|
+
agentDefinition,
|
|
247
|
+
};
|
|
248
|
+
// Transcript wiring, same gate as the top-level path: the child's
|
|
249
|
+
// `output_transcript` frontmatter wins, else the project default. Without
|
|
250
|
+
// it a nested run leaves no artifact but the string it returned — the
|
|
251
|
+
// parent's own transcript records the call and the answer, never the tool
|
|
252
|
+
// calls in between, which is exactly what a misbehaving child needs to
|
|
253
|
+
// explain itself. Filed under the ROOT session and this branch's config
|
|
254
|
+
// root, so a nested transcript lands in the same `tasks/` directory as its
|
|
255
|
+
// ancestors' rather than in a directory of its own.
|
|
256
|
+
const transcriptSessionId = rootSessionId !== undefined && (config?.outputTranscript ?? getOutputTranscriptDefault())
|
|
257
|
+
? rootSessionId
|
|
258
|
+
: undefined;
|
|
259
|
+
let childId;
|
|
260
|
+
const attachTranscript = (id) => {
|
|
261
|
+
childId = id;
|
|
262
|
+
if (transcriptSessionId === undefined)
|
|
263
|
+
return;
|
|
264
|
+
const rec = context.manager.getRecord(id);
|
|
265
|
+
if (!rec)
|
|
266
|
+
return;
|
|
267
|
+
rec.outputFile = createOutputFilePath(context.configCwd, id, transcriptSessionId);
|
|
268
|
+
writeInitialEntry(rec.outputFile, id, params.prompt, ctx.cwd);
|
|
269
|
+
};
|
|
270
|
+
options.onSessionCreated = (session) => {
|
|
271
|
+
const rec = childId === undefined ? undefined : context.manager.getRecord(childId);
|
|
272
|
+
if (rec?.outputFile && childId !== undefined) {
|
|
273
|
+
rec.outputCleanup = streamToOutputFile(session, rec.outputFile, childId, ctx.cwd);
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
// `ctx` is forwarded to the manager unmodified, never captured at tool-build
|
|
277
|
+
// time: each AgentSession builds its own ExtensionRunner from that session's
|
|
278
|
+
// cwd/sessionManager/modelRegistry, so this is the CHILD's context. Capturing
|
|
279
|
+
// one earlier would silently give a grandchild the wrong worktree base, the
|
|
280
|
+
// wrong conversation under inherit_context, and the wrong inherited model.
|
|
281
|
+
//
|
|
282
|
+
// spawn() throws on strict worktree-isolation failure and cwd validation —
|
|
283
|
+
// report it as a tool error, like the top-level Agent tool does, instead of
|
|
284
|
+
// letting it escape into the child's turn.
|
|
285
|
+
try {
|
|
286
|
+
if (invocation.runInBackground) {
|
|
287
|
+
const id = context.manager.spawn(context.pi, ctx, resolvedType, params.prompt, {
|
|
288
|
+
...options,
|
|
289
|
+
isBackground: true,
|
|
290
|
+
});
|
|
291
|
+
// Synchronous, before the event loop yields — onSessionCreated fires
|
|
292
|
+
// asynchronously inside runAgent, so the file is attached in time.
|
|
293
|
+
attachTranscript(id);
|
|
294
|
+
// Worktree isolation starts the agent asynchronously; surface its
|
|
295
|
+
// failure as a tool error, like the synchronous throw used to.
|
|
296
|
+
await context.manager.awaitStartup(id);
|
|
297
|
+
return textResult(`Nested agent started in background. Agent ID: ${id}`);
|
|
298
|
+
}
|
|
299
|
+
const { record } = await context.manager.spawnAndWait(context.pi, ctx, resolvedType, params.prompt, { ...options, signal }, attachTranscript);
|
|
300
|
+
return textResult(formatRecord(record, "inline"), record.status === "error");
|
|
301
|
+
}
|
|
302
|
+
catch (err) {
|
|
303
|
+
return textResult(err instanceof Error ? err.message : String(err), true);
|
|
304
|
+
}
|
|
305
|
+
},
|
|
306
|
+
});
|
|
307
|
+
const resultTool = defineTool({
|
|
308
|
+
name: NESTED_TOOL_NAMES[1],
|
|
309
|
+
label: "Get Nested Agent Result",
|
|
310
|
+
description: "Check or wait for a background nested agent owned by this parent.",
|
|
311
|
+
parameters: Type.Object({
|
|
312
|
+
agent_id: Type.String(),
|
|
313
|
+
wait: Type.Optional(Type.Boolean()),
|
|
314
|
+
}),
|
|
315
|
+
execute: async (_toolCallId, params, signal) => {
|
|
316
|
+
/** Wait abortably for a LIVE record; archived rows never wait. */
|
|
317
|
+
const waitForLive = async (record) => {
|
|
318
|
+
if (!params.wait || (record.status !== "queued" && record.status !== "running"))
|
|
319
|
+
return;
|
|
320
|
+
// Queued records have no promise until the manager starts them, so poll
|
|
321
|
+
// — abortably — until they leave the queue, then await. Cancellation
|
|
322
|
+
// stops only this wait; the nested child keeps running and unconsumed.
|
|
323
|
+
while (record.status === "queued") {
|
|
324
|
+
await abortable(new Promise(resolve => setTimeout(resolve, 250)), signal);
|
|
325
|
+
}
|
|
326
|
+
if (record.promise)
|
|
327
|
+
await abortable(record.promise, signal);
|
|
328
|
+
};
|
|
329
|
+
const record = context.manager.getRecord(params.agent_id);
|
|
330
|
+
if (record !== undefined) {
|
|
331
|
+
// A KNOWN but unowned live record is refused outright. Falling through
|
|
332
|
+
// to the archive here could surface a same-id archived row (after a
|
|
333
|
+
// resume) that this parent never owned.
|
|
334
|
+
if (!ownsRecord(record, context.parentAgentId)) {
|
|
335
|
+
return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
|
|
336
|
+
}
|
|
337
|
+
await waitForLive(record);
|
|
338
|
+
return textResult(formatRecord(record, "fetched"), record.status === "error");
|
|
339
|
+
}
|
|
340
|
+
// The runtime record is gone (evicted/reloaded). The root manager's
|
|
341
|
+
// durable store can still answer, but only for this exact parent.
|
|
342
|
+
if (context.archive === undefined) {
|
|
343
|
+
return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
|
|
344
|
+
}
|
|
345
|
+
const lookup = exactParentLookup(await context.archive.findOwned(params.agent_id, {
|
|
346
|
+
kind: "parent",
|
|
347
|
+
id: context.parentAgentId,
|
|
348
|
+
}), context.parentAgentId, params.agent_id);
|
|
349
|
+
// Recheck live after the async read: a resume that started meanwhile is
|
|
350
|
+
// the current truth, and an older saved answer must not shadow it.
|
|
351
|
+
const relive = context.manager.getRecord(params.agent_id);
|
|
352
|
+
if (relive !== undefined) {
|
|
353
|
+
if (!ownsRecord(relive, context.parentAgentId)) {
|
|
354
|
+
return textResult(`Nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
|
|
355
|
+
}
|
|
356
|
+
await waitForLive(relive);
|
|
357
|
+
return textResult(formatRecord(relive, "fetched"), relive.status === "error");
|
|
358
|
+
}
|
|
359
|
+
return textResult(formatArchivedLookup(lookup, params.agent_id), lookup.status === "found" ? lookup.report.status === "error" : true);
|
|
360
|
+
},
|
|
361
|
+
});
|
|
362
|
+
const steerTool = defineTool({
|
|
363
|
+
name: NESTED_TOOL_NAMES[2],
|
|
364
|
+
label: "Steer Nested Agent",
|
|
365
|
+
description: "Send guidance to a running nested agent owned by this parent.",
|
|
366
|
+
parameters: Type.Object({
|
|
367
|
+
agent_id: Type.String(),
|
|
368
|
+
message: Type.String(),
|
|
369
|
+
}),
|
|
370
|
+
execute: async (_toolCallId, params) => {
|
|
371
|
+
const record = context.manager.getRecord(params.agent_id);
|
|
372
|
+
if (!ownsRecord(record, context.parentAgentId) || record.status !== "running") {
|
|
373
|
+
return textResult(`Running nested agent not found or not owned by this parent: "${params.agent_id}".`, true);
|
|
374
|
+
}
|
|
375
|
+
// Session not ready yet — queue the steer. The manager flushes pending
|
|
376
|
+
// steers when the session is created (same contract as the top-level tool).
|
|
377
|
+
if (!record.session) {
|
|
378
|
+
if (!record.pendingSteers)
|
|
379
|
+
record.pendingSteers = [];
|
|
380
|
+
record.pendingSteers.push(params.message);
|
|
381
|
+
return textResult(`Steering message queued for nested agent ${params.agent_id}.`);
|
|
382
|
+
}
|
|
383
|
+
try {
|
|
384
|
+
await record.session.steer(params.message);
|
|
385
|
+
}
|
|
386
|
+
catch (err) {
|
|
387
|
+
return textResult(`Failed to steer nested agent: ${err instanceof Error ? err.message : String(err)}`, true);
|
|
388
|
+
}
|
|
389
|
+
return textResult(`Steering message sent to nested agent ${params.agent_id}.`);
|
|
390
|
+
},
|
|
391
|
+
});
|
|
392
|
+
return [agentTool, resultTool, steerTool];
|
|
393
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { AssistantMessage } from "@earendil-works/pi-ai";
|
|
2
|
+
/** Retain the provider's explanation, not a guessed backend root cause. */
|
|
3
|
+
export declare function sanitizeDiagnosticText(text: string | undefined, limit?: number): string | undefined;
|
|
4
|
+
/** Snapshot attribution now: session.model may already be a recovery target. */
|
|
5
|
+
export declare function assistantDiagnosticContext(message: AssistantMessage): {
|
|
6
|
+
provider: string | undefined;
|
|
7
|
+
model: string | undefined;
|
|
8
|
+
responseModel: string | undefined;
|
|
9
|
+
messageTimestamp: number;
|
|
10
|
+
stopReason: import("@earendil-works/pi-ai").StopReason;
|
|
11
|
+
};
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/** Bounded, allowlisted evidence only; never serialize provider objects or request context. */
|
|
2
|
+
import { stripVTControlCharacters } from "node:util";
|
|
3
|
+
function stripControls(text) {
|
|
4
|
+
// OSC/DCS/APC/PM/SOS strings (including unfinished ones) can contain secrets.
|
|
5
|
+
return stripVTControlCharacters(text
|
|
6
|
+
.replace(/(?:\x1b[\]P_^X]|[\x90\x98\x9d-\x9f])[\s\S]*?(?:\x07|\x1b\\|\x9c|$)/g, ""))
|
|
7
|
+
.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f-\x9f\p{Cf}]/gu, "");
|
|
8
|
+
}
|
|
9
|
+
/** Retain the provider's explanation, not a guessed backend root cause. */
|
|
10
|
+
export function sanitizeDiagnosticText(text, limit = 1024) {
|
|
11
|
+
if (text === undefined)
|
|
12
|
+
return undefined;
|
|
13
|
+
// Bound parsing/regex work too. Redaction precedes the final output truncation.
|
|
14
|
+
const inputLimit = 16_384;
|
|
15
|
+
let value = stripControls(text.slice(0, inputLimit)).trim();
|
|
16
|
+
// SDKs sometimes stringify an entire HTTP response into errorMessage. Extract
|
|
17
|
+
// only the conventional message field; never copy metadata, headers or bodies.
|
|
18
|
+
const structuredAt = value.search(/[[{]/);
|
|
19
|
+
if (structuredAt >= 0) {
|
|
20
|
+
const prefix = value.slice(0, structuredAt);
|
|
21
|
+
let explanation;
|
|
22
|
+
try {
|
|
23
|
+
const parsed = JSON.parse(value.slice(structuredAt));
|
|
24
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
25
|
+
const object = parsed;
|
|
26
|
+
const error = object.error;
|
|
27
|
+
explanation = error && typeof error === "object"
|
|
28
|
+
? error.message
|
|
29
|
+
: object.message;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
catch { /* Non-JSON/partial structured details are omitted, not logged. */ }
|
|
33
|
+
value = prefix + (typeof explanation === "string" ? explanation : "[structured details omitted]");
|
|
34
|
+
}
|
|
35
|
+
value = stripControls(value)
|
|
36
|
+
// A message field can itself contain a payload. Fail closed on its tail.
|
|
37
|
+
.replace(/[[{][\s\S]*/, "[structured details omitted]")
|
|
38
|
+
.replace(/\b(?:(?:request|response)[ _-]*)?(?:headers?|body|payload|prompts?|messages|input|config|options)["']?\s*[:=][\s\S]*/gi, "[details omitted]")
|
|
39
|
+
.replace(/\b(?:authorization|proxy-authorization|cookie|set-cookie|x-[\w-]+|content-[\w-]+|www-authenticate|location|retry-after|user-agent|host|date|server|connection|cache-control)["']?\s*[:=][\s\S]*/gi, "[headers omitted]")
|
|
40
|
+
// Do not retain stack traces, header blocks, or request dumps on later lines.
|
|
41
|
+
.split(/[\r\n]/, 1)[0]
|
|
42
|
+
.replace(/[a-z][a-z0-9+.-]*:\/\/[^\s"'<>]+/gi, "[URL omitted]")
|
|
43
|
+
.replace(/\b(?:bearer|basic)\s+[^\s,;]+/gi, "[credential redacted]")
|
|
44
|
+
.replace(/\b[\w-]*(?:api[_-]?key|token|secret|password|passwd|credential|signature)[\w-]*["']?\s*[:=]\s*(?:"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|[^\s,;]+)/gi, "[credential redacted]")
|
|
45
|
+
.replace(/\b(?:sk-|gh[pousr]_|github_pat_|xox[baprs]-)[a-z0-9_-]+/gi, "[credential redacted]")
|
|
46
|
+
.replace(/\beyJ[a-z0-9_-]+\.[a-z0-9_-]+\.[a-z0-9_-]+/gi, "[credential redacted]")
|
|
47
|
+
.replace(/[\x00-\x1f\x7f-\x9f\p{Cf}]/gu, "")
|
|
48
|
+
.replace(/\s+/g, " ")
|
|
49
|
+
.trim();
|
|
50
|
+
const suffix = " [truncated]";
|
|
51
|
+
return value.length > limit || text.length > inputLimit
|
|
52
|
+
? value.slice(0, limit - suffix.length) + suffix
|
|
53
|
+
: value;
|
|
54
|
+
}
|
|
55
|
+
/** Snapshot attribution now: session.model may already be a recovery target. */
|
|
56
|
+
export function assistantDiagnosticContext(message) {
|
|
57
|
+
return {
|
|
58
|
+
provider: sanitizeDiagnosticText(message.provider, 256),
|
|
59
|
+
model: sanitizeDiagnosticText(message.model, 256),
|
|
60
|
+
responseModel: sanitizeDiagnosticText(message.responseModel, 256),
|
|
61
|
+
messageTimestamp: message.timestamp,
|
|
62
|
+
stopReason: message.stopReason,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* output-file.ts — Streaming JSONL output file for agent transcripts.
|
|
3
|
+
*
|
|
4
|
+
* Creates a per-agent output file that streams conversation turns as JSONL,
|
|
5
|
+
* matching Claude Code's task output file format.
|
|
6
|
+
*/
|
|
7
|
+
import type { AgentSession } from "@earendil-works/pi-coding-agent";
|
|
8
|
+
export declare function getOutputTranscriptDefault(): boolean;
|
|
9
|
+
export declare function setOutputTranscriptDefault(b: boolean): void;
|
|
10
|
+
/**
|
|
11
|
+
* Encode a cwd path as a filesystem-safe directory name. Handles:
|
|
12
|
+
* - POSIX: "/home/user/project" → "home-user-project"
|
|
13
|
+
* - Windows: "C:\Users\foo\project" → "Users-foo-project"
|
|
14
|
+
* - UNC: "\\\\server\\share\\project" → "server-share-project"
|
|
15
|
+
*/
|
|
16
|
+
export declare function encodeCwd(cwd: string): string;
|
|
17
|
+
/**
|
|
18
|
+
* The per-session scratch directory, created if missing.
|
|
19
|
+
* Mirrors Claude Code's layout: /tmp/{prefix}-{uid}/{encoded-cwd}/{sessionId}/tasks
|
|
20
|
+
*
|
|
21
|
+
* Shared with the workflow tool, which persists each invocation's script here so
|
|
22
|
+
* iterating on one is edit-file-then-rerun — the same convention, one directory.
|
|
23
|
+
*/
|
|
24
|
+
export declare function sessionTaskDir(cwd: string, sessionId: string): string;
|
|
25
|
+
/** Create the output file path, ensuring the directory exists. */
|
|
26
|
+
export declare function createOutputFilePath(cwd: string, agentId: string, sessionId: string): string;
|
|
27
|
+
/**
|
|
28
|
+
* Ensure a transcript file exists without disturbing what is already in it.
|
|
29
|
+
*
|
|
30
|
+
* A resume reuses the agent's existing transcript (same deterministic path), so
|
|
31
|
+
* it must never call `writeInitialEntry` — that truncates, discarding turns the
|
|
32
|
+
* completion notification still points the user at, and any history the session
|
|
33
|
+
* has since compacted away is gone for good. Appending nothing creates the file
|
|
34
|
+
* when this is the agent's first transcript and is a no-op when it is not.
|
|
35
|
+
*/
|
|
36
|
+
export declare function ensureOutputFile(path: string): void;
|
|
37
|
+
/** Write the initial user prompt entry. */
|
|
38
|
+
export declare function writeInitialEntry(path: string, agentId: string, prompt: string, cwd: string): void;
|
|
39
|
+
/**
|
|
40
|
+
* Wait until every queued write to one transcript file has landed. Resolves
|
|
41
|
+
* immediately when the file is idle; the stream cleanup function returns it
|
|
42
|
+
* so a caller can await the final flush.
|
|
43
|
+
*/
|
|
44
|
+
export declare function drainOutputFile(path: string): Promise<void>;
|
|
45
|
+
/** Diagnostic only: serialized bytes accepted for a path but not yet written. */
|
|
46
|
+
export declare function pendingOutputBytes(path: string): number;
|
|
47
|
+
type OutputSession = Pick<AgentSession, "messages" | "retryAttempt" | "subscribe"> & {
|
|
48
|
+
agent?: Pick<AgentSession["agent"], "subscribe">;
|
|
49
|
+
};
|
|
50
|
+
/**
|
|
51
|
+
* Persist finalized events before retries can remove them from session.messages.
|
|
52
|
+
* Snapshot flushes also preserve eventless SDK additions (e.g. bashExecution).
|
|
53
|
+
* Lines are stringified at event time but written through an async per-file
|
|
54
|
+
* queue (see drainQueue). JSON serialization remains synchronous; disk waits
|
|
55
|
+
* and bounded producer checkpoints are asynchronous.
|
|
56
|
+
* A real Agent session also gets a producer listener registered after the
|
|
57
|
+
* session observer: it waits below the high-water mark at message_end and
|
|
58
|
+
* forces a drain at turn/run settlement, so slow disk stops the producer
|
|
59
|
+
* instead of growing an unbounded in-memory queue. Returns an idempotent final
|
|
60
|
+
* flush/unsubscribe that resolves once the flushed writes are on disk; never
|
|
61
|
+
* changes retry policy.
|
|
62
|
+
*/
|
|
63
|
+
export declare function streamToOutputFile(session: OutputSession, path: string, agentId: string, cwd: string, startIndex?: number, agentType?: string): () => Promise<void>;
|
|
64
|
+
export {};
|