@xzzpig/pi-subagents 0.1.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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
const WAIT_BUFFER = typeof SharedArrayBuffer !== "undefined" ? new SharedArrayBuffer(4) : undefined;
|
|
2
|
+
const WAIT_VIEW = WAIT_BUFFER ? new Int32Array(WAIT_BUFFER) : undefined;
|
|
3
|
+
const RETRYABLE_FILE_SYSTEM_ERROR_CODES = new Set(["EACCES", "EBUSY", "EPERM"]);
|
|
4
|
+
|
|
5
|
+
export const DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS = [10, 25, 50, 100, 200, 500, 1000, 2000, 4000] as const;
|
|
6
|
+
|
|
7
|
+
export type FileSystemRetryOptions = {
|
|
8
|
+
retryDelaysMs?: readonly number[];
|
|
9
|
+
wait?: (delayMs: number) => void;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
export function waitForFileSystemRetry(delayMs: number): void {
|
|
13
|
+
if (delayMs <= 0) return;
|
|
14
|
+
if (WAIT_VIEW) {
|
|
15
|
+
try {
|
|
16
|
+
// Callers are synchronous status/result writers; Atomics.wait gives
|
|
17
|
+
// Windows directory and rename locks time to clear without burning CPU.
|
|
18
|
+
Atomics.wait(WAIT_VIEW, 0, 0, delayMs);
|
|
19
|
+
return;
|
|
20
|
+
} catch {
|
|
21
|
+
// Fall through to the portable busy wait below.
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const end = Date.now() + delayMs;
|
|
25
|
+
while (Date.now() < end) {
|
|
26
|
+
// Portable fallback for runtimes where Atomics.wait is unavailable.
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function isRetryableFileSystemError(error: unknown): boolean {
|
|
31
|
+
const code = (error as NodeJS.ErrnoException | undefined)?.code;
|
|
32
|
+
return typeof code === "string" && RETRYABLE_FILE_SYSTEM_ERROR_CODES.has(code);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export function runFileSystemOperationWithRetry<T>(operation: () => T, options: FileSystemRetryOptions = {}): T {
|
|
36
|
+
const retryDelaysMs = options.retryDelaysMs ?? DEFAULT_FILE_SYSTEM_RETRY_DELAYS_MS;
|
|
37
|
+
const wait = options.wait ?? waitForFileSystemRetry;
|
|
38
|
+
for (let attempt = 0; ; attempt++) {
|
|
39
|
+
try {
|
|
40
|
+
return operation();
|
|
41
|
+
} catch (error) {
|
|
42
|
+
const delayMs = retryDelaysMs[attempt];
|
|
43
|
+
if (delayMs === undefined || !isRetryableFileSystemError(error)) throw error;
|
|
44
|
+
wait(delayMs);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import * as path from "node:path";
|
|
4
|
+
import { SessionManager } from "@earendil-works/pi-coding-agent";
|
|
5
|
+
import { findModelInfo, type ModelInfo } from "./model-info.ts";
|
|
6
|
+
|
|
7
|
+
type SubagentExecutionContext = "fresh" | "fork";
|
|
8
|
+
|
|
9
|
+
interface BranchSessionEntry {
|
|
10
|
+
type: string;
|
|
11
|
+
id?: string;
|
|
12
|
+
parentId?: string | null;
|
|
13
|
+
timestamp?: string;
|
|
14
|
+
message?: {
|
|
15
|
+
role?: string;
|
|
16
|
+
content?: unknown;
|
|
17
|
+
provider?: string;
|
|
18
|
+
api?: string;
|
|
19
|
+
model?: string;
|
|
20
|
+
};
|
|
21
|
+
thinkingLevel?: string;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface BranchSessionManager {
|
|
25
|
+
createBranchedSession(leafId: string): string | undefined;
|
|
26
|
+
getHeader?: () => BranchSessionEntry | null;
|
|
27
|
+
getEntries?: () => BranchSessionEntry[];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
interface ForkableSessionManager {
|
|
31
|
+
getSessionFile(): string | undefined;
|
|
32
|
+
getLeafId(): string | null;
|
|
33
|
+
getSessionDir?(): string;
|
|
34
|
+
openSession?: (path: string, sessionDir?: string) => BranchSessionManager;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
interface ForkContextResolverOptions {
|
|
38
|
+
openSession?: (path: string, sessionDir?: string) => BranchSessionManager;
|
|
39
|
+
/** Decide per child index whether a sanitized transcript must also disable the child's
|
|
40
|
+
* thinking. Defaults to true (the pre-existing conservative behavior) when omitted. */
|
|
41
|
+
forceThinkingOffForIndex?: (index: number) => boolean;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
interface ForkContextResolution {
|
|
45
|
+
sessionFile: string;
|
|
46
|
+
thinkingOverride?: "off";
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
interface ForkContextResolver {
|
|
50
|
+
sessionFileForIndex(index?: number): string | undefined;
|
|
51
|
+
thinkingOverrideForIndex(index?: number): "off" | undefined;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function resolveSubagentContext(value: unknown): SubagentExecutionContext {
|
|
55
|
+
return value === "fork" ? "fork" : "fresh";
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Decide whether a resolved child model uses Anthropic's provider or message API, which
|
|
59
|
+
* requires the sanitized fork to disable thinking. Unknown models stay conservative. */
|
|
60
|
+
export function forkedChildRequiresThinkingOff(
|
|
61
|
+
model: string | undefined,
|
|
62
|
+
availableModels?: ModelInfo[],
|
|
63
|
+
preferredProvider?: string,
|
|
64
|
+
): boolean {
|
|
65
|
+
if (!model) return true;
|
|
66
|
+
const info = findModelInfo(model, availableModels, preferredProvider);
|
|
67
|
+
if (!info) return true;
|
|
68
|
+
return info.provider.toLowerCase() === "anthropic"
|
|
69
|
+
|| info.api?.toLowerCase() === "anthropic-messages";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function isUnsafeAnthropicThinkingBlock(message: BranchSessionEntry["message"], block: unknown): boolean {
|
|
73
|
+
if (!message || !block || typeof block !== "object" || !("type" in block)) return false;
|
|
74
|
+
const provider = typeof message.provider === "string" ? message.provider.toLowerCase() : "";
|
|
75
|
+
const api = typeof message.api === "string" ? message.api.toLowerCase() : "";
|
|
76
|
+
const model = typeof message.model === "string" ? message.model.toLowerCase() : "";
|
|
77
|
+
const isAnthropic = provider === "anthropic" || api === "anthropic-messages" || model.startsWith("anthropic/");
|
|
78
|
+
if (block.type === "redacted_thinking") return true;
|
|
79
|
+
if (block.type !== "thinking" || !isAnthropic) return false;
|
|
80
|
+
const record = block as Record<string, unknown>;
|
|
81
|
+
const signature = "thinkingSignature" in record ? record.thinkingSignature : "signature" in record ? record.signature : undefined;
|
|
82
|
+
return record.redacted === true || (typeof signature === "string" && signature.length > 0);
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
function createEntryId(entries: BranchSessionEntry[]): string {
|
|
86
|
+
const ids = new Set(entries.map((entry) => entry.id).filter((id): id is string => typeof id === "string"));
|
|
87
|
+
for (let attempt = 0; attempt < 100; attempt++) {
|
|
88
|
+
const id = randomUUID().slice(0, 8);
|
|
89
|
+
if (!ids.has(id)) return id;
|
|
90
|
+
}
|
|
91
|
+
return randomUUID();
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function appendThinkingOffEntry(entries: BranchSessionEntry[]): void {
|
|
95
|
+
const last = entries[entries.length - 1];
|
|
96
|
+
if (last?.type === "thinking_level_change" && last.thinkingLevel === "off") return;
|
|
97
|
+
const parent = [...entries].reverse().find((entry) => typeof entry.id === "string");
|
|
98
|
+
entries.push({
|
|
99
|
+
type: "thinking_level_change",
|
|
100
|
+
id: createEntryId(entries),
|
|
101
|
+
parentId: parent?.id ?? null,
|
|
102
|
+
timestamp: new Date().toISOString(),
|
|
103
|
+
thinkingLevel: "off",
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function sanitizeUnsafeThinkingBlocks(entries: BranchSessionEntry[]): boolean {
|
|
108
|
+
let sanitized = false;
|
|
109
|
+
for (const entry of entries) {
|
|
110
|
+
if (entry.type !== "message" || entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
|
|
111
|
+
const filtered = entry.message.content.filter((block) => !isUnsafeAnthropicThinkingBlock(entry.message, block));
|
|
112
|
+
if (filtered.length === entry.message.content.length) continue;
|
|
113
|
+
entry.message.content = filtered;
|
|
114
|
+
sanitized = true;
|
|
115
|
+
}
|
|
116
|
+
return sanitized;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function readSessionEntries(sessionFile: string): BranchSessionEntry[] {
|
|
120
|
+
const lines = fs.readFileSync(sessionFile, "utf-8").split("\n").filter((line) => line.trim().length > 0);
|
|
121
|
+
return lines.map((line, index) => {
|
|
122
|
+
try {
|
|
123
|
+
return JSON.parse(line) as BranchSessionEntry;
|
|
124
|
+
} catch (error) {
|
|
125
|
+
const cause = error instanceof Error ? error : new Error(String(error));
|
|
126
|
+
throw new Error(`Unable to inspect forked session ${sessionFile}: invalid JSONL on line ${index + 1}: ${cause.message}`, { cause });
|
|
127
|
+
}
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
export function createForkContextResolver(
|
|
132
|
+
sessionManager: ForkableSessionManager,
|
|
133
|
+
requestedContext: unknown,
|
|
134
|
+
options: ForkContextResolverOptions = {},
|
|
135
|
+
): ForkContextResolver {
|
|
136
|
+
if (resolveSubagentContext(requestedContext) !== "fork") {
|
|
137
|
+
return {
|
|
138
|
+
sessionFileForIndex: () => undefined,
|
|
139
|
+
thinkingOverrideForIndex: () => undefined,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
const parentSessionFile = sessionManager.getSessionFile();
|
|
144
|
+
if (!parentSessionFile) {
|
|
145
|
+
throw new Error("Forked subagent context requires a persisted parent session.");
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const leafId = sessionManager.getLeafId();
|
|
149
|
+
if (!leafId) {
|
|
150
|
+
throw new Error("Forked subagent context requires a current leaf to fork from.");
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
const openSession = options.openSession
|
|
154
|
+
?? sessionManager.openSession
|
|
155
|
+
?? ((file: string, dir?: string) => SessionManager.open(file, dir));
|
|
156
|
+
const sessionDir = sessionManager.getSessionDir?.();
|
|
157
|
+
const cachedResolutions = new Map<number, ForkContextResolution>();
|
|
158
|
+
|
|
159
|
+
const resolveFork = (index = 0): ForkContextResolution => {
|
|
160
|
+
const cached = cachedResolutions.get(index);
|
|
161
|
+
if (cached) return cached;
|
|
162
|
+
try {
|
|
163
|
+
if (!fs.existsSync(parentSessionFile)) {
|
|
164
|
+
throw new Error(`Parent session file does not exist: ${parentSessionFile}. Pi has not persisted enough history to fork yet.`);
|
|
165
|
+
}
|
|
166
|
+
const sourceManager = openSession(parentSessionFile, sessionDir);
|
|
167
|
+
const sessionFile = sourceManager.createBranchedSession(leafId);
|
|
168
|
+
if (!sessionFile) {
|
|
169
|
+
throw new Error("Session manager did not return a forked session file.");
|
|
170
|
+
}
|
|
171
|
+
const forceThinkingOff = (sanitized: boolean): boolean =>
|
|
172
|
+
sanitized && (options.forceThinkingOffForIndex?.(index) ?? true);
|
|
173
|
+
let thinkingOverride: "off" | undefined;
|
|
174
|
+
if (!fs.existsSync(sessionFile)) {
|
|
175
|
+
const header = sourceManager.getHeader?.();
|
|
176
|
+
const entries = sourceManager.getEntries?.();
|
|
177
|
+
if (!header || !entries) {
|
|
178
|
+
throw new Error(`Session manager returned a forked session file that does not exist and cannot be persisted by fallback: ${sessionFile}`);
|
|
179
|
+
}
|
|
180
|
+
if (forceThinkingOff(sanitizeUnsafeThinkingBlocks(entries))) {
|
|
181
|
+
appendThinkingOffEntry(entries);
|
|
182
|
+
thinkingOverride = "off";
|
|
183
|
+
}
|
|
184
|
+
fs.mkdirSync(path.dirname(sessionFile), { recursive: true });
|
|
185
|
+
fs.writeFileSync(sessionFile, `${[header, ...entries].map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
|
|
186
|
+
} else {
|
|
187
|
+
const entries = readSessionEntries(sessionFile);
|
|
188
|
+
if (sanitizeUnsafeThinkingBlocks(entries)) {
|
|
189
|
+
if (forceThinkingOff(true)) {
|
|
190
|
+
appendThinkingOffEntry(entries);
|
|
191
|
+
thinkingOverride = "off";
|
|
192
|
+
}
|
|
193
|
+
fs.writeFileSync(sessionFile, `${entries.map((entry) => JSON.stringify(entry)).join("\n")}\n`, "utf-8");
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
const resolution = { sessionFile, ...(thinkingOverride ? { thinkingOverride } : {}) };
|
|
197
|
+
cachedResolutions.set(index, resolution);
|
|
198
|
+
return resolution;
|
|
199
|
+
} catch (error) {
|
|
200
|
+
const cause = error instanceof Error ? error : new Error(String(error));
|
|
201
|
+
throw new Error(`Failed to create forked subagent session: ${cause.message}`, { cause });
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
|
|
205
|
+
return {
|
|
206
|
+
sessionFileForIndex(index = 0): string | undefined {
|
|
207
|
+
return resolveFork(index).sessionFile;
|
|
208
|
+
},
|
|
209
|
+
thinkingOverrideForIndex(index = 0): "off" | undefined {
|
|
210
|
+
return resolveFork(index).thinkingOverride;
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Formatting utilities for display output
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import * as fs from "node:fs";
|
|
6
|
+
import * as path from "node:path";
|
|
7
|
+
import type { Usage, SingleResult } from "./types.ts";
|
|
8
|
+
import type { ChainStep } from "./settings.ts";
|
|
9
|
+
import { isDynamicParallelStep, isParallelStep } from "./settings.ts";
|
|
10
|
+
import { splitKnownThinkingSuffix, THINKING_LEVELS } from "./model-info.ts";
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Format token count with k suffix for large numbers
|
|
14
|
+
*/
|
|
15
|
+
export function formatTokens(n: number): string {
|
|
16
|
+
return n < 1000 ? String(n) : n < 10000 ? `${(n / 1000).toFixed(1)}k` : `${Math.round(n / 1000)}k`;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function formatModelThinking(model?: string, thinking?: string): string {
|
|
20
|
+
const parsed = model ? splitKnownThinkingSuffix(model) : undefined;
|
|
21
|
+
let displayModel = parsed?.baseModel ?? model;
|
|
22
|
+
const explicitThinking = THINKING_LEVELS.find((level) => level === thinking?.trim());
|
|
23
|
+
const displayThinking = parsed?.thinkingSuffix ? parsed.thinkingSuffix.slice(1) : explicitThinking;
|
|
24
|
+
if (displayModel) {
|
|
25
|
+
const slashIdx = displayModel.lastIndexOf("/");
|
|
26
|
+
if (slashIdx !== -1) displayModel = displayModel.slice(slashIdx + 1);
|
|
27
|
+
}
|
|
28
|
+
return [displayModel, displayThinking ? `thinking ${displayThinking}` : undefined].filter(Boolean).join(" · ");
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Format usage statistics into a compact string
|
|
33
|
+
*/
|
|
34
|
+
export function formatUsage(u: Usage, model?: string): string {
|
|
35
|
+
const parts: string[] = [];
|
|
36
|
+
if (u.turns) parts.push(`${u.turns} turn${u.turns > 1 ? "s" : ""}`);
|
|
37
|
+
if (u.input) parts.push(`in:${formatTokens(u.input)}`);
|
|
38
|
+
if (u.output) parts.push(`out:${formatTokens(u.output)}`);
|
|
39
|
+
if (u.cacheRead) parts.push(`R${formatTokens(u.cacheRead)}`);
|
|
40
|
+
if (u.cacheWrite) parts.push(`W${formatTokens(u.cacheWrite)}`);
|
|
41
|
+
if (u.cost) parts.push(`$${u.cost.toFixed(4)}`);
|
|
42
|
+
if (model) parts.push(model);
|
|
43
|
+
return parts.join(" ");
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Format duration in human-readable form
|
|
48
|
+
*/
|
|
49
|
+
export function formatDuration(ms: number): string {
|
|
50
|
+
if (ms < 1000) return `${ms}ms`;
|
|
51
|
+
if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
|
|
52
|
+
return `${Math.floor(ms / 60000)}m${Math.floor((ms % 60000) / 1000)}s`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Build a summary string for a completed/failed chain
|
|
57
|
+
*/
|
|
58
|
+
export function buildChainSummary(
|
|
59
|
+
steps: ChainStep[],
|
|
60
|
+
results: SingleResult[],
|
|
61
|
+
chainDir: string,
|
|
62
|
+
status: "completed" | "failed",
|
|
63
|
+
failedStep?: { index: number; error: string },
|
|
64
|
+
): string {
|
|
65
|
+
const stepNames = steps
|
|
66
|
+
.map((step) => (isParallelStep(step) ? `parallel[${step.parallel.length}]` : isDynamicParallelStep(step) ? `expand:${step.parallel.agent}` : step.agent))
|
|
67
|
+
.join(" → ");
|
|
68
|
+
|
|
69
|
+
const totalDuration = results.reduce((sum, r) => sum + (r.progress?.durationMs || 0), 0);
|
|
70
|
+
const durationStr = formatDuration(totalDuration);
|
|
71
|
+
|
|
72
|
+
const progressPath = path.join(chainDir, "progress.md");
|
|
73
|
+
const hasProgress = fs.existsSync(progressPath);
|
|
74
|
+
const allSkills = new Set<string>();
|
|
75
|
+
for (const r of results) {
|
|
76
|
+
if (r.skills) r.skills.forEach((s) => allSkills.add(s));
|
|
77
|
+
}
|
|
78
|
+
const skillsLine = allSkills.size > 0 ? `🔧 Skills: ${[...allSkills].join(", ")}` : "";
|
|
79
|
+
|
|
80
|
+
if (status === "completed") {
|
|
81
|
+
const stepWord = results.length === 1 ? "step" : "steps";
|
|
82
|
+
return `✅ Chain completed: ${stepNames} (${results.length} ${stepWord}, ${durationStr})${skillsLine ? `\n${skillsLine}` : ""}
|
|
83
|
+
|
|
84
|
+
📋 Progress: ${hasProgress ? progressPath : "(none)"}
|
|
85
|
+
📁 Artifacts: ${chainDir}`;
|
|
86
|
+
} else {
|
|
87
|
+
const stepInfo = failedStep ? ` at step ${failedStep.index + 1}` : "";
|
|
88
|
+
const errorInfo = failedStep?.error ? `: ${failedStep.error}` : "";
|
|
89
|
+
return `❌ Chain failed${stepInfo}${errorInfo}${skillsLine ? `\n${skillsLine}` : ""}
|
|
90
|
+
|
|
91
|
+
📋 Progress: ${hasProgress ? progressPath : "(none)"}
|
|
92
|
+
📁 Artifacts: ${chainDir}`;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Format a tool call for display
|
|
98
|
+
*/
|
|
99
|
+
export function formatToolCall(name: string, args: Record<string, unknown>, expanded = false): string {
|
|
100
|
+
switch (name) {
|
|
101
|
+
case "bash": {
|
|
102
|
+
const command = typeof args.command === "string" ? args.command : "";
|
|
103
|
+
const maxLength = expanded ? 240 : 60;
|
|
104
|
+
return `$ ${command.slice(0, maxLength)}${command.length > maxLength ? "..." : ""}`;
|
|
105
|
+
}
|
|
106
|
+
case "read":
|
|
107
|
+
case "write":
|
|
108
|
+
case "edit": {
|
|
109
|
+
const target = typeof args.path === "string"
|
|
110
|
+
? args.path
|
|
111
|
+
: typeof args.file_path === "string"
|
|
112
|
+
? args.file_path
|
|
113
|
+
: "";
|
|
114
|
+
return `${name} ${shortenPath(target)}`;
|
|
115
|
+
}
|
|
116
|
+
default: {
|
|
117
|
+
const s = JSON.stringify(args);
|
|
118
|
+
const maxLength = expanded ? 160 : 40;
|
|
119
|
+
return `${name} ${s.slice(0, maxLength)}${s.length > maxLength ? "..." : ""}`;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Shorten a path by replacing home directory with ~
|
|
126
|
+
*/
|
|
127
|
+
export function shortenPath(p: string): string {
|
|
128
|
+
const home = process.env.HOME;
|
|
129
|
+
if (home && p.startsWith(home)) {
|
|
130
|
+
return `~${p.slice(home.length)}`;
|
|
131
|
+
}
|
|
132
|
+
return p;
|
|
133
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import * as fs from "node:fs";
|
|
2
|
+
|
|
3
|
+
export interface DrainableSource {
|
|
4
|
+
pause(): void;
|
|
5
|
+
resume(): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface JsonlWriteStream {
|
|
9
|
+
write(chunk: string): boolean;
|
|
10
|
+
once(event: "drain", listener: () => void): JsonlWriteStream;
|
|
11
|
+
end(callback?: () => void): void;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const DEFAULT_MAX_JSONL_BYTES = 50 * 1024 * 1024;
|
|
15
|
+
|
|
16
|
+
interface JsonlWriterDeps {
|
|
17
|
+
createWriteStream?: (filePath: string) => JsonlWriteStream;
|
|
18
|
+
maxBytes?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
interface JsonlWriter {
|
|
22
|
+
writeLine(line: string): void;
|
|
23
|
+
close(): Promise<void>;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function createJsonlWriter(
|
|
27
|
+
filePath: string | undefined,
|
|
28
|
+
source: DrainableSource,
|
|
29
|
+
deps: JsonlWriterDeps = {},
|
|
30
|
+
): JsonlWriter {
|
|
31
|
+
if (!filePath) {
|
|
32
|
+
return {
|
|
33
|
+
writeLine() {},
|
|
34
|
+
async close() {},
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const createWriteStream = deps.createWriteStream ?? ((targetPath: string) => fs.createWriteStream(targetPath, { flags: "a" }));
|
|
39
|
+
let stream: JsonlWriteStream | undefined;
|
|
40
|
+
try {
|
|
41
|
+
stream = createWriteStream(filePath);
|
|
42
|
+
} catch {
|
|
43
|
+
return {
|
|
44
|
+
writeLine() {},
|
|
45
|
+
async close() {},
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let backpressured = false;
|
|
50
|
+
let closed = false;
|
|
51
|
+
let bytesWritten = 0;
|
|
52
|
+
const maxBytes = deps.maxBytes ?? DEFAULT_MAX_JSONL_BYTES;
|
|
53
|
+
|
|
54
|
+
return {
|
|
55
|
+
writeLine(line: string) {
|
|
56
|
+
if (!stream || closed || !line.trim()) return;
|
|
57
|
+
const chunk = `${line}\n`;
|
|
58
|
+
const chunkBytes = Buffer.byteLength(chunk, "utf-8");
|
|
59
|
+
if (bytesWritten + chunkBytes > maxBytes) return;
|
|
60
|
+
try {
|
|
61
|
+
const ok = stream.write(chunk);
|
|
62
|
+
bytesWritten += chunkBytes;
|
|
63
|
+
if (!ok && !backpressured) {
|
|
64
|
+
backpressured = true;
|
|
65
|
+
source.pause();
|
|
66
|
+
stream.once("drain", () => {
|
|
67
|
+
backpressured = false;
|
|
68
|
+
if (!closed) source.resume();
|
|
69
|
+
});
|
|
70
|
+
}
|
|
71
|
+
} catch {}
|
|
72
|
+
},
|
|
73
|
+
async close() {
|
|
74
|
+
if (!stream || closed) return;
|
|
75
|
+
closed = true;
|
|
76
|
+
const current = stream;
|
|
77
|
+
stream = undefined;
|
|
78
|
+
await new Promise<void>((resolve) => current.end(() => resolve()));
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import * as fs from "node:fs";
|
|
3
|
+
import type { AgentConfig } from "../agents/agents.ts";
|
|
4
|
+
|
|
5
|
+
export const AGENT_DEFINITION_PROJECTION_VERSION = 1 as const;
|
|
6
|
+
export const LAUNCH_BINDING_PROJECTION_VERSION = 1 as const;
|
|
7
|
+
|
|
8
|
+
function stableJson(value: unknown): string {
|
|
9
|
+
if (Array.isArray(value)) return `[${value.map(stableJson).join(",")}]`;
|
|
10
|
+
if (value && typeof value === "object") {
|
|
11
|
+
return `{${Object.entries(value as Record<string, unknown>)
|
|
12
|
+
.filter(([, entry]) => entry !== undefined)
|
|
13
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
14
|
+
.map(([key, entry]) => `${JSON.stringify(key)}:${stableJson(entry)}`)
|
|
15
|
+
.join(",")}}`;
|
|
16
|
+
}
|
|
17
|
+
return JSON.stringify(value);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function sha256(value: unknown): string {
|
|
21
|
+
return createHash("sha256").update(stableJson(value)).digest("hex");
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function fileDigest(filePath: string): string | undefined {
|
|
25
|
+
try {
|
|
26
|
+
return createHash("sha256").update(fs.readFileSync(filePath)).digest("hex");
|
|
27
|
+
} catch {
|
|
28
|
+
return undefined;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Public-safe, deterministic evidence for the parsed launch-affecting agent definition. */
|
|
33
|
+
export function projectAgentDefinition(agent: AgentConfig): Record<string, unknown> {
|
|
34
|
+
return {
|
|
35
|
+
version: AGENT_DEFINITION_PROJECTION_VERSION,
|
|
36
|
+
name: agent.name,
|
|
37
|
+
localName: agent.localName,
|
|
38
|
+
packageName: agent.packageName,
|
|
39
|
+
filePath: agent.filePath,
|
|
40
|
+
fileContentDigest: fileDigest(agent.filePath),
|
|
41
|
+
runner: agent.runner,
|
|
42
|
+
systemPrompt: agent.systemPrompt,
|
|
43
|
+
systemPromptMode: agent.systemPromptMode,
|
|
44
|
+
inheritProjectContext: agent.inheritProjectContext,
|
|
45
|
+
inheritSkills: agent.inheritSkills,
|
|
46
|
+
model: agent.model,
|
|
47
|
+
fallbackModels: agent.fallbackModels,
|
|
48
|
+
thinking: agent.thinking,
|
|
49
|
+
tools: agent.tools,
|
|
50
|
+
mcpDirectTools: agent.mcpDirectTools,
|
|
51
|
+
extensions: agent.extensions,
|
|
52
|
+
subagentOnlyExtensions: agent.subagentOnlyExtensions,
|
|
53
|
+
skills: agent.skills,
|
|
54
|
+
skillPath: agent.skillPath,
|
|
55
|
+
output: agent.output,
|
|
56
|
+
defaultReads: agent.defaultReads,
|
|
57
|
+
defaultProgress: agent.defaultProgress,
|
|
58
|
+
defaultContext: agent.defaultContext,
|
|
59
|
+
defaultAsync: agent.defaultAsync,
|
|
60
|
+
defaultTimeoutMs: agent.defaultTimeoutMs,
|
|
61
|
+
defaultTurnBudget: agent.defaultTurnBudget,
|
|
62
|
+
defaultAcceptance: agent.defaultAcceptance,
|
|
63
|
+
acceptanceRole: agent.acceptanceRole,
|
|
64
|
+
interactive: agent.interactive,
|
|
65
|
+
maxSubagentDepth: agent.maxSubagentDepth,
|
|
66
|
+
completionGuard: agent.completionGuard,
|
|
67
|
+
toolBudget: agent.toolBudget,
|
|
68
|
+
memory: agent.memory,
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function agentDefinitionDigest(agent: AgentConfig): string {
|
|
73
|
+
return sha256(projectAgentDefinition(agent));
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface LaunchBindingInput {
|
|
77
|
+
definitionDigest: string;
|
|
78
|
+
/** Caller task; runtime acceptance/output task annotations are explicitly outside the preflight-known subset. */
|
|
79
|
+
task?: string;
|
|
80
|
+
model?: string;
|
|
81
|
+
modelCandidates?: string[];
|
|
82
|
+
thinking?: string;
|
|
83
|
+
systemPrompt?: string | null;
|
|
84
|
+
systemPromptMode?: AgentConfig["systemPromptMode"];
|
|
85
|
+
inheritProjectContext: boolean;
|
|
86
|
+
inheritSkills: boolean;
|
|
87
|
+
skills?: string[];
|
|
88
|
+
tools?: string[];
|
|
89
|
+
extensions?: string[];
|
|
90
|
+
subagentOnlyExtensions?: string[];
|
|
91
|
+
mcpDirectTools?: string[];
|
|
92
|
+
outputPath?: string;
|
|
93
|
+
outputMode?: string;
|
|
94
|
+
structuredOutputSchema?: unknown;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Canonical projection of the resolved inputs handed to the child. */
|
|
98
|
+
export function projectLaunchBinding(input: LaunchBindingInput): Record<string, unknown> {
|
|
99
|
+
return {
|
|
100
|
+
version: LAUNCH_BINDING_PROJECTION_VERSION,
|
|
101
|
+
definitionDigest: input.definitionDigest,
|
|
102
|
+
taskDigest: input.task === undefined ? undefined : sha256(input.task),
|
|
103
|
+
// The ordered candidate set already contains each attempted model; keeping only
|
|
104
|
+
// this set makes retries correlate to the same preflight binding.
|
|
105
|
+
modelCandidates: input.modelCandidates,
|
|
106
|
+
thinking: input.thinking,
|
|
107
|
+
systemPromptDigest: input.systemPrompt === undefined || input.systemPrompt === null ? undefined : sha256(input.systemPrompt),
|
|
108
|
+
systemPromptMode: input.systemPromptMode,
|
|
109
|
+
inheritProjectContext: input.inheritProjectContext,
|
|
110
|
+
inheritSkills: input.inheritSkills,
|
|
111
|
+
skills: input.skills,
|
|
112
|
+
tools: input.tools,
|
|
113
|
+
extensions: input.extensions,
|
|
114
|
+
subagentOnlyExtensions: input.subagentOnlyExtensions,
|
|
115
|
+
mcpDirectTools: input.mcpDirectTools,
|
|
116
|
+
outputPath: input.outputPath,
|
|
117
|
+
outputMode: input.outputMode,
|
|
118
|
+
structuredOutputSchema: input.structuredOutputSchema,
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function launchBindingDigest(input: LaunchBindingInput): string {
|
|
123
|
+
return sha256(projectLaunchBinding(input));
|
|
124
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
|
|
2
|
+
export type ThinkingLevel = typeof THINKING_LEVELS[number];
|
|
3
|
+
export type ThinkingLevelMap = Partial<Record<ThinkingLevel, string | null>>;
|
|
4
|
+
|
|
5
|
+
export interface ModelInfo {
|
|
6
|
+
provider: string;
|
|
7
|
+
id: string;
|
|
8
|
+
fullId: string;
|
|
9
|
+
api?: string;
|
|
10
|
+
reasoning?: boolean;
|
|
11
|
+
thinkingLevelMap?: ThinkingLevelMap;
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
interface RegistryModelLike {
|
|
15
|
+
provider: string;
|
|
16
|
+
id: string;
|
|
17
|
+
api?: string;
|
|
18
|
+
reasoning?: boolean;
|
|
19
|
+
thinkingLevelMap?: ThinkingLevelMap;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function toModelInfo(model: RegistryModelLike): ModelInfo {
|
|
23
|
+
return {
|
|
24
|
+
provider: model.provider,
|
|
25
|
+
id: model.id,
|
|
26
|
+
fullId: `${model.provider}/${model.id}`,
|
|
27
|
+
api: model.api,
|
|
28
|
+
reasoning: model.reasoning,
|
|
29
|
+
thinkingLevelMap: model.thinkingLevelMap,
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Resolve the effective thinking level from a model string (which may contain a known suffix like `:high`)
|
|
34
|
+
* and an explicit thinking config value. Returns `undefined` when no thinking is applicable
|
|
35
|
+
* (e.g. no model was specified, or the model has no suffix and no config was provided). */
|
|
36
|
+
export function resolveEffectiveThinking(model: string | undefined, configThinking: string | false | undefined): string | undefined {
|
|
37
|
+
if (!model) return undefined;
|
|
38
|
+
const { thinkingSuffix } = splitKnownThinkingSuffix(model);
|
|
39
|
+
if (thinkingSuffix) return thinkingSuffix.slice(1);
|
|
40
|
+
return THINKING_LEVELS.find((level) => level === configThinking);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function splitKnownThinkingSuffix(model: string): { baseModel: string; thinkingSuffix: string } {
|
|
44
|
+
const colonIdx = model.lastIndexOf(":");
|
|
45
|
+
if (colonIdx === -1) return { baseModel: model, thinkingSuffix: "" };
|
|
46
|
+
const suffix = THINKING_LEVELS.find((level) => level === model.substring(colonIdx + 1));
|
|
47
|
+
if (!suffix) return { baseModel: model, thinkingSuffix: "" };
|
|
48
|
+
return {
|
|
49
|
+
baseModel: model.substring(0, colonIdx),
|
|
50
|
+
thinkingSuffix: `:${suffix}`,
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function findModelInfo(model: string | undefined, availableModels: ModelInfo[] | undefined, preferredProvider?: string): ModelInfo | undefined {
|
|
55
|
+
if (!model || !availableModels || availableModels.length === 0) return undefined;
|
|
56
|
+
const { baseModel } = splitKnownThinkingSuffix(model);
|
|
57
|
+
const exact = availableModels.find((entry) => entry.fullId === baseModel);
|
|
58
|
+
if (exact) return exact;
|
|
59
|
+
|
|
60
|
+
const matches = availableModels.filter((entry) => entry.id === baseModel);
|
|
61
|
+
if (preferredProvider) {
|
|
62
|
+
const preferred = matches.find((entry) => entry.provider === preferredProvider);
|
|
63
|
+
if (preferred) return preferred;
|
|
64
|
+
}
|
|
65
|
+
return matches.length === 1 ? matches[0] : undefined;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export function getSupportedThinkingLevels(model: ModelInfo | undefined): ThinkingLevel[] {
|
|
69
|
+
if (!model) return THINKING_LEVELS.filter((level) => level !== "max");
|
|
70
|
+
if (model.reasoning === false) return ["off"];
|
|
71
|
+
|
|
72
|
+
if (!model.thinkingLevelMap) return THINKING_LEVELS.filter((level) => level !== "max");
|
|
73
|
+
|
|
74
|
+
const levels = THINKING_LEVELS.filter((level) => {
|
|
75
|
+
const mapped = model.thinkingLevelMap?.[level];
|
|
76
|
+
if (mapped === null) return false;
|
|
77
|
+
if (level === "xhigh" || level === "max") return mapped !== undefined;
|
|
78
|
+
return true;
|
|
79
|
+
});
|
|
80
|
+
return levels;
|
|
81
|
+
}
|