@herbertgao/pi-extensions 2026.11.18 → 2026.11.20
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 +18 -0
- package/README.md +5 -5
- package/THIRD_PARTY_NOTICES.md +3 -24
- package/node_modules/@estebanforge/pi-antigravity-bridge/CHANGELOG.md +956 -0
- package/node_modules/{pi-antigravity → @estebanforge/pi-antigravity-bridge}/LICENSE +1 -1
- package/node_modules/@estebanforge/pi-antigravity-bridge/README.md +240 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/extensions/index.ts +2117 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/package.json +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/connection.ts +644 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/driver.ts +1043 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/events.ts +323 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/home.ts +145 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/jsonrpc.ts +243 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/setup.ts +107 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/acp/usage-estimate.ts +61 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agents.ts +64 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-install.ts +93 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-paths.ts +30 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-setup.ts +81 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/agy-version.ts +289 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-detect.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-gate.ts +233 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/approval-hook.ts +325 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts-ui.ts +88 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/artifacts.ts +144 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/ask-tool.ts +1221 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/background-watch.ts +225 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/bridge-catalog.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/config.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/daily-log.ts +196 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/dialog-lock.ts +48 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/diff-render.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver-types.ts +168 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/driver.ts +907 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/engine-picker.ts +160 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/frame-guard.ts +38 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/handoff-toast.ts +21 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-registration.ts +376 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/mcp-server.ts +618 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/models.ts +404 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/native-tools.ts +104 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/parked-turn.ts +125 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/patch-cleanup.ts +523 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/poll-fold.ts +55 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/prompt-images.ts +92 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/provider.ts +2214 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/queued-messages.ts +152 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/quota-notice.ts +40 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/redact.ts +27 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sessions.ts +197 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/skills.ts +207 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-events.ts +161 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/stream-sanitizer.ts +180 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/subagent-roster.ts +245 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/sysprompt-agent.ts +130 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks-ui.ts +90 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/tasks.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/usage.ts +174 -0
- package/node_modules/@estebanforge/pi-antigravity-bridge/src/web-tools.ts +320 -0
- package/node_modules/@herbertgao/pi-cc-extensions/CHANGELOG.md +6 -0
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/config/panel.ts +1 -1
- package/node_modules/@herbertgao/pi-cc-extensions/extensions/feature/shell/prompt-editor.ts +3 -1
- package/node_modules/@herbertgao/pi-cc-extensions/package.json +1 -1
- package/node_modules/@herbertgao/pi-subagents/CHANGELOG.md +317 -105
- package/node_modules/@herbertgao/pi-subagents/SECURITY.md +2 -2
- package/node_modules/@herbertgao/pi-subagents/docs/rpc.md +240 -36
- package/node_modules/@herbertgao/pi-subagents/docs/translations.md +63 -0
- package/node_modules/@herbertgao/pi-subagents/docs/workflows.md +1 -1
- package/node_modules/@herbertgao/pi-subagents/package.json +4 -4
- package/node_modules/@herbertgao/pi-subagents/src/agent-file-toggle.ts +2 -0
- package/node_modules/@herbertgao/pi-subagents/src/agent-manager.ts +89 -6
- package/node_modules/@herbertgao/pi-subagents/src/agent-runner.ts +6 -2
- package/node_modules/@herbertgao/pi-subagents/src/agent-types.ts +20 -11
- package/node_modules/@herbertgao/pi-subagents/src/cache-retention.ts +39 -0
- package/node_modules/@herbertgao/pi-subagents/src/completion-outbox.ts +5 -0
- package/node_modules/@herbertgao/pi-subagents/src/cross-extension-rpc.ts +185 -44
- package/node_modules/@herbertgao/pi-subagents/src/custom-agents.ts +7 -0
- package/node_modules/@herbertgao/pi-subagents/src/group-join.ts +9 -0
- package/node_modules/@herbertgao/pi-subagents/src/index.ts +126 -116
- package/node_modules/@herbertgao/pi-subagents/src/mention-clone.ts +3 -2
- package/node_modules/@herbertgao/pi-subagents/src/settings.ts +21 -0
- package/node_modules/@herbertgao/pi-subagents/src/subagent-info.ts +115 -0
- package/node_modules/@herbertgao/pi-subagents/src/types.ts +11 -7
- package/node_modules/@herbertgao/pi-subagents/src/ui/agent-widget.ts +2 -3
- package/node_modules/@herbertgao/pi-subagents/src/ui/conversation-viewer.ts +1 -1
- package/node_modules/@herbertgao/pi-subagents/src/workflow/meta.ts +2 -2
- package/node_modules/@herbertgao/pi-subagents/src/workflow-info.ts +184 -0
- package/node_modules/pi-commandcode-provider/CHANGELOG.md +10 -0
- package/node_modules/pi-commandcode-provider/README.md +3 -2
- package/node_modules/pi-commandcode-provider/index.ts +120 -13
- package/node_modules/pi-commandcode-provider/package.json +4 -3
- package/node_modules/pi-commandcode-provider/src/commandcode-catalog.ts +11 -2
- package/node_modules/pi-commandcode-provider/src/pricing.ts +17 -1
- package/node_modules/pi-commandcode-provider/src/quota-command.ts +3 -2
- package/node_modules/pi-commandcode-provider/src/zdr.ts +163 -0
- package/node_modules/pi-typesafe/README.md +1 -1
- package/node_modules/pi-typesafe/dist/ask.js +6 -3
- package/node_modules/pi-typesafe/dist/auth.d.ts +31 -7
- package/node_modules/pi-typesafe/dist/auth.js +159 -55
- package/node_modules/pi-typesafe/dist/batch.d.ts +16 -2
- package/node_modules/pi-typesafe/dist/batch.js +62 -22
- package/node_modules/pi-typesafe/dist/calibrate.d.ts +38 -11
- package/node_modules/pi-typesafe/dist/calibrate.js +56 -24
- package/node_modules/pi-typesafe/dist/client.d.ts +13 -0
- package/node_modules/pi-typesafe/dist/client.js +67 -27
- package/node_modules/pi-typesafe/dist/errors.d.ts +20 -0
- package/node_modules/pi-typesafe/dist/errors.js +105 -2
- package/node_modules/pi-typesafe/dist/extension.d.ts +106 -0
- package/node_modules/pi-typesafe/dist/extension.js +206 -106
- package/node_modules/pi-typesafe/dist/index.d.ts +8 -8
- package/node_modules/pi-typesafe/dist/index.js +3 -3
- package/node_modules/pi-typesafe/dist/key-prompt.d.ts +20 -0
- package/node_modules/pi-typesafe/dist/key-prompt.js +23 -3
- package/node_modules/pi-typesafe/dist/login.d.ts +58 -1
- package/node_modules/pi-typesafe/dist/login.js +167 -13
- package/node_modules/pi-typesafe/dist/schema.d.ts +3 -0
- package/node_modules/pi-typesafe/dist/schema.js +47 -13
- package/node_modules/pi-typesafe/dist/ui.d.ts +2 -1
- package/node_modules/pi-typesafe/dist/usage.d.ts +53 -0
- package/node_modules/pi-typesafe/dist/usage.js +79 -40
- package/node_modules/pi-typesafe/package.json +3 -3
- package/package.json +12 -15
- package/node_modules/pi-antigravity/README.md +0 -298
- package/node_modules/pi-antigravity/docs/reader-guarantees.md +0 -35
- package/node_modules/pi-antigravity/package.json +0 -87
- package/node_modules/pi-antigravity/src/auth/accounts.ts +0 -327
- package/node_modules/pi-antigravity/src/auth/index.ts +0 -23
- package/node_modules/pi-antigravity/src/auth/oauth.ts +0 -445
- package/node_modules/pi-antigravity/src/client/client.ts +0 -602
- package/node_modules/pi-antigravity/src/client/enterprise.ts +0 -150
- package/node_modules/pi-antigravity/src/client/index.ts +0 -2
- package/node_modules/pi-antigravity/src/diagnostics/diagnostics.ts +0 -104
- package/node_modules/pi-antigravity/src/diagnostics/index.ts +0 -1
- package/node_modules/pi-antigravity/src/features/generate-image.ts +0 -132
- package/node_modules/pi-antigravity/src/features/google-search.ts +0 -72
- package/node_modules/pi-antigravity/src/features/read-url-content.ts +0 -124
- package/node_modules/pi-antigravity/src/image/image.ts +0 -427
- package/node_modules/pi-antigravity/src/image/index.ts +0 -1
- package/node_modules/pi-antigravity/src/image/native.ts +0 -69
- package/node_modules/pi-antigravity/src/index.ts +0 -547
- package/node_modules/pi-antigravity/src/models/discovery.ts +0 -176
- package/node_modules/pi-antigravity/src/models/grouping.ts +0 -487
- package/node_modules/pi-antigravity/src/models/index.ts +0 -3
- package/node_modules/pi-antigravity/src/models/models.ts +0 -647
- package/node_modules/pi-antigravity/src/search/index.ts +0 -1
- package/node_modules/pi-antigravity/src/search/search.ts +0 -967
- package/node_modules/pi-antigravity/src/stream/index.ts +0 -1
- package/node_modules/pi-antigravity/src/stream/stream.ts +0 -1961
- package/node_modules/pi-antigravity/src/types/enums.ts +0 -52
- package/node_modules/pi-antigravity/src/types/index.ts +0 -2
- package/node_modules/pi-antigravity/src/types/types.ts +0 -329
- package/node_modules/pi-antigravity/src/usage/index.ts +0 -1
- package/node_modules/pi-antigravity/src/usage/usage.ts +0 -437
- package/node_modules/pi-antigravity/src/utils/address.ts +0 -180
- package/node_modules/pi-antigravity/src/utils/credits.ts +0 -149
- package/node_modules/pi-antigravity/src/utils/html.ts +0 -31
- package/node_modules/pi-antigravity/src/utils/http.ts +0 -96
- package/node_modules/pi-antigravity/src/utils/index.ts +0 -5
- package/node_modules/pi-antigravity/src/utils/security.ts +0 -278
- package/node_modules/pi-antigravity/src/utils/text.ts +0 -66
- package/node_modules/pi-antigravity/src/utils/util.ts +0 -217
- package/node_modules/pi-antigravity/src/web-fetch/document.ts +0 -83
- package/node_modules/pi-antigravity/src/web-fetch/fences.ts +0 -24
- package/node_modules/pi-antigravity/src/web-fetch/header.ts +0 -97
- package/node_modules/pi-antigravity/src/web-fetch/index.ts +0 -3
- package/node_modules/pi-antigravity/src/web-fetch/inspect.ts +0 -328
- package/node_modules/pi-antigravity/src/web-fetch/limits.ts +0 -4
- package/node_modules/pi-antigravity/src/web-fetch/markdown.ts +0 -744
- package/node_modules/pi-antigravity/src/web-fetch/mdn.ts +0 -164
- package/node_modules/pi-antigravity/src/web-fetch/media.ts +0 -11
- package/node_modules/pi-antigravity/src/web-fetch/metadata.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/representation.ts +0 -93
- package/node_modules/pi-antigravity/src/web-fetch/save.ts +0 -71
- package/node_modules/pi-antigravity/src/web-fetch/sites.ts +0 -138
- package/node_modules/pi-antigravity/src/web-fetch/vendor.d.ts +0 -9
- package/node_modules/pi-antigravity/src/web-fetch/web-fetch.ts +0 -957
- package/node_modules/pi-antigravity/tsconfig.json +0 -21
|
@@ -0,0 +1,907 @@
|
|
|
1
|
+
// Persistent agy stream-json driver.
|
|
2
|
+
//
|
|
3
|
+
// One long-lived `agy --input-format stream-json --output-format stream-json`
|
|
4
|
+
// process per provider instance. Turns are serialized through the driver
|
|
5
|
+
// queue; a turn that parks mid-flight (pi toolUse round-trip) keeps the agy
|
|
6
|
+
// process running and is re-entered via reentry() instead of spawning again.
|
|
7
|
+
//
|
|
8
|
+
// Recycle semantics: the child is killed and respawned when the next turn's
|
|
9
|
+
// process profile (model / effort / mode / cwd / conversation) drifts from the
|
|
10
|
+
// running one. Stats and a bounded
|
|
11
|
+
// lifecycle log feed /agy doctor.
|
|
12
|
+
//
|
|
13
|
+
// The driver never talks to the MCP bridge directly: the provider owns the
|
|
14
|
+
// toolUse round-trips and injects bridge_call activities via
|
|
15
|
+
// handle.pushExternal(). This keeps the driver testable with a fake child.
|
|
16
|
+
|
|
17
|
+
import { spawn, type ChildProcess } from "node:child_process";
|
|
18
|
+
import { randomUUID } from "node:crypto";
|
|
19
|
+
import { parseAgyLine } from "./stream-events.js";
|
|
20
|
+
import { isKnownNoiseLine, MAX_FRAME_BYTES, stripGluedNoise } from "./frame-guard.js";
|
|
21
|
+
import { bridgeMcpConfigDir, bridgeMcpConfigExists } from "./mcp-server.js";
|
|
22
|
+
import { gateHooksStaged } from "./approval-hook.js";
|
|
23
|
+
import { parkedTurnAnswer } from "./parked-turn.js";
|
|
24
|
+
import { defaultCliSettingsPath, ensureQueuedMessagesInFile } from "./queued-messages.js";
|
|
25
|
+
import { redactText } from "./redact.js";
|
|
26
|
+
import { StreamSanitizer, sanitizeSystemMessage } from "./stream-sanitizer.js";
|
|
27
|
+
import type {
|
|
28
|
+
AgyUsage,
|
|
29
|
+
DriverActivity,
|
|
30
|
+
DriverProfile,
|
|
31
|
+
DriverSnapshot,
|
|
32
|
+
DriverState,
|
|
33
|
+
DriverTurnRequest,
|
|
34
|
+
TurnDriver,
|
|
35
|
+
TurnHandle,
|
|
36
|
+
TurnOutcome,
|
|
37
|
+
} from "./driver-types.js";
|
|
38
|
+
|
|
39
|
+
export type {
|
|
40
|
+
DriverActivity,
|
|
41
|
+
DriverProfile,
|
|
42
|
+
DriverSnapshot,
|
|
43
|
+
DriverState,
|
|
44
|
+
DriverTurnRequest,
|
|
45
|
+
TurnHandle,
|
|
46
|
+
TurnOutcome,
|
|
47
|
+
} from "./driver-types.js";
|
|
48
|
+
|
|
49
|
+
export { StreamSanitizer, sanitizeSystemMessage };
|
|
50
|
+
|
|
51
|
+
const LIFECYCLE_LIMIT = 24;
|
|
52
|
+
const THINKING_TOKEN_FLOOR = 64;
|
|
53
|
+
|
|
54
|
+
interface ActiveTurn {
|
|
55
|
+
id: string;
|
|
56
|
+
request: DriverTurnRequest;
|
|
57
|
+
/** Activities not yet pulled by a consumer. */
|
|
58
|
+
buffer: DriverActivity[];
|
|
59
|
+
/** Wake waiting next() callers. */
|
|
60
|
+
wake: (() => void)[];
|
|
61
|
+
closed: boolean;
|
|
62
|
+
resolve: (o: TurnOutcome) => void;
|
|
63
|
+
outcome: Promise<TurnOutcome>;
|
|
64
|
+
overallTimer?: NodeJS.Timeout;
|
|
65
|
+
/** Overall-cap bookkeeping for park pauses: a wall-clock deadline while
|
|
66
|
+
* the timer runs, null while parked (parked time must not consume the
|
|
67
|
+
* budget), mirroring the ACP driver's remaining-budget semantics. */
|
|
68
|
+
overallDeadline: number | null;
|
|
69
|
+
/** Remaining budget captured at park time; null while the timer runs. */
|
|
70
|
+
overallRemainingMs: number | null;
|
|
71
|
+
idleTimer?: NodeJS.Timeout;
|
|
72
|
+
onAbort?: () => void;
|
|
73
|
+
response: string;
|
|
74
|
+
rawResponse: string;
|
|
75
|
+
sanitizer: StreamSanitizer;
|
|
76
|
+
usage?: AgyUsage;
|
|
77
|
+
conversationId?: string;
|
|
78
|
+
/** Wall clock at turn creation; the parked-turn probe filters
|
|
79
|
+
* transcript steps to those written after this. */
|
|
80
|
+
startedAt: number;
|
|
81
|
+
sawResult: boolean;
|
|
82
|
+
/** An agent_response or tool step arrived this turn. Distinguishes a
|
|
83
|
+
* real (if terse) turn from agy's silent over-cap drop, which settles
|
|
84
|
+
* SUCCESS with no model step at all (issue #2). */
|
|
85
|
+
sawModelStep: boolean;
|
|
86
|
+
/** Text-dedupe guard state (delta vs cumulative response_text). */
|
|
87
|
+
cumulativeText: boolean | undefined;
|
|
88
|
+
/** Open bridge parks. Each one suspends the stdout idle timer: agy is
|
|
89
|
+
* blocked waiting on the MCP HTTP response and produces no output, so
|
|
90
|
+
* inactivity is EXPECTED while parked. */
|
|
91
|
+
parks: number;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
/** The skip-permissions flag actually passed to agy. Plan mode never
|
|
95
|
+
* carries it: the flag auto-approves every permission request, and the CLI
|
|
96
|
+
* does not gate writes under plan mode (upstream #1181), so an
|
|
97
|
+
* auto-approved plan run is a write-capable run. #start (argv + profile)
|
|
98
|
+
* and #recycleCause (comparison) must both go through this, or plan turns
|
|
99
|
+
* recycle on every turn. */
|
|
100
|
+
function effectiveSkipPermissions(mode: DriverTurnRequest["mode"], skipPermissions: boolean): boolean {
|
|
101
|
+
return mode !== "plan" && skipPermissions;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Wait until the child's process GROUP is gone (POSIX) or return
|
|
105
|
+
* immediately on win32, where the driver does not use detached groups.
|
|
106
|
+
* Leader death alone is not enough: agy's own subprocesses can outlive it
|
|
107
|
+
* and late writes would recreate a removed home dir. Bounded by budgetMs;
|
|
108
|
+
* false means stragglers may remain (the startup sweep is the backstop). */
|
|
109
|
+
export function waitForPidGroupExit(pid: number | undefined, budgetMs = 2_000): Promise<boolean> {
|
|
110
|
+
if (!pid || process.platform === "win32") return Promise.resolve(true);
|
|
111
|
+
const deadline = Date.now() + budgetMs;
|
|
112
|
+
return new Promise<boolean>((resolve) => {
|
|
113
|
+
const tick = () => {
|
|
114
|
+
try {
|
|
115
|
+
process.kill(-pid, 0);
|
|
116
|
+
} catch {
|
|
117
|
+
resolve(true);
|
|
118
|
+
return;
|
|
119
|
+
}
|
|
120
|
+
if (Date.now() >= deadline) {
|
|
121
|
+
resolve(false);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
setTimeout(tick, 50);
|
|
125
|
+
};
|
|
126
|
+
tick();
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function emit(turn: ActiveTurn, activity: DriverActivity): void {
|
|
131
|
+
if (turn.closed) return;
|
|
132
|
+
if (turn.wake.length > 0) turn.wake.shift()!();
|
|
133
|
+
turn.buffer.push(activity);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function nextActivity(turn: ActiveTurn): Promise<DriverActivity | null> {
|
|
137
|
+
for (;;) {
|
|
138
|
+
if (turn.buffer.length > 0) return turn.buffer.shift()!;
|
|
139
|
+
if (turn.closed) return null;
|
|
140
|
+
await new Promise<void>((r) => turn.wake.push(r));
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function makeHandle(turn: ActiveTurn): TurnHandle {
|
|
145
|
+
return {
|
|
146
|
+
id: turn.id,
|
|
147
|
+
outcome: turn.outcome,
|
|
148
|
+
next: () => nextActivity(turn),
|
|
149
|
+
pushExternal: (activity) => {
|
|
150
|
+
if (activity.type === "bridge_call") {
|
|
151
|
+
turn.parks += 1;
|
|
152
|
+
// A park suspends both caps: agy is blocked waiting on the MCP
|
|
153
|
+
// HTTP response, so parked time consumes neither the stall guard
|
|
154
|
+
// nor the turn deadline (pi-tool and human-gated time stay free).
|
|
155
|
+
if (turn.overallTimer) {
|
|
156
|
+
clearTimeout(turn.overallTimer);
|
|
157
|
+
turn.overallTimer = undefined;
|
|
158
|
+
}
|
|
159
|
+
if (turn.overallDeadline !== null) {
|
|
160
|
+
turn.overallRemainingMs = Math.max(0, turn.overallDeadline - Date.now());
|
|
161
|
+
turn.overallDeadline = null;
|
|
162
|
+
}
|
|
163
|
+
if (turn.idleTimer) {
|
|
164
|
+
clearTimeout(turn.idleTimer);
|
|
165
|
+
turn.idleTimer = undefined;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
emit(turn, activity);
|
|
169
|
+
},
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
function nowIso(): string {
|
|
174
|
+
return new Date().toISOString().slice(11, 19);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** True when any usage counter carries a real value. The silent over-cap
|
|
178
|
+
* drop reports all-zero usage (no model call happened); a turn that burned
|
|
179
|
+
* any tokens demonstrably reached the model. */
|
|
180
|
+
function hasTokenEvidence(usage: AgyUsage | undefined): boolean {
|
|
181
|
+
if (!usage) return false;
|
|
182
|
+
return (
|
|
183
|
+
(usage.input_tokens ?? 0) > 0 ||
|
|
184
|
+
(usage.output_tokens ?? 0) > 0 ||
|
|
185
|
+
(usage.thinking_tokens ?? 0) > 0 ||
|
|
186
|
+
(usage.cache_read_tokens ?? 0) > 0 ||
|
|
187
|
+
(usage.total_tokens ?? 0) > 0
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/** True when `next` is a cumulative resend of `accumulated` (it repeats every
|
|
192
|
+
* byte already streamed) rather than a fresh delta. Exported for tests. */
|
|
193
|
+
export function isCumulativeResend(accumulated: string, next: string): boolean {
|
|
194
|
+
// Nothing accumulated yet: no resend is possible (first chunk).
|
|
195
|
+
return accumulated.length > 0 && next.length > accumulated.length && next.startsWith(accumulated);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Flip threshold for the same guard: short accumulations ("**", "#", "\n")
|
|
199
|
+
* are trivially extended by ordinary markdown deltas, and flipping on them
|
|
200
|
+
* corrupts every remaining frame of the turn. Require a respectable
|
|
201
|
+
* accumulation before believing a resend. Exported for tests. */
|
|
202
|
+
export const CUMULATIVE_FLIP_MIN_CHARS = 32;
|
|
203
|
+
|
|
204
|
+
/** Mode decision for the text-dedupe guard. Extracted for tests. */
|
|
205
|
+
export function shouldFlipToCumulative(accumulated: string, next: string): boolean {
|
|
206
|
+
return accumulated.length >= CUMULATIVE_FLIP_MIN_CHARS && isCumulativeResend(accumulated, next);
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export class StreamDriver implements TurnDriver {
|
|
210
|
+
#state: DriverState = "idle";
|
|
211
|
+
#child: ChildProcess | undefined;
|
|
212
|
+
#lastChildPid: number | undefined;
|
|
213
|
+
#stagedHomePath: string | undefined;
|
|
214
|
+
#generation = 0;
|
|
215
|
+
#profile: DriverProfile | undefined;
|
|
216
|
+
#boundConversation: string | undefined;
|
|
217
|
+
#active: ActiveTurn | undefined;
|
|
218
|
+
#queueTail: Promise<void> = Promise.resolve();
|
|
219
|
+
#stderrTail = "";
|
|
220
|
+
// Frames can split across pipe chunks; the trailing partial line lives here
|
|
221
|
+
// until its newline arrives (same scheme as JsonRpcSession.feed). Dropping
|
|
222
|
+
// it ate large tool frames and could hide the result frame of a turn.
|
|
223
|
+
#stdoutBuf = "";
|
|
224
|
+
#lifecycle: string[] = [];
|
|
225
|
+
/** Optional external lifecycle sink (the extension's daily file log).
|
|
226
|
+
* Fire-and-forget: the ring buffer stays the source for /agy doctor. */
|
|
227
|
+
log?: (msg: string, data?: unknown) => void;
|
|
228
|
+
/** Optional isolated-MCP-home wiring (issue #14). stagedHome() is
|
|
229
|
+
* consulted before every spawn: a path means the child runs with
|
|
230
|
+
* --gemini_dir <path> (top-level underscore form; the acp subcommand
|
|
231
|
+
* takes the hyphen form). releaseStagedHome() is awaited in close() AFTER
|
|
232
|
+
* the child's process group is confirmed dead - deliberately NOT in the
|
|
233
|
+
* child exit handler, which is generation-guarded and never fires on the
|
|
234
|
+
* close/recycle paths. */
|
|
235
|
+
stagedHome?: () => string | undefined;
|
|
236
|
+
releaseStagedHome?: (home: string, childPid: number | undefined) => Promise<void> | void;
|
|
237
|
+
#onTurnEnd: ((outcome: TurnOutcome) => void) | undefined;
|
|
238
|
+
#stats = {
|
|
239
|
+
spawns: 0,
|
|
240
|
+
turns: 0,
|
|
241
|
+
reused: 0,
|
|
242
|
+
recycles: 0,
|
|
243
|
+
lastRecycleReason: undefined as string | undefined,
|
|
244
|
+
recycleReasons: {} as Record<string, number>,
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
get state(): DriverState {
|
|
248
|
+
return this.#state;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
get activeHandle(): TurnHandle | null {
|
|
252
|
+
return this.#active && !this.#active.closed ? makeHandle(this.#active) : null;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
/** Called when a parked bridge call resolves or fails. Rearms the idle
|
|
256
|
+
* timer once no parks remain. */
|
|
257
|
+
kickIdle(): void {
|
|
258
|
+
const turn = this.#active;
|
|
259
|
+
if (!turn || turn.closed) return;
|
|
260
|
+
if (turn.parks > 0) turn.parks -= 1;
|
|
261
|
+
if (turn.parks === 0) {
|
|
262
|
+
if (turn.overallRemainingMs !== null) {
|
|
263
|
+
const remaining = turn.overallRemainingMs;
|
|
264
|
+
turn.overallRemainingMs = null;
|
|
265
|
+
this.#startOverallTimer(turn, remaining);
|
|
266
|
+
}
|
|
267
|
+
if (!turn.idleTimer) {
|
|
268
|
+
const idleMin = turn.request.inactivityMin ?? 5;
|
|
269
|
+
// 0 disables the stall guard (config inactivityTimeoutMin: 0).
|
|
270
|
+
if (idleMin > 0) {
|
|
271
|
+
turn.idleTimer = setTimeout(() => {
|
|
272
|
+
void this.#turnDeadlineGuard(turn, "stall", `agy stalled for ${idleMin}m with no output`);
|
|
273
|
+
}, idleMin * 60_000);
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
/** Hook: invoked with the outcome whenever a turn settles. The provider
|
|
280
|
+
* uses it to fail round-trips parked against a dead turn. */
|
|
281
|
+
set onTurnEnd(fn: ((outcome: TurnOutcome) => void) | undefined) {
|
|
282
|
+
this.#onTurnEnd = fn;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
snapshot(): DriverSnapshot {
|
|
286
|
+
return {
|
|
287
|
+
state: this.#state,
|
|
288
|
+
pid: this.#child?.pid,
|
|
289
|
+
conversationId: this.#boundConversation,
|
|
290
|
+
stats: { ...this.#stats, recycleReasons: { ...this.#stats.recycleReasons } },
|
|
291
|
+
lifecycle: [...this.#lifecycle],
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
/** Run one turn. Turn LIFETIMES are serialized: release fires only when
|
|
296
|
+
* the dispatched turn settles, so a second run() can never overlap an
|
|
297
|
+
* open turn (which would orphan the first). A turn parked on a pi toolUse
|
|
298
|
+
* round-trip stays open; the continuation path uses reentry(), which does
|
|
299
|
+
* not queue, so parking cannot deadlock the queue. */
|
|
300
|
+
run(request: DriverTurnRequest): Promise<TurnHandle> {
|
|
301
|
+
let release!: () => void;
|
|
302
|
+
const prev = this.#queueTail;
|
|
303
|
+
this.#queueTail = new Promise<void>((r) => (release = r));
|
|
304
|
+
return prev
|
|
305
|
+
.then(() => this.#runExclusive(request))
|
|
306
|
+
.then((handle) => {
|
|
307
|
+
void handle.outcome.catch(() => {}).then(() => release());
|
|
308
|
+
return handle;
|
|
309
|
+
})
|
|
310
|
+
.catch((err) => {
|
|
311
|
+
release();
|
|
312
|
+
throw err;
|
|
313
|
+
});
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Re-attach to the active turn (pi toolUse continuation). */
|
|
317
|
+
reentry(): TurnHandle | null {
|
|
318
|
+
return this.activeHandle;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
async #runExclusive(request: DriverTurnRequest): Promise<TurnHandle> {
|
|
322
|
+
// No shutdown latch: pi fires session_shutdown on /new, /resume and
|
|
323
|
+
// /fork (not only process exit), so a closed driver must respawn on the
|
|
324
|
+
// next turn instead of rejecting forever. Parity with the ACP driver
|
|
325
|
+
// fix (regression 2026-09-07).
|
|
326
|
+
if (request.signal?.aborted) throw new Error("aborted before start");
|
|
327
|
+
|
|
328
|
+
const cause = this.#recycleCause(request);
|
|
329
|
+
if (cause) await this.close("recycle", cause);
|
|
330
|
+
else if (this.#child) this.#stats.reused += 1;
|
|
331
|
+
if (!this.#child) this.#start(request);
|
|
332
|
+
|
|
333
|
+
const turn = this.#createTurn(request);
|
|
334
|
+
this.#active = turn;
|
|
335
|
+
this.#state = "running";
|
|
336
|
+
this.#stats.turns += 1;
|
|
337
|
+
this.#log("turn-start", {
|
|
338
|
+
model: request.model,
|
|
339
|
+
effort: request.effort,
|
|
340
|
+
mode: request.mode,
|
|
341
|
+
conversation: request.conversationId ?? null,
|
|
342
|
+
images: request.images?.length ?? 0,
|
|
343
|
+
});
|
|
344
|
+
this.#armTimers(turn);
|
|
345
|
+
|
|
346
|
+
const line = `${JSON.stringify({
|
|
347
|
+
event: "user",
|
|
348
|
+
message: { role: "user", content: request.prompt },
|
|
349
|
+
})}\n`;
|
|
350
|
+
const stdin = this.#child?.stdin;
|
|
351
|
+
try {
|
|
352
|
+
if (!stdin) throw new Error("agy driver stdin unavailable");
|
|
353
|
+
stdin.write(line);
|
|
354
|
+
} catch (err) {
|
|
355
|
+
this.#failTurn(
|
|
356
|
+
turn,
|
|
357
|
+
`failed to write to agy driver: ${err instanceof Error ? err.message : String(err)}`,
|
|
358
|
+
);
|
|
359
|
+
}
|
|
360
|
+
return makeHandle(turn);
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
#createTurn(request: DriverTurnRequest): ActiveTurn {
|
|
364
|
+
let resolve!: (o: TurnOutcome) => void;
|
|
365
|
+
const outcome = new Promise<TurnOutcome>((r) => (resolve = r));
|
|
366
|
+
const turn: ActiveTurn = {
|
|
367
|
+
id: randomUUID().slice(0, 8),
|
|
368
|
+
request,
|
|
369
|
+
buffer: [],
|
|
370
|
+
wake: [],
|
|
371
|
+
closed: false,
|
|
372
|
+
resolve,
|
|
373
|
+
outcome,
|
|
374
|
+
response: "",
|
|
375
|
+
rawResponse: "",
|
|
376
|
+
overallDeadline: null,
|
|
377
|
+
overallRemainingMs: null,
|
|
378
|
+
sanitizer: new StreamSanitizer(),
|
|
379
|
+
sawResult: false,
|
|
380
|
+
sawModelStep: false,
|
|
381
|
+
cumulativeText: undefined,
|
|
382
|
+
parks: 0,
|
|
383
|
+
startedAt: Date.now(),
|
|
384
|
+
};
|
|
385
|
+
if (request.signal) {
|
|
386
|
+
turn.onAbort = () => {
|
|
387
|
+
if (turn.closed) return;
|
|
388
|
+
this.#log(`abort:${turn.id}`);
|
|
389
|
+
this.#killChild();
|
|
390
|
+
this.#settle(turn, {
|
|
391
|
+
conversationId: turn.conversationId,
|
|
392
|
+
status: "ERROR",
|
|
393
|
+
response: turn.response,
|
|
394
|
+
error: "aborted",
|
|
395
|
+
usage: turn.usage,
|
|
396
|
+
finished: true,
|
|
397
|
+
aborted: true,
|
|
398
|
+
});
|
|
399
|
+
};
|
|
400
|
+
request.signal.addEventListener("abort", turn.onAbort, { once: true });
|
|
401
|
+
}
|
|
402
|
+
return turn;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
#armTimers(turn: ActiveTurn): void {
|
|
406
|
+
// 0 disables a cap (config turnTimeoutMin / inactivityTimeoutMin: 0):
|
|
407
|
+
// setTimeout(fn, 0) would fire instantly and kill every turn.
|
|
408
|
+
const totalMin = turn.request.timeoutMin ?? 10;
|
|
409
|
+
if (totalMin > 0) this.#startOverallTimer(turn, totalMin * 60_000);
|
|
410
|
+
const idleMin = turn.request.inactivityMin ?? 5;
|
|
411
|
+
if (idleMin > 0) {
|
|
412
|
+
turn.idleTimer = setTimeout(() => {
|
|
413
|
+
void this.#turnDeadlineGuard(turn, "stall", `agy stalled for ${idleMin}m with no output`);
|
|
414
|
+
}, idleMin * 60_000);
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
/** Arm the overall turn cap. A deadline is a wall-clock instant while
|
|
419
|
+
* running; parks capture the remainder and clear it (see
|
|
420
|
+
* ActiveTurn.overallDeadline). A 0ms remainder fires on the next tick,
|
|
421
|
+
* which is correct: the budget is spent. */
|
|
422
|
+
#startOverallTimer(turn: ActiveTurn, ms: number): void {
|
|
423
|
+
const totalMin = turn.request.timeoutMin ?? 10;
|
|
424
|
+
turn.overallDeadline = Date.now() + ms;
|
|
425
|
+
turn.overallTimer = setTimeout(() => {
|
|
426
|
+
void this.#turnDeadlineGuard(turn, "timeout", `agy exceeded the ${totalMin}m turn timeout`);
|
|
427
|
+
}, ms);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
#start(request: DriverTurnRequest): void {
|
|
431
|
+
this.#state = "starting";
|
|
432
|
+
this.#generation += 1;
|
|
433
|
+
const generation = this.#generation;
|
|
434
|
+
// Plan mode never carries the skip flag: the flag auto-approves ALL
|
|
435
|
+
// permission requests, and the CLI does not gate writes under plan
|
|
436
|
+
// mode (upstream google-antigravity/antigravity-cli#1181, probed
|
|
437
|
+
// 2026-10-07: the write executes in the same turn). An auto-approved
|
|
438
|
+
// plan run is a write-capable run. The profile stores the EFFECTIVE
|
|
439
|
+
// value so the recycle comparison stays consistent with the argv.
|
|
440
|
+
const skipPermissions = effectiveSkipPermissions(request.mode, request.skipPermissions);
|
|
441
|
+
this.#profile = {
|
|
442
|
+
cwd: request.cwd,
|
|
443
|
+
model: request.model,
|
|
444
|
+
effort: request.effort,
|
|
445
|
+
mode: request.mode,
|
|
446
|
+
skipPermissions,
|
|
447
|
+
agent: request.agent,
|
|
448
|
+
};
|
|
449
|
+
this.#boundConversation = request.conversationId ?? undefined;
|
|
450
|
+
this.#stderrTail = "";
|
|
451
|
+
|
|
452
|
+
ensureQueuedMessagesInFile(defaultCliSettingsPath());
|
|
453
|
+
|
|
454
|
+
// Issue #14: an isolated home means this child sees no foreign bridge
|
|
455
|
+
// registrations at all. Consulted per spawn so a post-recycle restage
|
|
456
|
+
// picks up a fresh global-config snapshot.
|
|
457
|
+
const home = this.stagedHome?.();
|
|
458
|
+
this.#stagedHomePath = home;
|
|
459
|
+
|
|
460
|
+
const args: string[] = ["--add-dir", request.cwd];
|
|
461
|
+
if (home) args.push("--gemini_dir", home);
|
|
462
|
+
// The bridge dir carries .agents/mcp_config.json (tool bridge) and, when
|
|
463
|
+
// the approval gate is on, .agents/hooks.json (gate staging). Only this
|
|
464
|
+
// session's agy ever gets it: standalone IDE/CLI sessions in the
|
|
465
|
+
// workspace must never load our gate (issue #5 isolation).
|
|
466
|
+
if (bridgeMcpConfigExists() || gateHooksStaged()) args.push("--add-dir", bridgeMcpConfigDir());
|
|
467
|
+
args.push("--model", request.model);
|
|
468
|
+
if (request.effort) args.push("--effort", request.effort);
|
|
469
|
+
args.push("--mode", request.mode);
|
|
470
|
+
if (request.agent) args.push("--agent", request.agent);
|
|
471
|
+
if (skipPermissions) args.push("--dangerously-skip-permissions");
|
|
472
|
+
if (request.conversationId) args.push("--conversation", request.conversationId);
|
|
473
|
+
args.push(
|
|
474
|
+
"--input-format",
|
|
475
|
+
"stream-json",
|
|
476
|
+
"--output-format",
|
|
477
|
+
"stream-json",
|
|
478
|
+
// Skills and slash commands are bridged/owned by pi, not expanded by agy.
|
|
479
|
+
"--disable-slash-commands",
|
|
480
|
+
);
|
|
481
|
+
|
|
482
|
+
// AGY_BIN is the repo-wide binary override (probe, doctor, ask-tool);
|
|
483
|
+
// the driver ignoring it made the --gemini_dir probe test a different
|
|
484
|
+
// binary than the one that actually spawns (issue #14 review round 3).
|
|
485
|
+
const bin = process.env.AGY_BIN || "agy";
|
|
486
|
+
const child = spawn(bin, args, {
|
|
487
|
+
cwd: request.cwd,
|
|
488
|
+
stdio: ["pipe", "pipe", "pipe"],
|
|
489
|
+
detached: process.platform !== "win32",
|
|
490
|
+
windowsHide: true,
|
|
491
|
+
});
|
|
492
|
+
this.#child = child;
|
|
493
|
+
// Kept past #killChild: close() must wait on THIS pid even after the
|
|
494
|
+
// child exited (or was deadline-killed), so late stragglers in the
|
|
495
|
+
// process group cannot write into a home we are about to remove.
|
|
496
|
+
this.#lastChildPid = child.pid;
|
|
497
|
+
this.#stdoutBuf = "";
|
|
498
|
+
this.#stats.spawns += 1;
|
|
499
|
+
// Pipe write failures surface asynchronously as stream 'error' events;
|
|
500
|
+
// the sync try/catch around stdin.write cannot see them. Without this
|
|
501
|
+
// listener an EPIPE (agy died mid-write) is uncaught and kills pi.
|
|
502
|
+
child.stdin!.on("error", (err) => {
|
|
503
|
+
if (generation !== this.#generation) return;
|
|
504
|
+
const turn = this.#active;
|
|
505
|
+
if (turn && !turn.closed) this.#failTurn(turn, `agy stdin write failed: ${err.message}`);
|
|
506
|
+
});
|
|
507
|
+
this.#log(`spawn:${child.pid ?? "?"}:${request.conversationId ? "resume" : "fresh"}`);
|
|
508
|
+
this.#state = "ready";
|
|
509
|
+
|
|
510
|
+
child.stdout!.setEncoding("utf8");
|
|
511
|
+
child.stdout!.on("data", (chunk: string) => {
|
|
512
|
+
if (generation !== this.#generation) return;
|
|
513
|
+
this.#onStdout(chunk);
|
|
514
|
+
});
|
|
515
|
+
child.stderr!.setEncoding("utf8");
|
|
516
|
+
child.stderr!.on("data", (chunk: string) => {
|
|
517
|
+
this.#stderrTail = (this.#stderrTail + chunk).slice(-8192);
|
|
518
|
+
});
|
|
519
|
+
child.on("exit", (code) => {
|
|
520
|
+
if (generation !== this.#generation) return;
|
|
521
|
+
const turn = this.#active;
|
|
522
|
+
this.#child = undefined;
|
|
523
|
+
this.#state = "dead";
|
|
524
|
+
this.#log(`exit:${code ?? "signal"}`);
|
|
525
|
+
if (turn && !turn.closed) {
|
|
526
|
+
if (turn.sawResult) {
|
|
527
|
+
this.#settle(turn, {
|
|
528
|
+
conversationId: turn.conversationId,
|
|
529
|
+
status: turn.usage || turn.response ? "OK" : "UNKNOWN",
|
|
530
|
+
response: turn.response,
|
|
531
|
+
usage: turn.usage,
|
|
532
|
+
finished: true,
|
|
533
|
+
aborted: false,
|
|
534
|
+
});
|
|
535
|
+
} else {
|
|
536
|
+
this.#failTurn(
|
|
537
|
+
turn,
|
|
538
|
+
// agy stderr can carry auth material; the tail becomes the
|
|
539
|
+
// user-facing error and a daily-log value.
|
|
540
|
+
redactText(this.#stderrTail.trim()) || `agy exited with status ${code ?? "signal"}`,
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
});
|
|
545
|
+
child.on("error", (err) => {
|
|
546
|
+
if (generation !== this.#generation) return;
|
|
547
|
+
const turn = this.#active;
|
|
548
|
+
this.#child = undefined;
|
|
549
|
+
this.#state = "dead";
|
|
550
|
+
if (turn && !turn.closed) this.#failTurn(turn, `agy spawn failed: ${err.message}`);
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
#onStdout(chunk: string): void {
|
|
555
|
+
// Buffer the trailing partial line: a frame split across pipe chunks is
|
|
556
|
+
// reassembled when its newline arrives (mirrors JsonRpcSession.feed).
|
|
557
|
+
this.#stdoutBuf += chunk;
|
|
558
|
+
if (this.#stdoutBuf.length > MAX_FRAME_BYTES) {
|
|
559
|
+
// A no-newline flood over the cap means the peer is broken or
|
|
560
|
+
// hostile: fail the turn and tear the process tree down instead of
|
|
561
|
+
// growing memory without bound.
|
|
562
|
+
const detail = `${this.#stdoutBuf.length} bytes buffered with no newline (cap ${MAX_FRAME_BYTES})`;
|
|
563
|
+
this.#stdoutBuf = "";
|
|
564
|
+
const turn = this.#active;
|
|
565
|
+
this.#log("frame-overflow", { detail });
|
|
566
|
+
if (turn && !turn.closed) this.#failTurn(turn, `stdout frame overflow: ${detail}`);
|
|
567
|
+
this.#killChild();
|
|
568
|
+
return;
|
|
569
|
+
}
|
|
570
|
+
const lines = this.#stdoutBuf.split("\n");
|
|
571
|
+
this.#stdoutBuf = lines.pop() ?? "";
|
|
572
|
+
const turn = this.#active;
|
|
573
|
+
if (!turn || turn.closed) return;
|
|
574
|
+
if (turn.idleTimer) turn.idleTimer.refresh();
|
|
575
|
+
for (const line of lines) {
|
|
576
|
+
if (!line.trim()) continue;
|
|
577
|
+
// Known foreign noise (e.g. the Chromium launcher behind a browser
|
|
578
|
+
// login) is dropped; a noise FRAGMENT glued onto a real frame is
|
|
579
|
+
// stripped so the frame still parses.
|
|
580
|
+
if (isKnownNoiseLine(line)) continue;
|
|
581
|
+
let parsed = parseAgyLine(line);
|
|
582
|
+
// Repair applies only to true parse failures (raw is the string
|
|
583
|
+
// fragment): a valid JSON object agy sent with an unrecognized shape
|
|
584
|
+
// also lands as "unknown" and must reach the turn untouched.
|
|
585
|
+
if (parsed.kind === "unknown" && typeof parsed.raw === "string") {
|
|
586
|
+
const repaired = stripGluedNoise(line);
|
|
587
|
+
if (repaired) parsed = parseAgyLine(repaired);
|
|
588
|
+
}
|
|
589
|
+
this.#applyParsed(turn, parsed);
|
|
590
|
+
if (turn.closed) return;
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
|
|
594
|
+
#applyParsed(turn: ActiveTurn, parsed: ReturnType<typeof parseAgyLine>): void {
|
|
595
|
+
switch (parsed.kind) {
|
|
596
|
+
case "init": {
|
|
597
|
+
if (parsed.conversationId) {
|
|
598
|
+
turn.conversationId = parsed.conversationId;
|
|
599
|
+
this.#boundConversation = parsed.conversationId;
|
|
600
|
+
}
|
|
601
|
+
if (parsed.usage) {
|
|
602
|
+
turn.usage = parsed.usage;
|
|
603
|
+
emit(turn, { type: "usage", usage: parsed.usage });
|
|
604
|
+
}
|
|
605
|
+
break;
|
|
606
|
+
}
|
|
607
|
+
case "step": {
|
|
608
|
+
const s = parsed.step;
|
|
609
|
+
if (s.conversation_id && !turn.conversationId) {
|
|
610
|
+
turn.conversationId = s.conversation_id;
|
|
611
|
+
this.#boundConversation = s.conversation_id;
|
|
612
|
+
}
|
|
613
|
+
if (s.usage) {
|
|
614
|
+
turn.usage = s.usage;
|
|
615
|
+
emit(turn, { type: "usage", usage: s.usage });
|
|
616
|
+
}
|
|
617
|
+
if (s.step_type === "agent_response") {
|
|
618
|
+
turn.sawModelStep = true;
|
|
619
|
+
const text =
|
|
620
|
+
typeof s.text_delta === "string"
|
|
621
|
+
? s.text_delta
|
|
622
|
+
: typeof s.response_text === "string"
|
|
623
|
+
? s.response_text
|
|
624
|
+
: "";
|
|
625
|
+
if (text) this.#appendAgentText(turn, text);
|
|
626
|
+
if (typeof s.thinking_tokens === "number" && s.thinking_tokens >= THINKING_TOKEN_FLOOR) {
|
|
627
|
+
emit(turn, { type: "thought", tokens: s.thinking_tokens });
|
|
628
|
+
}
|
|
629
|
+
break;
|
|
630
|
+
}
|
|
631
|
+
if (s.step_type === "tool") {
|
|
632
|
+
turn.sawModelStep = true;
|
|
633
|
+
const name = s.tool_name ?? s.tool_info?.name ?? "tool";
|
|
634
|
+
const args =
|
|
635
|
+
s.tool_info?.parameters && typeof s.tool_info.parameters === "object"
|
|
636
|
+
? (s.tool_info.parameters as Record<string, unknown>)
|
|
637
|
+
: {};
|
|
638
|
+
if (s.state === "ACTIVE") {
|
|
639
|
+
emit(turn, { type: "tool_start", stepId: s.step_index, name, args });
|
|
640
|
+
} else if (s.state === "DONE") {
|
|
641
|
+
emit(turn, {
|
|
642
|
+
type: "tool_done",
|
|
643
|
+
stepId: s.step_index,
|
|
644
|
+
name,
|
|
645
|
+
args,
|
|
646
|
+
output: typeof s.response_text === "string" ? s.response_text : undefined,
|
|
647
|
+
durationSeconds: s.duration_seconds,
|
|
648
|
+
});
|
|
649
|
+
} else if (s.state === "ERROR") {
|
|
650
|
+
emit(turn, {
|
|
651
|
+
type: "tool_error",
|
|
652
|
+
stepId: s.step_index,
|
|
653
|
+
name,
|
|
654
|
+
message: s.error_message ?? "tool error",
|
|
655
|
+
});
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
// user_input / checkpoint: no provider-facing activity.
|
|
659
|
+
break;
|
|
660
|
+
}
|
|
661
|
+
case "result": {
|
|
662
|
+
turn.sawResult = true;
|
|
663
|
+
const r = parsed.result;
|
|
664
|
+
if (r.conversation_id) turn.conversationId = r.conversation_id;
|
|
665
|
+
if (r.usage) turn.usage = r.usage;
|
|
666
|
+
// agy reports SUCCESS on live stream-json runs (OK seen in older builds).
|
|
667
|
+
const ok = r.status === "OK" || r.status === "SUCCESS";
|
|
668
|
+
const status = ok ? "OK" : "ERROR";
|
|
669
|
+
// Prefer the streamed accumulation, fall back to the result body.
|
|
670
|
+
const fallback = typeof r.response === "string" ? sanitizeSystemMessage(r.response) : "";
|
|
671
|
+
const response = turn.response || fallback;
|
|
672
|
+
if (!turn.response && fallback) {
|
|
673
|
+
turn.sanitizer.reset();
|
|
674
|
+
}
|
|
675
|
+
turn.response = response;
|
|
676
|
+
this.#settle(turn, {
|
|
677
|
+
conversationId: turn.conversationId,
|
|
678
|
+
status,
|
|
679
|
+
response,
|
|
680
|
+
error: status === "ERROR" ? (r.error ?? "agy reported an error") : undefined,
|
|
681
|
+
usage: r.usage ?? turn.usage,
|
|
682
|
+
finished: true,
|
|
683
|
+
aborted: false,
|
|
684
|
+
});
|
|
685
|
+
break;
|
|
686
|
+
}
|
|
687
|
+
default:
|
|
688
|
+
break;
|
|
689
|
+
}
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
#appendAgentText(turn: ActiveTurn, text: string): void {
|
|
693
|
+
// response_text is observed as a delta stream; guard against builds that
|
|
694
|
+
// resend the full text. A cumulative sender's second chunk CONTAINS
|
|
695
|
+
// everything accumulated so far as a prefix. Two guards against
|
|
696
|
+
// misflips (round-7 review): short accumulations never flip, and a
|
|
697
|
+
// cumulative frame that no longer extends the accumulator is evidence
|
|
698
|
+
// of a misflip - fall back to append mode.
|
|
699
|
+
let rawDelta = "";
|
|
700
|
+
if (turn.cumulativeText === undefined) {
|
|
701
|
+
turn.cumulativeText = false;
|
|
702
|
+
} else if (
|
|
703
|
+
!turn.cumulativeText &&
|
|
704
|
+
shouldFlipToCumulative(turn.rawResponse, text)
|
|
705
|
+
) {
|
|
706
|
+
turn.cumulativeText = true;
|
|
707
|
+
}
|
|
708
|
+
if (turn.cumulativeText) {
|
|
709
|
+
if (!text.startsWith(turn.rawResponse)) {
|
|
710
|
+
// Misflip evidence: back to deltas.
|
|
711
|
+
turn.cumulativeText = false;
|
|
712
|
+
turn.rawResponse += text;
|
|
713
|
+
rawDelta = text;
|
|
714
|
+
} else if (text.length > turn.rawResponse.length) {
|
|
715
|
+
rawDelta = text.slice(turn.rawResponse.length);
|
|
716
|
+
turn.rawResponse = text;
|
|
717
|
+
} else {
|
|
718
|
+
return;
|
|
719
|
+
}
|
|
720
|
+
} else {
|
|
721
|
+
turn.rawResponse += text;
|
|
722
|
+
rawDelta = text;
|
|
723
|
+
}
|
|
724
|
+
|
|
725
|
+
if (rawDelta.length > 0) {
|
|
726
|
+
const sanitizedDelta = turn.sanitizer.push(rawDelta);
|
|
727
|
+
if (sanitizedDelta.length > 0) {
|
|
728
|
+
turn.response += sanitizedDelta;
|
|
729
|
+
emit(turn, { type: "text", delta: sanitizedDelta });
|
|
730
|
+
}
|
|
731
|
+
}
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
#settle(turn: ActiveTurn, outcome: TurnOutcome): void {
|
|
735
|
+
if (turn.closed) return;
|
|
736
|
+
turn.closed = true;
|
|
737
|
+
const flushed = turn.sanitizer.flush();
|
|
738
|
+
if (flushed.length > 0) {
|
|
739
|
+
turn.response += flushed;
|
|
740
|
+
emit(turn, { type: "text", delta: flushed });
|
|
741
|
+
}
|
|
742
|
+
if (outcome.deadline && outcome.status === "OK") {
|
|
743
|
+
outcome.response = outcome.response || turn.response;
|
|
744
|
+
} else {
|
|
745
|
+
outcome.response = turn.response || outcome.response;
|
|
746
|
+
}
|
|
747
|
+
if (turn.overallTimer) clearTimeout(turn.overallTimer);
|
|
748
|
+
if (turn.idleTimer) clearTimeout(turn.idleTimer);
|
|
749
|
+
if (turn.onAbort && turn.request.signal) {
|
|
750
|
+
turn.request.signal.removeEventListener("abort", turn.onAbort);
|
|
751
|
+
}
|
|
752
|
+
this.#active = undefined;
|
|
753
|
+
this.#state = this.#child ? "ready" : "dead";
|
|
754
|
+
for (const wake of turn.wake) wake();
|
|
755
|
+
turn.wake = [];
|
|
756
|
+
// Evidence fields every consumer can rely on. modelOutputSeen separates a
|
|
757
|
+
// real (if terse) turn from agy's silent over-cap drop, which settles
|
|
758
|
+
// SUCCESS with NO model step, empty response, and zero usage (issue #2).
|
|
759
|
+
const usage = outcome.usage ?? turn.usage;
|
|
760
|
+
const enriched: TurnOutcome = {
|
|
761
|
+
...outcome,
|
|
762
|
+
usage,
|
|
763
|
+
sawResult: turn.sawResult,
|
|
764
|
+
modelOutputSeen:
|
|
765
|
+
turn.sawModelStep ||
|
|
766
|
+
outcome.response.length > 0 ||
|
|
767
|
+
hasTokenEvidence(usage),
|
|
768
|
+
};
|
|
769
|
+
turn.resolve(enriched);
|
|
770
|
+
try {
|
|
771
|
+
this.#onTurnEnd?.(enriched);
|
|
772
|
+
} catch {
|
|
773
|
+
/* listener errors must not break settling */
|
|
774
|
+
}
|
|
775
|
+
}
|
|
776
|
+
|
|
777
|
+
/** Stall / total-timeout guard shared by both timer sites. Kills the
|
|
778
|
+
* child FIRST (bumping the generation so a racing exit handler cannot
|
|
779
|
+
* settle the turn ERROR mid-probe), then probes the conversation's
|
|
780
|
+
* brain transcript for a clean final-response step written during the
|
|
781
|
+
* turn (parked turn: agy finished its answer but never streamed it).
|
|
782
|
+
* One found, the turn settles OK with the withheld answer instead of
|
|
783
|
+
* discarding finished work; either way the next turn respawns into a
|
|
784
|
+
* known state. */
|
|
785
|
+
async #turnDeadlineGuard(turn: ActiveTurn, label: "timeout" | "stall", message: string): Promise<void> {
|
|
786
|
+
if (turn.closed) return;
|
|
787
|
+
this.#log(`${label}:${turn.id}`);
|
|
788
|
+
this.#killChild();
|
|
789
|
+
let parked: string | undefined;
|
|
790
|
+
try {
|
|
791
|
+
parked = turn.conversationId
|
|
792
|
+
? await parkedTurnAnswer(turn.conversationId, turn.startedAt)
|
|
793
|
+
: undefined;
|
|
794
|
+
} catch {
|
|
795
|
+
parked = undefined; // the guard must never throw
|
|
796
|
+
}
|
|
797
|
+
if (parked !== undefined) {
|
|
798
|
+
this.#settle(turn, {
|
|
799
|
+
conversationId: turn.conversationId,
|
|
800
|
+
status: "OK",
|
|
801
|
+
response: sanitizeSystemMessage(parked),
|
|
802
|
+
usage: turn.usage,
|
|
803
|
+
finished: true,
|
|
804
|
+
aborted: false,
|
|
805
|
+
deadline: label,
|
|
806
|
+
});
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
this.#failTurn(turn, message, label);
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
#failTurn(turn: ActiveTurn, message: string, deadline?: "timeout" | "stall"): void {
|
|
813
|
+
this.#settle(turn, {
|
|
814
|
+
conversationId: turn.conversationId,
|
|
815
|
+
status: "ERROR",
|
|
816
|
+
response: turn.response,
|
|
817
|
+
error: message,
|
|
818
|
+
usage: turn.usage,
|
|
819
|
+
finished: true,
|
|
820
|
+
aborted: false,
|
|
821
|
+
deadline,
|
|
822
|
+
});
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
#recycleCause(next: DriverTurnRequest): string | undefined {
|
|
826
|
+
const cur = this.#profile;
|
|
827
|
+
if (!cur) return undefined;
|
|
828
|
+
if (cur.cwd !== next.cwd) return "cwd";
|
|
829
|
+
if (cur.model !== next.model) return "model";
|
|
830
|
+
if (cur.effort !== next.effort) return "effort";
|
|
831
|
+
if (cur.mode !== next.mode) return "mode";
|
|
832
|
+
if (cur.skipPermissions !== effectiveSkipPermissions(next.mode, next.skipPermissions)) {
|
|
833
|
+
return "permissions";
|
|
834
|
+
}
|
|
835
|
+
if (cur.agent !== next.agent) return "agent";
|
|
836
|
+
if (!next.conversationId) return this.#boundConversation ? "conversation-reset" : undefined;
|
|
837
|
+
return next.conversationId === this.#boundConversation ? undefined : "conversation";
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
async close(reason: "recycle" | "shutdown", cause?: string): Promise<void> {
|
|
841
|
+
const child = this.#child;
|
|
842
|
+
if (reason === "recycle" && cause) {
|
|
843
|
+
this.#stats.recycles += 1;
|
|
844
|
+
this.#stats.lastRecycleReason = cause;
|
|
845
|
+
this.#stats.recycleReasons[cause] = (this.#stats.recycleReasons[cause] ?? 0) + 1;
|
|
846
|
+
}
|
|
847
|
+
this.#log(`close:${reason}${cause ? `:${cause}` : ""}`);
|
|
848
|
+
const turn = this.#active;
|
|
849
|
+
if (turn && !turn.closed) {
|
|
850
|
+
this.#failTurn(turn, `agy driver ${reason === "recycle" ? "recycled" : "shut down"} mid-turn${cause ? ` (${cause})` : ""}`);
|
|
851
|
+
}
|
|
852
|
+
// Home disposal must NOT be gated on a live child: the child can exit
|
|
853
|
+
// (or be deadline-killed) well before close runs, and an early return
|
|
854
|
+
// would strand the staged home with its stale own entry (issue #14
|
|
855
|
+
// review round 2, blocker 2).
|
|
856
|
+
const home = this.#stagedHomePath;
|
|
857
|
+
const homePid = child?.pid ?? this.#lastChildPid;
|
|
858
|
+
if (child) this.#killChild();
|
|
859
|
+
this.#state = reason === "shutdown" ? "dead" : "idle";
|
|
860
|
+
if (home && this.releaseStagedHome) {
|
|
861
|
+
// Leader death is not group death: agy's own subprocesses can
|
|
862
|
+
// outlive it and late writes would recreate a removed home dir
|
|
863
|
+
// (issue #14 reporter's shutdown trap). Wait for the group, then
|
|
864
|
+
// dispose; the session-start sweep is the backstop for stragglers.
|
|
865
|
+
await waitForPidGroupExit(homePid);
|
|
866
|
+
this.#stagedHomePath = undefined;
|
|
867
|
+
await this.releaseStagedHome(home, homePid);
|
|
868
|
+
}
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
#killChild(): void {
|
|
872
|
+
const child = this.#child;
|
|
873
|
+
if (!child) return;
|
|
874
|
+
this.#child = undefined;
|
|
875
|
+
this.#generation += 1;
|
|
876
|
+
this.#stdoutBuf = "";
|
|
877
|
+
try {
|
|
878
|
+
child.stdout?.removeAllListeners();
|
|
879
|
+
child.stderr?.removeAllListeners();
|
|
880
|
+
} catch {
|
|
881
|
+
/* already gone */
|
|
882
|
+
}
|
|
883
|
+
try {
|
|
884
|
+
if (process.platform !== "win32" && child.pid) {
|
|
885
|
+
process.kill(-child.pid, "SIGTERM");
|
|
886
|
+
setTimeout(() => {
|
|
887
|
+
try {
|
|
888
|
+
if (child.pid) process.kill(-child.pid, "SIGKILL");
|
|
889
|
+
} catch {
|
|
890
|
+
/* already dead */
|
|
891
|
+
}
|
|
892
|
+
}, 750);
|
|
893
|
+
} else {
|
|
894
|
+
child.kill("SIGTERM");
|
|
895
|
+
}
|
|
896
|
+
} catch {
|
|
897
|
+
/* already dead */
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
#log(msg: string, data?: unknown): void {
|
|
902
|
+
const line = `${nowIso()} ${msg}${data !== undefined ? ` ${JSON.stringify(data)}` : ""}`;
|
|
903
|
+
this.#lifecycle.push(line);
|
|
904
|
+
if (this.#lifecycle.length > LIFECYCLE_LIMIT) this.#lifecycle.shift();
|
|
905
|
+
this.log?.(msg, data);
|
|
906
|
+
}
|
|
907
|
+
}
|