@bastani/atomic 0.9.10 → 0.9.11-alpha.1
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 +14 -0
- package/dist/builtin/cursor/CHANGELOG.md +6 -0
- package/dist/builtin/cursor/package.json +2 -2
- package/dist/builtin/intercom/CHANGELOG.md +6 -0
- package/dist/builtin/intercom/package.json +2 -2
- package/dist/builtin/mcp/CHANGELOG.md +6 -0
- package/dist/builtin/mcp/package.json +1 -1
- package/dist/builtin/subagents/CHANGELOG.md +6 -0
- package/dist/builtin/subagents/package.json +1 -1
- package/dist/builtin/web-access/CHANGELOG.md +6 -0
- package/dist/builtin/web-access/package.json +1 -1
- package/dist/builtin/workflows/CHANGELOG.md +17 -0
- package/dist/builtin/workflows/README.md +8 -3
- package/dist/builtin/workflows/builtin/deep-research-codebase.ts +1 -1
- package/dist/builtin/workflows/package.json +1 -1
- package/dist/builtin/workflows/src/durable/backend.ts +2 -2
- package/dist/builtin/workflows/src/durable/dbos-embedded-postgres-root.ts +173 -0
- package/dist/builtin/workflows/src/durable/dbos-embedded-postgres.ts +36 -12
- package/dist/builtin/workflows/src/durable/dbos-lifecycle.ts +9 -3
- package/dist/builtin/workflows/src/durable/factory.ts +35 -6
- package/dist/builtin/workflows/src/durable/local-command.ts +11 -2
- package/dist/builtin/workflows/src/extension/extension-lifecycle.ts +14 -2
- package/dist/builtin/workflows/src/extension/public-types.ts +3 -4
- package/dist/builtin/workflows/src/extension/render-call.ts +4 -0
- package/dist/builtin/workflows/src/extension/render-result.ts +31 -1
- package/dist/builtin/workflows/src/extension/workflow-prompts.ts +5 -2
- package/dist/builtin/workflows/src/extension/workflow-schema.ts +3 -2
- package/dist/builtin/workflows/src/extension/workflow-tool-content.ts +1 -0
- package/dist/builtin/workflows/src/extension/workflow-tool-control.ts +88 -2
- package/dist/builtin/workflows/src/extension/workflow-tool.ts +13 -0
- package/dist/core/agent-session-events.d.ts.map +1 -1
- package/dist/core/agent-session-events.js +2 -1
- package/dist/core/agent-session-events.js.map +1 -1
- package/dist/core/agent-session-retry.d.ts.map +1 -1
- package/dist/core/agent-session-retry.js +7 -0
- package/dist/core/agent-session-retry.js.map +1 -1
- package/dist/core/agent-session-runtime.d.ts +13 -0
- package/dist/core/agent-session-runtime.d.ts.map +1 -1
- package/dist/core/agent-session-runtime.js +12 -0
- package/dist/core/agent-session-runtime.js.map +1 -1
- package/dist/core/atomic-guide-command.d.ts.map +1 -1
- package/dist/core/atomic-guide-command.js +2 -0
- package/dist/core/atomic-guide-command.js.map +1 -1
- package/dist/core/auth-storage-backends.d.ts +4 -0
- package/dist/core/auth-storage-backends.d.ts.map +1 -1
- package/dist/core/auth-storage-backends.js +48 -3
- package/dist/core/auth-storage-backends.js.map +1 -1
- package/dist/core/auth-storage.d.ts.map +1 -1
- package/dist/core/auth-storage.js +27 -11
- package/dist/core/auth-storage.js.map +1 -1
- package/dist/core/codex-errors.d.ts +3 -0
- package/dist/core/codex-errors.d.ts.map +1 -0
- package/dist/core/codex-errors.js +12 -0
- package/dist/core/codex-errors.js.map +1 -0
- package/dist/core/slash-commands.js +1 -1
- package/dist/core/slash-commands.js.map +1 -1
- package/dist/modes/interactive/interactive-auth-routing.d.ts +2 -1
- package/dist/modes/interactive/interactive-auth-routing.d.ts.map +1 -1
- package/dist/modes/interactive/interactive-auth-routing.js +10 -5
- package/dist/modes/interactive/interactive-auth-routing.js.map +1 -1
- package/dist/modes/interactive/interactive-autocomplete.js +12 -2
- package/dist/modes/interactive/interactive-autocomplete.js.map +1 -1
- package/dist/modes/interactive-engine/extension-ui-bridge.d.ts +3 -1
- package/dist/modes/interactive-engine/extension-ui-bridge.d.ts.map +1 -1
- package/dist/modes/interactive-engine/extension-ui-bridge.js +6 -0
- package/dist/modes/interactive-engine/extension-ui-bridge.js.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.d.ts +4 -5
- package/dist/modes/interactive-engine/isolated-runtime.d.ts.map +1 -1
- package/dist/modes/interactive-engine/isolated-runtime.js +14 -24
- package/dist/modes/interactive-engine/isolated-runtime.js.map +1 -1
- package/dist/modes/interactive-engine/remote-model-catalog.d.ts +15 -0
- package/dist/modes/interactive-engine/remote-model-catalog.d.ts.map +1 -0
- package/dist/modes/interactive-engine/remote-model-catalog.js +67 -0
- package/dist/modes/interactive-engine/remote-model-catalog.js.map +1 -0
- package/dist/modes/rpc/rpc-client-api.d.ts +8 -1
- package/dist/modes/rpc/rpc-client-api.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-client-api.js +9 -0
- package/dist/modes/rpc/rpc-client-api.js.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-command-handler.js +30 -0
- package/dist/modes/rpc/rpc-command-handler.js.map +1 -1
- package/dist/modes/rpc/rpc-types.d.ts +67 -7
- package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
- package/dist/modes/rpc/rpc-types.js.map +1 -1
- package/docs/docs.json +9 -1
- package/docs/models/artificial-analysis-index.md +82 -0
- package/docs/models/model-selection.md +63 -0
- package/docs/models/pareto-efficiency.md +64 -0
- package/docs/providers.md +5 -1
- package/docs/quickstart.md +1 -1
- package/docs/rpc.md +27 -0
- package/docs/workflows.md +20 -7
- package/npm-shrinkwrap.json +24 -24
- package/package.json +4 -4
|
@@ -11,16 +11,25 @@ export interface LocalCommandResult {
|
|
|
11
11
|
|
|
12
12
|
const OUTPUT_LIMIT_BYTES = 16_384;
|
|
13
13
|
|
|
14
|
+
export interface LocalCommandOptions {
|
|
15
|
+
readonly env?: Readonly<Record<string, string>>;
|
|
16
|
+
/** POSIX drop-privilege identity for the spawned process (root only). */
|
|
17
|
+
readonly uid?: number;
|
|
18
|
+
readonly gid?: number;
|
|
19
|
+
}
|
|
20
|
+
|
|
14
21
|
export function runLocalCommand(
|
|
15
22
|
command: string,
|
|
16
23
|
args: readonly string[],
|
|
17
|
-
|
|
24
|
+
options?: LocalCommandOptions,
|
|
18
25
|
): Promise<LocalCommandResult> {
|
|
19
26
|
return new Promise((resolve, reject) => {
|
|
20
27
|
const child = spawn(command, [...args], {
|
|
21
28
|
stdio: ["ignore", "pipe", "pipe"],
|
|
22
29
|
windowsHide: true,
|
|
23
|
-
...(env !== undefined ? { env: { ...process.env, ...env } } : {}),
|
|
30
|
+
...(options?.env !== undefined ? { env: { ...process.env, ...options.env } } : {}),
|
|
31
|
+
...(options?.uid !== undefined ? { uid: options.uid } : {}),
|
|
32
|
+
...(options?.gid !== undefined ? { gid: options.gid } : {}),
|
|
24
33
|
});
|
|
25
34
|
let stdout = "";
|
|
26
35
|
let stderr = "";
|
|
@@ -16,10 +16,22 @@ import { shutdownDbos } from "../durable/dbos-lifecycle.js";
|
|
|
16
16
|
|
|
17
17
|
let processShutdownInstalled = false;
|
|
18
18
|
|
|
19
|
+
/**
|
|
20
|
+
* Session dispose and process exit must never crash on durability teardown:
|
|
21
|
+
* a genuine flush/stop failure is diagnostic, not fatal, and an unhandled
|
|
22
|
+
* rejection here turns an otherwise-successful run into a nonzero exit.
|
|
23
|
+
*/
|
|
24
|
+
function shutdownDbosQuietly(): Promise<void> {
|
|
25
|
+
return shutdownDbos().catch((error: unknown) => {
|
|
26
|
+
const detail = error instanceof Error ? error.message : String(error);
|
|
27
|
+
console.error(`atomic-workflows: DBOS durability shutdown failed: ${detail}`);
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
19
31
|
function installDbosProcessShutdown(): void {
|
|
20
32
|
if (processShutdownInstalled) return;
|
|
21
33
|
processShutdownInstalled = true;
|
|
22
|
-
process.once("beforeExit", () =>
|
|
34
|
+
process.once("beforeExit", () => void shutdownDbosQuietly());
|
|
23
35
|
}
|
|
24
36
|
|
|
25
37
|
export interface WorkflowLifecycleRegistrationDeps {
|
|
@@ -123,6 +135,6 @@ export function registerWorkflowLifecycleHandlers(
|
|
|
123
135
|
deps.storeWidgetRef.current = null;
|
|
124
136
|
runtimeState.resetWorkflowDiscoveryForSession();
|
|
125
137
|
runtimeState.setNotificationsActive(false);
|
|
126
|
-
await
|
|
138
|
+
await shutdownDbosQuietly();
|
|
127
139
|
});
|
|
128
140
|
}
|
|
@@ -2,6 +2,7 @@ import type {
|
|
|
2
2
|
CreateAgentSessionOptions,
|
|
3
3
|
DefaultResourceLoaderInheritanceSnapshot,
|
|
4
4
|
} from "@bastani/atomic";
|
|
5
|
+
import type { Api, Model } from "@earendil-works/pi-ai/compat";
|
|
5
6
|
import type { SessionManager } from "../shared/persistence-restore.js";
|
|
6
7
|
import type { StageSessionRuntime } from "../runs/foreground/stage-runner.js";
|
|
7
8
|
import type { RunStatus, StageStatus } from "../shared/store-types.js";
|
|
@@ -58,10 +59,7 @@ export interface PiCommandOptions {
|
|
|
58
59
|
getArgumentCompletions?: (partial: string) => PiArgumentCompletionResult | Promise<PiArgumentCompletionResult>;
|
|
59
60
|
}
|
|
60
61
|
|
|
61
|
-
export
|
|
62
|
-
readonly provider: string;
|
|
63
|
-
readonly id: string;
|
|
64
|
-
}
|
|
62
|
+
export type PiRuntimeModel = Model<Api>;
|
|
65
63
|
|
|
66
64
|
export interface PiRuntimeModelRegistry {
|
|
67
65
|
getAvailable(): PiRuntimeModel[];
|
|
@@ -222,6 +220,7 @@ export interface WorkflowToolArgs {
|
|
|
222
220
|
workflow?: string;
|
|
223
221
|
inputs?: WorkflowInputValues;
|
|
224
222
|
action?:
|
|
223
|
+
| "models"
|
|
225
224
|
| "run"
|
|
226
225
|
| "list"
|
|
227
226
|
| "get"
|
|
@@ -11,6 +11,7 @@ export interface WorkflowToolArgs {
|
|
|
11
11
|
workflow?: string;
|
|
12
12
|
inputs?: WorkflowInputValues;
|
|
13
13
|
action?:
|
|
14
|
+
| "models"
|
|
14
15
|
| "run"
|
|
15
16
|
| "list"
|
|
16
17
|
| "get"
|
|
@@ -106,6 +107,9 @@ export function renderCall(args: WorkflowToolArgs, opts: RenderCallOpts = {}): s
|
|
|
106
107
|
case "get":
|
|
107
108
|
line = name === undefined ? "workflow: get" : `workflow: get ${quoted(name)}`;
|
|
108
109
|
break;
|
|
110
|
+
case "models":
|
|
111
|
+
line = "workflow: list configured models";
|
|
112
|
+
break;
|
|
109
113
|
default:
|
|
110
114
|
line = name === undefined ? `workflow: ${action}` : `workflow: ${action} ${quoted(name)}`;
|
|
111
115
|
break;
|
|
@@ -149,6 +149,14 @@ type ReloadResult = WorkflowReloadReport & { action: "reload"; status: "ok" | "n
|
|
|
149
149
|
type InterruptResult = { action: "interrupt"; runId: string; status: string; message: string };
|
|
150
150
|
type QuitResult = { action: "quit"; runId: string; status: string; message: string };
|
|
151
151
|
type ResumeResult = { action: "resume"; runId: string; status: string; message: string };
|
|
152
|
+
export interface ModelCatalogEntry {
|
|
153
|
+
provider: string;
|
|
154
|
+
id: string;
|
|
155
|
+
fullId: string;
|
|
156
|
+
isCurrent: boolean;
|
|
157
|
+
availableThinkingLevels?: readonly string[];
|
|
158
|
+
}
|
|
159
|
+
type ModelsResult = { action: "models"; models: ModelCatalogEntry[] };
|
|
152
160
|
|
|
153
161
|
export type WorkflowToolResult =
|
|
154
162
|
| ListResult
|
|
@@ -165,7 +173,8 @@ export type WorkflowToolResult =
|
|
|
165
173
|
| ReloadResult
|
|
166
174
|
| InterruptResult
|
|
167
175
|
| QuitResult
|
|
168
|
-
| ResumeResult
|
|
176
|
+
| ResumeResult
|
|
177
|
+
| ModelsResult;
|
|
169
178
|
|
|
170
179
|
export interface RenderResultOpts {
|
|
171
180
|
isPartial?: boolean;
|
|
@@ -432,6 +441,27 @@ export function renderResult(result: WorkflowToolResult, opts?: RenderResultOpts
|
|
|
432
441
|
return renderNotice("WORKFLOW RESUME", `${r.runId}: ${r.message}`, opts, themed);
|
|
433
442
|
}
|
|
434
443
|
|
|
444
|
+
case "models": {
|
|
445
|
+
const r = result as ModelsResult;
|
|
446
|
+
if (r.models.length === 0) {
|
|
447
|
+
return renderNotice("WORKFLOW MODELS", "no models in configured catalog — configured-auth snapshot, not proof of credentials, entitlements, OAuth freshness, or live provider access.", opts, themed);
|
|
448
|
+
}
|
|
449
|
+
const currentLine = r.models.find((model) => model.isCurrent);
|
|
450
|
+
const lines = r.models.map((model) => {
|
|
451
|
+
const levels = model.availableThinkingLevels?.length
|
|
452
|
+
? ` [levels: ${model.availableThinkingLevels.join(", ")}]`
|
|
453
|
+
: "";
|
|
454
|
+
return `${model.provider}/${model.id}${model.isCurrent ? " (current)" : ""}${levels}`;
|
|
455
|
+
}).join("; ");
|
|
456
|
+
const suffix = currentLine !== undefined ? "" : " (no current model)";
|
|
457
|
+
return renderNotice(
|
|
458
|
+
"WORKFLOW MODELS",
|
|
459
|
+
`${lines}${suffix} — configured-auth catalog snapshot, not proof of credentials, entitlements, OAuth freshness, or live provider access.`,
|
|
460
|
+
opts,
|
|
461
|
+
themed,
|
|
462
|
+
);
|
|
463
|
+
}
|
|
464
|
+
|
|
435
465
|
default: {
|
|
436
466
|
// Runtime guard — handles values coerced from external sources.
|
|
437
467
|
const fallback = result as { action: string; message?: string };
|
|
@@ -1,12 +1,14 @@
|
|
|
1
1
|
export const WORKFLOW_TOOL_DESCRIPTION =
|
|
2
2
|
"Run named builtin, project, user, or package workflows; custom definitions may import reusable project/package workflows or builtin definitions from @bastani/workflows/builtin and nest them with ctx.workflow(...), including deeper composition within the configured maxDepth; " +
|
|
3
3
|
"when workflow execution fits but another shape would better achieve the task, author a custom TypeScript workflow({...}) inline with normal coding tools, reload it, and run it; " +
|
|
4
|
-
"discover with list/get/inputs, list session runs with status (no runId; statusFilter narrows the list), inspect status/stages/stage details, " +
|
|
4
|
+
"discover with list/get/inputs/models, list session runs with status (no runId; statusFilter narrows the list), inspect status/stages/stage details, " +
|
|
5
5
|
"send prompt answers or steering, pause/resume/interrupt/quit runs, and reload workflow resources. " +
|
|
6
6
|
"For large stage handoffs, write context to files/artifacts, pass paths via reads, and prompt downstream agents to 'Read the file at <path>...' instead of injecting large previous text. " +
|
|
7
7
|
"For transcripts, prefer status/stages/stage to get sessionFile/transcriptPath, " +
|
|
8
8
|
"quote the exact path without rewriting separators (Windows backslashes are valid), " +
|
|
9
|
-
"then search it with rg/grep and read small ranges; transcript is path-only by default when sessionFile/transcriptPath exists, explicit tail/limit returns bounded previews, and missing transcript paths fall back to a small preview."
|
|
9
|
+
"then search it with rg/grep and read small ranges; transcript is path-only by default when sessionFile/transcriptPath exists, explicit tail/limit returns bounded previews, and missing transcript paths fall back to a small preview. " +
|
|
10
|
+
"Use action 'models' to inspect models in the configured catalog; the result is a configured-auth snapshot showing what's present in the registry with configured authentication, not proof of credentials, entitlements, OAuth freshness, or live provider access. " +
|
|
11
|
+
"When authoring a workflow that should dynamically select a model, first call workflow({ action: 'models' }) to inspect the configured catalog, then select from the returned provider/id entries considering the isCurrent marker and available thinking levels.";
|
|
10
12
|
|
|
11
13
|
export const DEFAULT_PROMPT_GUIDANCE: string[] = [
|
|
12
14
|
`**Workflows**: Treat workflows as the default execution path for any non-trivial task and for any request that has inherent structure plus an objective you can make verifiable. Use the \`workflow\` tool for existing named workflows; when the task needs a graph that is not installed, author a custom TypeScript \`workflow({...})\` inline with normal coding tools, reload workflow resources, and run it.
|
|
@@ -30,6 +32,7 @@ export const DEFAULT_PROMPT_GUIDANCE: string[] = [
|
|
|
30
32
|
- When a user asks to create or edit a workflow, clarify only unresolved requirements that materially affect its purpose, inputs, stages, handoffs, validation, success criteria, or starter pattern. Read the workflow docs/examples, implement the TypeScript definition with normal coding tools, reload it, and run representative test inputs before presenting it. Use the create-spec skill when it adds value; it is not mandatory when context is already sufficient.
|
|
31
33
|
- Consult docs/workflows.md and its starter patterns (Classify-and-act, Fan-out-and-synthesize, Adversarial verification, Generate-and-filter, Tournament, and Loop until done) when designing a stage graph.
|
|
32
34
|
- Treat workflow composition as a first-class authoring option. Before duplicating stages, inspect reusable workflow modules and builtin exports; import their definitions and invoke them with \`ctx.workflow(...)\`, mapping typed inputs and consuming only declared outputs. Nested workflows can themselves import children, so combine small reusable graphs into a richer parent while respecting \`maxDepth\`.
|
|
35
|
+
- Prefer \`ctx.tool(name, args, fn)\` for workflow-owned TypeScript operations with side effects, such as filesystem writes, network mutations, and external API actions. A completed \`ctx.tool\` call is durably checkpointed with its serializable result, so resume replays that result without rerunning \`fn\`. Keep pure computation and side-effect-free transformations as ordinary TypeScript. Do not wrap agent-stage internals or every function call indiscriminately; this rule applies to side effects orchestrated directly by the workflow definition.
|
|
33
36
|
- Pass large stage context through files/artifacts and \`reads\` with an explicit \`Read the file at <path>...\` prompt rather than large \`previous\` payloads or injected session history.
|
|
34
37
|
- Separate implementation/review acceptance from explicitly authorized final actions such as PR/MR/review creation, release tagging, deployment, or publication. Stop implementation loops once acceptance is proven and carry a remaining final action separately.
|
|
35
38
|
- A model stage sees its local prompt, artifacts, tools, and reads, not the graph name or surrounding implementation. State the concrete action, evidence, and success criteria directly.`,
|
|
@@ -9,6 +9,7 @@ export const WorkflowParametersSchema = Type.Object({
|
|
|
9
9
|
description: "Key/value inputs passed to a named workflow run.",
|
|
10
10
|
})),
|
|
11
11
|
action: Type.Optional(Type.Union([
|
|
12
|
+
Type.Literal("models"),
|
|
12
13
|
Type.Literal("run"),
|
|
13
14
|
Type.Literal("list"),
|
|
14
15
|
Type.Literal("get"),
|
|
@@ -24,7 +25,7 @@ export const WorkflowParametersSchema = Type.Object({
|
|
|
24
25
|
Type.Literal("resume"),
|
|
25
26
|
Type.Literal("reload"),
|
|
26
27
|
], {
|
|
27
|
-
description: "Workflow action: run/list/get/inputs/status, inspect stage metadata, send messages or prompt answers, pause/resume/interrupt/quit runs, or reload workflow resources. 'status' without runId lists every workflow run in the current session with concise per-run summaries (status, timing, active stages, awaiting-input prompts); filter the listing with statusFilter. 'status' with runId returns one run's full detail. For transcript inspection, prefer status/stages/stage first to get sessionFile/transcriptPath, quote the exact path without rewriting separators (Windows backslashes are valid), then search it with rg/grep and read small ranges; transcript is path-only by default when sessionFile/transcriptPath exists, explicit tail/limit returns bounded previews, and missing transcript paths fall back to a small preview.",
|
|
28
|
+
description: "Workflow action: run/list/get/inputs/models/status, inspect stage metadata, send messages or prompt answers, pause/resume/interrupt/quit runs, inspect the configured model catalog, or reload workflow resources. 'status' without runId lists every workflow run in the current session with concise per-run summaries (status, timing, active stages, awaiting-input prompts); filter the listing with statusFilter. 'status' with runId returns one run's full detail. For transcript inspection, prefer status/stages/stage first to get sessionFile/transcriptPath, quote the exact path without rewriting separators (Windows backslashes are valid), then search it with rg/grep and read small ranges; transcript is path-only by default when sessionFile/transcriptPath exists, explicit tail/limit returns bounded previews, and missing transcript paths fall back to a small preview.",
|
|
28
29
|
})),
|
|
29
30
|
runId: Type.Optional(Type.String({
|
|
30
31
|
description: "Run identifier or unique prefix for status/stages/stage/transcript/send/pause/resume/interrupt/quit. Omit runId with action 'status' to list all session runs and their statuses. Use '--all' or all:true for supported bulk run-control actions.",
|
|
@@ -54,7 +55,7 @@ export const WorkflowParametersSchema = Type.Object({
|
|
|
54
55
|
description: "Filter stages (stages action) or listed runs (status action without runId) by status; 'all' (default) includes everything. For the status listing, run statuses match directly, 'awaiting_input' selects runs with at least one stage awaiting input or pending human prompt, and in-flight runs are listed first.",
|
|
55
56
|
})),
|
|
56
57
|
format: Type.Optional(Type.Union([Type.Literal("text"), Type.Literal("json")], {
|
|
57
|
-
description: "Agent-visible output format for data-bearing inspection actions (status, stages, stage, transcript); 'json' returns the full structured result.",
|
|
58
|
+
description: "Agent-visible output format for data-bearing inspection actions (models, status, stages, stage, transcript); 'json' returns the full structured result.",
|
|
58
59
|
})),
|
|
59
60
|
limit: Type.Optional(Type.Integer({
|
|
60
61
|
minimum: 0,
|
|
@@ -9,6 +9,8 @@ import { quitAllRuns, quitRun } from "../runs/background/quit.js";
|
|
|
9
9
|
import { store } from "../shared/store.js";
|
|
10
10
|
import { getDurableBackend } from "../durable/factory.js";
|
|
11
11
|
import type { WorkflowExecutionPolicy } from "../shared/types.js";
|
|
12
|
+
import type { ResumableWorkflowEntry } from "../durable/types.js";
|
|
13
|
+
import type { RunSnapshot } from "../shared/store-types.js";
|
|
12
14
|
import type { ExtensionRuntime } from "./runtime.js";
|
|
13
15
|
import type { WorkflowToolResult } from "./render-result.js";
|
|
14
16
|
import type { WorkflowToolArgs } from "./public-types.js";
|
|
@@ -27,6 +29,7 @@ import {
|
|
|
27
29
|
workflowHasPausedStages,
|
|
28
30
|
workflowHasPausedState,
|
|
29
31
|
} from "../runs/background/workflow-lifecycle-aggregate.js";
|
|
32
|
+
import { resolveWorkflowResumeTarget } from "./workflow-durable-resume-command.js";
|
|
30
33
|
|
|
31
34
|
export interface WorkflowControlActionDeps {
|
|
32
35
|
reloadWorkflowResources: () => Promise<WorkflowReloadReport | void> | void;
|
|
@@ -250,14 +253,97 @@ async function resumeDurableShadow(
|
|
|
250
253
|
};
|
|
251
254
|
}
|
|
252
255
|
|
|
256
|
+
async function resumePreparedDurableTarget(
|
|
257
|
+
runId: string,
|
|
258
|
+
deps: Pick<WorkflowControlActionDeps, "getRuntime" | "policy">,
|
|
259
|
+
): Promise<WorkflowToolResult> {
|
|
260
|
+
try {
|
|
261
|
+
const resumed = await deps.getRuntime().resumeDurableWorkflow(runId, { policy: deps.policy });
|
|
262
|
+
return {
|
|
263
|
+
action: "resume",
|
|
264
|
+
runId: resumed.ok ? resumed.runId : runId,
|
|
265
|
+
status: resumed.ok ? "running" : "noop",
|
|
266
|
+
message: resumed.message,
|
|
267
|
+
};
|
|
268
|
+
} catch (error) {
|
|
269
|
+
return controlFailure("resume", runId, error);
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
async function resolveExplicitDurableTarget(
|
|
273
|
+
target: string,
|
|
274
|
+
args: WorkflowToolArgs,
|
|
275
|
+
deps: Pick<WorkflowControlActionDeps, "getRuntime" | "policy" | "ensureWorkflowResourcesLoaded">,
|
|
276
|
+
liveRuns: readonly RunSnapshot[] = [],
|
|
277
|
+
): Promise<WorkflowToolResult> {
|
|
278
|
+
const runtime = deps.getRuntime();
|
|
279
|
+
let durable: readonly ResumableWorkflowEntry[];
|
|
280
|
+
try {
|
|
281
|
+
await deps.ensureWorkflowResourcesLoaded();
|
|
282
|
+
durable = await runtime.prepareDurableResumable(target);
|
|
283
|
+
} catch (error) {
|
|
284
|
+
return controlFailure("resume", target, error);
|
|
285
|
+
}
|
|
286
|
+
const resolved = resolveWorkflowResumeTarget(target, liveRuns, durable, []);
|
|
287
|
+
if (resolved.kind === "ambiguous") {
|
|
288
|
+
const matches = resolved.matches.map((match) => match.workflowId);
|
|
289
|
+
return {
|
|
290
|
+
action: "resume",
|
|
291
|
+
runId: target,
|
|
292
|
+
status: "noop",
|
|
293
|
+
message: `Ambiguous run prefix "${target}" matches: ${matches.join(", ")}`,
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
if (resolved.kind === "durable") return resumePreparedDurableTarget(resolved.workflowId, deps);
|
|
297
|
+
if (resolved.kind === "live") {
|
|
298
|
+
return workflowResumeAction({ ...args, runId: resolved.workflowId }, deps);
|
|
299
|
+
}
|
|
300
|
+
if (resolved.kind === "completed") {
|
|
301
|
+
return {
|
|
302
|
+
action: "resume",
|
|
303
|
+
runId: resolved.workflowId,
|
|
304
|
+
status: "noop",
|
|
305
|
+
message: `Workflow ${resolved.workflowId} is completed, not resumable.`,
|
|
306
|
+
};
|
|
307
|
+
}
|
|
308
|
+
const durableHandle = getDurableBackend().getWorkflow(target);
|
|
309
|
+
const isZeroProgressCandidate = durableHandle !== undefined
|
|
310
|
+
&& (durableHandle.status === "paused" || durableHandle.status === "running")
|
|
311
|
+
&& durableHandle.completedCheckpoints === 0
|
|
312
|
+
&& durableHandle.pendingPrompts === 0;
|
|
313
|
+
if (isZeroProgressCandidate) {
|
|
314
|
+
return {
|
|
315
|
+
action: "resume",
|
|
316
|
+
runId: target,
|
|
317
|
+
status: "noop",
|
|
318
|
+
message: `Workflow ${target} has no durable checkpoint or pending prompt progress and is not resumable.`,
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
if (durableHandle !== undefined) return resumePreparedDurableTarget(target, deps);
|
|
322
|
+
return { action: "resume", runId: target, status: "noop", message: `Run not found: ${target}` };
|
|
323
|
+
}
|
|
324
|
+
|
|
253
325
|
export async function workflowResumeAction(
|
|
254
326
|
args: WorkflowToolArgs,
|
|
255
327
|
deps: Pick<WorkflowControlActionDeps, "getRuntime" | "policy" | "ensureWorkflowResourcesLoaded">,
|
|
256
328
|
): Promise<WorkflowToolResult> {
|
|
257
329
|
const target = resolveToolRunTarget(args, "No active run to resume.");
|
|
258
330
|
if (target.kind === "all") return { action: "resume", runId: "--all", status: "noop", message: "Resume does not support --all." };
|
|
259
|
-
if (target.kind === "ambiguous")
|
|
260
|
-
|
|
331
|
+
if (target.kind === "ambiguous") {
|
|
332
|
+
const liveMatches = store.runs().filter((run) => target.matches.includes(run.id));
|
|
333
|
+
return resolveExplicitDurableTarget(target.target, args, deps, liveMatches);
|
|
334
|
+
}
|
|
335
|
+
if (target.kind === "not_found") {
|
|
336
|
+
const explicitTarget = args.runId?.trim();
|
|
337
|
+
if (explicitTarget !== undefined && explicitTarget.length > 0) {
|
|
338
|
+
return resolveExplicitDurableTarget(explicitTarget, args, deps);
|
|
339
|
+
}
|
|
340
|
+
return { action: "resume", runId: target.target, status: "noop", message: target.message };
|
|
341
|
+
}
|
|
342
|
+
const explicitTarget = args.runId?.trim();
|
|
343
|
+
if (explicitTarget !== undefined && explicitTarget.length > 0 && explicitTarget !== target.runId) {
|
|
344
|
+
const liveMatches = store.runs().filter((run) => run.id.startsWith(explicitTarget));
|
|
345
|
+
return resolveExplicitDurableTarget(explicitTarget, args, deps, liveMatches);
|
|
346
|
+
}
|
|
261
347
|
const backend = getDurableBackend();
|
|
262
348
|
const exact = store.runs().find((run) => run.id === target.runId);
|
|
263
349
|
const shadow = exact === undefined ? "not_shadow" : classifyDurableResumeShadow(exact, store, { backend });
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { getSupportedThinkingLevels } from "@earendil-works/pi-ai/compat";
|
|
1
2
|
import { inspectRun } from "../runs/background/status.js";
|
|
2
3
|
import type { WorkflowExecutionPolicy } from "../shared/types.js";
|
|
3
4
|
import type { ExtensionRuntime } from "./runtime.js";
|
|
@@ -63,6 +64,18 @@ export function makeExecuteWorkflowTool(
|
|
|
63
64
|
case "get":
|
|
64
65
|
await ensureWorkflowResourcesVisible();
|
|
65
66
|
return workflowGetResult(getRuntime(), args);
|
|
67
|
+
case "models": {
|
|
68
|
+
const available = ctx.modelRegistry?.getAvailable() ?? [];
|
|
69
|
+
const current = ctx.model;
|
|
70
|
+
const models = available.map((m) => ({
|
|
71
|
+
provider: m.provider,
|
|
72
|
+
id: m.id,
|
|
73
|
+
fullId: `${m.provider}/${m.id}`,
|
|
74
|
+
isCurrent: current !== undefined && m.provider === current.provider && m.id === current.id,
|
|
75
|
+
availableThinkingLevels: getSupportedThinkingLevels(m),
|
|
76
|
+
}));
|
|
77
|
+
return { action: "models", models };
|
|
78
|
+
}
|
|
66
79
|
case "list":
|
|
67
80
|
case "inputs": {
|
|
68
81
|
await ensureWorkflowResourcesVisible();
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-events.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-events.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAe,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-events.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-events.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,YAAY,EAAE,MAAM,+BAA+B,CAAC;AAC9E,OAAO,KAAK,EAAE,gBAAgB,EAAE,OAAO,EAAe,MAAM,8BAA8B,CAAC;AAI3F,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC9F,OAAO,EAA0F,KAAK,iBAAi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CAAC,IAAI,EAAE,YAAY,EAAE,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC,IAAI,CAAC,CAuE9F;AAED;;;;GAIG;AAEH,wBAAgB,SAAS,CAAC,IAAI,EAAE,YAAY,EAAE,QAAQ,EAAE,yBAAyB,GAAG,MAAM,IAAI,CAU7F;AAED;;;;GAIG;AAEH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAK7D;AAED;;;GAGG;AAEH,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAG1D;AAED;;;GAGG;AAEH,wBAAgB,OAAO,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAQhD;AAMD,uBAAuB;AAEvB,eAAO,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;CAkBrC,CAAC"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { disposeSessionAsyncJobManager } from "./async/session-manager.js";
|
|
2
2
|
import { cleanupSessionResources } from "@earendil-works/pi-ai/compat";
|
|
3
|
+
import { formatCodexProviderError } from "./codex-errors.js";
|
|
3
4
|
import { formatCopilotProviderError } from "./copilot-errors.js";
|
|
4
5
|
import { customMessageExcludesContext, isSingleGenericAbortTextContent, replacementAbortContent } from "./agent-session-types.js";
|
|
5
6
|
import { normalizeMessageContent } from "./messages.js";
|
|
@@ -194,7 +195,7 @@ export function _applyProviderErrorGuidance(event) {
|
|
|
194
195
|
const assistantMessage = event.message;
|
|
195
196
|
if (assistantMessage.stopReason !== "error" || !assistantMessage.errorMessage)
|
|
196
197
|
return;
|
|
197
|
-
assistantMessage.errorMessage = formatCopilotProviderError(assistantMessage.provider, assistantMessage.errorMessage);
|
|
198
|
+
assistantMessage.errorMessage = formatCodexProviderError(assistantMessage.provider, formatCopilotProviderError(assistantMessage.provider, assistantMessage.errorMessage));
|
|
198
199
|
}
|
|
199
200
|
/** Resolve the pending retry promise */
|
|
200
201
|
export function _resolveRetry() {
|
|
@@ -1 +1 @@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AAoB;IACxD,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC,KAAK,CAAC,SAAS,CAAC,IAAI,CAAC,iBAAiB,CAAC,CAAC;AACvE,CAAC;AAED;;;GAGG;AAEH,MAAM,UAAU,OAAO;IACtB,IAAI,CAAC,gBAAgB,CAAC,UAAU,CAC/B,6WAA6W,CAC7W,CAAC;IACF,6BAA6B,CAAC,IAAI,CAAC,gBAAgB,EAAE,IAAI,CAAC,yBAAyB,CAAC,CAAC;IACrF,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAC5B,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC;IAC1B,uBAAuB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AACzC,CAAC;AAED,4EAA4E;AAC5E,yBAAyB;AACzB,4EAA4E;AAE5E,uBAAuB;AAEvB,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,KAAK;IACL,gBAAgB;IAChB,iBAAiB;IACjB,8BAA8B;IAC9B,4BAA4B;IAC5B,kBAAkB;IAClB,2BAA2B;IAC3B,2BAA2B;IAC3B,aAAa;IACb,mBAAmB;IACnB,yBAAyB;IACzB,sBAAsB;IACtB,mBAAmB;IACnB,SAAS;IACT,oBAAoB;IACpB,iBAAiB;IACjB,OAAO;CACP,CAAC","sourcesContent":["import { disposeSessionAsyncJobManager } from \"./async/session-manager.js\";\nimport type { AgentEvent, AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { cleanupSessionResources } from \"@earendil-works/pi-ai/compat\";\nimport { formatCopilotProviderError } from \"./copilot-errors.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { customMessageExcludesContext, isSingleGenericAbortTextContent, replacementAbortContent, type AgentSessionEvent, type AgentSessionEventListener } from \"./agent-session-types.ts\";\nimport type { MessageEndEvent, MessageStartEvent, MessageUpdateEvent, ToolExecutionEndEvent, ToolExecutionStartEvent, ToolExecutionUpdateEvent, TurnEndEvent, TurnStartEvent } from \"./extensions/index.ts\";\nimport { normalizeMessageContent } from \"./messages.ts\";\n\nexport function _emit(this: AgentSession, event: AgentSessionEvent): void {\n\tfor (const l of this._eventListeners) {\n\t\tl(event);\n\t}\n}\n\n\nexport function _emitQueueUpdate(this: AgentSession): void {\n\tthis._emit({\n\t\ttype: \"queue_update\",\n\t\tsteering: [...this._steeringMessages],\n\t\tfollowUp: [...this._followUpMessages],\n\t});\n}\n\n/** Internal handler for agent events - shared by subscribe and reconnect */\n\nexport function _handleAgentEvent(this: AgentSession, event: AgentEvent): void {\n\t// Create retry promise synchronously before queueing async processing.\n\t// Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()\n\t// as soon as agent.prompt() resolves. If _retryPromise is created only inside\n\t// _processAgentEvent, slow earlier queued events can delay agent_end processing\n\t// and waitForRetry() can miss the in-flight retry.\n\tthis._createRetryPromiseForAgentEnd(event);\n\n\tthis._agentEventQueue = this._agentEventQueue.then(\n\t\t() => this._processAgentEvent(event),\n\t\t() => this._processAgentEvent(event),\n\t);\n\n\t// Keep queue alive if an event handler fails\n\tthis._agentEventQueue.catch(() => {});\n}\n\n\nexport function _createRetryPromiseForAgentEnd(this: AgentSession, event: AgentEvent): void {\n\tif (event.type !== \"agent_end\" || this._retryPromise) {\n\t\treturn;\n\t}\n\n\tconst settings = this.settingsManager.getRetrySettings();\n\tif (!settings.enabled && this._fallbackModels.length === 0) {\n\t\treturn;\n\t}\n\n\tconst lastAssistant = this._findLastAssistantInMessages(event.messages);\n\tif (!lastAssistant) {\n\t\treturn;\n\t}\n\n\tconst shouldRetry = this._isRetryableError(lastAssistant) || this._isEmptyCompletion(lastAssistant) || this._isSafetyRefusal(lastAssistant);\n\tif (!shouldRetry) {\n\t\treturn;\n\t}\n\n\tthis._retryPromise = new Promise((resolve) => {\n\t\tthis._retryResolve = resolve;\n\t});\n}\n\n\nexport function _findLastAssistantInMessages(this: AgentSession, messages: AgentMessage[]): AssistantMessage | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"assistant\") {\n\t\t\treturn message as AssistantMessage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n\nexport async function _processAgentEvent(this: AgentSession, event: AgentEvent): Promise<void> {\n\t// When a user message starts, check if it's from either queue and remove it BEFORE emitting\n\t// This ensures the UI sees the updated queue state\n\tif (event.type === \"message_start\" && event.message.role === \"user\") {\n\t\tthis._overflowRecoveryAttempted = false;\n\t\tthis._fallbackAttemptedKeys.clear();\n\t\tconst messageText = this._getUserMessageText(event.message);\n\t\tif (messageText) {\n\t\t\t// Check steering queue first\n\t\t\tconst steeringIndex = this._steeringMessages.indexOf(messageText);\n\t\t\tif (steeringIndex !== -1) {\n\t\t\t\tthis._steeringMessages.splice(steeringIndex, 1);\n\t\t\t\tthis._emitQueueUpdate();\n\t\t\t} else {\n\t\t\t\t// Check follow-up queue\n\t\t\t\tconst followUpIndex = this._followUpMessages.indexOf(messageText);\n\t\t\t\tif (followUpIndex !== -1) {\n\t\t\t\t\tthis._followUpMessages.splice(followUpIndex, 1);\n\t\t\t\t\tthis._emitQueueUpdate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tthis._applyInterruptAbortMessage(event);\n\tthis._applyProviderErrorGuidance(event);\n\n\t// Emit to extensions first\n\tawait this._emitExtensionEvent(event);\n\n\t// Notify all listeners\n\tthis._emit(event);\n\n\t// Handle session persistence\n\tif (event.type === \"message_end\") {\n\t\t// Check if this is a custom message from extensions\n\t\tif (event.message.role === \"custom\") {\n\t\t\t// Persist as CustomMessageEntry\n\t\t\tthis.sessionManager.appendCustomMessageEntry(\n\t\t\t\tevent.message.customType,\n\t\t\t\tevent.message.content,\n\t\t\t\tevent.message.display,\n\t\t\t\tevent.message.details,\n\t\t\t\tcustomMessageExcludesContext(event.message),\n\t\t\t);\n\t\t} else if (\n\t\t\tevent.message.role === \"user\" ||\n\t\t\tevent.message.role === \"assistant\" ||\n\t\t\tevent.message.role === \"toolResult\"\n\t\t) {\n\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\tthis._normalizePersistedGeminiToolArgs(event.message);\n\t\t\t}\n\t\t\t// Regular LLM message - persist as SessionMessageEntry\n\t\t\tthis.sessionManager.appendMessage(event.message);\n\t\t}\n\t\t// Other message types (bashExecution, branchSummary) are persisted elsewhere\n\n\t\t// Track assistant message for auto-compaction (checked on agent_end)\n\t\tif (event.message.role === \"assistant\") {\n\t\t\tthis._lastAssistantMessage = event.message;\n\n\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\t\t\t// Treat degenerate empty completions (no content, zero output tokens) and\n\t\t\t// intercepted canned safety refusals as failures alongside stopReason ===\n\t\t\t// \"error\". Otherwise such a turn that stops with reason \"stop\"/\"length\"\n\t\t\t// would reset the retry counter on every attempt, causing unbounded\n\t\t\t// retries instead of honoring maxRetries.\n\t\t\tconst assistantFailed = assistantMsg.stopReason === \"error\" || this._isEmptyCompletion(assistantMsg) || this._isSafetyRefusal(assistantMsg);\n\t\t\tif (!assistantFailed) {\n\t\t\t\tthis._fallbackAttemptedKeys.clear();\n\t\t\t\tthis._overflowRecoveryAttempted = false;\n\t\t\t\tthis._outputBudgetErrorContinuationAttempts = 0;\n\t\t\t}\n\n\t\t\t// A non-truncated assistant response means the length-continuation loop\n\t\t\t// made progress (or the turn completed cleanly), so reset the bounded\n\t\t\t// output-cap continuation counter.\n\t\t\tif (assistantMsg.stopReason !== \"length\") {\n\t\t\t\tthis._lengthContinuationAttempts = 0;\n\t\t\t}\n\n\t\t\t// Reset retry counter immediately on successful assistant response\n\t\t\t// This prevents accumulation across multiple LLM calls within a turn\n\t\t\tif (!assistantFailed && this._retryAttempt > 0) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\t});\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check auto-retry and auto-compaction after agent completes\n\tif (event.type === \"agent_end\" && this._lastAssistantMessage) {\n\t\tconst msg = this._lastAssistantMessage;\n\t\tthis._lastAssistantMessage = undefined;\n\t\tconst postToolPreflightFailed =\n\t\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\t\tmsg.errorMessage === this._postToolCompactionPreflightError;\n\n\t\t// Check for retryable errors first (overloaded, rate limit, server errors,\n\t\t// transient provider finish_reason errors, degenerate empty completions,\n\t\t// or intercepted canned safety refusals)\n\t\tconst retryableError = !postToolPreflightFailed && this._isRetryableError(msg);\n\t\tconst emptyCompletion = !postToolPreflightFailed && !retryableError && this._isEmptyCompletion(msg);\n\t\tconst safetyRefusal =\n\t\t\t!postToolPreflightFailed && !retryableError && !emptyCompletion && this._isSafetyRefusal(msg);\n\t\tif (retryableError || emptyCompletion || safetyRefusal) {\n\t\t\tif (emptyCompletion && !msg.errorMessage) {\n\t\t\t\t// Surface a clear reason in the retry banner; empty completions carry no\n\t\t\t\t// provider error message of their own.\n\t\t\t\tmsg.errorMessage = \"Provider returned an empty completion\";\n\t\t\t} else if (safetyRefusal && !msg.errorMessage) {\n\t\t\t\tmsg.errorMessage = \"Provider returned a canned safety refusal\";\n\t\t\t}\n\t\t\tconst didRetry = await this._handleRetryableError(msg);\n\t\t\tif (didRetry) return; // Retry was initiated, don't proceed to compaction\n\t\t}\n\n\t\tthis._resolveRetry();\n\t\tawait this._checkCompaction(msg);\n\t}\n}\n\n\nexport function _applyInterruptAbortMessage(this: AgentSession, event: AgentEvent): void {\n\tconst abortMessage = this._activeInterruptAbortMessage;\n\tif (!abortMessage) return;\n\n\tif (event.type === \"tool_execution_end\" && event.isError && isSingleGenericAbortTextContent(event.result.content)) {\n\t\tevent.result.content = replacementAbortContent(abortMessage);\n\t\treturn;\n\t}\n\n\tif (event.type !== \"message_start\" && event.type !== \"message_end\") return;\n\n\tif (event.message.role === \"toolResult\" && event.message.isError && isSingleGenericAbortTextContent(event.message.content)) {\n\t\tevent.message.content = replacementAbortContent(abortMessage);\n\t\treturn;\n\t}\n\n\tif (event.message.role === \"assistant\") {\n\t\tconst assistantMessage = event.message as AssistantMessage;\n\t\tif (assistantMessage.stopReason === \"aborted\") {\n\t\t\tassistantMessage.errorMessage = abortMessage;\n\t\t}\n\t}\n}\n\n\nexport function _applyProviderErrorGuidance(this: AgentSession, event: AgentEvent): void {\n\tif (event.type !== \"message_start\" && event.type !== \"message_update\" && event.type !== \"message_end\") return;\n\tif (event.message.role !== \"assistant\") return;\n\n\tconst assistantMessage = event.message as AssistantMessage;\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return;\n\n\tassistantMessage.errorMessage = formatCopilotProviderError(\n\t\tassistantMessage.provider,\n\t\tassistantMessage.errorMessage,\n\t);\n}\n\n/** Resolve the pending retry promise */\n\nexport function _resolveRetry(this: AgentSession): void {\n\tif (this._retryResolve) {\n\t\tthis._retryResolve();\n\t\tthis._retryResolve = undefined;\n\t\tthis._retryPromise = undefined;\n\t}\n}\n\n/** Extract text content from a message */\n\nexport function _getUserMessageText(this: AgentSession, message: Message): string {\n\tif (message.role !== \"user\") return \"\";\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tconst textBlocks = content.filter((c) => c.type === \"text\");\n\treturn textBlocks.map((c) => (c as TextContent).text).join(\"\");\n}\n\n/** Find the last assistant message in agent state (including aborted ones) */\n\nexport function _findLastAssistantMessage(this: AgentSession): AssistantMessage | undefined {\n\tconst messages = this.agent.state.messages;\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst msg = messages[i];\n\t\tif (msg.role === \"assistant\") {\n\t\t\treturn msg as AssistantMessage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n\nexport function _replaceMessageInPlace(this: AgentSession, target: AgentMessage, replacement: AgentMessage): void {\n\t// Agent-core stores the finalized message object in its state before emitting message_end.\n\t// SessionManager persistence happens later in _processAgentEvent() with event.message.\n\t// Mutating this object in place keeps agent state, later turn/agent events, listeners,\n\t// and the eventual SessionManager.appendMessage(event.message) persistence in sync.\n\tif (target === replacement) {\n\t\treturn;\n\t}\n\n\tconst targetRecord = target as unknown as Record<string, unknown>;\n\tfor (const key of Object.keys(targetRecord)) {\n\t\tdelete targetRecord[key];\n\t}\n\tObject.assign(targetRecord, replacement);\n}\n\n/** Emit extension events based on agent events */\n\nexport async function _emitExtensionEvent(this: AgentSession, event: AgentEvent): Promise<void> {\n\tif (event.type === \"agent_start\") {\n\t\tthis._turnIndex = 0;\n\t\tawait this._extensionRunner.emit({ type: \"agent_start\" });\n\t} else if (event.type === \"agent_end\") {\n\t\tawait this._extensionRunner.emit({ type: \"agent_end\", messages: event.messages });\n\t} else if (event.type === \"turn_start\") {\n\t\tconst extensionEvent: TurnStartEvent = {\n\t\t\ttype: \"turn_start\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"turn_end\") {\n\t\tconst extensionEvent: TurnEndEvent = {\n\t\t\ttype: \"turn_end\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\tmessage: event.message,\n\t\t\ttoolResults: event.toolResults,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\tthis._turnIndex++;\n\t} else if (event.type === \"message_start\") {\n\t\tconst extensionEvent: MessageStartEvent = {\n\t\t\ttype: \"message_start\",\n\t\t\tmessage: event.message,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"message_update\") {\n\t\tconst extensionEvent: MessageUpdateEvent = {\n\t\t\ttype: \"message_update\",\n\t\t\tmessage: event.message,\n\t\t\tassistantMessageEvent: event.assistantMessageEvent,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"message_end\") {\n\t\tconst extensionEvent: MessageEndEvent = {\n\t\t\ttype: \"message_end\",\n\t\t\tmessage: event.message,\n\t\t};\n\t\tconst replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);\n\t\tif (replacement) {\n\t\t\tthis._replaceMessageInPlace(event.message, normalizeMessageContent(replacement));\n\t\t}\n\t} else if (event.type === \"tool_execution_start\") {\n\t\tconst extensionEvent: ToolExecutionStartEvent = {\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\targs: event.args,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"tool_execution_update\") {\n\t\tconst extensionEvent: ToolExecutionUpdateEvent = {\n\t\t\ttype: \"tool_execution_update\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\targs: event.args,\n\t\t\tpartialResult: event.partialResult,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"tool_execution_end\") {\n\t\tconst extensionEvent: ToolExecutionEndEvent = {\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\tresult: event.result,\n\t\t\tisError: event.isError,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t}\n}\n\n/**\n * Subscribe to agent events.\n * Session persistence is handled internally (saves messages on message_end).\n * Multiple listeners can be added. Returns unsubscribe function for this listener.\n */\n\nexport function subscribe(this: AgentSession, listener: AgentSessionEventListener): () => void {\n\tthis._eventListeners.push(listener);\n\n\t// Return unsubscribe function for this specific listener\n\treturn () => {\n\t\tconst index = this._eventListeners.indexOf(listener);\n\t\tif (index !== -1) {\n\t\t\tthis._eventListeners.splice(index, 1);\n\t\t}\n\t};\n}\n\n/**\n * Temporarily disconnect from agent events.\n * User listeners are preserved and will receive events again after resubscribe().\n * Used internally during operations that need to pause event processing.\n */\n\nexport function _disconnectFromAgent(this: AgentSession): void {\n\tif (this._unsubscribeAgent) {\n\t\tthis._unsubscribeAgent();\n\t\tthis._unsubscribeAgent = undefined;\n\t}\n}\n\n/**\n * Reconnect to agent events after _disconnectFromAgent().\n * Preserves all existing listeners.\n */\n\nexport function _reconnectToAgent(this: AgentSession): void {\n\tif (this._unsubscribeAgent) return; // Already connected\n\tthis._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);\n}\n\n/**\n * Remove all listeners and disconnect from agent.\n * Call this when completely done with the session.\n */\n\nexport function dispose(this: AgentSession): void {\n\tthis._extensionRunner.invalidate(\n\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t);\n\tdisposeSessionAsyncJobManager(this._asyncJobManager, this._asyncJobManagerSessionId);\n\tthis._disconnectFromAgent();\n\tthis._eventListeners = [];\n\tcleanupSessionResources(this.sessionId);\n}\n\n// =========================================================================\n// Read-only State Access\n// =========================================================================\n\n/** Full agent state */\n\nexport const agentSessionEventsMethods = {\n\t_emit,\n\t_emitQueueUpdate,\n\t_handleAgentEvent,\n\t_createRetryPromiseForAgentEnd,\n\t_findLastAssistantInMessages,\n\t_processAgentEvent,\n\t_applyInterruptAbortMessage,\n\t_applyProviderErrorGuidance,\n\t_resolveRetry,\n\t_getUserMessageText,\n\t_findLastAssistantMessage,\n\t_replaceMessageInPlace,\n\t_emitExtensionEvent,\n\tsubscribe,\n\t_disconnectFromAgent,\n\t_reconnectToAgent,\n\tdispose,\n};\n"]}
|
|
1
|
+
{"version":3,"file":"agent-session-events.js","sourceRoot":"","sources":["../../src/core/agent-session-events.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,6BAA6B,EAAE,MAAM,4BAA4B,CAAC;AAG3E,OAAO,EAAE,uBAAuB,EAAE,MAAM,8BAA8B,CAAC;AACvE,OAAO,EAAE,wBAAwB,EAAE,MAAM,mBAAmB,CAAC;AAC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OAAO;IACtB,IAAI,CAAC,gBAAgB,CAAC,UAAU,CAC/B,6WAA6W,CAC7W,CAAC;IACF,6BAA6B,CAAC,IAAI,CAAC,gBAAgB,EAAE,IAAI,CAAC,yBAAyB,CAAC,CAAC;IACrF,IAAI,CAAC,oBAAoB,EAAE,CAAC;IAC5B,IAAI,CAAC,eAAe,GAAG,EAAE,CAAC;IAC1B,uBAAuB,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AACzC,CAAC;AAED,4EAA4E;AAC5E,yBAAyB;AACzB,4EAA4E;AAE5E,uBAAuB;AAEvB,MAAM,CAAC,MAAM,yBAAyB,GAAG;IACxC,KAAK;IACL,gBAAgB;IAChB,iBAAiB;IACjB,8BAA8B;IAC9B,4BAA4B;IAC5B,kBAAkB;IAClB,2BAA2B;IAC3B,2BAA2B;IAC3B,aAAa;IACb,mBAAmB;IACnB,yBAAyB;IACzB,sBAAsB;IACtB,mBAAmB;IACnB,SAAS;IACT,oBAAoB;IACpB,iBAAiB;IACjB,OAAO;CACP,CAAC","sourcesContent":["import { disposeSessionAsyncJobManager } from \"./async/session-manager.js\";\nimport type { AgentEvent, AgentMessage } from \"@earendil-works/pi-agent-core\";\nimport type { AssistantMessage, Message, TextContent } from \"@earendil-works/pi-ai/compat\";\nimport { cleanupSessionResources } from \"@earendil-works/pi-ai/compat\";\nimport { formatCodexProviderError } from \"./codex-errors.ts\";\nimport { formatCopilotProviderError } from \"./copilot-errors.ts\";\nimport type { AgentSessionInternalSurface as AgentSession } from \"./agent-session-methods.ts\";\nimport { customMessageExcludesContext, isSingleGenericAbortTextContent, replacementAbortContent, type AgentSessionEvent, type AgentSessionEventListener } from \"./agent-session-types.ts\";\nimport type { MessageEndEvent, MessageStartEvent, MessageUpdateEvent, ToolExecutionEndEvent, ToolExecutionStartEvent, ToolExecutionUpdateEvent, TurnEndEvent, TurnStartEvent } from \"./extensions/index.ts\";\nimport { normalizeMessageContent } from \"./messages.ts\";\n\nexport function _emit(this: AgentSession, event: AgentSessionEvent): void {\n\tfor (const l of this._eventListeners) {\n\t\tl(event);\n\t}\n}\n\n\nexport function _emitQueueUpdate(this: AgentSession): void {\n\tthis._emit({\n\t\ttype: \"queue_update\",\n\t\tsteering: [...this._steeringMessages],\n\t\tfollowUp: [...this._followUpMessages],\n\t});\n}\n\n/** Internal handler for agent events - shared by subscribe and reconnect */\n\nexport function _handleAgentEvent(this: AgentSession, event: AgentEvent): void {\n\t// Create retry promise synchronously before queueing async processing.\n\t// Agent.emit() calls this handler synchronously, and prompt() calls waitForRetry()\n\t// as soon as agent.prompt() resolves. If _retryPromise is created only inside\n\t// _processAgentEvent, slow earlier queued events can delay agent_end processing\n\t// and waitForRetry() can miss the in-flight retry.\n\tthis._createRetryPromiseForAgentEnd(event);\n\n\tthis._agentEventQueue = this._agentEventQueue.then(\n\t\t() => this._processAgentEvent(event),\n\t\t() => this._processAgentEvent(event),\n\t);\n\n\t// Keep queue alive if an event handler fails\n\tthis._agentEventQueue.catch(() => {});\n}\n\n\nexport function _createRetryPromiseForAgentEnd(this: AgentSession, event: AgentEvent): void {\n\tif (event.type !== \"agent_end\" || this._retryPromise) {\n\t\treturn;\n\t}\n\n\tconst settings = this.settingsManager.getRetrySettings();\n\tif (!settings.enabled && this._fallbackModels.length === 0) {\n\t\treturn;\n\t}\n\n\tconst lastAssistant = this._findLastAssistantInMessages(event.messages);\n\tif (!lastAssistant) {\n\t\treturn;\n\t}\n\n\tconst shouldRetry = this._isRetryableError(lastAssistant) || this._isEmptyCompletion(lastAssistant) || this._isSafetyRefusal(lastAssistant);\n\tif (!shouldRetry) {\n\t\treturn;\n\t}\n\n\tthis._retryPromise = new Promise((resolve) => {\n\t\tthis._retryResolve = resolve;\n\t});\n}\n\n\nexport function _findLastAssistantInMessages(this: AgentSession, messages: AgentMessage[]): AssistantMessage | undefined {\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst message = messages[i];\n\t\tif (message.role === \"assistant\") {\n\t\t\treturn message as AssistantMessage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n\nexport async function _processAgentEvent(this: AgentSession, event: AgentEvent): Promise<void> {\n\t// When a user message starts, check if it's from either queue and remove it BEFORE emitting\n\t// This ensures the UI sees the updated queue state\n\tif (event.type === \"message_start\" && event.message.role === \"user\") {\n\t\tthis._overflowRecoveryAttempted = false;\n\t\tthis._fallbackAttemptedKeys.clear();\n\t\tconst messageText = this._getUserMessageText(event.message);\n\t\tif (messageText) {\n\t\t\t// Check steering queue first\n\t\t\tconst steeringIndex = this._steeringMessages.indexOf(messageText);\n\t\t\tif (steeringIndex !== -1) {\n\t\t\t\tthis._steeringMessages.splice(steeringIndex, 1);\n\t\t\t\tthis._emitQueueUpdate();\n\t\t\t} else {\n\t\t\t\t// Check follow-up queue\n\t\t\t\tconst followUpIndex = this._followUpMessages.indexOf(messageText);\n\t\t\t\tif (followUpIndex !== -1) {\n\t\t\t\t\tthis._followUpMessages.splice(followUpIndex, 1);\n\t\t\t\t\tthis._emitQueueUpdate();\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\n\tthis._applyInterruptAbortMessage(event);\n\tthis._applyProviderErrorGuidance(event);\n\n\t// Emit to extensions first\n\tawait this._emitExtensionEvent(event);\n\n\t// Notify all listeners\n\tthis._emit(event);\n\n\t// Handle session persistence\n\tif (event.type === \"message_end\") {\n\t\t// Check if this is a custom message from extensions\n\t\tif (event.message.role === \"custom\") {\n\t\t\t// Persist as CustomMessageEntry\n\t\t\tthis.sessionManager.appendCustomMessageEntry(\n\t\t\t\tevent.message.customType,\n\t\t\t\tevent.message.content,\n\t\t\t\tevent.message.display,\n\t\t\t\tevent.message.details,\n\t\t\t\tcustomMessageExcludesContext(event.message),\n\t\t\t);\n\t\t} else if (\n\t\t\tevent.message.role === \"user\" ||\n\t\t\tevent.message.role === \"assistant\" ||\n\t\t\tevent.message.role === \"toolResult\"\n\t\t) {\n\t\t\tif (event.message.role === \"assistant\") {\n\t\t\t\tthis._normalizePersistedGeminiToolArgs(event.message);\n\t\t\t}\n\t\t\t// Regular LLM message - persist as SessionMessageEntry\n\t\t\tthis.sessionManager.appendMessage(event.message);\n\t\t}\n\t\t// Other message types (bashExecution, branchSummary) are persisted elsewhere\n\n\t\t// Track assistant message for auto-compaction (checked on agent_end)\n\t\tif (event.message.role === \"assistant\") {\n\t\t\tthis._lastAssistantMessage = event.message;\n\n\t\t\tconst assistantMsg = event.message as AssistantMessage;\n\t\t\t// Treat degenerate empty completions (no content, zero output tokens) and\n\t\t\t// intercepted canned safety refusals as failures alongside stopReason ===\n\t\t\t// \"error\". Otherwise such a turn that stops with reason \"stop\"/\"length\"\n\t\t\t// would reset the retry counter on every attempt, causing unbounded\n\t\t\t// retries instead of honoring maxRetries.\n\t\t\tconst assistantFailed = assistantMsg.stopReason === \"error\" || this._isEmptyCompletion(assistantMsg) || this._isSafetyRefusal(assistantMsg);\n\t\t\tif (!assistantFailed) {\n\t\t\t\tthis._fallbackAttemptedKeys.clear();\n\t\t\t\tthis._overflowRecoveryAttempted = false;\n\t\t\t\tthis._outputBudgetErrorContinuationAttempts = 0;\n\t\t\t}\n\n\t\t\t// A non-truncated assistant response means the length-continuation loop\n\t\t\t// made progress (or the turn completed cleanly), so reset the bounded\n\t\t\t// output-cap continuation counter.\n\t\t\tif (assistantMsg.stopReason !== \"length\") {\n\t\t\t\tthis._lengthContinuationAttempts = 0;\n\t\t\t}\n\n\t\t\t// Reset retry counter immediately on successful assistant response\n\t\t\t// This prevents accumulation across multiple LLM calls within a turn\n\t\t\tif (!assistantFailed && this._retryAttempt > 0) {\n\t\t\t\tthis._emit({\n\t\t\t\t\ttype: \"auto_retry_end\",\n\t\t\t\t\tsuccess: true,\n\t\t\t\t\tattempt: this._retryAttempt,\n\t\t\t\t});\n\t\t\t\tthis._retryAttempt = 0;\n\t\t\t}\n\t\t}\n\t}\n\n\t// Check auto-retry and auto-compaction after agent completes\n\tif (event.type === \"agent_end\" && this._lastAssistantMessage) {\n\t\tconst msg = this._lastAssistantMessage;\n\t\tthis._lastAssistantMessage = undefined;\n\t\tconst postToolPreflightFailed =\n\t\t\tthis._postToolCompactionPreflightError !== undefined &&\n\t\t\tmsg.errorMessage === this._postToolCompactionPreflightError;\n\n\t\t// Check for retryable errors first (overloaded, rate limit, server errors,\n\t\t// transient provider finish_reason errors, degenerate empty completions,\n\t\t// or intercepted canned safety refusals)\n\t\tconst retryableError = !postToolPreflightFailed && this._isRetryableError(msg);\n\t\tconst emptyCompletion = !postToolPreflightFailed && !retryableError && this._isEmptyCompletion(msg);\n\t\tconst safetyRefusal =\n\t\t\t!postToolPreflightFailed && !retryableError && !emptyCompletion && this._isSafetyRefusal(msg);\n\t\tif (retryableError || emptyCompletion || safetyRefusal) {\n\t\t\tif (emptyCompletion && !msg.errorMessage) {\n\t\t\t\t// Surface a clear reason in the retry banner; empty completions carry no\n\t\t\t\t// provider error message of their own.\n\t\t\t\tmsg.errorMessage = \"Provider returned an empty completion\";\n\t\t\t} else if (safetyRefusal && !msg.errorMessage) {\n\t\t\t\tmsg.errorMessage = \"Provider returned a canned safety refusal\";\n\t\t\t}\n\t\t\tconst didRetry = await this._handleRetryableError(msg);\n\t\t\tif (didRetry) return; // Retry was initiated, don't proceed to compaction\n\t\t}\n\n\t\tthis._resolveRetry();\n\t\tawait this._checkCompaction(msg);\n\t}\n}\n\n\nexport function _applyInterruptAbortMessage(this: AgentSession, event: AgentEvent): void {\n\tconst abortMessage = this._activeInterruptAbortMessage;\n\tif (!abortMessage) return;\n\n\tif (event.type === \"tool_execution_end\" && event.isError && isSingleGenericAbortTextContent(event.result.content)) {\n\t\tevent.result.content = replacementAbortContent(abortMessage);\n\t\treturn;\n\t}\n\n\tif (event.type !== \"message_start\" && event.type !== \"message_end\") return;\n\n\tif (event.message.role === \"toolResult\" && event.message.isError && isSingleGenericAbortTextContent(event.message.content)) {\n\t\tevent.message.content = replacementAbortContent(abortMessage);\n\t\treturn;\n\t}\n\n\tif (event.message.role === \"assistant\") {\n\t\tconst assistantMessage = event.message as AssistantMessage;\n\t\tif (assistantMessage.stopReason === \"aborted\") {\n\t\t\tassistantMessage.errorMessage = abortMessage;\n\t\t}\n\t}\n}\n\n\nexport function _applyProviderErrorGuidance(this: AgentSession, event: AgentEvent): void {\n\tif (event.type !== \"message_start\" && event.type !== \"message_update\" && event.type !== \"message_end\") return;\n\tif (event.message.role !== \"assistant\") return;\n\n\tconst assistantMessage = event.message as AssistantMessage;\n\tif (assistantMessage.stopReason !== \"error\" || !assistantMessage.errorMessage) return;\n\n\tassistantMessage.errorMessage = formatCodexProviderError(\n\t\tassistantMessage.provider,\n\t\tformatCopilotProviderError(assistantMessage.provider, assistantMessage.errorMessage),\n\t);\n}\n\n/** Resolve the pending retry promise */\n\nexport function _resolveRetry(this: AgentSession): void {\n\tif (this._retryResolve) {\n\t\tthis._retryResolve();\n\t\tthis._retryResolve = undefined;\n\t\tthis._retryPromise = undefined;\n\t}\n}\n\n/** Extract text content from a message */\n\nexport function _getUserMessageText(this: AgentSession, message: Message): string {\n\tif (message.role !== \"user\") return \"\";\n\tconst content = message.content;\n\tif (typeof content === \"string\") return content;\n\tconst textBlocks = content.filter((c) => c.type === \"text\");\n\treturn textBlocks.map((c) => (c as TextContent).text).join(\"\");\n}\n\n/** Find the last assistant message in agent state (including aborted ones) */\n\nexport function _findLastAssistantMessage(this: AgentSession): AssistantMessage | undefined {\n\tconst messages = this.agent.state.messages;\n\tfor (let i = messages.length - 1; i >= 0; i--) {\n\t\tconst msg = messages[i];\n\t\tif (msg.role === \"assistant\") {\n\t\t\treturn msg as AssistantMessage;\n\t\t}\n\t}\n\treturn undefined;\n}\n\n\nexport function _replaceMessageInPlace(this: AgentSession, target: AgentMessage, replacement: AgentMessage): void {\n\t// Agent-core stores the finalized message object in its state before emitting message_end.\n\t// SessionManager persistence happens later in _processAgentEvent() with event.message.\n\t// Mutating this object in place keeps agent state, later turn/agent events, listeners,\n\t// and the eventual SessionManager.appendMessage(event.message) persistence in sync.\n\tif (target === replacement) {\n\t\treturn;\n\t}\n\n\tconst targetRecord = target as unknown as Record<string, unknown>;\n\tfor (const key of Object.keys(targetRecord)) {\n\t\tdelete targetRecord[key];\n\t}\n\tObject.assign(targetRecord, replacement);\n}\n\n/** Emit extension events based on agent events */\n\nexport async function _emitExtensionEvent(this: AgentSession, event: AgentEvent): Promise<void> {\n\tif (event.type === \"agent_start\") {\n\t\tthis._turnIndex = 0;\n\t\tawait this._extensionRunner.emit({ type: \"agent_start\" });\n\t} else if (event.type === \"agent_end\") {\n\t\tawait this._extensionRunner.emit({ type: \"agent_end\", messages: event.messages });\n\t} else if (event.type === \"turn_start\") {\n\t\tconst extensionEvent: TurnStartEvent = {\n\t\t\ttype: \"turn_start\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\ttimestamp: Date.now(),\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"turn_end\") {\n\t\tconst extensionEvent: TurnEndEvent = {\n\t\t\ttype: \"turn_end\",\n\t\t\tturnIndex: this._turnIndex,\n\t\t\tmessage: event.message,\n\t\t\ttoolResults: event.toolResults,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t\tthis._turnIndex++;\n\t} else if (event.type === \"message_start\") {\n\t\tconst extensionEvent: MessageStartEvent = {\n\t\t\ttype: \"message_start\",\n\t\t\tmessage: event.message,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"message_update\") {\n\t\tconst extensionEvent: MessageUpdateEvent = {\n\t\t\ttype: \"message_update\",\n\t\t\tmessage: event.message,\n\t\t\tassistantMessageEvent: event.assistantMessageEvent,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"message_end\") {\n\t\tconst extensionEvent: MessageEndEvent = {\n\t\t\ttype: \"message_end\",\n\t\t\tmessage: event.message,\n\t\t};\n\t\tconst replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);\n\t\tif (replacement) {\n\t\t\tthis._replaceMessageInPlace(event.message, normalizeMessageContent(replacement));\n\t\t}\n\t} else if (event.type === \"tool_execution_start\") {\n\t\tconst extensionEvent: ToolExecutionStartEvent = {\n\t\t\ttype: \"tool_execution_start\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\targs: event.args,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"tool_execution_update\") {\n\t\tconst extensionEvent: ToolExecutionUpdateEvent = {\n\t\t\ttype: \"tool_execution_update\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\targs: event.args,\n\t\t\tpartialResult: event.partialResult,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t} else if (event.type === \"tool_execution_end\") {\n\t\tconst extensionEvent: ToolExecutionEndEvent = {\n\t\t\ttype: \"tool_execution_end\",\n\t\t\ttoolCallId: event.toolCallId,\n\t\t\ttoolName: event.toolName,\n\t\t\tresult: event.result,\n\t\t\tisError: event.isError,\n\t\t};\n\t\tawait this._extensionRunner.emit(extensionEvent);\n\t}\n}\n\n/**\n * Subscribe to agent events.\n * Session persistence is handled internally (saves messages on message_end).\n * Multiple listeners can be added. Returns unsubscribe function for this listener.\n */\n\nexport function subscribe(this: AgentSession, listener: AgentSessionEventListener): () => void {\n\tthis._eventListeners.push(listener);\n\n\t// Return unsubscribe function for this specific listener\n\treturn () => {\n\t\tconst index = this._eventListeners.indexOf(listener);\n\t\tif (index !== -1) {\n\t\t\tthis._eventListeners.splice(index, 1);\n\t\t}\n\t};\n}\n\n/**\n * Temporarily disconnect from agent events.\n * User listeners are preserved and will receive events again after resubscribe().\n * Used internally during operations that need to pause event processing.\n */\n\nexport function _disconnectFromAgent(this: AgentSession): void {\n\tif (this._unsubscribeAgent) {\n\t\tthis._unsubscribeAgent();\n\t\tthis._unsubscribeAgent = undefined;\n\t}\n}\n\n/**\n * Reconnect to agent events after _disconnectFromAgent().\n * Preserves all existing listeners.\n */\n\nexport function _reconnectToAgent(this: AgentSession): void {\n\tif (this._unsubscribeAgent) return; // Already connected\n\tthis._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);\n}\n\n/**\n * Remove all listeners and disconnect from agent.\n * Call this when completely done with the session.\n */\n\nexport function dispose(this: AgentSession): void {\n\tthis._extensionRunner.invalidate(\n\t\t\"This extension ctx is stale after session replacement or reload. Do not use a captured pi or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().\",\n\t);\n\tdisposeSessionAsyncJobManager(this._asyncJobManager, this._asyncJobManagerSessionId);\n\tthis._disconnectFromAgent();\n\tthis._eventListeners = [];\n\tcleanupSessionResources(this.sessionId);\n}\n\n// =========================================================================\n// Read-only State Access\n// =========================================================================\n\n/** Full agent state */\n\nexport const agentSessionEventsMethods = {\n\t_emit,\n\t_emitQueueUpdate,\n\t_handleAgentEvent,\n\t_createRetryPromiseForAgentEnd,\n\t_findLastAssistantInMessages,\n\t_processAgentEvent,\n\t_applyInterruptAbortMessage,\n\t_applyProviderErrorGuidance,\n\t_resolveRetry,\n\t_getUserMessageText,\n\t_findLastAssistantMessage,\n\t_replaceMessageInPlace,\n\t_emitExtensionEvent,\n\tsubscribe,\n\t_disconnectFromAgent,\n\t_reconnectToAgent,\n\tdispose,\n};\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"agent-session-retry.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAO,gBAAgB,EAAS,MAAM,8BAA8B,CAAC;
|
|
1
|
+
{"version":3,"file":"agent-session-retry.d.ts","sourceRoot":"","sources":["../../src/core/agent-session-retry.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAO,gBAAgB,EAAS,MAAM,8BAA8B,CAAC;AAOjF,OAAO,KAAK,EAAE,2BAA2B,IAAI,YAAY,EAAE,MAAM,4BAA4B,CAAC;AA4E9F,wBAAgB,iBAAiB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAmCxF;AAED;;;;;;;;GAQG;AAEH,wBAAgB,iCAAiC,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,IAAI,CAWrG;AAED;;;;;;;;;;;;;GAaG;AAEH,wBAAgB,kBAAkB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAsBzF;AAmCD,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAsBvF;AAED;;;GAGG;AAEH,wBAAsB,yBAAyB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CAmE/G;AAED,wBAAsB,qBAAqB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,OAAO,CAAC,CA4E3G;AAED;;GAEG;AAEH,wBAAgB,UAAU,CAAC,IAAI,EAAE,YAAY,GAAG,IAAI,CAInD;AAED;;;GAGG;AAEH,wBAAsB,YAAY,CAAC,IAAI,EAAE,YAAY,GAAG,OAAO,CAAC,IAAI,CAAC,CAOpE;AAED,kDAAkD;AAElD,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,YAAY,EAAE,OAAO,EAAE,OAAO,GAAG,IAAI,CAE9E;AAMD;;;;;;;GAOG;AAEH,eAAO,MAAM,wBAAwB;;;;;;;;;;CAUpC,CAAC"}
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { clampThinkingLevel, isContextOverflow, modelsAreEqual } from "@earendil-works/pi-ai/compat";
|
|
2
2
|
import { sleep } from "../utils/sleep.js";
|
|
3
3
|
import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
|
|
4
|
+
import { isCodexTokenInvalidationError } from "./codex-errors.js";
|
|
4
5
|
import { isCopilotGeminiModel } from "./copilot-gemini-payload-sanitizer.js";
|
|
5
6
|
import { normalizeToolArgumentsForModel } from "./copilot-gemini-tool-arguments.js";
|
|
6
7
|
const THINKING_SUFFIXES = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
@@ -87,6 +88,12 @@ export function _isRetryableError(message) {
|
|
|
87
88
|
const contextWindow = this.model?.contextWindow ?? 0;
|
|
88
89
|
if (isContextOverflow(message, contextWindow))
|
|
89
90
|
return false;
|
|
91
|
+
// A definitive Codex authentication rejection is terminal. It takes
|
|
92
|
+
// precedence over transport diagnostics recorded during WebSocket-to-SSE
|
|
93
|
+
// fallback so those earlier diagnostics cannot trigger a pointless retry.
|
|
94
|
+
const provider = message.provider || this.model?.provider;
|
|
95
|
+
if (provider && isCodexTokenInvalidationError(provider, message.errorMessage))
|
|
96
|
+
return false;
|
|
90
97
|
if (hasProviderTransportDiagnostic(message) || hasProviderModelUnavailableDiagnostic(message))
|
|
91
98
|
return true;
|
|
92
99
|
if (!message.errorMessage)
|