@moondeck/station 1.0.12 → 1.0.14
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/images/standard/Dockerfile +32 -0
- package/images/standard/README.md +7 -7
- package/lib/agent-cli-issue-attachments.ts +117 -0
- package/lib/agent-cli-issue-comments.ts +103 -0
- package/lib/agent-cli-issues.ts +445 -0
- package/lib/agent-cli.ts +153 -45
- package/lib/agents/agy-pin.ts +36 -0
- package/lib/agents/agy-scrub.ts +11 -0
- package/lib/agents/claude.ts +5 -2
- package/lib/agents/codex.ts +5 -0
- package/lib/agents/factory.ts +1 -0
- package/lib/agents/gemini-credentials.ts +61 -0
- package/lib/agents/gemini-stream.fixture.json +439 -0
- package/lib/agents/gemini.ts +836 -0
- package/lib/agents/transport.ts +5 -2
- package/lib/credential-cleanup-inventory.ts +19 -1
- package/lib/credential-consumers/engines.ts +70 -9
- package/lib/engine-accounts.ts +3 -0
- package/lib/engine-login.ts +162 -7
- package/lib/engine-spawn-env.ts +63 -0
- package/lib/issue-markdown.generated.ts +658 -0
- package/lib/orchestrator.ts +68 -25
- package/lib/standard-image-pin.ts +2 -1
- package/lib/standard-image.ts +9 -1
- package/lib/task-credential-cleanup.ts +3 -1
- package/package.json +1 -1
- package/scripts/agent/task-up.sh +36 -0
- package/scripts/agent/uai-env-exec.sh +89 -1
- package/src/cloud-credentials.ts +6 -0
- package/src/engine-account-paths.ts +2 -0
- package/src/engine-usage.ts +1 -0
- package/src/index.ts +4 -1
- package/src/main.ts +7 -1
- package/src/protocol.ts +7 -4
- package/src/task-env-names.ts +70 -0
|
@@ -0,0 +1,836 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* GeminiSession — a real AgentSession backed by Google's **Antigravity CLI**
|
|
3
|
+
* (`agy`), run inside the task environment on the operator's own Google AI
|
|
4
|
+
* subscription (Free / Plus / Pro / Ultra):
|
|
5
|
+
*
|
|
6
|
+
* sh -c '<preflight; exec agy>' gemini-agy /home/node/.local/bin/agy \
|
|
7
|
+
* -p "<prompt>" --output-format stream-json \
|
|
8
|
+
* --dangerously-skip-permissions --disable-slash-commands \
|
|
9
|
+
* [--model <slug>] [--conversation <conversationId>]
|
|
10
|
+
*
|
|
11
|
+
* One-shot per turn (like Cursor/Grok/Kimi); sends serialized; continuity via
|
|
12
|
+
* `--conversation <id>` captured from the stream. Verified against agy 1.5.16
|
|
13
|
+
* on a Google AI Plus account (docs/gemini-antigravity-engine.md; redacted
|
|
14
|
+
* captures in gemini-stream.fixture.json):
|
|
15
|
+
*
|
|
16
|
+
* {"event":"init","conversation_id":…,"init":{model,cwd,tools,permission_mode}}
|
|
17
|
+
* → conversation id
|
|
18
|
+
* {"event":"step_update","step_update":{step_type:"agent_response",
|
|
19
|
+
* state:"ACTIVE"|"DONE",text_delta?,usage?}} → message_delta
|
|
20
|
+
* {"event":"step_update","step_update":{step_type:"tool",tool_name,
|
|
21
|
+
* tool_info:{name,parameters,output?}}} → tool_call card (once per step)
|
|
22
|
+
* {"event":"step_update",…subagent_info…} → tool_call card
|
|
23
|
+
* user_input / system_message / checkpoint steps → skipped (usage still summed)
|
|
24
|
+
* {"event":"result","result":{status,response,error?,finished_reason?,usage}}
|
|
25
|
+
* → message_complete + turn end
|
|
26
|
+
*
|
|
27
|
+
* USAGE: `result.usage` is cumulative over the whole CONVERSATION even in a
|
|
28
|
+
* one-shot `--conversation` run, so per-turn usage is the sum of this run's
|
|
29
|
+
* per-step `usage` (one entry per step_index). `input_tokens` excludes
|
|
30
|
+
* `cache_read_tokens`; `output_tokens` already includes `thinking_tokens`.
|
|
31
|
+
* No cost: it's a subscription. Account limits are Moondeck-observed (no
|
|
32
|
+
* provider windows on the turn stream); `parseAgyUsageCommand` reads the
|
|
33
|
+
* on-demand `agy -p /usage --output-format json` report for when a reader is
|
|
34
|
+
* wired up.
|
|
35
|
+
*
|
|
36
|
+
* BRIEFING: agy has no system-prompt flag, and a custom `--agent` agent.md
|
|
37
|
+
* strips the default toolset (verified), so the briefing folds into turn 1
|
|
38
|
+
* like Cursor.
|
|
39
|
+
*
|
|
40
|
+
* PERMISSIONS: `--dangerously-skip-permissions`. The container is the
|
|
41
|
+
* sandbox, and agy's own sandbox (and so its `auto` mode) needs unprivileged
|
|
42
|
+
* user namespaces that task containers don't have. Without the flag, shell
|
|
43
|
+
* commands are silently soft-denied.
|
|
44
|
+
*
|
|
45
|
+
* AUTH: agy's own file token store (see gemini-credentials.ts, the seam for the
|
|
46
|
+
* pending ADR-154 decision). A tiny in-container sh wrapper checks the token
|
|
47
|
+
* file EXISTS before agy starts (exit 97 → clear "sign in" error), because a
|
|
48
|
+
* signed-out agy prints a login URL and blocks ~60 s on a paste prompt. A
|
|
49
|
+
* stderr `Authentication required` line is caught as a backstop. Nothing here
|
|
50
|
+
* ever reads the token; stderr is scrubbed of OAuth URLs before it can reach
|
|
51
|
+
* an error message.
|
|
52
|
+
*
|
|
53
|
+
* INTERRUPT: the wrapper exec's agy, so TERM/INT/HUP reach agy itself. A stop
|
|
54
|
+
* sends SIGTERM, which agy treats like SIGINT (it ends the turn with
|
|
55
|
+
* `finished_reason:"interrupted"`, verified on 1.5.16), then SIGKILL after the
|
|
56
|
+
* grace period. Where the provider cannot deliver the signal into the
|
|
57
|
+
* container (docker exec doesn't proxy it), killing the client still ends the
|
|
58
|
+
* turn here, as for the other one-shot engines; agy may outlive it but can
|
|
59
|
+
* only touch its own agy dir.
|
|
60
|
+
*/
|
|
61
|
+
|
|
62
|
+
import { requireContainerRuntimeOperational } from "../runtime-guard";
|
|
63
|
+
import type {
|
|
64
|
+
TaskEnvironmentAgentSessionSurface,
|
|
65
|
+
TaskEnvironmentSessionRequest,
|
|
66
|
+
} from "../task-environment/types";
|
|
67
|
+
import type { EngineUsageWindow } from "../../src/protocol";
|
|
68
|
+
import {
|
|
69
|
+
AGENT_SESSION_OUTPUT_BUFFER_BYTES,
|
|
70
|
+
spawnEnvironmentProcess,
|
|
71
|
+
type AgentEnvironmentProcess,
|
|
72
|
+
} from "./proc";
|
|
73
|
+
import { rateLimitErrorUsage } from "./rate-limit";
|
|
74
|
+
import { GEMINI_SPAWN_BLANKS } from "../engine-spawn-env";
|
|
75
|
+
import { register } from "./registry";
|
|
76
|
+
import {
|
|
77
|
+
AGY_LOGIN_COMMAND,
|
|
78
|
+
geminiCredentialSource,
|
|
79
|
+
} from "./gemini-credentials";
|
|
80
|
+
import type {
|
|
81
|
+
AgentEvent,
|
|
82
|
+
AgentEventHandler,
|
|
83
|
+
AgentKind,
|
|
84
|
+
AgentSession,
|
|
85
|
+
AgentUsage,
|
|
86
|
+
RosterAgent,
|
|
87
|
+
} from "./types";
|
|
88
|
+
|
|
89
|
+
/** Installed by the image's INSTALL_GEMINI layer (and by Google's
|
|
90
|
+
* install.sh); absolute so a non-login provider process doesn't need PATH. */
|
|
91
|
+
export const AGY_BIN = "/home/node/.local/bin/agy";
|
|
92
|
+
|
|
93
|
+
/** Exit status of the wrapper when the token file is missing. */
|
|
94
|
+
export const GEMINI_SIGNED_OUT_EXIT = 97;
|
|
95
|
+
|
|
96
|
+
/** Exit status of the wrapper when the agy binary isn't in this environment
|
|
97
|
+
* (an image built without INSTALL_GEMINI, or a Cloud machine image that
|
|
98
|
+
* doesn't carry it yet). */
|
|
99
|
+
export const GEMINI_NOT_INSTALLED_EXIT = 96;
|
|
100
|
+
|
|
101
|
+
export const GEMINI_NOT_INSTALLED_MESSAGE =
|
|
102
|
+
"The Antigravity CLI (agy) isn't installed in this task's environment, so " +
|
|
103
|
+
"Gemini agents can't run here yet. Use another engine for this task.";
|
|
104
|
+
|
|
105
|
+
/** Exit status of the wrapper when the spawn has no agy dir of its own
|
|
106
|
+
* (UAI_GEMINI_DIR unset or empty): fail closed rather than use ~/.gemini. */
|
|
107
|
+
export const GEMINI_NO_DIR_EXIT = 95;
|
|
108
|
+
|
|
109
|
+
export const GEMINI_NO_DIR_MESSAGE =
|
|
110
|
+
"This Gemini agent has no account directory of its own (UAI_GEMINI_DIR), so it " +
|
|
111
|
+
"won't run: Gemini agents run only on an AI account from Connections → AI Accounts.";
|
|
112
|
+
|
|
113
|
+
/** Exit status of the wrapper when an API-key account has an empty key. */
|
|
114
|
+
export const GEMINI_MISSING_KEY_EXIT = 98;
|
|
115
|
+
|
|
116
|
+
/** The env var an API-key Gemini account sets (ADR-154 §6 env-token lane). */
|
|
117
|
+
export const GEMINI_API_KEY_ENV = "GEMINI_API_KEY";
|
|
118
|
+
|
|
119
|
+
/** agy's documented switch to the Gemini API: a per-run settings overlay,
|
|
120
|
+
* never written to settings.json. Verified on 1.5.16. */
|
|
121
|
+
export const GEMINI_API_KEY_SETTINGS = '{"modelProvider":"gemini"}';
|
|
122
|
+
|
|
123
|
+
export const GEMINI_MISSING_KEY_MESSAGE =
|
|
124
|
+
"This Gemini account's API key is missing or empty. Paste the key again in " +
|
|
125
|
+
"Connections → AI Accounts, then send the message again.";
|
|
126
|
+
|
|
127
|
+
export const GEMINI_INVALID_KEY_MESSAGE =
|
|
128
|
+
"Google rejected this Gemini API key (API_KEY_INVALID). Paste a valid key in " +
|
|
129
|
+
"Connections → AI Accounts, then send the message again.";
|
|
130
|
+
|
|
131
|
+
export type GeminiAuthMode = "subscription" | "api-key";
|
|
132
|
+
|
|
133
|
+
/** Set by the leased-account env (credential-consumers/engines.ts,
|
|
134
|
+
* GEMINI_AUTH_ENV) to the account's kind. Mirrored here so the adapter needn't
|
|
135
|
+
* import the consumer. */
|
|
136
|
+
export const GEMINI_AUTH_MARKER_ENV = "UAI_GEMINI_AUTH";
|
|
137
|
+
|
|
138
|
+
/** The leased credential decides the mode: the marker says which kind of
|
|
139
|
+
* account this is (a leased spawn also carries GEMINI_API_KEY blanked for a
|
|
140
|
+
* subscription account, so key presence alone can't decide). Without a
|
|
141
|
+
* marker (a runner's own sign-in), a non-empty key means API-key mode. */
|
|
142
|
+
export function geminiAuthMode(agentEnv: Record<string, string>): GeminiAuthMode {
|
|
143
|
+
const marker = agentEnv[GEMINI_AUTH_MARKER_ENV];
|
|
144
|
+
if (marker === "api-key" || marker === "subscription") return marker;
|
|
145
|
+
return (agentEnv[GEMINI_API_KEY_ENV] ?? "").length > 0 ? "api-key" : "subscription";
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export const GEMINI_SIGNED_OUT_MESSAGE =
|
|
149
|
+
"Gemini isn't signed in. Sign in to Antigravity on this machine: run " +
|
|
150
|
+
`\`${AGY_LOGIN_COMMAND}\` in a terminal, then send the message again.`;
|
|
151
|
+
|
|
152
|
+
// The effort is part of the slug, so no separate effort flag; any id is
|
|
153
|
+
// typable. One list serves both auth modes, Hydrogen (every plan, and the
|
|
154
|
+
// Free/Plus default) first:
|
|
155
|
+
// - subscription: `agy models` on a Google AI Plus account, agy 1.5.16
|
|
156
|
+
// (2026-11-24). Gemini 3.8 Flash, Claude 4.6 and GPT-OSS leave Free/Plus
|
|
157
|
+
// on 2026-11-30 (antigravity.google/docs/models); drop them then. Pro /
|
|
158
|
+
// Ultra add Neon, Carbon and Argon.
|
|
159
|
+
// - API key (`modelProvider: "gemini"`): agy's built-in Gemini API catalog,
|
|
160
|
+
// listed by `agy models` with a placeholder key (no real key was available
|
|
161
|
+
// to verify which a given key can call): Neon, Carbon, Argon, Hydrogen,
|
|
162
|
+
// 3.8/3.7/3.6 Flash, 3.1 Pro.
|
|
163
|
+
export const GEMINI_MODELS = [
|
|
164
|
+
"gemini-4-hydrogen-medium",
|
|
165
|
+
"gemini-4-hydrogen-high",
|
|
166
|
+
"gemini-4-hydrogen-xhigh",
|
|
167
|
+
"gemini-4-hydrogen-low",
|
|
168
|
+
"gemini-3.8-flash-high",
|
|
169
|
+
"gemini-3.8-flash-medium",
|
|
170
|
+
"gemini-3.8-flash-low",
|
|
171
|
+
"gemini-4-neon-high",
|
|
172
|
+
"gemini-4-carbon-high",
|
|
173
|
+
"gemini-4-argon-high",
|
|
174
|
+
"gemini-3.1-pro-high",
|
|
175
|
+
"claude-sonnet-4-6",
|
|
176
|
+
"claude-opus-4-6-thinking",
|
|
177
|
+
"gpt-oss-120b-medium",
|
|
178
|
+
];
|
|
179
|
+
const GEMINI_DEFAULT_MODEL = "gemini-4-hydrogen-medium";
|
|
180
|
+
const GEMINI_EFFORTS: string[] = []; // effort is baked into the model slug
|
|
181
|
+
|
|
182
|
+
/** How long an interrupted agy gets to write its interrupted result before
|
|
183
|
+
* the client is killed outright. */
|
|
184
|
+
const INTERRUPT_GRACE_MS = 5_000;
|
|
185
|
+
const STDERR_KEEP_CHARS = 16_384;
|
|
186
|
+
|
|
187
|
+
// ---------------------------------------------------------------------------
|
|
188
|
+
// In-container launcher.
|
|
189
|
+
// ---------------------------------------------------------------------------
|
|
190
|
+
|
|
191
|
+
/** The env var naming the agy "gemini dir" a spawn runs in: a leased
|
|
192
|
+
* subscription's per-agent home (credential-consumers/engines.ts), or the
|
|
193
|
+
* API-key dir set below. agy gets it as `--gemini_dir` (agy 1.5.16: a flag
|
|
194
|
+
* the CLI accepts and `agy acp --help` documents; it moves agy's token store
|
|
195
|
+
* and conversations, while HOME, and so the commands agy runs, stay put). */
|
|
196
|
+
export const GEMINI_DIR_ENV = "UAI_GEMINI_DIR";
|
|
197
|
+
|
|
198
|
+
/** POSIX sh: the mode's preflight (subscription: the token file exists, never
|
|
199
|
+
* read; API key: GEMINI_API_KEY is non-empty, since agy itself exits 0 with
|
|
200
|
+
* empty output when it's unset, and any token file in its dir is removed so
|
|
201
|
+
* an API-key spawn never sees one), then `exec` agy with `--gemini_dir`.
|
|
202
|
+
* exec, not a background child: a stop or kill reaches agy itself, and no
|
|
203
|
+
* agy can outlive its launcher and rewrite a token file. `$@` is the agy
|
|
204
|
+
* argv. */
|
|
205
|
+
export function geminiLauncherScript(
|
|
206
|
+
tokenRelativePath: string,
|
|
207
|
+
mode: GeminiAuthMode = "subscription",
|
|
208
|
+
): string {
|
|
209
|
+
if (
|
|
210
|
+
!/^[A-Za-z0-9._/-]+$/.test(tokenRelativePath) ||
|
|
211
|
+
tokenRelativePath.startsWith("/") ||
|
|
212
|
+
tokenRelativePath.split("/").some((part) => part === ".." || part === "." || part === "")
|
|
213
|
+
) {
|
|
214
|
+
throw new Error("gemini token path must be a plain relative path");
|
|
215
|
+
}
|
|
216
|
+
const preflight =
|
|
217
|
+
mode === "api-key"
|
|
218
|
+
? [
|
|
219
|
+
`if [ -z "$${GEMINI_API_KEY_ENV}" ]; then echo "uai-gemini: GEMINI_API_KEY is empty" >&2; exit ${GEMINI_MISSING_KEY_EXIT}; fi`,
|
|
220
|
+
`rm -f "$gd/${tokenRelativePath}"`,
|
|
221
|
+
]
|
|
222
|
+
: [
|
|
223
|
+
`if [ ! -s "$gd/${tokenRelativePath}" ]; then echo "uai-gemini: not signed in to Antigravity" >&2; exit ${GEMINI_SIGNED_OUT_EXIT}; fi`,
|
|
224
|
+
];
|
|
225
|
+
return [
|
|
226
|
+
`if [ ! -x "$1" ]; then echo "uai-gemini: agy is not installed" >&2; exit ${GEMINI_NOT_INSTALLED_EXIT}; fi`,
|
|
227
|
+
`gd="\${${GEMINI_DIR_ENV}:-}"`,
|
|
228
|
+
`if [ -z "$gd" ]; then echo "uai-gemini: no agy dir (UAI_GEMINI_DIR)" >&2; exit ${GEMINI_NO_DIR_EXIT}; fi`,
|
|
229
|
+
...preflight,
|
|
230
|
+
`exec "$@" --gemini_dir "$gd" </dev/null`,
|
|
231
|
+
].join("\n");
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// ---------------------------------------------------------------------------
|
|
235
|
+
// Pure protocol mapping.
|
|
236
|
+
// ---------------------------------------------------------------------------
|
|
237
|
+
|
|
238
|
+
export interface AgyResult {
|
|
239
|
+
status: string;
|
|
240
|
+
response: string;
|
|
241
|
+
error?: string;
|
|
242
|
+
finishedReason?: string;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
export interface MappedAgyLine {
|
|
246
|
+
conversationId?: string;
|
|
247
|
+
model?: string;
|
|
248
|
+
textDelta?: string;
|
|
249
|
+
/** A tool or subagent step; `stepIndex` de-duplicates ACTIVE/DONE. */
|
|
250
|
+
toolCall?: { stepIndex: number; title: string; detail: string };
|
|
251
|
+
/** Per-step token usage (the latest one per step_index wins). */
|
|
252
|
+
stepUsage?: { stepIndex: number; usage: AgyTokenCounts };
|
|
253
|
+
result?: AgyResult;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
export interface AgyTokenCounts {
|
|
257
|
+
input: number;
|
|
258
|
+
output: number;
|
|
259
|
+
cacheRead: number;
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
function obj(value: unknown): Record<string, unknown> | undefined {
|
|
263
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
264
|
+
? (value as Record<string, unknown>)
|
|
265
|
+
: undefined;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
function count(value: unknown): number {
|
|
269
|
+
return typeof value === "number" && Number.isSafeInteger(value) && value >= 0 ? value : 0;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function tokenCounts(value: unknown): AgyTokenCounts | undefined {
|
|
273
|
+
const u = obj(value);
|
|
274
|
+
if (!u) return undefined;
|
|
275
|
+
return {
|
|
276
|
+
input: count(u.input_tokens),
|
|
277
|
+
// agy's output_tokens already includes thinking_tokens (verified:
|
|
278
|
+
// total_tokens = input_tokens + output_tokens).
|
|
279
|
+
output: count(u.output_tokens),
|
|
280
|
+
cacheRead: count(u.cache_read_tokens),
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
// agy tool parameters are PascalCase (`CommandLine` on run_command).
|
|
285
|
+
const TOOL_DETAIL_KEYS = [
|
|
286
|
+
"CommandLine",
|
|
287
|
+
"Command",
|
|
288
|
+
"AbsolutePath",
|
|
289
|
+
"TargetFile",
|
|
290
|
+
"FilePath",
|
|
291
|
+
"Path",
|
|
292
|
+
"DirectoryPath",
|
|
293
|
+
"SearchPath",
|
|
294
|
+
"Query",
|
|
295
|
+
"Url",
|
|
296
|
+
"command",
|
|
297
|
+
"path",
|
|
298
|
+
"file_path",
|
|
299
|
+
"query",
|
|
300
|
+
"url",
|
|
301
|
+
];
|
|
302
|
+
|
|
303
|
+
function toolDetail(parameters: unknown): string {
|
|
304
|
+
const params = obj(parameters);
|
|
305
|
+
if (!params) return "";
|
|
306
|
+
for (const key of TOOL_DETAIL_KEYS) {
|
|
307
|
+
const v = params[key];
|
|
308
|
+
if (typeof v === "string" && v.trim()) return v.slice(0, 500);
|
|
309
|
+
}
|
|
310
|
+
for (const v of Object.values(params)) {
|
|
311
|
+
if (typeof v === "string" && v.trim()) return v.slice(0, 500);
|
|
312
|
+
}
|
|
313
|
+
return "";
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
export function mapAgyLine(line: string): MappedAgyLine {
|
|
317
|
+
const t = line.trim();
|
|
318
|
+
if (!t.startsWith("{")) return {};
|
|
319
|
+
let m: Record<string, unknown>;
|
|
320
|
+
try {
|
|
321
|
+
m = JSON.parse(t) as Record<string, unknown>;
|
|
322
|
+
} catch {
|
|
323
|
+
return {};
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
if (m.event === "init") {
|
|
327
|
+
const init = obj(m.init);
|
|
328
|
+
return {
|
|
329
|
+
...(typeof m.conversation_id === "string" && m.conversation_id
|
|
330
|
+
? { conversationId: m.conversation_id }
|
|
331
|
+
: {}),
|
|
332
|
+
...(typeof init?.model === "string" ? { model: init.model } : {}),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
if (m.event === "step_update") {
|
|
337
|
+
const s = obj(m.step_update);
|
|
338
|
+
if (!s) return {};
|
|
339
|
+
const stepIndex = typeof s.step_index === "number" ? s.step_index : -1;
|
|
340
|
+
const out: MappedAgyLine = {};
|
|
341
|
+
if (typeof s.conversation_id === "string" && s.conversation_id) {
|
|
342
|
+
out.conversationId = s.conversation_id;
|
|
343
|
+
}
|
|
344
|
+
const usage = tokenCounts(s.usage);
|
|
345
|
+
if (usage && stepIndex >= 0) out.stepUsage = { stepIndex, usage };
|
|
346
|
+
if (s.step_type === "agent_response" && typeof s.text_delta === "string" && s.text_delta) {
|
|
347
|
+
out.textDelta = s.text_delta;
|
|
348
|
+
}
|
|
349
|
+
if (s.step_type === "tool" && stepIndex >= 0) {
|
|
350
|
+
const info = obj(s.tool_info);
|
|
351
|
+
const name =
|
|
352
|
+
(typeof s.tool_name === "string" && s.tool_name) ||
|
|
353
|
+
(typeof info?.name === "string" && info.name) ||
|
|
354
|
+
"tool";
|
|
355
|
+
out.toolCall = { stepIndex, title: name, detail: toolDetail(info?.parameters) };
|
|
356
|
+
} else if (stepIndex >= 0 && obj(s.subagent_info)) {
|
|
357
|
+
const subs = obj(s.subagent_info)?.subagents;
|
|
358
|
+
const roles = Array.isArray(subs)
|
|
359
|
+
? subs
|
|
360
|
+
.map((x) => {
|
|
361
|
+
const sub = obj(x);
|
|
362
|
+
return typeof sub?.role === "string"
|
|
363
|
+
? sub.role
|
|
364
|
+
: typeof sub?.type_name === "string"
|
|
365
|
+
? sub.type_name
|
|
366
|
+
: "";
|
|
367
|
+
})
|
|
368
|
+
.filter(Boolean)
|
|
369
|
+
: [];
|
|
370
|
+
out.toolCall = { stepIndex, title: "subagent", detail: roles.join(", ") };
|
|
371
|
+
}
|
|
372
|
+
return out;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
if (m.event === "result") {
|
|
376
|
+
const r = obj(m.result);
|
|
377
|
+
if (!r) return {};
|
|
378
|
+
return {
|
|
379
|
+
...(typeof r.conversation_id === "string" && r.conversation_id
|
|
380
|
+
? { conversationId: r.conversation_id }
|
|
381
|
+
: {}),
|
|
382
|
+
result: {
|
|
383
|
+
status: typeof r.status === "string" ? r.status : "ERROR",
|
|
384
|
+
response: typeof r.response === "string" ? r.response : "",
|
|
385
|
+
...(typeof r.error === "string" && r.error ? { error: r.error } : {}),
|
|
386
|
+
...(typeof r.finished_reason === "string"
|
|
387
|
+
? { finishedReason: r.finished_reason }
|
|
388
|
+
: {}),
|
|
389
|
+
},
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
return {};
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
/** Sum one run's per-step usage into the turn's AgentUsage. */
|
|
396
|
+
export function sumAgyStepUsage(
|
|
397
|
+
steps: ReadonlyMap<number, AgyTokenCounts>,
|
|
398
|
+
model: string | undefined,
|
|
399
|
+
): AgentUsage | undefined {
|
|
400
|
+
if (steps.size === 0) return undefined;
|
|
401
|
+
let input = 0;
|
|
402
|
+
let output = 0;
|
|
403
|
+
let cacheRead = 0;
|
|
404
|
+
for (const u of steps.values()) {
|
|
405
|
+
input += u.input;
|
|
406
|
+
output += u.output;
|
|
407
|
+
cacheRead += u.cacheRead;
|
|
408
|
+
}
|
|
409
|
+
return {
|
|
410
|
+
...(model ? { model } : {}),
|
|
411
|
+
inputTokens: input,
|
|
412
|
+
outputTokens: output,
|
|
413
|
+
cacheReadTokens: cacheRead,
|
|
414
|
+
};
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export function isAgyInterrupted(result: AgyResult): boolean {
|
|
418
|
+
return (
|
|
419
|
+
result.finishedReason === "interrupted" ||
|
|
420
|
+
result.status === "INTERRUPTED" ||
|
|
421
|
+
result.status === "CANCELED"
|
|
422
|
+
);
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const AUTH_FAILURE = /authentication (?:required|failed|timed out|interrupted)|please sign in/i;
|
|
426
|
+
|
|
427
|
+
export function isAgyAuthFailure(text: string | undefined): boolean {
|
|
428
|
+
return Boolean(text && AUTH_FAILURE.test(text));
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
export { scrubAgyDiagnostics } from "./agy-scrub";
|
|
432
|
+
import { scrubAgyDiagnostics } from "./agy-scrub";
|
|
433
|
+
|
|
434
|
+
// ---------------------------------------------------------------------------
|
|
435
|
+
// `agy -p /usage --output-format json` reader (pure).
|
|
436
|
+
// ---------------------------------------------------------------------------
|
|
437
|
+
|
|
438
|
+
export interface GeminiQuotaReading {
|
|
439
|
+
status: "allowed" | "warning" | "limited";
|
|
440
|
+
/** Earliest reset among exhausted buckets, epoch ms. */
|
|
441
|
+
resetsAt?: number;
|
|
442
|
+
windows: EngineUsageWindow[];
|
|
443
|
+
observedAt: number;
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
const WINDOW_MINUTES: Record<string, number> = { weekly: 7 * 24 * 60, "5h": 5 * 60 };
|
|
447
|
+
const QUOTA_WARNING_REMAINING = 0.1;
|
|
448
|
+
|
|
449
|
+
/**
|
|
450
|
+
* Parse agy's `/usage` command envelope:
|
|
451
|
+
* {command:{name:"usage",data:{groups:[{name,buckets:[{id,window,
|
|
452
|
+
* remaining_fraction,reset_time}]}]}}}
|
|
453
|
+
* Each bucket becomes an EngineUsageWindow named by its id (gemini-weekly,
|
|
454
|
+
* 3p-weekly, 3p-5h). A bucket that hasn't started reports reset_time
|
|
455
|
+
* 1970-01-01, which is treated as no reset. Returns null for anything else.
|
|
456
|
+
*/
|
|
457
|
+
export function parseAgyUsageCommand(
|
|
458
|
+
raw: string | unknown,
|
|
459
|
+
now: number = Date.now(),
|
|
460
|
+
): GeminiQuotaReading | null {
|
|
461
|
+
let envelope: unknown = raw;
|
|
462
|
+
if (typeof raw === "string") {
|
|
463
|
+
try {
|
|
464
|
+
envelope = JSON.parse(raw);
|
|
465
|
+
} catch {
|
|
466
|
+
return null;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
const command = obj(obj(envelope)?.command);
|
|
470
|
+
if (command?.name !== "usage") return null;
|
|
471
|
+
const groups = obj(command.data)?.groups;
|
|
472
|
+
if (!Array.isArray(groups)) return null;
|
|
473
|
+
const windows: EngineUsageWindow[] = [];
|
|
474
|
+
let status: GeminiQuotaReading["status"] = "allowed";
|
|
475
|
+
let resetsAt: number | undefined;
|
|
476
|
+
for (const g of groups) {
|
|
477
|
+
const buckets = obj(g)?.buckets;
|
|
478
|
+
if (!Array.isArray(buckets)) continue;
|
|
479
|
+
for (const b of buckets) {
|
|
480
|
+
const bucket = obj(b);
|
|
481
|
+
if (!bucket || typeof bucket.id !== "string" || !bucket.id) continue;
|
|
482
|
+
const window: EngineUsageWindow = { window: bucket.id.slice(0, 64) };
|
|
483
|
+
const minutes =
|
|
484
|
+
typeof bucket.window === "string" ? WINDOW_MINUTES[bucket.window] : undefined;
|
|
485
|
+
if (minutes) window.windowMinutes = minutes;
|
|
486
|
+
const remaining =
|
|
487
|
+
typeof bucket.remaining_fraction === "number" &&
|
|
488
|
+
Number.isFinite(bucket.remaining_fraction)
|
|
489
|
+
? Math.min(1, Math.max(0, bucket.remaining_fraction))
|
|
490
|
+
: undefined;
|
|
491
|
+
if (remaining !== undefined) {
|
|
492
|
+
window.usedPercent = Math.round((1 - remaining) * 10_000) / 100;
|
|
493
|
+
}
|
|
494
|
+
const reset =
|
|
495
|
+
typeof bucket.reset_time === "string" ? Date.parse(bucket.reset_time) : NaN;
|
|
496
|
+
if (Number.isFinite(reset) && reset > 0) window.resetsAt = reset;
|
|
497
|
+
windows.push(window);
|
|
498
|
+
if (remaining !== undefined && remaining <= 0) {
|
|
499
|
+
status = "limited";
|
|
500
|
+
if (window.resetsAt && (resetsAt === undefined || window.resetsAt < resetsAt)) {
|
|
501
|
+
resetsAt = window.resetsAt;
|
|
502
|
+
}
|
|
503
|
+
} else if (
|
|
504
|
+
remaining !== undefined &&
|
|
505
|
+
remaining < QUOTA_WARNING_REMAINING &&
|
|
506
|
+
status === "allowed"
|
|
507
|
+
) {
|
|
508
|
+
status = "warning";
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
if (windows.length === 0) return null;
|
|
513
|
+
return { status, ...(resetsAt === undefined ? {} : { resetsAt }), windows, observedAt: now };
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
// ---------------------------------------------------------------------------
|
|
517
|
+
// Session
|
|
518
|
+
// ---------------------------------------------------------------------------
|
|
519
|
+
|
|
520
|
+
export type Spawner = (
|
|
521
|
+
request: TaskEnvironmentSessionRequest,
|
|
522
|
+
) => AgentEnvironmentProcess;
|
|
523
|
+
|
|
524
|
+
export class GeminiSession implements AgentSession {
|
|
525
|
+
readonly agentId: string;
|
|
526
|
+
readonly kind: AgentKind = "gemini";
|
|
527
|
+
|
|
528
|
+
private readonly environment: TaskEnvironmentAgentSessionSurface;
|
|
529
|
+
private readonly model?: string;
|
|
530
|
+
private readonly systemPreamble: string;
|
|
531
|
+
private readonly agentEnv: Record<string, string>;
|
|
532
|
+
private readonly spawner: Spawner;
|
|
533
|
+
private readonly interruptGraceMs: number;
|
|
534
|
+
private readonly authMode: GeminiAuthMode;
|
|
535
|
+
|
|
536
|
+
private readonly handlers = new Set<AgentEventHandler>();
|
|
537
|
+
private conversationId: string | null = null;
|
|
538
|
+
private current: AgentEnvironmentProcess | null = null;
|
|
539
|
+
/** Each spawned process's exit, for stop() and close() to wait on. */
|
|
540
|
+
private readonly exits = new WeakMap<AgentEnvironmentProcess, Promise<void>>();
|
|
541
|
+
private interrupting = false;
|
|
542
|
+
private queue: Promise<void> = Promise.resolve();
|
|
543
|
+
private sentPreamble = false;
|
|
544
|
+
private closed = false;
|
|
545
|
+
|
|
546
|
+
constructor(args: {
|
|
547
|
+
taskId: string;
|
|
548
|
+
agent: RosterAgent;
|
|
549
|
+
environment: TaskEnvironmentAgentSessionSurface;
|
|
550
|
+
systemPreamble: string;
|
|
551
|
+
agentEnv?: Record<string, string>;
|
|
552
|
+
spawner?: Spawner;
|
|
553
|
+
interruptGraceMs?: number;
|
|
554
|
+
}) {
|
|
555
|
+
this.agentId = args.agent.id;
|
|
556
|
+
this.environment = args.environment;
|
|
557
|
+
this.model = args.agent.model;
|
|
558
|
+
this.systemPreamble = args.systemPreamble;
|
|
559
|
+
this.agentEnv = args.agentEnv ?? {};
|
|
560
|
+
this.spawner =
|
|
561
|
+
args.spawner ?? ((request) => spawnEnvironmentProcess(this.environment, request));
|
|
562
|
+
this.interruptGraceMs = args.interruptGraceMs ?? INTERRUPT_GRACE_MS;
|
|
563
|
+
this.authMode = geminiAuthMode(this.agentEnv);
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
/** The agy conversation this session resumes (null before the first turn). */
|
|
567
|
+
get currentConversationId(): string | null {
|
|
568
|
+
return this.conversationId;
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
onEvent(handler: AgentEventHandler): () => void {
|
|
572
|
+
this.handlers.add(handler);
|
|
573
|
+
return () => this.handlers.delete(handler);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
private emit(event: AgentEvent): void {
|
|
577
|
+
if (this.closed && event.type !== "exit") return;
|
|
578
|
+
for (const h of this.handlers) h(event);
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
async send(text: string): Promise<void> {
|
|
582
|
+
if (this.closed) return;
|
|
583
|
+
const turn = this.queue.catch(() => {}).then(() => this.runTurn(text));
|
|
584
|
+
this.queue = turn;
|
|
585
|
+
return turn;
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
buildRequest(prompt: string): TaskEnvironmentSessionRequest {
|
|
589
|
+
const argv = [
|
|
590
|
+
"/bin/sh",
|
|
591
|
+
"-c",
|
|
592
|
+
geminiLauncherScript(geminiCredentialSource().containerTokenPath, this.authMode),
|
|
593
|
+
"gemini-agy", // $0 for the launcher
|
|
594
|
+
AGY_BIN,
|
|
595
|
+
"-p",
|
|
596
|
+
prompt,
|
|
597
|
+
"--output-format",
|
|
598
|
+
"stream-json",
|
|
599
|
+
// The container is the isolation boundary; agy's own sandbox can't run
|
|
600
|
+
// there, and without this every shell command is soft-denied.
|
|
601
|
+
"--dangerously-skip-permissions",
|
|
602
|
+
// A chat message that starts with "/" is text for the model.
|
|
603
|
+
"--disable-slash-commands",
|
|
604
|
+
];
|
|
605
|
+
if (this.authMode === "api-key") argv.push("--settings", GEMINI_API_KEY_SETTINGS);
|
|
606
|
+
if (this.model) argv.push("--model", this.model);
|
|
607
|
+
if (this.conversationId) argv.push("--conversation", this.conversationId);
|
|
608
|
+
return {
|
|
609
|
+
argv: argv as [string, ...string[]],
|
|
610
|
+
projectEnvProfile: "task",
|
|
611
|
+
user: "node",
|
|
612
|
+
env: {
|
|
613
|
+
// App-shared Google names agy routes by (engine-spawn-env.ts).
|
|
614
|
+
...GEMINI_SPAWN_BLANKS,
|
|
615
|
+
...this.agentEnv,
|
|
616
|
+
// The image pins the binary; it must not rewrite itself mid-task.
|
|
617
|
+
AGY_CLI_DISABLE_AUTO_UPDATE: "true",
|
|
618
|
+
// Subscription: always agy's file store, never a keyring that a
|
|
619
|
+
// container may happen to expose over D-Bus. (An API-key account's
|
|
620
|
+
// GEMINI_API_KEY arrives in agentEnv from the lease.)
|
|
621
|
+
...(this.authMode === "subscription" ? { AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1" } : {}),
|
|
622
|
+
},
|
|
623
|
+
maxOutputBytes: AGENT_SESSION_OUTPUT_BUFFER_BYTES,
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
private emitSignedOut(): void {
|
|
628
|
+
this.emit({ type: "error", message: GEMINI_SIGNED_OUT_MESSAGE, aborted: true });
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
private emitTurnError(message: string): void {
|
|
632
|
+
const accountUsage = rateLimitErrorUsage(message);
|
|
633
|
+
if (accountUsage) {
|
|
634
|
+
this.emit({ type: "account_usage", usage: accountUsage });
|
|
635
|
+
this.emit({
|
|
636
|
+
type: "error",
|
|
637
|
+
message,
|
|
638
|
+
retryable: "rate_limit",
|
|
639
|
+
...(accountUsage.resetsAt === undefined ? {} : { resetsAt: accountUsage.resetsAt }),
|
|
640
|
+
});
|
|
641
|
+
} else {
|
|
642
|
+
this.emit({ type: "error", message });
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
private async runTurn(text: string): Promise<void> {
|
|
647
|
+
if (this.closed) return;
|
|
648
|
+
requireContainerRuntimeOperational();
|
|
649
|
+
// No system-prompt flag and `--agent` strips the tools, so the briefing
|
|
650
|
+
// folds into the first turn; later turns carry it via --conversation.
|
|
651
|
+
const prompt =
|
|
652
|
+
!this.sentPreamble && this.systemPreamble.trim().length > 0
|
|
653
|
+
? `${this.systemPreamble}\n\n---\n\n${text}`
|
|
654
|
+
: text;
|
|
655
|
+
this.sentPreamble = true;
|
|
656
|
+
this.interrupting = false;
|
|
657
|
+
|
|
658
|
+
const child = this.spawner(this.buildRequest(prompt));
|
|
659
|
+
this.current = child;
|
|
660
|
+
this.exits.set(
|
|
661
|
+
child,
|
|
662
|
+
new Promise<void>((resolve) => {
|
|
663
|
+
child.on("exit", () => resolve());
|
|
664
|
+
child.on("error", () => resolve());
|
|
665
|
+
}),
|
|
666
|
+
);
|
|
667
|
+
|
|
668
|
+
let acc = "";
|
|
669
|
+
let buf = "";
|
|
670
|
+
let model = this.model;
|
|
671
|
+
let result: AgyResult | undefined;
|
|
672
|
+
let signedOut = false;
|
|
673
|
+
let reportedError = false;
|
|
674
|
+
const toolSteps = new Set<number>();
|
|
675
|
+
const stepUsage = new Map<number, AgyTokenCounts>();
|
|
676
|
+
|
|
677
|
+
const consume = (chunk: string): void => {
|
|
678
|
+
buf += chunk;
|
|
679
|
+
let nl: number;
|
|
680
|
+
while ((nl = buf.indexOf("\n")) >= 0) {
|
|
681
|
+
const line = buf.slice(0, nl);
|
|
682
|
+
buf = buf.slice(nl + 1);
|
|
683
|
+
const m = mapAgyLine(line);
|
|
684
|
+
if (m.conversationId) this.conversationId = m.conversationId;
|
|
685
|
+
if (m.model) model = m.model;
|
|
686
|
+
if (m.stepUsage) stepUsage.set(m.stepUsage.stepIndex, m.stepUsage.usage);
|
|
687
|
+
if (m.textDelta) {
|
|
688
|
+
acc += m.textDelta;
|
|
689
|
+
this.emit({ type: "message_delta", text: m.textDelta });
|
|
690
|
+
}
|
|
691
|
+
if (m.toolCall && !toolSteps.has(m.toolCall.stepIndex)) {
|
|
692
|
+
toolSteps.add(m.toolCall.stepIndex);
|
|
693
|
+
this.emit({
|
|
694
|
+
type: "tool_call",
|
|
695
|
+
id: `${this.conversationId ?? "agy"}:${m.toolCall.stepIndex}`,
|
|
696
|
+
title: m.toolCall.title,
|
|
697
|
+
detail: m.toolCall.detail,
|
|
698
|
+
});
|
|
699
|
+
}
|
|
700
|
+
if (m.result) result = m.result;
|
|
701
|
+
}
|
|
702
|
+
};
|
|
703
|
+
child.stdout?.on("data", (b: Buffer) => consume(b.toString("utf8")));
|
|
704
|
+
let stderr = "";
|
|
705
|
+
child.stderr?.on("data", (b: Buffer) => {
|
|
706
|
+
stderr = (stderr + b.toString("utf8")).slice(-STDERR_KEEP_CHARS);
|
|
707
|
+
// Backstop for the preflight: a signed-out (or revoked) agy prints this
|
|
708
|
+
// and then waits ~60 s for a pasted code. Kill it instead.
|
|
709
|
+
if (!signedOut && /Authentication required/i.test(stderr)) {
|
|
710
|
+
signedOut = true;
|
|
711
|
+
void this.stop(child);
|
|
712
|
+
}
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
const code = await new Promise<number | null>((resolve) => {
|
|
716
|
+
let settled = false;
|
|
717
|
+
const finish = (exitCode: number | null, spawnErr?: string): void => {
|
|
718
|
+
if (settled) return;
|
|
719
|
+
settled = true;
|
|
720
|
+
this.current = null;
|
|
721
|
+
if (buf.trim().length > 0) consume("\n");
|
|
722
|
+
if (spawnErr && !this.closed) {
|
|
723
|
+
reportedError = true;
|
|
724
|
+
this.emit({ type: "error", message: `agy spawn failed: ${spawnErr}` });
|
|
725
|
+
}
|
|
726
|
+
resolve(exitCode);
|
|
727
|
+
};
|
|
728
|
+
child.on("exit", (exitCode) => finish(exitCode));
|
|
729
|
+
child.on("error", (err) => finish(null, err.message));
|
|
730
|
+
});
|
|
731
|
+
if (this.closed) return;
|
|
732
|
+
|
|
733
|
+
const usage = sumAgyStepUsage(stepUsage, model);
|
|
734
|
+
const interrupted =
|
|
735
|
+
(result !== undefined && isAgyInterrupted(result)) ||
|
|
736
|
+
(result === undefined && this.interrupting);
|
|
737
|
+
|
|
738
|
+
if (!reportedError && code === GEMINI_NO_DIR_EXIT) {
|
|
739
|
+
this.emit({ type: "error", message: GEMINI_NO_DIR_MESSAGE, aborted: true });
|
|
740
|
+
reportedError = true;
|
|
741
|
+
} else if (!reportedError && code === GEMINI_NOT_INSTALLED_EXIT) {
|
|
742
|
+
this.emit({ type: "error", message: GEMINI_NOT_INSTALLED_MESSAGE, aborted: true });
|
|
743
|
+
reportedError = true;
|
|
744
|
+
} else if (!reportedError && code === GEMINI_MISSING_KEY_EXIT) {
|
|
745
|
+
this.emit({ type: "error", message: GEMINI_MISSING_KEY_MESSAGE, aborted: true });
|
|
746
|
+
reportedError = true;
|
|
747
|
+
} else if (
|
|
748
|
+
!reportedError &&
|
|
749
|
+
result !== undefined &&
|
|
750
|
+
result.status !== "SUCCESS" &&
|
|
751
|
+
/API_KEY_INVALID|API key not valid/i.test(result.error ?? "")
|
|
752
|
+
) {
|
|
753
|
+
this.emit({ type: "error", message: GEMINI_INVALID_KEY_MESSAGE, aborted: true });
|
|
754
|
+
reportedError = true;
|
|
755
|
+
} else if (
|
|
756
|
+
!reportedError &&
|
|
757
|
+
this.authMode === "subscription" &&
|
|
758
|
+
(signedOut ||
|
|
759
|
+
code === GEMINI_SIGNED_OUT_EXIT ||
|
|
760
|
+
(result?.status !== "SUCCESS" && isAgyAuthFailure(result?.error)))
|
|
761
|
+
) {
|
|
762
|
+
this.emitSignedOut();
|
|
763
|
+
reportedError = true;
|
|
764
|
+
} else if (!reportedError && result && !interrupted && result.status !== "SUCCESS") {
|
|
765
|
+
this.emitTurnError(scrubAgyDiagnostics(result.error ?? `agy turn ended ${result.status}`));
|
|
766
|
+
reportedError = true;
|
|
767
|
+
} else if (!reportedError && !result && !interrupted && code !== 0) {
|
|
768
|
+
const tail = scrubAgyDiagnostics(stderr).trim().slice(-500);
|
|
769
|
+
this.emitTurnError(`agy exited ${code ?? "null"}${tail ? `: ${tail}` : ""}`);
|
|
770
|
+
reportedError = true;
|
|
771
|
+
}
|
|
772
|
+
|
|
773
|
+
const finalText = result?.status === "SUCCESS" && result.response ? result.response : acc;
|
|
774
|
+
if (finalText) this.emit({ type: "message_complete", text: finalText });
|
|
775
|
+
this.emit({
|
|
776
|
+
type: "turn_complete",
|
|
777
|
+
...(usage ? { usage } : {}),
|
|
778
|
+
...(interrupted ? { aborted: true } : {}),
|
|
779
|
+
});
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
/** SIGTERM first: the launcher exec'd agy, so the signal reaches agy itself,
|
|
783
|
+
* which ends the turn with an "interrupted" result and exits (verified for
|
|
784
|
+
* SIGTERM and SIGINT on 1.5.16). SIGKILL only if it hasn't exited after the
|
|
785
|
+
* grace period. Resolves once the process has exited or been killed. */
|
|
786
|
+
private stop(child: AgentEnvironmentProcess): Promise<void> {
|
|
787
|
+
const exited = this.exits.get(child) ?? Promise.resolve();
|
|
788
|
+
child.kill("SIGTERM");
|
|
789
|
+
let timer: NodeJS.Timeout | undefined;
|
|
790
|
+
const killed = new Promise<void>((resolve) => {
|
|
791
|
+
timer = setTimeout(() => {
|
|
792
|
+
child.kill("SIGKILL");
|
|
793
|
+
resolve();
|
|
794
|
+
}, this.interruptGraceMs);
|
|
795
|
+
timer.unref?.();
|
|
796
|
+
});
|
|
797
|
+
return Promise.race([exited, killed]).finally(() => clearTimeout(timer));
|
|
798
|
+
}
|
|
799
|
+
|
|
800
|
+
async interrupt(): Promise<void> {
|
|
801
|
+
const child = this.current;
|
|
802
|
+
if (!child) return;
|
|
803
|
+
this.interrupting = true;
|
|
804
|
+
void this.stop(child);
|
|
805
|
+
}
|
|
806
|
+
|
|
807
|
+
async resolvePermission(): Promise<void> {
|
|
808
|
+
/* --dangerously-skip-permissions auto-approves; nothing to resolve */
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** Waits for a running agy to exit (or be killed after the grace period),
|
|
812
|
+
* so no agy outlives its session and rewrites its token file later. */
|
|
813
|
+
async close(): Promise<void> {
|
|
814
|
+
if (this.closed) return;
|
|
815
|
+
this.closed = true;
|
|
816
|
+
const child = this.current;
|
|
817
|
+
if (child) await this.stop(child);
|
|
818
|
+
this.current = null;
|
|
819
|
+
this.emit({ type: "exit", code: 0 });
|
|
820
|
+
this.handlers.clear();
|
|
821
|
+
}
|
|
822
|
+
}
|
|
823
|
+
|
|
824
|
+
register({
|
|
825
|
+
kind: "gemini",
|
|
826
|
+
label: "Gemini",
|
|
827
|
+
supportedModels: () => [...GEMINI_MODELS],
|
|
828
|
+
defaultModel: GEMINI_DEFAULT_MODEL,
|
|
829
|
+
supportedEfforts: () => [...GEMINI_EFFORTS],
|
|
830
|
+
// ADR-178: gemini accounts live only in the cloud vault, so a runner offers
|
|
831
|
+
// gemini through its lease (CLOUD_CREDENTIAL_KINDS), never on a sign-in of
|
|
832
|
+
// its own: outside the lease there is nothing to run it on.
|
|
833
|
+
available: () => false,
|
|
834
|
+
create: async ({ taskId, agent, environment, systemPreamble, agentEnv }) =>
|
|
835
|
+
new GeminiSession({ taskId, agent, environment, systemPreamble, agentEnv }),
|
|
836
|
+
});
|