@estebanforge/pi-antigravity-bridge 1.19.0 → 1.20.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +18 -0
- package/README.md +3 -1
- package/extensions/index.ts +11 -0
- package/package.json +1 -1
- package/src/auth-state.ts +104 -0
- package/src/config.ts +44 -1
- package/src/provider.ts +68 -30
- package/src/quota-notice.ts +4 -2
package/CHANGELOG.md
CHANGED
|
@@ -2,6 +2,24 @@
|
|
|
2
2
|
|
|
3
3
|
All notable changes to this project will be documented in this file.
|
|
4
4
|
|
|
5
|
+
## [1.20.0] - 2026-12-03
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
|
|
9
|
+
- Diverged sync continuations no longer stamp a trimmed transcript onto the stale ACP conversation (issue #40, reported and first patched by @rochecompaan; landed with the divergence predicate narrowed to the trim case): when a context hook (pi-context-paging) trims or rewrites earlier turns while a sync turn is parked on a bridge call, the continuation re-plans as a `changed-inflight-prefix` rebuild, and settlement used to ignore the plan (bound() + dispatching() + finish() skipped the id check via freshConversation and adopted the old conversation id), so the terminal checkpoint claimed the trimmed transcript equals the old conversation and every later turn kept continuing warm on a conversation that still holds the evicted turns. Settlement now invalidates with the plan reason and persists the invalidated record, so the next user turn rebuilds a fresh conversation from the trimmed transcript; the churn gate is untouched (it counts only fresh-dispatch `changed-prefix` streaks, not invalidReason rebuilds). The divergence guard is deliberately narrow: a steered continuation (`new-user-during-turn`) is not divergence because the steering carrier already delivered the steer into the same conversation, so its settlement stays terminal and warm, pinned by a new steered-continuation provider test.
|
|
10
|
+
|
|
11
|
+
### Added
|
|
12
|
+
|
|
13
|
+
- Auth-state detection with zero credential reads: agy's logged-out and expired-session failures used to surface as raw driver error text with no actionable guidance. A new auth-state module classifies the evidenced auth error wording in driver/spawn error strings and start-anchored notice text a settled turn may carry (same conservative shape as the quota notice: start anchor, 400-character cap), and reclassifies both into a fixed actionable errorMessage ("run `agy acp --login`") that pi-ai classifies as fail-fast — no retry loop, no provider failover, and the raw upstream text is never echoed, so copy drift cannot poison the classification. The module also watches the five known agy credential files by stat metadata only (size/mtime/inode, never a content read, keeping credentials inside the official runtime per Antigravity ToS §6), and session startup now emits a soft once-per-process hint when no credential marker exists anywhere — hedged, because keyring-only logins may legitimately leave none; on agy 1.5.22 the live marker is ~/.config/antigravity/credential-user-scope. Pinned by tests/auth-state.test.ts (10 cases, including the fail-fast classification asserted against pi-ai's real isRetryableAssistantError).
|
|
14
|
+
|
|
15
|
+
- Configurable ACP context-digest character cap (issue #41, patch by @pechhe; `acp.digestMaxChars` / `AGY_ACP_DIGEST_MAX_CHARS`, valid range `4000`-`120000`, default `24000`): applies to both primary ACP context digests and fresh-rebuild fallback digests (`stream-json` keeps its inline `8000` / `25KB` prompt cap). Lets sessions with large post-compaction tails (such as `keepRecentTokens >= 40000`) preserve recent kept turns after compaction rotation within the `120000`-char `embeddedContext` envelope verified by `scripts/probe-acp-context.mjs`. Invalid or out-of-range values fall back to `24000` with a `parseWarnings` entry.
|
|
16
|
+
|
|
17
|
+
## [1.19.1] - 2026-12-03
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- The shared-quota notice was never detected as a quota exhaustion (issue #39, thanks to @hectormr206 for the report and the fix diagnosis): its prefix word before "quota reached" is hyphenated ("Third-party"), which the detection pattern's `[a-z]+` word class could not match, so the ACP turn settled as a normal reply with no errorMessage and provider failover / model fallback chains never fired — the session kept answering with the notice until the reset. The optional prefix word now allows internal hyphens (`[a-z][a-z-]*`) while staying letter-initial, so a leading dash still cannot open it; the start anchor, the 400-character cap and the retryable errorMessage classification are unchanged, pinned by seven new cases in the quota-notice tests.
|
|
22
|
+
|
|
5
23
|
## [1.19.0] - 2026-12-02
|
|
6
24
|
|
|
7
25
|
### Added
|
package/README.md
CHANGED
|
@@ -130,11 +130,12 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
|
|
|
130
130
|
| `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` |
|
|
131
131
|
| `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` |
|
|
132
132
|
| `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` |
|
|
133
|
+
| `acp.digestMaxChars` | Max characters for ACP context-continuity digests (`embeddedContext` block). Valid range: `4000`-`120000`. Raise when sessions keep a large post-compaction tail (e.g. `keepRecentTokens >= 40000`) so recent kept turns are not starved after compaction rotation. The digest persists in agy's conversation DB, so a raised cap raises the context cost of every later turn, and it also lifts the compaction-summary clamp. Applies to `handoff: digest` (default) only; `handoff: sync` ships history as a framed block under its own 3 MiB budget | `24000` |
|
|
133
134
|
| `acp.leanAgent` | Lean agent mode for the ACP engine: spawns agy with a staged custom agent that excludes the default components, so the model's only tool is the generic `call_mcp_tool` wrapper reaching the bridge MCP server — no native read/command/subagent tools and a much smaller first-turn context (measured ~0.6-0.9k vs ~19.3k input tokens on agy 1.5.22). The agent body is generated from the live bridge catalog at spawn: under `bridgeTools: "codemode"` the model works through one codemode script tool; under `"all"` the seven pi builtins are callable by name and extension tools via `bridge_tool_info`. The agent file stages inside the isolated ACP home per spawn (nothing lands in the global agents dir; a global agent named `pi-bridge-lean` is never touched); the tool protocol rides the agent body (all provider prompt notes are suppressed); session keys gain an `@lean` marker so a flip starts a fresh conversation. Restart applies; bridge-surface changes after a spawn (`/agy bridge`, `/agy tools`) leave the staged body stale until the next pi start. `manage_task`/`list_resources`/`read_resource` stay model-visible (agy keeps them under exclusion). ACP only | `false` |
|
|
134
135
|
|
|
135
136
|
Boolean keys (`readOnly`, `skipPermissions`, `askTool`, `webTools`, `digest`, `systemPrompt`, `acp.sessionRetryOnTimeout`) take JSON booleans, the `/agy` vocabulary as strings (`on`/`off`, `1`/`0`, case and whitespace tolerated), and the JSON numbers `0`/`1`, so a hand-edited `"off"` means off instead of silently on (issue #23). Unrecognized values fall back to the key's default - `readOnly` falls closed to `true` - and surface a `config warnings:` row in `/agy doctor` plus a startup warning toast. The `AGY_*` env vars keep their own grammars: notably `AGY_SKIP_PERMISSIONS` does not accept `on` (only `1`/`true` enable there), and while an env var is set the matching file value is never parsed, so it emits no warning for the value it overrides.
|
|
136
137
|
|
|
137
|
-
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.
|
|
138
|
+
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_DIGEST_MAX_CHARS`, `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.
|
|
138
139
|
|
|
139
140
|
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.
|
|
140
141
|
|
|
@@ -197,6 +198,7 @@ For isolation when running any agent that executes commands without a confirmati
|
|
|
197
198
|
| `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. |
|
|
198
199
|
| `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. |
|
|
199
200
|
| `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`. |
|
|
201
|
+
| `AGY_ACP_DIGEST_MAX_CHARS` | Max characters for ACP context-continuity digests (`4000`-`120000`, default `24000`). Wins over `config.acp.digestMaxChars`. |
|
|
200
202
|
| `AGY_ACP_LEAN_AGENT` | `1`/`true`/`on` spawns the ACP engine with the staged lean agent: bridge MCP tools only, no native agy tools (default off; restart applies). Wins over `config.acp.leanAgent`. |
|
|
201
203
|
| `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`. |
|
|
202
204
|
| `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. |
|
package/extensions/index.ts
CHANGED
|
@@ -51,6 +51,7 @@ import {
|
|
|
51
51
|
type NativeDisplayEvent,
|
|
52
52
|
} from "../src/provider.js";
|
|
53
53
|
import { handoffToast } from "../src/handoff-toast.js";
|
|
54
|
+
import { hasAntigravityAuthMetadata } from "../src/auth-state.js";
|
|
54
55
|
import { collectNativeFileOps } from "../src/native-fileops.js";
|
|
55
56
|
import { preemptParkedTurnForCompaction } from "../src/compaction-preempt.js";
|
|
56
57
|
import { PollRunFolder, type PollRunData } from "../src/poll-fold.js";
|
|
@@ -251,6 +252,7 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
251
252
|
let agySetupOffer: (() => Promise<void>) | null = null;
|
|
252
253
|
let agyMissingWarned = false;
|
|
253
254
|
let agyVersionWarned = false;
|
|
255
|
+
let agyAuthHintWarned = false;
|
|
254
256
|
let agyVersionMessage = "";
|
|
255
257
|
// Two turn engines behind one contract: `agy acp` (default for new
|
|
256
258
|
// installs) and the stream-json `agy` CLI
|
|
@@ -920,6 +922,15 @@ export default async function (pi: ExtensionAPI): Promise<void> {
|
|
|
920
922
|
return;
|
|
921
923
|
}
|
|
922
924
|
const rawCheck = await checkAgyCliVersion(binary);
|
|
925
|
+
// Soft, once-per-process login hint: newer agy keeps tokens in the OS
|
|
926
|
+
// credential store, so marker-file absence is a hint, not proof.
|
|
927
|
+
if (!agyAuthHintWarned && !hasAntigravityAuthMetadata()) {
|
|
928
|
+
agyAuthHintWarned = true;
|
|
929
|
+
const authHint = "No Antigravity credentials found on this machine. Run `agy acp --login` before selecting an antigravity model (a keyring-only login may leave no credential files, in which case ignore this).";
|
|
930
|
+
fileLog.log("auth-metadata", { found: false }, "warn");
|
|
931
|
+
if (ctx.mode === "tui") ctx.ui.notify(authHint, "warning");
|
|
932
|
+
else console.error(`[antigravity-bridge] ${authHint}`);
|
|
933
|
+
}
|
|
923
934
|
const floor = selectedEngine === "acp" ? MIN_AGY_ACP_VERSION : MIN_AGY_VERSION;
|
|
924
935
|
const check = agyVersionVerdict(rawCheck.raw, floor);
|
|
925
936
|
if (check.status !== "unsupported") return;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@estebanforge/pi-antigravity-bridge",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.20.0",
|
|
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",
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Zero-credential auth-state detection for the local agy runtime.
|
|
2
|
+
//
|
|
3
|
+
// Two signals, both deliberately content-blind: deterministic driver error
|
|
4
|
+
// TEXT classifies a logged-out or expired account, and credential-file
|
|
5
|
+
// METADATA (statSync only, never a content read) reports whether any
|
|
6
|
+
// credential marker exists on disk. agy 1.5.x keeps tokens in the OS
|
|
7
|
+
// credential store, so missing marker files are a hint, not proof.
|
|
8
|
+
//
|
|
9
|
+
// The reclassified errorMessage wording is load-bearing: pi-ai's
|
|
10
|
+
// isRetryableAssistantError gates provider failover, and login is a
|
|
11
|
+
// deterministic, human-fixable failure, so the message carries no
|
|
12
|
+
// retryable marker (fail fast, no retry loop, no provider handoff). Raw
|
|
13
|
+
// upstream error text is never echoed, so copy drift cannot poison the
|
|
14
|
+
// classification or leak credential-store details.
|
|
15
|
+
|
|
16
|
+
import fs from "node:fs";
|
|
17
|
+
import os from "node:os";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
|
|
20
|
+
export interface AuthMetadataOptions {
|
|
21
|
+
home?: string;
|
|
22
|
+
env?: NodeJS.ProcessEnv;
|
|
23
|
+
platform?: NodeJS.Platform;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Cross-platform user config dir (holds antigravity/credential-user-scope). */
|
|
27
|
+
export function resolveAntigravityUserConfigDir(
|
|
28
|
+
platform: NodeJS.Platform = process.platform,
|
|
29
|
+
home: string = os.homedir(),
|
|
30
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
31
|
+
): string {
|
|
32
|
+
if (platform === "win32") {
|
|
33
|
+
const appData = env.APPDATA?.trim();
|
|
34
|
+
return appData ? path.resolve(appData) : path.join(home, "AppData", "Roaming");
|
|
35
|
+
}
|
|
36
|
+
if (platform === "darwin") return path.join(home, "Library", "Application Support");
|
|
37
|
+
const xdg = env.XDG_CONFIG_HOME?.trim();
|
|
38
|
+
return xdg ? path.resolve(xdg) : path.join(home, ".config");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Every file agy is known to keep account credential state in. Watched by
|
|
42
|
+
* stat metadata only; newer agy versions keep tokens in the OS credential
|
|
43
|
+
* store and leave only the scope marker on disk. */
|
|
44
|
+
export function antigravityAuthMetadataPaths(options: AuthMetadataOptions = {}): string[] {
|
|
45
|
+
const home = options.home ?? os.homedir();
|
|
46
|
+
const env = options.env ?? process.env;
|
|
47
|
+
const gemini = path.join(home, ".gemini");
|
|
48
|
+
const appData = path.join(gemini, "antigravity-cli");
|
|
49
|
+
const userConfig = resolveAntigravityUserConfigDir(options.platform ?? process.platform, home, env);
|
|
50
|
+
return [
|
|
51
|
+
path.join(gemini, "jetski-standalone-oauth-token"),
|
|
52
|
+
path.join(gemini, "oauth_creds.json"),
|
|
53
|
+
path.join(gemini, "google_accounts.json"),
|
|
54
|
+
path.join(appData, "antigravity-oauth-token"),
|
|
55
|
+
path.join(userConfig, "antigravity", "credential-user-scope"),
|
|
56
|
+
];
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function metadataSignature(file: string): string {
|
|
60
|
+
try {
|
|
61
|
+
const stat = fs.statSync(file);
|
|
62
|
+
// Size + mtime + inode identify state without one content byte.
|
|
63
|
+
return stat.isFile() ? `f:${stat.size}:${stat.mtimeMs}:${stat.ino}` : "nonfile";
|
|
64
|
+
} catch {
|
|
65
|
+
return "missing";
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** True when at least one credential marker file exists on disk. */
|
|
70
|
+
export function hasAntigravityAuthMetadata(options: AuthMetadataOptions = {}): boolean {
|
|
71
|
+
return antigravityAuthMetadataPaths(options).some((file) => metadataSignature(file) !== "missing");
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// Evidence-based agy/gRPC auth failure wording. Unanchored by design: it
|
|
75
|
+
// runs on machine-generated driver error strings, never on settled agent
|
|
76
|
+
// prose (detectAuthNotice guards that path instead).
|
|
77
|
+
const AUTH_ERROR_PATTERN =
|
|
78
|
+
/(?:authentication\s+required|not\s+logged\s+in(?:\s+to|to)?\s+antigravity|oauth\s+session\s+expired|token\s+(?:has\s+)?(?:expired|revoked|invalid)|invalid\s+token|invalid_grant|\bunauthenticated\b|\bHTTP\s*401\b|\bcode["\s:]+401\b|error\s+getting\s+token\s+source)/i;
|
|
79
|
+
|
|
80
|
+
/** Classify a driver/spawn error string as an agy login or session failure. */
|
|
81
|
+
export function isAuthErrorMessage(text: string): boolean {
|
|
82
|
+
if (!text) return false;
|
|
83
|
+
return AUTH_ERROR_PATTERN.test(text);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const AUTH_NOTICE_MAX_CHARS = 400;
|
|
87
|
+
// Start-anchored like the quota notice: only a notice-shaped (near-)whole
|
|
88
|
+
// response reclassifies; an answer that merely discusses 401s stays an answer.
|
|
89
|
+
const AUTH_NOTICE_PATTERN =
|
|
90
|
+
/^\s*(?:⚠\s*)?(?:(?:error)\s*:\s*)?(?:[a-z][a-z-]*\s+)?(?:authentication\s+required|not\s+logged\s+in(?:\s+to|to)?\s+antigravity|oauth\s+session\s+expired|token\s+(?:has\s+)?(?:expired|revoked|invalid)|invalid_grant|\bunauthenticated\b)/i;
|
|
91
|
+
|
|
92
|
+
/** Classify a settled response as a login notice agy delivered as agent text.
|
|
93
|
+
* Conservative by design: false negatives keep a normal reply, false
|
|
94
|
+
* positives would turn real answers into errors. */
|
|
95
|
+
export function detectAuthNotice(response: string): boolean {
|
|
96
|
+
const trimmed = response.trim();
|
|
97
|
+
if (trimmed.length === 0 || trimmed.length > AUTH_NOTICE_MAX_CHARS) return false;
|
|
98
|
+
return AUTH_NOTICE_PATTERN.test(trimmed);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/** Retryability-relevant pi errorMessage for a detected auth failure. */
|
|
102
|
+
export function authErrorMessage(): string {
|
|
103
|
+
return "Antigravity login missing or expired. Run `agy acp --login` in a terminal, then retry this turn.";
|
|
104
|
+
}
|
package/src/config.ts
CHANGED
|
@@ -96,6 +96,13 @@ export interface AcpConfig {
|
|
|
96
96
|
* recover if the server process itself has a wedged socket.
|
|
97
97
|
* Env AGY_ACP_SESSION_RETRY wins over the file. */
|
|
98
98
|
sessionRetryOnTimeout: boolean;
|
|
99
|
+
/** Max characters for ACP context-continuity digests (embeddedContext
|
|
100
|
+
* resource block). Default 24000; valid range 4000..120000 (120k verified
|
|
101
|
+
* by scripts/probe-acp-context.mjs). Raise when sessions keep a large
|
|
102
|
+
* post-compaction tail (e.g. keepRecentTokens >= 40k) so recent turns are
|
|
103
|
+
* not starved after compaction rotation. Env AGY_ACP_DIGEST_MAX_CHARS wins
|
|
104
|
+
* over the file. Stream-json ignores this and keeps its 8k / 25KB cap. */
|
|
105
|
+
digestMaxChars: number;
|
|
99
106
|
/** Lean agent mode: spawn the ACP engine with a staged lean agent file
|
|
100
107
|
* (default components excluded) so the model's only tool is the bridge
|
|
101
108
|
* MCP surface. Default false; changing it requires a pi restart (the
|
|
@@ -256,6 +263,7 @@ const DEFAULTS: AgyConfig = {
|
|
|
256
263
|
usageEstimate: "estimate",
|
|
257
264
|
sessionTimeoutMs: 20_000,
|
|
258
265
|
sessionRetryOnTimeout: false,
|
|
266
|
+
digestMaxChars: 24_000,
|
|
259
267
|
leanAgent: false,
|
|
260
268
|
},
|
|
261
269
|
};
|
|
@@ -263,6 +271,13 @@ const DEFAULTS: AgyConfig = {
|
|
|
263
271
|
const MIN_ACP_SESSION_TIMEOUT_MS = 1_000;
|
|
264
272
|
const MAX_ACP_SESSION_TIMEOUT_MS = 300_000;
|
|
265
273
|
|
|
274
|
+
// issue #41, patch by @pechhe: 120k is the probe-verified extremity-recall
|
|
275
|
+
// ceiling (scripts/probe-acp-context.mjs); below the floor the digest clamps
|
|
276
|
+
// to summary-head-only.
|
|
277
|
+
export const DEFAULT_ACP_DIGEST_MAX_CHARS = 24_000;
|
|
278
|
+
export const MIN_ACP_DIGEST_MAX_CHARS = 4_000;
|
|
279
|
+
export const MAX_ACP_DIGEST_MAX_CHARS = 120_000;
|
|
280
|
+
|
|
266
281
|
function parseSessionTimeoutMs(raw: unknown, fallback: number): number {
|
|
267
282
|
if (raw === undefined || raw === null || String(raw).trim() === "") return fallback;
|
|
268
283
|
const n = typeof raw === "number" ? raw : Number(String(raw).trim());
|
|
@@ -270,6 +285,25 @@ function parseSessionTimeoutMs(raw: unknown, fallback: number): number {
|
|
|
270
285
|
return n >= MIN_ACP_SESSION_TIMEOUT_MS && n <= MAX_ACP_SESSION_TIMEOUT_MS ? n : fallback;
|
|
271
286
|
}
|
|
272
287
|
|
|
288
|
+
function parseAcpDigestMaxChars(
|
|
289
|
+
raw: unknown,
|
|
290
|
+
fallback: number,
|
|
291
|
+
label?: string,
|
|
292
|
+
warnings?: string[],
|
|
293
|
+
): number {
|
|
294
|
+
if (raw === undefined || raw === null || (typeof raw === "string" && raw.trim() === "")) return fallback;
|
|
295
|
+
const n = typeof raw === "number" ? raw : typeof raw === "string" ? Number(raw.trim()) : Number.NaN;
|
|
296
|
+
if (Number.isSafeInteger(n) && n >= MIN_ACP_DIGEST_MAX_CHARS && n <= MAX_ACP_DIGEST_MAX_CHARS) {
|
|
297
|
+
return n;
|
|
298
|
+
}
|
|
299
|
+
if (label && warnings) {
|
|
300
|
+
warnings.push(
|
|
301
|
+
`${label}: ${JSON.stringify(raw)} is not an integer in ${MIN_ACP_DIGEST_MAX_CHARS}..${MAX_ACP_DIGEST_MAX_CHARS}; using default ${fallback}`,
|
|
302
|
+
);
|
|
303
|
+
}
|
|
304
|
+
return fallback;
|
|
305
|
+
}
|
|
306
|
+
|
|
273
307
|
/** Hard ceiling for a free-typed turn cap: one day, in minutes. */
|
|
274
308
|
export const MAX_TURN_CAP_MIN = 1440;
|
|
275
309
|
|
|
@@ -531,6 +565,11 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
531
565
|
const sessionRetryOnTimeout = envSessionRetry !== undefined
|
|
532
566
|
? ["1", "true", "on"].includes(envSessionRetry.toLowerCase())
|
|
533
567
|
: parseBoolish(fileAcp.sessionRetryOnTimeout, "acp.sessionRetryOnTimeout", DEFAULTS.acp.sessionRetryOnTimeout, parseWarnings);
|
|
568
|
+
const envDigestMax = process.env.AGY_ACP_DIGEST_MAX_CHARS;
|
|
569
|
+
const digestMaxChars =
|
|
570
|
+
envDigestMax !== undefined
|
|
571
|
+
? parseAcpDigestMaxChars(envDigestMax, DEFAULTS.acp.digestMaxChars, "AGY_ACP_DIGEST_MAX_CHARS", parseWarnings)
|
|
572
|
+
: parseAcpDigestMaxChars(fileAcp.digestMaxChars, DEFAULTS.acp.digestMaxChars, "acp.digestMaxChars", parseWarnings);
|
|
534
573
|
const envLeanRaw = process.env.AGY_ACP_LEAN_AGENT;
|
|
535
574
|
const leanAgent =
|
|
536
575
|
envLeanRaw === undefined
|
|
@@ -540,7 +579,7 @@ export function loadConfig(configFile: string = configPath()): AgyConfig {
|
|
|
540
579
|
parseWarnings.push(`AGY_ACP_LEAN_AGENT: ${JSON.stringify(envLeanRaw)} is not a recognized boolean (true/false, on/off, 1/0); using default ${DEFAULTS.acp.leanAgent}`);
|
|
541
580
|
return DEFAULTS.acp.leanAgent;
|
|
542
581
|
})());
|
|
543
|
-
const acp: AcpConfig = { usageEstimate, sessionTimeoutMs, sessionRetryOnTimeout, leanAgent };
|
|
582
|
+
const acp: AcpConfig = { usageEstimate, sessionTimeoutMs, sessionRetryOnTimeout, digestMaxChars, leanAgent };
|
|
544
583
|
|
|
545
584
|
// Custom agent for stream-json turns (--agent). Env wins over the file
|
|
546
585
|
// (same pattern as mode). Normalized (trim/cap/control-strip); an empty
|
|
@@ -616,6 +655,10 @@ export function saveConfig(patch: ConfigPatch, configFile: string = configPath()
|
|
|
616
655
|
patchAcp?.sessionRetryOnTimeout
|
|
617
656
|
?? parseBoolishLiteral(fileAcp.sessionRetryOnTimeout)
|
|
618
657
|
?? DEFAULTS.acp.sessionRetryOnTimeout,
|
|
658
|
+
digestMaxChars: parseAcpDigestMaxChars(
|
|
659
|
+
patchAcp?.digestMaxChars ?? fileAcp.digestMaxChars,
|
|
660
|
+
DEFAULTS.acp.digestMaxChars,
|
|
661
|
+
),
|
|
619
662
|
leanAgent:
|
|
620
663
|
patchAcp?.leanAgent
|
|
621
664
|
?? parseBoolishLiteral(fileAcp.leanAgent)
|
package/src/provider.ts
CHANGED
|
@@ -43,8 +43,9 @@ import { toAgyEffort, type AgyModelEntry } from "./models.js";
|
|
|
43
43
|
import { AcpHistorySync, OutboundFrameBudgetError } from "./acp/history-sync.js";
|
|
44
44
|
import { SessionStore } from "./sessions.js";
|
|
45
45
|
import { detectQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
|
|
46
|
+
import { authErrorMessage, detectAuthNotice, isAuthErrorMessage } from "./auth-state.js";
|
|
46
47
|
import { redactText } from "./redact.js";
|
|
47
|
-
import { loadConfig } from "./config.js";
|
|
48
|
+
import { DEFAULT_ACP_DIGEST_MAX_CHARS, loadConfig } from "./config.js";
|
|
48
49
|
import { GATE_MARKER, mapNativeToShadow, stripMarkerFields } from "./approval-gate.js";
|
|
49
50
|
import type { ApprovalDecision, ApprovalPayload, ApprovalParkApi } from "./mcp-server.js";
|
|
50
51
|
import path from "node:path";
|
|
@@ -404,7 +405,7 @@ const DIGEST_MAX_CHARS = 8000;
|
|
|
404
405
|
* (scripts/probe-acp-context.mjs, 2026-11-24), so 24k is transport-safe
|
|
405
406
|
* and shrinks the newest-first partial-render hole. stream-json keeps
|
|
406
407
|
* DIGEST_MAX_CHARS: its digest rides inline under the prompt byte cap. */
|
|
407
|
-
const ACP_DIGEST_MAX_CHARS =
|
|
408
|
+
const ACP_DIGEST_MAX_CHARS = DEFAULT_ACP_DIGEST_MAX_CHARS;
|
|
408
409
|
|
|
409
410
|
/** stream-json single-prompt silent-drop cap (issue #2, probed 2026-09-30):
|
|
410
411
|
* the CLI drops any prompt past ~25KB with SUCCESS and an empty response,
|
|
@@ -419,8 +420,12 @@ export const STREAM_JSON_PROMPT_MARGIN = 4_096;
|
|
|
419
420
|
the silent-drop budget alongside the user's own prompt bytes. Returns
|
|
420
421
|
null when the budget is already exhausted (ship nothing rather than a
|
|
421
422
|
digest that would push the turn over the drop cap). */
|
|
422
|
-
export function digestMaxCharsForEngine(
|
|
423
|
-
|
|
423
|
+
export function digestMaxCharsForEngine(
|
|
424
|
+
engine: string,
|
|
425
|
+
promptLength: number,
|
|
426
|
+
acpMaxChars: number = ACP_DIGEST_MAX_CHARS,
|
|
427
|
+
): number | null {
|
|
428
|
+
if (engine === "acp") return acpMaxChars;
|
|
424
429
|
const budget = STREAM_JSON_PROMPT_CAP - promptLength - STREAM_JSON_PROMPT_MARGIN;
|
|
425
430
|
return budget > 0 ? Math.min(DIGEST_MAX_CHARS, budget) : null;
|
|
426
431
|
}
|
|
@@ -2398,7 +2403,7 @@ async function runTurnDriver(
|
|
|
2398
2403
|
} catch (err) {
|
|
2399
2404
|
const msg = err instanceof Error ? err.message : String(err);
|
|
2400
2405
|
deps.log?.("turn-error", { reason: "dispatch-failed", error: msg }, "error");
|
|
2401
|
-
finalize(stream, blocks, "error", err instanceof OutboundFrameBudgetError ? msg : `agy failed to start: ${msg}`);
|
|
2406
|
+
finalize(stream, blocks, "error", err instanceof OutboundFrameBudgetError ? msg : isAuthErrorMessage(msg) ? authErrorMessage() : `agy failed to start: ${msg}`);
|
|
2402
2407
|
return;
|
|
2403
2408
|
}
|
|
2404
2409
|
}
|
|
@@ -2407,7 +2412,7 @@ async function runTurnDriver(
|
|
|
2407
2412
|
// marker-only digest beside a sliced prompt is noise that also breaks
|
|
2408
2413
|
// agy's server-side prompt cache.
|
|
2409
2414
|
const wantDigest = (config.digest || compactionHandoff || compactionResume) && !runTruncated;
|
|
2410
|
-
const maxChars = digestMaxCharsForEngine(engine, promptBytes);
|
|
2415
|
+
const maxChars = digestMaxCharsForEngine(engine, promptBytes, config.acp.digestMaxChars);
|
|
2411
2416
|
// A late delivery into a conversation agy already holds stays digest-less
|
|
2412
2417
|
// (the digest would re-send context agy has); into a fresh conversation
|
|
2413
2418
|
// (post-preempt rotation, #33) the late prompt is the FIRST thing agy
|
|
@@ -2545,7 +2550,7 @@ async function runTurnDriver(
|
|
|
2545
2550
|
const freshDigest = wantDigest
|
|
2546
2551
|
? buildContextDigestResult(context.messages, 0, {
|
|
2547
2552
|
bound: false,
|
|
2548
|
-
maxChars:
|
|
2553
|
+
maxChars: config.acp.digestMaxChars,
|
|
2549
2554
|
end: run.runStart,
|
|
2550
2555
|
includeLast: compactionResume,
|
|
2551
2556
|
})
|
|
@@ -2605,7 +2610,7 @@ async function runTurnDriver(
|
|
|
2605
2610
|
// callId and stay consumed, as before).
|
|
2606
2611
|
for (const l of late) if (l.callId) deps.roundTrips.unclaim(l.callId);
|
|
2607
2612
|
deps.log?.("turn-error", { reason: "driver-start-failed", error: msg }, "error");
|
|
2608
|
-
finalize(stream, blocks, "error", `agy failed to start: ${msg}`);
|
|
2613
|
+
finalize(stream, blocks, "error", isAuthErrorMessage(msg) ? authErrorMessage() : `agy failed to start: ${msg}`);
|
|
2609
2614
|
return;
|
|
2610
2615
|
}
|
|
2611
2616
|
}
|
|
@@ -2744,6 +2749,13 @@ async function runTurnDriver(
|
|
|
2744
2749
|
finalize(stream, blocks, "error", quotaErrorMessage(quota));
|
|
2745
2750
|
return;
|
|
2746
2751
|
}
|
|
2752
|
+
// Same strand as the quota notice: agy can settle a logged-out account
|
|
2753
|
+
// as notice text with end_turn instead of a driver error.
|
|
2754
|
+
if (detectAuthNotice(outcome.response)) {
|
|
2755
|
+
deps.log?.("turn-error", { reason: "auth-expired" }, "error");
|
|
2756
|
+
finalize(stream, blocks, "error", authErrorMessage());
|
|
2757
|
+
return;
|
|
2758
|
+
}
|
|
2747
2759
|
}
|
|
2748
2760
|
// Gap closer: the result landed while the turn was still live (reentry
|
|
2749
2761
|
// above), the turn ended, and the model never polled. Same strand, same
|
|
@@ -2846,32 +2858,58 @@ async function runTurnDriver(
|
|
|
2846
2858
|
(isContinuation && !digestDispatched && !ephemeral && deps.handoffRuntime?.mode.get(key) === "sync");
|
|
2847
2859
|
if (syncContract && !ephemeral) {
|
|
2848
2860
|
try {
|
|
2849
|
-
const
|
|
2850
|
-
|
|
2851
|
-
(
|
|
2852
|
-
const recon = new AcpHistorySync(context.messages, existing, {
|
|
2861
|
+
const recon = syncTurn
|
|
2862
|
+
? undefined
|
|
2863
|
+
: new AcpHistorySync(context.messages, existing, {
|
|
2853
2864
|
continuation: isContinuation,
|
|
2854
2865
|
isBacklogShape: isBacklogUserShape,
|
|
2855
2866
|
});
|
|
2867
|
+
// Only a moved prefix (context-hook rewrite mid-park) means the old
|
|
2868
|
+
// conversation can no longer match the transcript. A steered
|
|
2869
|
+
// continuation (new-user-during-turn) is NOT divergence: the steering
|
|
2870
|
+
// carrier already delivered the steer into this conversation, so the
|
|
2871
|
+
// terminal checkpoint stays correct and warm continuation survives.
|
|
2872
|
+
// issue #40: patch by @rochecompaan, landed with the predicate
|
|
2873
|
+
// narrowed from plan.kind !== resume to this single reason.
|
|
2874
|
+
const divergedContinuation = recon !== undefined && recon.plan.reason === "changed-inflight-prefix";
|
|
2875
|
+
let settleSync: AcpHistorySync;
|
|
2876
|
+
let result: { settled: "terminal" } | { settled: "invalidated"; reason: string };
|
|
2877
|
+
if (divergedContinuation) {
|
|
2878
|
+
// The transcript diverged while the turn was parked (for example,
|
|
2879
|
+
// a context-paging extension trimmed older turns before the
|
|
2880
|
+
// continuation). This continuation still ran on the old ACP
|
|
2881
|
+
// conversation, so stamping a terminal checkpoint for the trimmed
|
|
2882
|
+
// transcript would pin subsequent turns to that stale conversation.
|
|
2883
|
+
// Invalidate instead so the next user turn rebuilds fresh.
|
|
2884
|
+
recon.invalidate(recon.plan.reason);
|
|
2885
|
+
const convId = outcome.conversationId ?? existing?.conversationId ?? null;
|
|
2886
|
+
if (convId) recon.adoptBinding(convId);
|
|
2887
|
+
settleSync = recon;
|
|
2888
|
+
result = { settled: "invalidated", reason: recon.plan.reason };
|
|
2889
|
+
} else {
|
|
2890
|
+
if (recon) {
|
|
2856
2891
|
recon.bound(key);
|
|
2857
2892
|
recon.dispatching();
|
|
2858
|
-
|
|
2859
|
-
}
|
|
2860
|
-
|
|
2861
|
-
|
|
2862
|
-
|
|
2863
|
-
|
|
2864
|
-
|
|
2865
|
-
|
|
2866
|
-
|
|
2867
|
-
|
|
2868
|
-
|
|
2869
|
-
|
|
2870
|
-
|
|
2871
|
-
|
|
2872
|
-
|
|
2873
|
-
|
|
2874
|
-
|
|
2893
|
+
settleSync = recon;
|
|
2894
|
+
} else {
|
|
2895
|
+
settleSync = syncTurn!;
|
|
2896
|
+
}
|
|
2897
|
+
result = settleSync.finish(
|
|
2898
|
+
{
|
|
2899
|
+
// A late-start failure leaves the steer undelivered: a terminal
|
|
2900
|
+
// checkpoint would claim it. Invalidate so the next turn re-plans
|
|
2901
|
+
// and the rebuild re-ships the steer as the newest user entry.
|
|
2902
|
+
ok: outcome.status === "OK" && !lateStartFailed,
|
|
2903
|
+
conversationId: outcome.conversationId ?? null,
|
|
2904
|
+
aborted: outcome.aborted,
|
|
2905
|
+
promptAttempted: outcome.promptAttempted,
|
|
2906
|
+
promptTerminal: outcome.promptTerminal,
|
|
2907
|
+
},
|
|
2908
|
+
blocks.partial,
|
|
2909
|
+
context.messages,
|
|
2910
|
+
existing?.conversationId,
|
|
2911
|
+
);
|
|
2912
|
+
}
|
|
2875
2913
|
deps.log?.(
|
|
2876
2914
|
"sync-settle",
|
|
2877
2915
|
{
|
|
@@ -2942,7 +2980,7 @@ async function runTurnDriver(
|
|
|
2942
2980
|
return;
|
|
2943
2981
|
}
|
|
2944
2982
|
if (outcome.status === "ERROR") {
|
|
2945
|
-
finalize(stream, blocks, "error", outcome.error ?? "agy turn failed");
|
|
2983
|
+
finalize(stream, blocks, "error", (outcome.error && isAuthErrorMessage(outcome.error)) ? authErrorMessage() : outcome.error ?? "agy turn failed");
|
|
2946
2984
|
return;
|
|
2947
2985
|
}
|
|
2948
2986
|
if (blocks.textIdx === null && outcome.response) {
|
package/src/quota-notice.ts
CHANGED
|
@@ -17,8 +17,10 @@ export interface QuotaNotice {
|
|
|
17
17
|
|
|
18
18
|
// Anchored at the start and length-capped so only a notice-shaped
|
|
19
19
|
// (near-)whole response reclassifies; a long answer that merely discusses
|
|
20
|
-
// quota must never match.
|
|
21
|
-
|
|
20
|
+
// quota must never match. The optional prefix word may be hyphenated
|
|
21
|
+
// ("Third-party quota reached", issue #39) but stays letter-initial, so a
|
|
22
|
+
// leading dash cannot open it.
|
|
23
|
+
const NOTICE_PATTERN = /^\s*(?:⚠\s*)?(?:[a-z][a-z-]*\s+)?quota\s+(?:reached|exhausted|exceeded|limit reached)/i;
|
|
22
24
|
const RESET_PATTERN = /resets?\s+in\s+((?:\d+h)?(?:\d+m)?(?:\d+s))/i;
|
|
23
25
|
const NOTICE_MAX_CHARS = 400;
|
|
24
26
|
|