@estebanforge/pi-antigravity-bridge 1.10.6 → 1.10.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/README.md +5 -1
- package/extensions/index.ts +78 -21
- package/package.json +1 -1
- package/src/acp/connection.ts +28 -10
- package/src/acp/driver.ts +31 -1
- package/src/acp/jsonrpc.ts +12 -1
- package/src/bridge-catalog.ts +171 -3
- package/src/config.ts +48 -7
- package/src/provider.ts +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,20 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.10.8] - 2026-11-16
|
|
6
|
+
|
|
7
|
+
### Added
|
|
8
|
+
|
|
9
|
+
- **Actionable hint on ACP `session/new` and `session/load` timeouts.** When `session/new` or `session/load` times out after `initialize` succeeded, the error message now notes that `agy acp` is running and points to network/proxy reachability to Google APIs or `agy` sign-in, and the connection logs a `session-op-timeout` warning record.
|
|
10
|
+
- **Configurable ACP session operation timeout (`acp.sessionTimeoutMs` / `AGY_ACP_SESSION_TIMEOUT_MS`).** Defaults to the existing `20000`ms (`20`s) and applies to `session/new`, `session/load`, `session/set_config_option`, and `session/close`. Accepts `1000`-`300000`ms via `config.json`, environment variable, or the `/agy` settings picker.
|
|
11
|
+
- **Optional `session/new` retry on timeout (`acp.sessionRetryOnTimeout` / `AGY_ACP_SESSION_RETRY`).** Disabled by default (`false`). When enabled, `AcpDriver` retries `session/new` once on a silent timeout while `agy acp` is still alive and logs `session-new-retry` (warns in the setting description that it doubles wait time on dead networks and may not clear a wedged internal socket).
|
|
12
|
+
|
|
13
|
+
## [1.10.7] - 2026-11-15
|
|
14
|
+
|
|
15
|
+
### Fixed
|
|
16
|
+
|
|
17
|
+
- **Extension Pi tools are no longer silently evicted by `agy acp`'s per-model tool-declaration byte budget.** `agy acp` enforces a per-model declaration cap and keeps only the smallest tools, silently dropping larger extension tools such as `git_commit` and `AskClaude`, and strips any argument not declared under `properties` even when `additionalProperties: true` is set. `tools/list` now exposes only active Pi default tools (`read`, `bash`, `edit`, `write`, `grep`, `find`, `ls`) directly alongside two compact proxy tools: `bridge_tool_info` (lists extension tool names with a 4,000-char description cap and wildcard `["*"]` fallback, returning full descriptions and schemas on demand) and `bridge_call_tool` (accepts `name` plus a stringified JSON object or plain object in `arguments_json` and validates against the active authorized Pi catalog before dispatching). Direct calls by tool name stay authorized so cached schemas from earlier sessions still work while disabled or hidden tools stay blocked.
|
|
18
|
+
|
|
5
19
|
## [1.10.6] - 2026-11-13
|
|
6
20
|
|
|
7
21
|
### Fixed
|
package/README.md
CHANGED
|
@@ -122,8 +122,10 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
|
|
|
122
122
|
| `systemPrompt` | `on` (send pi's system prompt - operating instructions plus the global agent-dir `AGENTS.md` and ancestor `AGENTS.md`/`CLAUDE.md` - to the first prompt of each new agy conversation, plus a tool-priority note: Pi Bridge tools win over agy's native interactive ones, which never reach the user. Delivery: stream-json stages it as an agy agent file via `--agent`, off the prompt line - the CLI silently drops single prompts past a ~25KB cap and the dropped turn kills the conversation; the carrier declares the productive toolset explicitly (omitting `tools:` reads as a read-only set upstream, issue #13) plus `subagent: false` + `agents: []` so the native subagent tools stay masked (ACP carries no agent file, so its natives remain and the tool-priority note steers the model to pi delegation). ACP prepends it to the first prompt) or `off` (agy-native behavior) | `on` |
|
|
123
123
|
| `turnTimeoutMin` | Overall cap on ONE agy turn, minutes, both engines. Parked time (pi-tool round-trips, escalated calls, human-gated approvals) does not count against it on either engine: the cap pauses with remaining-budget semantics and resumes on unpark. When it fires, the bridge kills the agy process mid-task ("ACP turn exceeded the 10m deadline" / "agy exceeded the 10m turn timeout") - it is a bridge cap, not a Google server limit. Default is TTY-aware: `0` (no cap) on an interactive pi - you are the backstop with Esc; `20` headless, where nobody can abort and one runaway turn blocks the serialized turn queue. Opt into a gate with 1-1440 (free type via `config.json` or `/agy timeout <1-1440|off>`, or the `/agy` picker's preset list); `0` disables explicitly; anything else falls back to the TTY-aware default. The 5m inactivity stall guard always still bounds a hung server | `0` TTY / `20` headless |
|
|
124
124
|
| `inactivityTimeoutMin` | Silence cap, minutes, both engines: no stream-json stdout / no ACP session/update for this long fails the turn as a stall. `0` disables the guard. Parks (bridge calls, escalated calls, ACP permission dialogs) pause it; agy-native long steps such as builds do not. A false kill costs the whole turn, and on stream-json a stall kill with no result frame clears the conversation binding. Keep `5`; use `2`-`3` only when native steps are known to be short; do not use `1` | `5` |
|
|
125
|
+
| `acp.sessionTimeoutMs` | Timeout in ms for ACP `session/new`, `session/load`, `session/set_config_option`, and `session/close`. Valid range: `1000`-`300000`. Raise only on slow or proxied networks | `20000` |
|
|
126
|
+
| `acp.sessionRetryOnTimeout` | Advanced: transparently retry `session/new` once when it times out while `agy acp` is still alive. **Warning:** doubles total wait time on dead networks and may not recover if `agy`'s internal socket is wedged | `false` |
|
|
125
127
|
|
|
126
|
-
Env overrides: `AGY_BRIDGE_TOOLS`, `AGY_ASK_TOOL`, `AGY_WEB_TOOLS`, `AGY_DIGEST`, `AGY_SYSTEM_PROMPT`, `AGY_TURN_TIMEOUT_MIN`, `AGY_INACTIVITY_TIMEOUT_MIN`. Env wins over the file, so while `AGY_DIGEST` or `AGY_SYSTEM_PROMPT` is set, the matching `/agy digest` or `/agy system-prompt` toggle persists a value that never takes effect.
|
|
128
|
+
Env overrides: `AGY_BRIDGE_TOOLS`, `AGY_ASK_TOOL`, `AGY_WEB_TOOLS`, `AGY_DIGEST`, `AGY_SYSTEM_PROMPT`, `AGY_TURN_TIMEOUT_MIN`, `AGY_INACTIVITY_TIMEOUT_MIN`, `AGY_ACP_SESSION_TIMEOUT_MS`, `AGY_ACP_SESSION_RETRY`. Env wins over the file, so while `AGY_DIGEST` or `AGY_SYSTEM_PROMPT` is set, the matching `/agy digest` or `/agy system-prompt` toggle persists a value that never takes effect.
|
|
127
129
|
|
|
128
130
|
The `activate_skill` catalog mirrors pi's directory-based skill discovery: the two global dirs plus project dirs, the latter only when pi has trusted the project (same gate pi itself applies). Pi's other skill sources - the `skills` settings array, `package.json` entries, and `--skill` CLI paths - are not mirrored and won't appear in the catalog.
|
|
129
131
|
|
|
@@ -184,6 +186,8 @@ For isolation when running any agent that executes commands without a confirmati
|
|
|
184
186
|
| `AGY_READONLY` | `1`/`true`/`on` (or any set value except `0`/`false`/`off`/empty) turns every provider turn and the `AskAntigravity` tool into a visible refusal (fail-closed: the CLI has no review-only enforcement on any path, [#1181](https://github.com/google-antigravity/antigravity-cli/issues/1181)). Wins over the config file. |
|
|
185
187
|
| `AGY_SKIP_PERMISSIONS` | `1`/`true` (default) to pass `--dangerously-skip-permissions` so commands don't hang on an unanswerable prompt in `-p` mode. `0`/`false` to prompt (hangs any `run_command` non-interactively). Wins over the config file. |
|
|
186
188
|
| `AGY_USAGE_ESTIMATE` | Fallback ACP token display when the server omits usage: `estimate` (default; live client-side per-delta estimates), `direct`, `off`. Exact server usage always wins. Wins over the config file. |
|
|
189
|
+
| `AGY_ACP_SESSION_TIMEOUT_MS` | Timeout in ms for ACP `session/new`, `session/load`, `session/set_config_option`, and `session/close` (`1000`-`300000`, default `20000`). Wins over `config.acp.sessionTimeoutMs`. |
|
|
190
|
+
| `AGY_ACP_SESSION_RETRY` | `1`/`true`/`on` to retry ACP `session/new` once on silent timeout while `agy acp` is alive (default off). Warning: doubles wait time on dead networks and may not clear a wedged socket. Wins over `config.acp.sessionRetryOnTimeout`. |
|
|
187
191
|
| `AGY_DEFAULT_MODEL` | Default model for the `AskAntigravity` tool: `flash`/`pro`/`gemini`, or an exact id such as `gemini-4-hydrogen`. Default `gemini-4-hydrogen`; the tier suffix rides `AGY_DEFAULT_THINKING`. Wins over the config file. |
|
|
188
192
|
| `AGY_DEFAULT_THINKING` | Default thinking tier for the `AskAntigravity` tool: `low`/`medium`/`high`. Anything else falls back to `medium`. Wins over the config file. |
|
|
189
193
|
| `AGY_DEBUG` | `1`/`true`/`on` writes the full trail to the daily log (driver lifecycle, raw bridge traffic). Default off: **only `error` records land on disk** - routine disk writes are zero for regular users, and warnings surface as UI toasts instead. |
|
package/extensions/index.ts
CHANGED
|
@@ -65,7 +65,7 @@ import { agyAuthenticationMessage } from "../src/agy-install.js";
|
|
|
65
65
|
import { createAgySetupOffer } from "../src/agy-setup.js";
|
|
66
66
|
import { ensureQueuedMessagesDefaults } from "../src/queued-messages.js";
|
|
67
67
|
import type { TurnDriver, TurnOutcome } from "../src/driver-types.js";
|
|
68
|
-
import { CONFIG_PATH, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
|
|
68
|
+
import { CONFIG_PATH, loadConfig, logsDir, MAX_TURN_CAP_MIN, parseCapMinutes, removeLegacyAcpBin, saveConfig, type AcpConfig, type AgyMode, type BridgeTools, type Engine, type ThinkingTier } from "../src/config.js";
|
|
69
69
|
import { agyMissingMessage, ENGINE_SETTINGS_ROW_ID, engineSettingsRow, isAgyInstalled, savedEngineMessage, showEnginePicker, shouldOfferEnginePicker } from "../src/engine-picker.js";
|
|
70
70
|
import { agyVersionVerdict, checkAgyCliVersion, describeAgyVersionCheck, MIN_AGY_ACP_VERSION, MIN_AGY_VERSION, MIN_GEMINI_DIR_VERSION, probeGeminiDirFlag, resolveStreamHomeMode } from "../src/agy-version.js";
|
|
71
71
|
import { isValidAgyAgentName, listAgyAgents } from "../src/agents.js";
|
|
@@ -99,7 +99,17 @@ import {
|
|
|
99
99
|
type SkillLite,
|
|
100
100
|
} from "../src/skills.js";
|
|
101
101
|
import { mapAgyToolToNative } from "../src/native-tools.js";
|
|
102
|
-
import {
|
|
102
|
+
import {
|
|
103
|
+
CALL_TOOL_NAME,
|
|
104
|
+
TOOL_INFO_TOOL_NAME,
|
|
105
|
+
bridgeCallToolDef,
|
|
106
|
+
bridgeToolInfoDef,
|
|
107
|
+
bridgedPiTools,
|
|
108
|
+
formatBridgeToolInfo,
|
|
109
|
+
parseBridgeCallRequest,
|
|
110
|
+
partitionBridgeTools,
|
|
111
|
+
serializeToolSchema,
|
|
112
|
+
} from "../src/bridge-catalog.js";
|
|
103
113
|
import { Type } from "typebox";
|
|
104
114
|
import { patchStatus, restorePatch } from "../src/patch-cleanup.js";
|
|
105
115
|
import { withDialogLock } from "../src/dialog-lock.js";
|
|
@@ -226,7 +236,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
226
236
|
"start-failed", "spawn-error", "parse-error", "write-failed",
|
|
227
237
|
"mode-apply-failed", "timeout", "stall", "auth-required",
|
|
228
238
|
"session-load-failed-creating-fresh", "connection-exited", "cancel-failed",
|
|
229
|
-
"unsupported-server-request",
|
|
239
|
+
"unsupported-server-request", "session-op-timeout", "session-new-retry",
|
|
230
240
|
]);
|
|
231
241
|
const streamDriver = new StreamDriver();
|
|
232
242
|
// Mirror the stream driver's lifecycle ring into the daily file log
|
|
@@ -321,6 +331,8 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
321
331
|
// a restart. Without this the driver defaults to "estimate" and the
|
|
322
332
|
// config knob (incl. "off") is dead.
|
|
323
333
|
usageEstimate: () => loadConfig().acp.usageEstimate,
|
|
334
|
+
sessionOpTimeoutMs: () => loadConfig().acp.sessionTimeoutMs,
|
|
335
|
+
sessionRetryOnTimeout: () => loadConfig().acp.sessionRetryOnTimeout,
|
|
324
336
|
// ACP request_permission parity with the approval gate: skipPermissions
|
|
325
337
|
// turns auto-allow in the driver; approvals.mode allow short-circuits
|
|
326
338
|
// to the same synchronous allow; everything else opens a dialog (esc
|
|
@@ -863,16 +875,17 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
863
875
|
const listTools = () => {
|
|
864
876
|
// /mcp and pi.setActiveTools() update the same live catalog. ACP gets
|
|
865
877
|
// this endpoint through session/new or session/load; no global config write.
|
|
866
|
-
const
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
878
|
+
const mode = loadConfig().bridgeTools;
|
|
879
|
+
const { direct, proxied } = partitionBridgeTools(getBridgeTools());
|
|
880
|
+
const tools = direct.map((t) => ({
|
|
881
|
+
name: t.name,
|
|
882
|
+
description: t.description ?? t.name,
|
|
883
|
+
inputSchema: serializeToolSchema(t.parameters),
|
|
884
|
+
}));
|
|
885
|
+
if (mode !== "none" && proxied.length > 0) {
|
|
886
|
+
tools.push(bridgeToolInfoDef(proxied), bridgeCallToolDef());
|
|
887
|
+
}
|
|
888
|
+
if (skills.length > 0 && mode !== "none") {
|
|
876
889
|
tools.push({
|
|
877
890
|
name: ACTIVATE_SKILL_TOOL_NAME,
|
|
878
891
|
description: `Activate a pi Agent Skill by name. Catalog:\n${catalogSummary(skills)}`,
|
|
@@ -917,19 +930,32 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
917
930
|
if (view && view.state !== "running") roundTrips.markDelivered(wanted);
|
|
918
931
|
return Promise.resolve(formatPollAnswer(wanted, view));
|
|
919
932
|
}
|
|
920
|
-
if (name
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
return roundTrips.onToolCall(callId, name, args, signal).then((r) => {
|
|
933
|
+
if (name === TOOL_INFO_TOOL_NAME) {
|
|
934
|
+
const { proxied } = partitionBridgeTools(getBridgeTools());
|
|
935
|
+
return Promise.resolve(formatBridgeToolInfo(proxied, args.names));
|
|
936
|
+
}
|
|
937
|
+
const dispatchPiTool = (targetName: string, targetArgs: Record<string, unknown>) =>
|
|
938
|
+
roundTrips.onToolCall(callId, targetName, targetArgs, signal).then((r) => {
|
|
927
939
|
// Early-ack: answer the HTTP request before agy's ~180s client
|
|
928
940
|
// deadline with a poll handle; pi keeps executing meanwhile.
|
|
929
941
|
if (!("escalated" in r)) return r;
|
|
930
|
-
mcpLog("call-tool-escalated", { name, callId: r.callId });
|
|
942
|
+
mcpLog("call-tool-escalated", { name: targetName, callId: r.callId });
|
|
931
943
|
return formatEscalatedAck(r);
|
|
932
944
|
});
|
|
945
|
+
if (name === CALL_TOOL_NAME) {
|
|
946
|
+
const parsed = parseBridgeCallRequest(args, getBridgeTools());
|
|
947
|
+
if (!parsed.ok) {
|
|
948
|
+
return Promise.resolve({ content: [{ type: "text", text: parsed.error }], isError: true });
|
|
949
|
+
}
|
|
950
|
+
return dispatchPiTool(parsed.name, parsed.args);
|
|
951
|
+
}
|
|
952
|
+
if (name !== ACTIVATE_SKILL_TOOL_NAME) {
|
|
953
|
+
// Direct calls by tool name stay authorized so cached schemas from
|
|
954
|
+
// earlier sessions still work, while disabled/hidden tools stay blocked.
|
|
955
|
+
if (!getBridgeTools().some((tool) => tool.name === name)) {
|
|
956
|
+
return Promise.resolve({ content: [{ type: "text", text: `Pi tool ${name} is not active or not exposed to Antigravity` }], isError: true });
|
|
957
|
+
}
|
|
958
|
+
return dispatchPiTool(name, args);
|
|
933
959
|
}
|
|
934
960
|
const wanted = typeof args.name === "string" ? args.name : "";
|
|
935
961
|
const skill = loadConfig().bridgeTools !== "none" ? findSkillByName(skills, wanted) : undefined;
|
|
@@ -1165,6 +1191,7 @@ interface PendingConfig {
|
|
|
1165
1191
|
bridgeTools?: BridgeTools;
|
|
1166
1192
|
digest?: boolean;
|
|
1167
1193
|
systemPrompt?: boolean;
|
|
1194
|
+
acp?: Partial<AcpConfig>;
|
|
1168
1195
|
}
|
|
1169
1196
|
|
|
1170
1197
|
function settingsRows(ctx: AgyCommandCtx): string[] {
|
|
@@ -1864,6 +1891,22 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
|
|
|
1864
1891
|
currentValue: config.systemPrompt ? "on" : "off",
|
|
1865
1892
|
values: ["on", "off"],
|
|
1866
1893
|
},
|
|
1894
|
+
{
|
|
1895
|
+
id: "acp-session-timeout",
|
|
1896
|
+
label: "ACP session timeout (ms)",
|
|
1897
|
+
description:
|
|
1898
|
+
"Timeout in ms for ACP session/new, session/load, and session/close. Default 20000 (20s). Raise only on slow/proxied networks; custom values (1000-300000) can be set in config.json or AGY_ACP_SESSION_TIMEOUT_MS.",
|
|
1899
|
+
currentValue: String(config.acp.sessionTimeoutMs),
|
|
1900
|
+
values: ["20000", "30000", "45000", "60000", "90000"],
|
|
1901
|
+
},
|
|
1902
|
+
{
|
|
1903
|
+
id: "acp-session-retry",
|
|
1904
|
+
label: "ACP session/new retry (advanced)",
|
|
1905
|
+
description:
|
|
1906
|
+
"WARNING: disabled by default. Retries session/new once on silent timeout while agy acp is alive. Doubles total wait time on dead networks and may not recover if agy's internal socket is wedged.",
|
|
1907
|
+
currentValue: config.acp.sessionRetryOnTimeout ? "on" : "off",
|
|
1908
|
+
values: ["off", "on"],
|
|
1909
|
+
},
|
|
1867
1910
|
];
|
|
1868
1911
|
|
|
1869
1912
|
const resolved = await ui.custom<string | undefined>(
|
|
@@ -1899,6 +1942,16 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
|
|
|
1899
1942
|
pending.digest = newValue === "on";
|
|
1900
1943
|
} else if (id === "system-prompt") {
|
|
1901
1944
|
pending.systemPrompt = newValue === "on";
|
|
1945
|
+
} else if (id === "acp-session-timeout") {
|
|
1946
|
+
pending.acp = {
|
|
1947
|
+
...pending.acp,
|
|
1948
|
+
sessionTimeoutMs: Number(newValue),
|
|
1949
|
+
};
|
|
1950
|
+
} else if (id === "acp-session-retry") {
|
|
1951
|
+
pending.acp = {
|
|
1952
|
+
...pending.acp,
|
|
1953
|
+
sessionRetryOnTimeout: newValue === "on",
|
|
1954
|
+
};
|
|
1902
1955
|
}
|
|
1903
1956
|
},
|
|
1904
1957
|
},
|
|
@@ -1951,6 +2004,10 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
|
|
|
1951
2004
|
pending.digest !== undefined ? `digest=${next.digest ? "on" : "off"}` : null,
|
|
1952
2005
|
pending.systemPrompt !== undefined ? `system-prompt=${next.systemPrompt ? "on" : "off"}` : null,
|
|
1953
2006
|
pending.turnTimeoutMin !== undefined ? `turn cap=${next.turnTimeoutMin === 0 ? "off" : `${next.turnTimeoutMin}m`}` : null,
|
|
2007
|
+
pending.acp?.sessionTimeoutMs !== undefined ? `ACP session timeout=${next.acp.sessionTimeoutMs}ms` : null,
|
|
2008
|
+
pending.acp?.sessionRetryOnTimeout !== undefined
|
|
2009
|
+
? `ACP session/new retry=${next.acp.sessionRetryOnTimeout ? "on" : "off"}`
|
|
2010
|
+
: null,
|
|
1954
2011
|
]
|
|
1955
2012
|
.filter(Boolean)
|
|
1956
2013
|
.join(", ");
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@estebanforge/pi-antigravity-bridge",
|
|
3
|
-
"version": "1.10.
|
|
3
|
+
"version": "1.10.8",
|
|
4
4
|
"description": "Gemini provider for Pi on the Antigravity ACP server (official Google ACP) or the stream-json agy CLI. Use antigravity/* models in Pi. Full /model picker support. Models runs Pi's tools. ToS safe to use.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"pi-package",
|
package/src/acp/connection.ts
CHANGED
|
@@ -18,7 +18,7 @@ import { spawn, type ChildProcess } from "node:child_process";
|
|
|
18
18
|
import { frameCarriesUsage } from "./events.js";
|
|
19
19
|
import type { AgyUsage } from "../driver-types.js";
|
|
20
20
|
import { redactText } from "../redact.js";
|
|
21
|
-
import { JsonRpcResponseError, JsonRpcSession } from "./jsonrpc.js";
|
|
21
|
+
import { JsonRpcResponseError, JsonRpcSession, JsonRpcTimeoutError } from "./jsonrpc.js";
|
|
22
22
|
import { removeStagedAgyHome, stageAgyHome } from "./home.js";
|
|
23
23
|
|
|
24
24
|
export interface AcpMcpServer {
|
|
@@ -70,6 +70,9 @@ export interface AcpConnectionOptions {
|
|
|
70
70
|
onPermissionRequest?: AcpPermissionHandler;
|
|
71
71
|
/** Park budget for one permission dialog. Tests shrink it. */
|
|
72
72
|
permissionParkMs?: number;
|
|
73
|
+
/** Timeout in ms for session/new, session/load, set_config_option, and
|
|
74
|
+
* session/close. Defaults to SESSION_OP_TIMEOUT_MS (20000). */
|
|
75
|
+
sessionOpTimeoutMs?: number | (() => number);
|
|
73
76
|
}
|
|
74
77
|
|
|
75
78
|
const INIT_TIMEOUT_MS = 30_000;
|
|
@@ -258,11 +261,19 @@ export class AcpConnection {
|
|
|
258
261
|
return typeof v === "string" ? v : undefined;
|
|
259
262
|
}
|
|
260
263
|
|
|
264
|
+
#sessionOpTimeoutMs(): number {
|
|
265
|
+
const opt = this.#opts.sessionOpTimeoutMs;
|
|
266
|
+
const resolved = typeof opt === "function" ? opt() : opt;
|
|
267
|
+
return typeof resolved === "number" && Number.isFinite(resolved) && resolved > 0
|
|
268
|
+
? resolved
|
|
269
|
+
: SESSION_OP_TIMEOUT_MS;
|
|
270
|
+
}
|
|
271
|
+
|
|
261
272
|
async newSession(cwd: string): Promise<AcpSessionInfo> {
|
|
262
273
|
const result = (await this.guarded(
|
|
263
274
|
"session/new",
|
|
264
275
|
{ cwd, mcpServers: this.#mcpServers() },
|
|
265
|
-
|
|
276
|
+
this.#sessionOpTimeoutMs(),
|
|
266
277
|
)) as Record<string, unknown>;
|
|
267
278
|
const sessionId = result.sessionId;
|
|
268
279
|
if (typeof sessionId !== "string" || sessionId.length === 0) {
|
|
@@ -282,7 +293,7 @@ export class AcpConnection {
|
|
|
282
293
|
const result = (await this.request(
|
|
283
294
|
"session/load",
|
|
284
295
|
{ sessionId, cwd, mcpServers: this.#mcpServers() },
|
|
285
|
-
|
|
296
|
+
this.#sessionOpTimeoutMs(),
|
|
286
297
|
)) as Record<string, unknown> | undefined;
|
|
287
298
|
this.lastConfigOptions = result?.configOptions;
|
|
288
299
|
} finally {
|
|
@@ -294,7 +305,7 @@ export class AcpConnection {
|
|
|
294
305
|
const result = (await this.guarded(
|
|
295
306
|
"session/set_config_option",
|
|
296
307
|
{ sessionId, configId, value },
|
|
297
|
-
|
|
308
|
+
this.#sessionOpTimeoutMs(),
|
|
298
309
|
)) as Record<string, unknown> | undefined;
|
|
299
310
|
this.lastConfigOptions = result?.configOptions;
|
|
300
311
|
}
|
|
@@ -350,7 +361,7 @@ export class AcpConnection {
|
|
|
350
361
|
}
|
|
351
362
|
|
|
352
363
|
async closeSession(sessionId: string): Promise<void> {
|
|
353
|
-
await this.guarded("session/close", { sessionId },
|
|
364
|
+
await this.guarded("session/close", { sessionId }, this.#sessionOpTimeoutMs());
|
|
354
365
|
}
|
|
355
366
|
|
|
356
367
|
/** Protocol-level permission answering: policy "auto" selects the first
|
|
@@ -468,11 +479,7 @@ export class AcpConnection {
|
|
|
468
479
|
/** Wrap a request: -32000 family becomes AcpAuthError with the remediation
|
|
469
480
|
* the server provided. */
|
|
470
481
|
private async guarded(method: string, params: unknown, timeoutMs: number): Promise<unknown> {
|
|
471
|
-
|
|
472
|
-
return await this.request(method, params, timeoutMs);
|
|
473
|
-
} catch (err) {
|
|
474
|
-
throw translateError(method, err);
|
|
475
|
-
}
|
|
482
|
+
return await this.request(method, params, timeoutMs);
|
|
476
483
|
}
|
|
477
484
|
|
|
478
485
|
async request(method: string, params?: unknown, timeoutMs?: number): Promise<unknown> {
|
|
@@ -480,6 +487,9 @@ export class AcpConnection {
|
|
|
480
487
|
try {
|
|
481
488
|
return await this.#rpc.request(method, params, timeoutMs);
|
|
482
489
|
} catch (err) {
|
|
490
|
+
if (err instanceof JsonRpcTimeoutError) {
|
|
491
|
+
this.#opts.log("session-op-timeout", { method, timeoutMs: err.timeoutMs });
|
|
492
|
+
}
|
|
483
493
|
throw translateError(method, err);
|
|
484
494
|
}
|
|
485
495
|
}
|
|
@@ -579,6 +589,14 @@ export function parseAcpTurnUsage(value: unknown): AgyUsage | undefined {
|
|
|
579
589
|
|
|
580
590
|
export function translateError(method: string, err: unknown): Error {
|
|
581
591
|
if (err instanceof AcpAuthError) return err;
|
|
592
|
+
if (err instanceof JsonRpcTimeoutError) {
|
|
593
|
+
if (method === "session/new" || method === "session/load") {
|
|
594
|
+
const hint = "initialize succeeded, so agy acp is running; check network/proxy reachability to Google APIs or agy sign-in";
|
|
595
|
+
if (err.message.includes(hint)) return err;
|
|
596
|
+
return new JsonRpcTimeoutError(err.method, err.timeoutMs, `${err.message} (${hint})`);
|
|
597
|
+
}
|
|
598
|
+
return err;
|
|
599
|
+
}
|
|
582
600
|
if (err instanceof JsonRpcResponseError) {
|
|
583
601
|
if (err.code === -32000) {
|
|
584
602
|
const detail = typeof err.data === "object" && err.data !== null ? (err.data as { message?: unknown }).message : undefined;
|
package/src/acp/driver.ts
CHANGED
|
@@ -22,6 +22,7 @@ import { randomUUID } from "node:crypto";
|
|
|
22
22
|
import type { UsageEstimate } from "../config.js";
|
|
23
23
|
import { AcpConnection, type AcpMcpServer, type AcpPermissionRequest } from "./connection.js";
|
|
24
24
|
import type { AcpPermissionHandler } from "./connection.js";
|
|
25
|
+
import { JsonRpcTimeoutError } from "./jsonrpc.js";
|
|
25
26
|
import { mapStopReason, mapUpdate, TextAccumulator, type AcpEditDiff } from "./events.js";
|
|
26
27
|
import { estimateTokens, synthesizeUsage } from "./usage-estimate.js";
|
|
27
28
|
import type {
|
|
@@ -61,6 +62,12 @@ export interface AcpDriverOptions {
|
|
|
61
62
|
* "auto" answers the first allow option synchronously, "deny" consults
|
|
62
63
|
* the human handler or fail-closes. Default deny. */
|
|
63
64
|
permissionPolicy?: () => "auto" | "deny";
|
|
65
|
+
/** Timeout in ms for session/new, session/load, set_config_option, and
|
|
66
|
+
* session/close. Defaults to AcpConnection's 20000ms. */
|
|
67
|
+
sessionOpTimeoutMs?: number | (() => number);
|
|
68
|
+
/** Advanced: transparently retry session/new once on timeout while the
|
|
69
|
+
* connection is still alive. Default false. */
|
|
70
|
+
sessionRetryOnTimeout?: boolean | (() => boolean);
|
|
64
71
|
log?: (msg: string, data?: unknown) => void;
|
|
65
72
|
}
|
|
66
73
|
|
|
@@ -288,7 +295,7 @@ export class AcpDriver implements TurnDriver {
|
|
|
288
295
|
await conn.loadSession(request.conversationId, request.cwd);
|
|
289
296
|
turn.sessionId = request.conversationId;
|
|
290
297
|
} else {
|
|
291
|
-
const created = await conn
|
|
298
|
+
const created = await this.#newSessionWithOptionalRetry(conn, turn);
|
|
292
299
|
turn.sessionId = created.sessionId;
|
|
293
300
|
this.#stats.sessionsCreated += 1;
|
|
294
301
|
this.#log("session-new", { sessionId: created.sessionId });
|
|
@@ -555,6 +562,7 @@ export class AcpDriver implements TurnDriver {
|
|
|
555
562
|
? (req) => this.#parkForPermission(req)
|
|
556
563
|
: undefined,
|
|
557
564
|
permissionParkMs: this.#opts.permissionParkMs,
|
|
565
|
+
sessionOpTimeoutMs: this.#opts.sessionOpTimeoutMs,
|
|
558
566
|
onUpdate: (sessionId, update) => this.#onConnectionUpdate(sessionId, update),
|
|
559
567
|
onExit: (info) => this.#onConnectionExit(conn, info),
|
|
560
568
|
});
|
|
@@ -799,6 +807,28 @@ export class AcpDriver implements TurnDriver {
|
|
|
799
807
|
});
|
|
800
808
|
}
|
|
801
809
|
|
|
810
|
+
#sessionRetryOnTimeout(): boolean {
|
|
811
|
+
const opt = this.#opts.sessionRetryOnTimeout;
|
|
812
|
+
return (typeof opt === "function" ? opt() : opt) === true;
|
|
813
|
+
}
|
|
814
|
+
|
|
815
|
+
async #newSessionWithOptionalRetry(conn: AcpConnection, turn: ActiveTurn): Promise<{ sessionId: string }> {
|
|
816
|
+
try {
|
|
817
|
+
return await conn.newSession(turn.request.cwd);
|
|
818
|
+
} catch (err) {
|
|
819
|
+
if (
|
|
820
|
+
err instanceof JsonRpcTimeoutError &&
|
|
821
|
+
!turn.aborted &&
|
|
822
|
+
conn.alive &&
|
|
823
|
+
this.#sessionRetryOnTimeout()
|
|
824
|
+
) {
|
|
825
|
+
this.#log("session-new-retry", { timeoutMs: err.timeoutMs });
|
|
826
|
+
return await conn.newSession(turn.request.cwd);
|
|
827
|
+
}
|
|
828
|
+
throw err;
|
|
829
|
+
}
|
|
830
|
+
}
|
|
831
|
+
|
|
802
832
|
/** Usage synthesis mode, resolved per turn (follows live config). */
|
|
803
833
|
#usageMode(): UsageEstimate {
|
|
804
834
|
const opt = this.#opts.usageEstimate;
|
package/src/acp/jsonrpc.ts
CHANGED
|
@@ -189,7 +189,7 @@ export class JsonRpcSession {
|
|
|
189
189
|
if (effective > 0) {
|
|
190
190
|
pending.timer = setTimeout(() => {
|
|
191
191
|
this.#pending.delete(id);
|
|
192
|
-
reject(new
|
|
192
|
+
reject(new JsonRpcTimeoutError(method, effective));
|
|
193
193
|
}, effective);
|
|
194
194
|
}
|
|
195
195
|
this.#pending.set(id, pending);
|
|
@@ -218,6 +218,17 @@ export class JsonRpcSession {
|
|
|
218
218
|
}
|
|
219
219
|
}
|
|
220
220
|
|
|
221
|
+
export class JsonRpcTimeoutError extends Error {
|
|
222
|
+
readonly method: string;
|
|
223
|
+
readonly timeoutMs: number;
|
|
224
|
+
constructor(method: string, timeoutMs: number, message?: string) {
|
|
225
|
+
super(message ?? `ACP request timed out after ${timeoutMs}ms: ${method}`);
|
|
226
|
+
this.name = "JsonRpcTimeoutError";
|
|
227
|
+
this.method = method;
|
|
228
|
+
this.timeoutMs = timeoutMs;
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
221
232
|
/** A JSON-RPC `error` result, preserving code + data (the -32602 `loc` paths
|
|
222
233
|
* and the -32601 method name are correction oracles; see the reference doc). */
|
|
223
234
|
export class JsonRpcResponseError extends Error {
|
package/src/bridge-catalog.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import type { BridgeTools } from "./config.js";
|
|
2
|
+
import { POLL_TOOL_NAME } from "./provider.js";
|
|
3
|
+
import { ACTIVATE_SKILL_TOOL_NAME } from "./skills.js";
|
|
2
4
|
|
|
3
5
|
export interface BridgeToolInfo {
|
|
4
6
|
name: string;
|
|
@@ -7,6 +9,37 @@ export interface BridgeToolInfo {
|
|
|
7
9
|
sourceInfo?: { source?: string };
|
|
8
10
|
}
|
|
9
11
|
|
|
12
|
+
export const TOOL_INFO_TOOL_NAME = "bridge_tool_info";
|
|
13
|
+
export const CALL_TOOL_NAME = "bridge_call_tool";
|
|
14
|
+
const MAX_DESC_NAMES_CHARS = 4000;
|
|
15
|
+
const MAX_INFO_TOOLS_PER_CALL = 20;
|
|
16
|
+
|
|
17
|
+
/** Pi's seven built-in default tools; only these stay always-loaded when active. */
|
|
18
|
+
const PI_DEFAULT_TOOLS = new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]);
|
|
19
|
+
|
|
20
|
+
const BRIDGE_INTERNAL_TOOLS = new Set([
|
|
21
|
+
"AskAntigravity",
|
|
22
|
+
"antigravity",
|
|
23
|
+
"agy_web_search",
|
|
24
|
+
"agy_read_url",
|
|
25
|
+
POLL_TOOL_NAME,
|
|
26
|
+
ACTIVATE_SKILL_TOOL_NAME,
|
|
27
|
+
TOOL_INFO_TOOL_NAME,
|
|
28
|
+
CALL_TOOL_NAME,
|
|
29
|
+
]);
|
|
30
|
+
|
|
31
|
+
const DEFAULT_INPUT_SCHEMA: object = { type: "object", properties: {}, additionalProperties: true };
|
|
32
|
+
|
|
33
|
+
/** Serialize a tool's TypeBox/JSON schema safely for MCP exposure. */
|
|
34
|
+
export function serializeToolSchema(parameters?: object): object {
|
|
35
|
+
if (!parameters) return DEFAULT_INPUT_SCHEMA;
|
|
36
|
+
try {
|
|
37
|
+
return JSON.parse(JSON.stringify(parameters)) as object;
|
|
38
|
+
} catch {
|
|
39
|
+
return DEFAULT_INPUT_SCHEMA;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
10
43
|
/** The bridge has one live HTTP endpoint. Catalog and dispatch must both use
|
|
11
44
|
* the CURRENT Pi active set: /mcp and pi.setActiveTools() can change it mid-session.
|
|
12
45
|
* A stale tools/call must not bypass a disabled Pi tool. */
|
|
@@ -19,11 +52,146 @@ export function bridgedPiTools(
|
|
|
19
52
|
enabled.has(tool.name) && !hidden.has(tool.name) &&
|
|
20
53
|
// Never bridge the bridge's own tools. agy has native web tools, so
|
|
21
54
|
// our quota-burning one-shot wrappers must not tempt it through MCP.
|
|
22
|
-
|
|
23
|
-
tool.name !== "agy_web_search" && tool.name !== "agy_read_url" &&
|
|
24
|
-
tool.name !== "bridge_poll_result" && tool.name !== "activate_skill" &&
|
|
55
|
+
!BRIDGE_INTERNAL_TOOLS.has(tool.name) &&
|
|
25
56
|
(mode === "mcp"
|
|
26
57
|
? /pi-mcp-adapter/.test(tool.sourceInfo?.source ?? "")
|
|
27
58
|
: tool.sourceInfo?.source !== "builtin"),
|
|
28
59
|
);
|
|
29
60
|
}
|
|
61
|
+
|
|
62
|
+
/** Split authorized bridge tools into always-loaded Pi defaults and proxied extension tools. */
|
|
63
|
+
export function partitionBridgeTools<T extends BridgeToolInfo>(tools: readonly T[]): { direct: T[]; proxied: T[] } {
|
|
64
|
+
const direct: T[] = [];
|
|
65
|
+
const proxied: T[] = [];
|
|
66
|
+
for (const tool of tools) {
|
|
67
|
+
if (PI_DEFAULT_TOOLS.has(tool.name)) direct.push(tool);
|
|
68
|
+
else proxied.push(tool);
|
|
69
|
+
}
|
|
70
|
+
return { direct, proxied };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Build the bridge_tool_info MCP tool definition listing proxied extension tool names. */
|
|
74
|
+
export function bridgeToolInfoDef(proxied: readonly BridgeToolInfo[]): {
|
|
75
|
+
name: string;
|
|
76
|
+
description: string;
|
|
77
|
+
inputSchema: object;
|
|
78
|
+
} {
|
|
79
|
+
const cleaned = proxied.map((t) => t.name.replace(/[\r\n]+/g, " ").trim()).filter(Boolean);
|
|
80
|
+
let namesText = "";
|
|
81
|
+
let shown = 0;
|
|
82
|
+
for (const n of cleaned) {
|
|
83
|
+
const next = shown === 0 ? n : `${namesText}, ${n}`;
|
|
84
|
+
if (next.length > MAX_DESC_NAMES_CHARS && shown > 0) break;
|
|
85
|
+
namesText = next;
|
|
86
|
+
shown++;
|
|
87
|
+
}
|
|
88
|
+
const remainder = cleaned.length - shown;
|
|
89
|
+
const suffix = remainder > 0 ? `, ... (+${remainder} more; pass names: ["*"] to list all)` : "";
|
|
90
|
+
return {
|
|
91
|
+
name: TOOL_INFO_TOOL_NAME,
|
|
92
|
+
description: `Inspect description and parameter schema for extension Pi tools before calling them via ${CALL_TOOL_NAME}. Pass ["*"] to list all names. Available extension tools (${cleaned.length}): ${namesText}${suffix}`,
|
|
93
|
+
inputSchema: {
|
|
94
|
+
type: "object",
|
|
95
|
+
properties: {
|
|
96
|
+
names: {
|
|
97
|
+
type: "array",
|
|
98
|
+
items: { type: "string" },
|
|
99
|
+
description: 'Exact Pi tool names to inspect (or ["*"] to list all available extension tools).',
|
|
100
|
+
},
|
|
101
|
+
},
|
|
102
|
+
required: ["names"],
|
|
103
|
+
},
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** Build the bridge_call_tool MCP tool definition for invoking proxied extension tools. */
|
|
108
|
+
export function bridgeCallToolDef(): { name: string; description: string; inputSchema: object } {
|
|
109
|
+
return {
|
|
110
|
+
name: CALL_TOOL_NAME,
|
|
111
|
+
description: `Invoke an extension Pi tool listed in ${TOOL_INFO_TOOL_NAME}. Inspect its schema with ${TOOL_INFO_TOOL_NAME} first, then pass its exact name and a stringified JSON object in arguments_json.`,
|
|
112
|
+
inputSchema: {
|
|
113
|
+
type: "object",
|
|
114
|
+
properties: {
|
|
115
|
+
name: { type: "string", description: "Exact Pi tool name to invoke." },
|
|
116
|
+
arguments_json: {
|
|
117
|
+
type: "string",
|
|
118
|
+
description: "Stringified JSON object of tool arguments (omit or '{}' if none).",
|
|
119
|
+
},
|
|
120
|
+
},
|
|
121
|
+
required: ["name"],
|
|
122
|
+
},
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Format full descriptions and schemas for requested Pi tools. */
|
|
127
|
+
export function formatBridgeToolInfo(
|
|
128
|
+
authorized: readonly BridgeToolInfo[],
|
|
129
|
+
rawNames: unknown,
|
|
130
|
+
): { content: Array<{ type: "text"; text: string }>; isError: boolean } {
|
|
131
|
+
const names = Array.isArray(rawNames)
|
|
132
|
+
? rawNames.filter((n): n is string => typeof n === "string" && n.trim().length > 0).map((n) => n.trim())
|
|
133
|
+
: [];
|
|
134
|
+
if (names.length === 0) {
|
|
135
|
+
return { content: [{ type: "text", text: "Error: names must be a non-empty array of tool names" }], isError: true };
|
|
136
|
+
}
|
|
137
|
+
if (names.includes("*")) {
|
|
138
|
+
const list = authorized.map((t) => t.name).join(", ") || "(none)";
|
|
139
|
+
return {
|
|
140
|
+
content: [{ type: "text", text: `Available extension tools (${authorized.length}): ${list}` }],
|
|
141
|
+
isError: false,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
const capped = names.slice(0, MAX_INFO_TOOLS_PER_CALL);
|
|
145
|
+
const byName = new Map(authorized.map((t) => [t.name, t]));
|
|
146
|
+
const sections: string[] = [];
|
|
147
|
+
const missing: string[] = [];
|
|
148
|
+
for (const name of capped) {
|
|
149
|
+
const tool = byName.get(name);
|
|
150
|
+
if (!tool) {
|
|
151
|
+
missing.push(name);
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
154
|
+
sections.push(
|
|
155
|
+
`### ${tool.name}\n${tool.description ?? tool.name}\n\nParameters schema:\n${JSON.stringify(serializeToolSchema(tool.parameters), null, 2)}`,
|
|
156
|
+
);
|
|
157
|
+
}
|
|
158
|
+
if (missing.length > 0) sections.push(`Unknown or inactive tools: ${missing.join(", ")}`);
|
|
159
|
+
if (names.length > MAX_INFO_TOOLS_PER_CALL) {
|
|
160
|
+
sections.push(`Note: truncated to first ${MAX_INFO_TOOLS_PER_CALL} requested tools (${names.length} requested).`);
|
|
161
|
+
}
|
|
162
|
+
return {
|
|
163
|
+
content: [{ type: "text", text: sections.join("\n\n---\n\n") }],
|
|
164
|
+
isError: missing.length === capped.length,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** Validate and parse a bridge_call_tool payload against currently authorized Pi tools. */
|
|
169
|
+
export function parseBridgeCallRequest(
|
|
170
|
+
raw: Record<string, unknown>,
|
|
171
|
+
authorized: readonly BridgeToolInfo[],
|
|
172
|
+
): { ok: true; name: string; args: Record<string, unknown> } | { ok: false; error: string } {
|
|
173
|
+
const name = typeof raw.name === "string" ? raw.name.trim() : "";
|
|
174
|
+
if (!name) return { ok: false, error: "Error: name must be a non-empty string" };
|
|
175
|
+
if (BRIDGE_INTERNAL_TOOLS.has(name) || !authorized.some((t) => t.name === name)) {
|
|
176
|
+
return { ok: false, error: `Pi tool ${name} is not active or not exposed to Antigravity` };
|
|
177
|
+
}
|
|
178
|
+
const rawJson = raw.arguments_json;
|
|
179
|
+
if (rawJson === undefined || rawJson === null || rawJson === "") {
|
|
180
|
+
return { ok: true, name, args: {} };
|
|
181
|
+
}
|
|
182
|
+
if (typeof rawJson === "object" && !Array.isArray(rawJson)) {
|
|
183
|
+
return { ok: true, name, args: rawJson as Record<string, unknown> };
|
|
184
|
+
}
|
|
185
|
+
if (typeof rawJson !== "string") {
|
|
186
|
+
return { ok: false, error: "Error: arguments_json must be a stringified JSON object" };
|
|
187
|
+
}
|
|
188
|
+
try {
|
|
189
|
+
const parsed = JSON.parse(rawJson) as unknown;
|
|
190
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
191
|
+
return { ok: false, error: "Error: arguments_json must decode to a JSON object" };
|
|
192
|
+
}
|
|
193
|
+
return { ok: true, name, args: parsed as Record<string, unknown> };
|
|
194
|
+
} catch (err) {
|
|
195
|
+
return { ok: false, error: `Error: invalid arguments_json (${err instanceof Error ? err.message : String(err)})` };
|
|
196
|
+
}
|
|
197
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -84,6 +84,16 @@ export interface AcpConfig {
|
|
|
84
84
|
* usage surfaces show nonzero numbers. Estimates are labeled as such in
|
|
85
85
|
* /agy doctor and auto-disable when the server sends real usage. */
|
|
86
86
|
usageEstimate: UsageEstimate;
|
|
87
|
+
/** Timeout in ms for ACP session operations (session/new, session/load,
|
|
88
|
+
* session/set_config_option, session/close). Default 20000 (20s); valid
|
|
89
|
+
* range 1000..300000. Env AGY_ACP_SESSION_TIMEOUT_MS wins over the file. */
|
|
90
|
+
sessionTimeoutMs: number;
|
|
91
|
+
/** Advanced: transparently retry session/new once when it times out while
|
|
92
|
+
* the ACP server is still alive. Default false. Warning: doubles the wait
|
|
93
|
+
* on genuinely dead networks (e.g. 40s at default 20s timeout) and may not
|
|
94
|
+
* recover if the server process itself has a wedged socket.
|
|
95
|
+
* Env AGY_ACP_SESSION_RETRY wins over the file. */
|
|
96
|
+
sessionRetryOnTimeout: boolean;
|
|
87
97
|
}
|
|
88
98
|
|
|
89
99
|
export interface AgyConfig {
|
|
@@ -211,9 +221,23 @@ const DEFAULTS: AgyConfig = {
|
|
|
211
221
|
turnTimeoutMin: 0, // placeholder: the real default is resolved per loadConfig call (defaultTurnTimeoutMin)
|
|
212
222
|
inactivityTimeoutMin: 5,
|
|
213
223
|
approvals: { gateMode: "auto", mode: "ask" },
|
|
214
|
-
acp: {
|
|
224
|
+
acp: {
|
|
225
|
+
usageEstimate: "estimate",
|
|
226
|
+
sessionTimeoutMs: 20_000,
|
|
227
|
+
sessionRetryOnTimeout: false,
|
|
228
|
+
},
|
|
215
229
|
};
|
|
216
230
|
|
|
231
|
+
const MIN_ACP_SESSION_TIMEOUT_MS = 1_000;
|
|
232
|
+
const MAX_ACP_SESSION_TIMEOUT_MS = 300_000;
|
|
233
|
+
|
|
234
|
+
function parseSessionTimeoutMs(raw: unknown, fallback: number): number {
|
|
235
|
+
if (raw === undefined || raw === null || String(raw).trim() === "") return fallback;
|
|
236
|
+
const n = typeof raw === "number" ? raw : Number(String(raw).trim());
|
|
237
|
+
if (!Number.isSafeInteger(n)) return fallback;
|
|
238
|
+
return n >= MIN_ACP_SESSION_TIMEOUT_MS && n <= MAX_ACP_SESSION_TIMEOUT_MS ? n : fallback;
|
|
239
|
+
}
|
|
240
|
+
|
|
217
241
|
/** Hard ceiling for a free-typed turn cap: one day, in minutes. */
|
|
218
242
|
export const MAX_TURN_CAP_MIN = 1440;
|
|
219
243
|
|
|
@@ -389,7 +413,15 @@ export function loadConfig(configPath: string = CONFIG_PATH): AgyConfig {
|
|
|
389
413
|
).toLowerCase();
|
|
390
414
|
const usageEstimate: UsageEstimate =
|
|
391
415
|
usageRaw === "direct" || usageRaw === "off" ? usageRaw : "estimate";
|
|
392
|
-
const
|
|
416
|
+
const sessionTimeoutMs = parseSessionTimeoutMs(
|
|
417
|
+
process.env.AGY_ACP_SESSION_TIMEOUT_MS ?? fileAcp.sessionTimeoutMs,
|
|
418
|
+
DEFAULTS.acp.sessionTimeoutMs,
|
|
419
|
+
);
|
|
420
|
+
const envSessionRetry = process.env.AGY_ACP_SESSION_RETRY;
|
|
421
|
+
const sessionRetryOnTimeout = envSessionRetry !== undefined
|
|
422
|
+
? ["1", "true", "on"].includes(envSessionRetry.toLowerCase())
|
|
423
|
+
: fileAcp.sessionRetryOnTimeout === true;
|
|
424
|
+
const acp: AcpConfig = { usageEstimate, sessionTimeoutMs, sessionRetryOnTimeout };
|
|
393
425
|
|
|
394
426
|
// Custom agent for stream-json turns (--agent). Env wins over the file
|
|
395
427
|
// (same pattern as mode). Normalized (trim/cap/control-strip); an empty
|
|
@@ -450,7 +482,9 @@ function writeConfigJson(configPath: string, value: unknown): void {
|
|
|
450
482
|
* disk on any unrelated save, outliving the env var). Nested objects are
|
|
451
483
|
* re-normalized to their known keys: a raw passthrough would resurrect
|
|
452
484
|
* legacy keys (acp.permissions) that loadConfig normalization drops. */
|
|
453
|
-
export
|
|
485
|
+
export type ConfigPatch = Partial<Omit<AgyConfig, "acp">> & { acp?: Partial<AcpConfig> };
|
|
486
|
+
|
|
487
|
+
export function saveConfig(patch: ConfigPatch, configPath: string = CONFIG_PATH): AgyConfig {
|
|
454
488
|
const file = readConfigFile(configPath);
|
|
455
489
|
// Null-safe on nested objects: a hand-edited or legacy file can carry
|
|
456
490
|
// "acp": null; loadConfig tolerates it, so must saveConfig. Key presence
|
|
@@ -464,16 +498,23 @@ export function saveConfig(patch: Partial<AgyConfig>, configPath: string = CONFI
|
|
|
464
498
|
// save, switching an existing install to ACP on the next start.
|
|
465
499
|
const persistedEngine = patch.engine ?? file.engine
|
|
466
500
|
?? (fs.existsSync(configPath) ? "stream-json" : DEFAULT_ENGINE);
|
|
501
|
+
const { acp: patchAcp, ...restPatch } = patch;
|
|
502
|
+
const mergedAcp: AcpConfig = {
|
|
503
|
+
usageEstimate: patchAcp?.usageEstimate ?? fileAcp.usageEstimate ?? DEFAULTS.acp.usageEstimate,
|
|
504
|
+
sessionTimeoutMs: parseSessionTimeoutMs(
|
|
505
|
+
patchAcp?.sessionTimeoutMs ?? fileAcp.sessionTimeoutMs,
|
|
506
|
+
DEFAULTS.acp.sessionTimeoutMs,
|
|
507
|
+
),
|
|
508
|
+
sessionRetryOnTimeout: patchAcp?.sessionRetryOnTimeout ?? (fileAcp.sessionRetryOnTimeout === true),
|
|
509
|
+
};
|
|
467
510
|
const next: AgyConfig = {
|
|
468
511
|
...DEFAULTS,
|
|
469
512
|
...file,
|
|
470
|
-
...(file.acp !== undefined
|
|
471
|
-
? { acp: { usageEstimate: fileAcp.usageEstimate ?? DEFAULTS.acp.usageEstimate } }
|
|
472
|
-
: {}),
|
|
473
513
|
...(file.approvals !== undefined
|
|
474
514
|
? { approvals: { gateMode: fileApprovals.gateMode ?? DEFAULTS.approvals.gateMode, mode: fileApprovals.mode ?? DEFAULTS.approvals.mode } }
|
|
475
515
|
: {}),
|
|
476
|
-
...
|
|
516
|
+
...restPatch,
|
|
517
|
+
acp: mergedAcp,
|
|
477
518
|
engine: narrowEngine(String(persistedEngine).toLowerCase()),
|
|
478
519
|
};
|
|
479
520
|
writeConfigJson(configPath, next);
|
package/src/provider.ts
CHANGED
|
@@ -179,7 +179,7 @@ export const SYSTEM_PROMPT_END = "[END SYSTEM PROMPT]";
|
|
|
179
179
|
* the user's machine must go through the bridge. Rides the systemPrompt
|
|
180
180
|
* gate: the note ships only when the system prompt ships. */
|
|
181
181
|
export const TOOL_PRIORITY_NOTE =
|
|
182
|
-
"[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit, execute). Image files are visible to you: the Pi Bridge read tool returns image files as visible images (png, jpg, webp, gif, bmp), so never claim you cannot view images. When a bridge call answers STILL RUNNING, poll bridge_poll_result before doing other work: until you poll, the result (including any image) stays undelivered to you. Delegate subagent work the same way: when pi's tool list includes a delegation tool (for example subagent, Agent, agent_spawn, agent_wait, or subagent_run), always delegate through it and never through the native invoke_subagent, run_subagent, or manage_subagents; use native ones only if no pi delegation tool is listed, because native subagents run inside agy and are invisible to pi and anything watching it. Long-running bridge calls do not fail: after ~20 seconds the bridge answers STILL RUNNING with a callId; fetch the result with bridge_poll_result and poll until it lands. For work you already know is long, prefer exec_command's session-output pattern or background agents so you keep working while it runs.]";
|
|
182
|
+
"[Tool priority: this conversation runs inside pi, not as a standalone agy session; the user only sees what surfaces in pi. Native interactive tools, for example ask_question, never reach the user. When a Pi Bridge tool covers the same purpose, always use the Pi Bridge tool; for user questions use ask_user_question. Your native file tools such as view_file only read brain artifacts and reject real filesystem paths; for any path on the user's machine use the Pi Bridge tools (read, ls, grep, find, edit, execute). Image files are visible to you: the Pi Bridge read tool returns image files as visible images (png, jpg, webp, gif, bmp), so never claim you cannot view images. Extension Pi tools not declared directly are listed in bridge_tool_info; call bridge_tool_info to inspect their description and schema, then call bridge_call_tool to run them. When a bridge call answers STILL RUNNING, poll bridge_poll_result before doing other work: until you poll, the result (including any image) stays undelivered to you. Delegate subagent work the same way: when pi's tool list includes a delegation tool (for example subagent, Agent, agent_spawn, agent_wait, or subagent_run), always delegate through it and never through the native invoke_subagent, run_subagent, or manage_subagents; use native ones only if no pi delegation tool is listed, because native subagents run inside agy and are invisible to pi and anything watching it. Long-running bridge calls do not fail: after ~20 seconds the bridge answers STILL RUNNING with a callId; fetch the result with bridge_poll_result and poll until it lands. For work you already know is long, prefer exec_command's session-output pattern or background agents so you keep working while it runs.]";
|
|
183
183
|
|
|
184
184
|
/** Assemble the full agy prompt: system prompt block, pi-side digest, user
|
|
185
185
|
* prompt. Empty parts are dropped. Pure; exported for unit testing.
|