@estebanforge/pi-antigravity-bridge 1.20.1 → 1.21.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 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.21.0] - 2026-12-05
6
+
7
+ ### Added
8
+
9
+ - ACP conversations now receive mid-session pi system-prompt changes (issue #45, reported by @sevenc-nanashi with a PoC): extensions that rewrite the system prompt inside one pi session (plan-mode switches, context-hook rewrites) ship exactly one update block to the bound agy conversation instead of being ignored until the next fresh conversation. A sha256 of the last delivered prompt plus an update count ride the session record (`systemPromptHash`/`systemPromptUpdates`), so each change delivers once across restarts; claims land only on delivery proof (settle OK or park), a failed update turn re-ships, late strands/resume seeds defer to the next plain turn, a churning prompt (changes every turn) caps at 8 updates per conversation with a single warn and then stays stale like before, and records written before this feature adopt the current prompt as their baseline instead of re-shipping to every existing session. stream-json keeps the fresh-only gate (its carrier is a staged agent file fixed per process; an inline block risks the ~25KB silent drop) and the `/agy system-prompt` copy now says so ([src/provider.ts](src/provider.ts), [src/sessions.ts](src/sessions.ts), [extensions/index.ts](extensions/index.ts), [tests/provider-sysprompt.test.ts](tests/provider-sysprompt.test.ts), [tests/provider-sync.test.ts](tests/provider-sync.test.ts), [tests/sessions.test.ts](tests/sessions.test.ts)).
10
+
11
+ ## [1.20.2] - 2026-12-05
12
+
13
+ ### Fixed
14
+
15
+ - ACP `sync` handoff (`AGY_HANDOFF=sync`) now sends the current user request block ahead of the `urn:pi-bridge:history:v1` replay resource in `session/prompt` so large replay histories do not bury the live request (issue #44, reported and first patched by @rochecompaan; digest ordering for `urn:pi-bridge:context-digest` is unchanged, and the history preamble no longer claims the input "follows separately"; wire order is pinned by tests while model-level validation is the reporter's exact-marker runs on one model) ([src/acp/connection.ts](src/acp/connection.ts), [src/acp/history-sync.ts](src/acp/history-sync.ts), [src/history-projection.ts](src/history-projection.ts), [tests/acp-driver.test.ts](tests/acp-driver.test.ts)).
16
+
17
+ - agy's quota and auth notices no longer settle as successful replies when the turn also ran thinking or tool calls (issue #43, reported and first patched by @hectormr206): the settle-path guard previously applied to text-only turns only, so a subagent with thinking enabled received `⚠ Individual quota reached. ... Resets in 3h41m42s.` as its final answer and pi provider failover never fired. After thought/tool activity, detection now reclassifies a start-anchored notice (<= 400 chars) emitted after the last non-text activity: quota requires the agy signature ("upgrade your subscription to increase your limits"; Individual and Third-party copies) and settles retryable for failover, while auth additionally requires a vendor reference ("agy" or "Antigravity", because work reports legitimately start with the same auth phrases) and settles fail-fast like all auth errors (login is a human action: no retry loop, no failover); the full settled response backs up the post-activity text when a later activity wiped it. Loose notices after activity, answers that merely discuss quota/auth wording, and the session binding keep their previous behavior ([src/quota-notice.ts](src/quota-notice.ts), [src/auth-state.ts](src/auth-state.ts), [src/provider.ts](src/provider.ts)).
18
+
5
19
  ## [1.20.1] - 2026-12-04
6
20
 
7
21
  ### Fixed
package/README.md CHANGED
@@ -123,7 +123,7 @@ If `agy models` fails at load (binary missing, auth not done, network stall), a
123
123
  | `webTools` | `false` (no web tools), `true` (register `agy_web_search` + `agy_read_url` as Pi tools, usable by ANY provider's model). Each call spawns a one-shot search-only `agy` agent (plan mode, bridge MCP inheritance off), gates the answer on an observed native `search_web`/`read_url_content` step, and spends Antigravity quota. Off by default: Antigravity sessions already have native web tools on both engines; these serve other providers | `false` |
124
124
  | `bridgeTools` | `none` (no pi tools; an active approval gate still starts the listener gate-only, and no global registration is written), `all` (every pi tool except the core builtins, incl. other `Ask*` delegations; pi 1.x builtin MCP and `tool_search` tools bridge on both engines through the info/call pair, and on ACP pi's builtins - read, ls, grep, find, edit, write, bash - are declared directly, since ACP's native tool calls execute agy-side and would otherwise bypass pi entirely), `mcp` (pi-mcp-adapter tools, pi 1.x builtin MCP and `tool_search` tools + skills bridge only), `codemode` (pi's `codemode` tool + the info/call pair only; requires pi's codemode tool to be active, e.g. `--tools codemode`) | `all` |
125
125
  | `digest` | Self-gating delta of pi-side context (compaction summaries, other-provider turns, handoffs after a mid-session switch) shipped to agy only when the delta is non-empty, each piece once. Pure antigravity sessions get byte-stable prompts and an intact prompt cache. `false` = agy prompts contain only your message; a conversation opened mid-session starts without prior pi-side context | `true` |
126
- | `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; on ACP with `bridgeTools: "all"` and bash active, an extra ACP note steers long commands onto the bridge bash (a silent native command past the stall guard is killed). 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 `false` (agy-native behavior) | `true` |
126
+ | `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; on ACP with `bridgeTools: "all"` and bash active, an extra ACP note steers long commands onto the bridge bash (a silent native command past the stall guard is killed). 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, and on ACP a mid-session prompt change (plan-mode switches, context-hook rewrites) ships one hashed update block to the bound conversation so extensions that rewrite the prompt work mid-session (issue #45; capped at 8 updates per conversation, churn past that warns once and stays stale; stream-json conversations keep the version they started with)) or `false` (agy-native behavior) | `true` |
127
127
  | `readOnly` | `true`: fail-closed kill switch - every provider turn and the `AskAntigravity` tool are refused with a visible error (the CLI has no review-only enforcement, see [Permissions](#permissions) and [readOnly](#readonly)). In the file, any value that is not a recognized boolean spelling (or an explicit blank) also fails closed to `true` | `false` |
128
128
  | `skipPermissions` | `true`: pass `--dangerously-skip-permissions` so agy tool calls never hang on an unanswerable prompt in non-interactive runs; DANGEROUS: agy executes commands without per-action review (see [Permissions](#permissions)). `false`: prompt instead - hangs any `run_command` in `-p` mode | `true` |
129
129
  | `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 |
@@ -154,7 +154,7 @@ The `activate_skill` catalog mirrors pi's directory-based skill discovery: the t
154
154
  /agy model flash|pro|gemini fallback model for the AskAntigravity tool; callers may override per call
155
155
  /agy thinking low|medium|high fallback thinking tier for the AskAntigravity tool; callers may override per call
156
156
  /agy digest on|off ship pi-side context to agy when the delta is non-empty (default on; see table above)
157
- /agy system-prompt on|off send pi's system prompt + AGENTS.md + the Pi Bridge tool-priority note to new agy conversations (default on)
157
+ /agy system-prompt on|off send pi's system prompt + AGENTS.md + the Pi Bridge tool-priority note to new agy conversations, with mid-session prompt-change updates on ACP (default on)
158
158
  /agy lean on|off lean ACP agent: bridge MCP tools only, no native agy tools (ACP engine only; restart applies; a flip starts a fresh conversation)
159
159
  /agy bridge all|mcp|codemode|none which pi tools the MCP bridge exposes to agy (default all; codemode = scripts only; none = bridge off; a running server picks up the new catalog immediately, a stopped one on the next start)
160
160
  /agy tools [hide|show <name>|reset] session-only bridge-catalog hides (multi-word names OK; reset restores the full set; bare lists exposed + hidden; never touches saved config)
@@ -2037,7 +2037,7 @@ function registerAgyCommand(pi: ExtensionAPI, ctx: AgyCommandCtx): void {
2037
2037
  const next = saveConfig({ systemPrompt: val === "on" });
2038
2038
  ui?.notify(
2039
2039
  next.systemPrompt
2040
- ? "system-prompt on. pi's system prompt (incl. global and project AGENTS.md) is prepended to the first prompt of each new agy conversation. Existing conversations keep the version they started with."
2040
+ ? "system-prompt on. pi's system prompt (incl. global and project AGENTS.md) is prepended to the first prompt of each new agy conversation; on ACP a mid-session prompt change ships one update block to the bound conversation. stream-json conversations keep the version they started with (the staged agent file is per process)."
2041
2041
  : "system-prompt off. agy runs on its own system prompt; pi instructions and AGENTS.md files are not sent.",
2042
2042
  "info",
2043
2043
  );
@@ -2190,7 +2190,7 @@ async function openAgyPicker(ui: ExtensionUIContext, ctx: AgyCommandCtx): Promis
2190
2190
  id: "system-prompt",
2191
2191
  label: "System prompt",
2192
2192
  description:
2193
- "Prepend pi's system prompt (incl. AGENTS.md files) to the first prompt of each new agy conversation.",
2193
+ "Prepend pi's system prompt (incl. AGENTS.md files) to new agy conversations; on ACP, mid-session changes ship as update blocks.",
2194
2194
  currentValue: config.systemPrompt ? "on" : "off",
2195
2195
  values: ["on", "off"],
2196
2196
  },
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@estebanforge/pi-antigravity-bridge",
3
- "version": "1.20.1",
3
+ "version": "1.21.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",
@@ -16,6 +16,7 @@
16
16
 
17
17
  import { spawn, type ChildProcess } from "node:child_process";
18
18
  import { frameCarriesUsage } from "./events.js";
19
+ import { HISTORY_URI } from "./history-sync.js";
19
20
  import type { AgyUsage } from "../driver-types.js";
20
21
  import { redactText } from "../redact.js";
21
22
  import { JsonRpcResponseError, JsonRpcSession, JsonRpcTimeoutError } from "./jsonrpc.js";
@@ -386,13 +387,19 @@ export class AcpConnection {
386
387
  images: Array<{ data: string; mimeType: string }> = [],
387
388
  contextBlock?: { uri: string; text: string },
388
389
  ): Promise<{ stopReason: string; usage?: AgyUsage }> {
389
- // Block order: images, then the embedded-context resource (pi-side
390
- // digest), then the text question last (it refers to everything before
390
+ // Two block orders. Sync replays ship up to megabytes of framed history
391
+ // as the embedded resource; a trailing request after it was received by
392
+ // the engine but lost by the model (issue #44), so the request goes
393
+ // first for history replays. Everything else (digest resources, plain
394
+ // prompts) keeps the question last (it refers to everything before
391
395
  // it). Shapes per the ACP v1 content-block schema; embeddedContext is
392
396
  // advertised in promptCapabilities (verified run 5).
397
+ const requestFirst = contextBlock?.uri === HISTORY_URI;
398
+ const requestBlock: Record<string, unknown> = { type: "text", text };
393
399
  const blocks: Array<Record<string, unknown>> = [
394
400
  ...images.map((i) => ({ type: "image", data: i.data, mimeType: i.mimeType })),
395
401
  ];
402
+ if (requestFirst) blocks.push(requestBlock);
396
403
  if (contextBlock) {
397
404
  blocks.push({
398
405
  type: "resource",
@@ -403,7 +410,7 @@ export class AcpConnection {
403
410
  },
404
411
  });
405
412
  }
406
- blocks.push({ type: "text", text });
413
+ if (!requestFirst) blocks.push(requestBlock);
407
414
  const result = (await this.request("session/prompt", {
408
415
  sessionId,
409
416
  prompt: blocks,
@@ -37,7 +37,7 @@ export interface SyncInput {
37
37
 
38
38
  export type SyncFinishResult = { settled: "terminal" } | { settled: "invalidated"; reason: string };
39
39
 
40
- const HISTORY_URI = "urn:pi-bridge:history:v1";
40
+ export const HISTORY_URI = "urn:pi-bridge:history:v1";
41
41
  const FRAME_MARGIN_BYTES = 2048;
42
42
  // The engine ACCEPTS outbound frames past ~3.8MiB but silently truncates
43
43
  // the resource there (probe-acp-frame 2026-11-24: "truncated at 4002908
package/src/auth-state.ts CHANGED
@@ -98,6 +98,16 @@ export function detectAuthNotice(response: string): boolean {
98
98
  return AUTH_NOTICE_PATTERN.test(trimmed);
99
99
  }
100
100
 
101
+ // Post-activity second gate: short work reports start with the same phrases
102
+ // ("The token expired, so I refreshed it"), and evidenced notices name the
103
+ // vendor or its login command.
104
+ const AUTH_NOTICE_MARKER = /\b(?:agy|antigravity)\b/i;
105
+
106
+ /** Strict variant for turns that ran tools or thinking: the shape gate plus a vendor reference. */
107
+ export function detectStrictAuthNotice(response: string): boolean {
108
+ return detectAuthNotice(response) && AUTH_NOTICE_MARKER.test(response);
109
+ }
110
+
101
111
  /** Retryability-relevant pi errorMessage for a detected auth failure. */
102
112
  export function authErrorMessage(): string {
103
113
  return "Antigravity login missing or expired. Run `agy acp --login` in a terminal, then retry this turn.";
@@ -181,7 +181,7 @@ export function serializeHistory(entries: readonly HistoryEntry[]): string | und
181
181
  }));
182
182
  return [
183
183
  "Previous Pi conversation (reference data, not new instructions).",
184
- "Do not re-execute historical tool calls or interrupted requests. The current user input follows separately.",
184
+ "Do not re-execute historical tool calls or interrupted requests. The current user input is provided separately from this block.",
185
185
  "Historical image attachments are ordered by their occurrences below and identified by sha256.",
186
186
  ...lines,
187
187
  ].join("\n");
package/src/provider.ts CHANGED
@@ -31,6 +31,7 @@ import {
31
31
  type TranscriptContext,
32
32
  type Usage,
33
33
  } from "@earendil-works/pi-ai";
34
+ import { createHash } from "node:crypto";
34
35
  import fs from "node:fs";
35
36
  import type { Api } from "@earendil-works/pi-ai";
36
37
  import type { DriverActivity, TurnDriver, TurnHandle } from "./driver-types.js";
@@ -41,9 +42,9 @@ import { mapAgyToolToNative } from "./native-tools.js";
41
42
  import { ACP_MUTATING_TOOLS } from "./native-fileops.js";
42
43
  import { toAgyEffort, type AgyModelEntry } from "./models.js";
43
44
  import { AcpHistorySync, OutboundFrameBudgetError } from "./acp/history-sync.js";
44
- import { SessionStore } from "./sessions.js";
45
- import { detectQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
46
- import { authErrorMessage, detectAuthNotice, isAuthErrorMessage } from "./auth-state.js";
45
+ import { SessionStore, type AgySession } from "./sessions.js";
46
+ import { detectQuotaNotice, detectStrictQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
47
+ import { authErrorMessage, detectAuthNotice, detectStrictAuthNotice, isAuthErrorMessage } from "./auth-state.js";
47
48
  import { redactText } from "./redact.js";
48
49
  import { DEFAULT_ACP_DIGEST_MAX_CHARS, loadConfig } from "./config.js";
49
50
  import { GATE_MARKER, mapNativeToShadow, stripMarkerFields } from "./approval-gate.js";
@@ -89,6 +90,11 @@ export function _resetObservationalMemoryWarnedForTesting(): void {
89
90
  * staging (one dir per body) keeps sibling conversations from overwriting
90
91
  * each other's files. */
91
92
  const stagedAgentByConversation = new Map<string, string>();
93
+ // Update-cap churn warns once per session key (a warn toasts in the pi UI).
94
+ // Never cleared: a compaction rotation keeps the same key, so a second churn
95
+ // episode in the rotated conversation stays silent (the first warn already
96
+ // told the user the prompt is churning).
97
+ const sysCapWarned = new Set<string>();
92
98
 
93
99
  /** Per-session mid-park steering cursor: the context length the current turn
94
100
  * was dispatched with, and the transcript index past the last steer actually
@@ -237,12 +243,73 @@ export const DIGEST_PREAMBLE =
237
243
  // machine-level or project-level instructions. agy has no system-prompt flag
238
244
  // (verified against `agy --help`), so the only delivery path is the prompt
239
245
  // text. We prepend it as a delimited block on the FIRST prompt of a fresh
240
- // conversation only: agy keeps its own history, the block stays byte-identical
241
- // afterwards, and agy's server-side prompt cache keeps hitting.
246
+ // conversation; on ACP a bound conversation whose prompt CHANGED mid-session
247
+ // (plan-mode switches, context-hook rewrites, issue #45) ships one update
248
+ // block, hashed on the session record so each change delivers exactly once.
249
+ // agy history is append-only, so the update leaves the server-side prompt
250
+ // cache prefix intact; stream-json keeps the fresh-only gate (its delivery is
251
+ // a staged agent file fixed per process, and an inline block risks the
252
+ // ~25KB silent drop).
242
253
 
243
254
  export const SYSTEM_PROMPT_PREAMBLE =
244
255
  "[The following is the system prompt of the pi session that spawned this conversation: operating instructions plus project context (AGENTS.md files). Apply it for this whole conversation.]";
245
256
 
257
+ export const SYSTEM_PROMPT_UPDATE_PREAMBLE =
258
+ "[The pi session's system prompt has changed. The block below supersedes every earlier pi system prompt block in this conversation: replace all previously stated pi operating instructions and project context with the block below and apply it from now on.]";
259
+
260
+ /** Update-block ceiling per conversation. Guards a prompt that changes every
261
+ * turn (timestamp lines, memory-injecting extensions): each update costs N
262
+ * tokens of permanent context until compaction rotates the conversation, so
263
+ * past the cap the conversation stays stale (the pre-#45 behavior) and the
264
+ * churn warns once. */
265
+ export const SYS_PROMPT_UPDATE_CAP = 8;
266
+
267
+ export interface SysPromptPlanInput {
268
+ /** config.systemPrompt. */
269
+ enabled: boolean;
270
+ /** Updates ride prompt text: ACP only. */
271
+ engineIsAcp: boolean;
272
+ /** getCurrentSystemPrompt() for this turn; undefined = none. */
273
+ current: string | undefined;
274
+ /** A conversation is already bound to this session. */
275
+ bound: boolean;
276
+ storedHash: string | undefined;
277
+ storedUpdates: number | undefined;
278
+ /** Plain user-prompt dispatch (late strands, resume seeds and other
279
+ * synthetic prompts defer the update to the next plain turn). */
280
+ plain: boolean;
281
+ }
282
+
283
+ export interface SysPromptPlan {
284
+ ship: "fresh" | "update" | null;
285
+ capped: boolean;
286
+ /** Values to write on a delivered (settled OK / parked) turn; a null ship
287
+ * preserves the stored values, a legacy record adopts the baseline. */
288
+ claimHash: string | undefined;
289
+ claimUpdates: number | undefined;
290
+ }
291
+
292
+ export const hashSysPrompt = (sys: string): string => createHash("sha256").update(sys).digest("hex");
293
+
294
+ /** Pure mid-session system-prompt decision table (issue #45). The digest and
295
+ * sync paths both call this per turn; the claims land only on delivery
296
+ * proof (settle OK / park), so a failed update turn re-ships next turn. */
297
+ export function planSystemPrompt(i: SysPromptPlanInput, cap: number = SYS_PROMPT_UPDATE_CAP): SysPromptPlan {
298
+ const preserved: SysPromptPlan = { ship: null, capped: false, claimHash: i.storedHash, claimUpdates: i.storedUpdates };
299
+ if (!i.enabled || !i.current) return preserved;
300
+ const hash = hashSysPrompt(i.current);
301
+ if (!i.bound) return { ship: "fresh", capped: false, claimHash: hash, claimUpdates: 0 };
302
+ if (!i.engineIsAcp) return preserved;
303
+ // Record predates the field: adopt the current prompt as the baseline
304
+ // (at most one missed change from before the upgrade) instead of
305
+ // re-shipping the block to every existing conversation at once.
306
+ if (i.storedHash === undefined) return { ship: null, capped: false, claimHash: hash, claimUpdates: 0 };
307
+ if (hash === i.storedHash) return preserved;
308
+ if (!i.plain) return preserved;
309
+ if ((i.storedUpdates ?? 0) >= cap) return { ship: null, capped: true, claimHash: i.storedHash, claimUpdates: i.storedUpdates };
310
+ return { ship: "update", capped: false, claimHash: hash, claimUpdates: (i.storedUpdates ?? 0) + 1 };
311
+ }
312
+
246
313
  export const SYSTEM_PROMPT_END = "[END SYSTEM PROMPT]";
247
314
 
248
315
  /** Brief tool-priority note appended inside every system prompt block: agy
@@ -278,15 +345,16 @@ export function buildFullPrompt(
278
345
  systemPrompt: string | undefined,
279
346
  digest: string,
280
347
  prompt: string,
281
- options?: { codemodeOnly?: boolean; acpToolsDirect?: boolean; lean?: boolean },
348
+ options?: { codemodeOnly?: boolean; acpToolsDirect?: boolean; lean?: boolean; sysPromptUpdate?: boolean },
282
349
  ): string {
283
350
  const parts: string[] = [];
284
351
  if (systemPrompt) {
352
+ const preamble = options?.sysPromptUpdate ? SYSTEM_PROMPT_UPDATE_PREAMBLE : SYSTEM_PROMPT_PREAMBLE;
285
353
  const notes = toolNotes(options);
286
354
  parts.push(
287
355
  notes.length > 0
288
- ? `${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${notes}\n\n${SYSTEM_PROMPT_END}`
289
- : `${SYSTEM_PROMPT_PREAMBLE}\n\n${systemPrompt}\n\n${SYSTEM_PROMPT_END}`,
356
+ ? `${preamble}\n\n${systemPrompt}\n\n${notes}\n\n${SYSTEM_PROMPT_END}`
357
+ : `${preamble}\n\n${systemPrompt}\n\n${SYSTEM_PROMPT_END}`,
290
358
  );
291
359
  }
292
360
  if (digest) {
@@ -2142,6 +2210,22 @@ async function runTurnDriver(
2142
2210
  // settle (and the park persist) sit outside the fresh-pass block, so the
2143
2211
  // binding is function-level (the round-1 settle scope trap).
2144
2212
  let syncTurn: AcpHistorySync | undefined;
2213
+ // The mid-session system-prompt decision for THIS dispatching pass (issue
2214
+ // #45). Set by the sync gate or the digest gate below; read by the settle
2215
+ // and park writes, which claim hash+count only on delivery proof.
2216
+ let sysPlan: SysPromptPlan | undefined;
2217
+ // Record fields for the settle/park writes: plan claims on delivery proof,
2218
+ // otherwise preserve whatever the record holds (store.set replaces the
2219
+ // whole record - dropping the fields would silently reset the baseline
2220
+ // and the update count on turns that never read them, e.g. continuations).
2221
+ const sysRecordFields = (delivered: boolean): Pick<AgySession, "systemPromptHash" | "systemPromptUpdates"> => {
2222
+ const hash = delivered && sysPlan?.claimHash !== undefined ? sysPlan.claimHash : existing?.systemPromptHash;
2223
+ const updates = delivered && sysPlan?.claimUpdates !== undefined ? sysPlan.claimUpdates : existing?.systemPromptUpdates;
2224
+ return {
2225
+ ...(hash !== undefined ? { systemPromptHash: hash } : {}),
2226
+ ...(updates !== undefined ? { systemPromptUpdates: updates } : {}),
2227
+ };
2228
+ };
2145
2229
  // Name of the carrier agent staged for THIS turn's fresh conversation, if
2146
2230
  // any. Recorded into stagedAgentByConversation once the outcome binds the
2147
2231
  // conversation id, so later gate-closed turns pass the same agent.
@@ -2347,15 +2431,30 @@ async function runTurnDriver(
2347
2431
  } else if (turn.plan.kind !== "rebuild") {
2348
2432
  handoffRuntime?.rebuildStreak.delete(key);
2349
2433
  }
2350
- const gateOpen = Boolean(config.systemPrompt) && turn.freshConversation;
2351
- const sys = gateOpen ? getCurrentSystemPrompt(context.messages) || undefined : undefined;
2434
+ // Sync dispatches are always plain (the gate above excludes late,
2435
+ // resume and compaction passes): the update decision is final here.
2436
+ const syncSys = config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined;
2437
+ sysPlan = planSystemPrompt({
2438
+ enabled: Boolean(config.systemPrompt),
2439
+ engineIsAcp: true,
2440
+ current: syncSys,
2441
+ bound: !turn.freshConversation,
2442
+ storedHash: existing?.systemPromptHash,
2443
+ storedUpdates: existing?.systemPromptUpdates,
2444
+ plain: true,
2445
+ });
2446
+ if (sysPlan.capped && !sysCapWarned.has(key)) {
2447
+ sysCapWarned.add(key);
2448
+ deps.log?.("sysprompt-update-capped", { key, updates: existing?.systemPromptUpdates }, "warn");
2449
+ }
2450
+ const sys = sysPlan.ship === "fresh" || sysPlan.ship === "update" ? syncSys : undefined;
2352
2451
  const syncImages = [...images, ...late.flatMap((l) => l.images ?? [])];
2353
2452
  try {
2354
2453
  // inputFor hard-fails past the outbound frame budget and the
2355
2454
  // coordinator calls throw on invariants: both must fail the turn
2356
2455
  // visibly, not surface as an unhandled rejection.
2357
2456
  const input = turn.inputFor({
2358
- prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect, lean }) + stageImageNote(syncImages),
2457
+ prompt: buildFullPrompt(sys, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect, lean, sysPromptUpdate: sysPlan.ship === "update" }) + stageImageNote(syncImages),
2359
2458
  images: syncImages,
2360
2459
  });
2361
2460
  turn.bound(key);
@@ -2377,12 +2476,26 @@ async function runTurnDriver(
2377
2476
  turn.adoptBinding(sessionId);
2378
2477
  if (!rotationGuardArmed()) {
2379
2478
  const rec = turn.record();
2380
- if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId });
2479
+ if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId, ...sysRecordFields(false) });
2381
2480
  }
2382
2481
  },
2383
2482
  onSessionLoadFailed: () => {
2384
2483
  // session/load died: re-plan as a rebuild and ship the whole
2385
2484
  // history to a fresh conversation; the gate re-opens there.
2485
+ // The swap prompt is a fresh block into a NEW conversation:
2486
+ // re-plan so the settle claims that decision. Keeping the
2487
+ // bound plan would land the dead binding's update claim on
2488
+ // the new conversation (inflated update count, or a capped
2489
+ // plan pinning the new conversation to the old hash).
2490
+ sysPlan = planSystemPrompt({
2491
+ enabled: Boolean(config.systemPrompt),
2492
+ engineIsAcp: true,
2493
+ current: syncSys,
2494
+ bound: false,
2495
+ storedHash: undefined,
2496
+ storedUpdates: undefined,
2497
+ plain: true,
2498
+ });
2386
2499
  const fresh = turn.loadFailed({
2387
2500
  prompt:
2388
2501
  buildFullPrompt(config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined, "", userPrompt ?? "", { codemodeOnly: codemodeNote, acpToolsDirect, lean }) +
@@ -2485,20 +2598,36 @@ async function runTurnDriver(
2485
2598
  // The uri is suffixed per turn so a deduping server cannot serve stale
2486
2599
  // content on turn 2+.
2487
2600
  const embeddedDigest = deps.engine === "acp" && digestFinal ? digestFinal : undefined;
2488
- // G10, fresh conversations only (bound conversations ride agy's own
2489
- // history; re-sending would bloat every prompt and bust the cache).
2490
- // stream-json delivery is a staged agent file, NOT prompt text: agy's
2491
- // stream-json path silently drops any turn past a ~25KB input cap and
2492
- // the dropped turn leaves the conversation permanently unresponsive
2493
- // (issue #2, probed 2026-09-30), and the block routinely crossed it.
2494
- // ACP keeps the inline block (JSON-RPC transport; --agent is a CLI
2495
- // feature). A user-configured agent always wins: never clobber it.
2496
- const gateOpen = config.systemPrompt && !existing?.conversationId;
2497
- const rawSysPrompt = gateOpen ? getCurrentSystemPrompt(context.messages) || undefined : undefined;
2498
- let sysPrompt = rawSysPrompt;
2601
+ // G10: fresh conversations ship the block; on ACP a bound conversation
2602
+ // whose prompt changed mid-session ships one update block (issue #45).
2603
+ // stream-json stays fresh-only: its delivery is a staged agent file
2604
+ // fixed per process, and an inline block risks the ~25KB silent drop
2605
+ // that leaves a conversation permanently unresponsive (issue #2, probed
2606
+ // 2026-09-30). ACP keeps the inline block (JSON-RPC transport; --agent
2607
+ // is a CLI feature). A user-configured agent always wins: never clobber.
2608
+ const rawSysPrompt = config.systemPrompt ? getCurrentSystemPrompt(context.messages) || undefined : undefined;
2609
+ if (!syncTurn) {
2610
+ sysPlan = planSystemPrompt({
2611
+ enabled: Boolean(config.systemPrompt),
2612
+ engineIsAcp: deps.engine === "acp",
2613
+ current: rawSysPrompt,
2614
+ bound: Boolean(existing?.conversationId),
2615
+ storedHash: existing?.systemPromptHash,
2616
+ storedUpdates: existing?.systemPromptUpdates,
2617
+ // Late strands, resume seeds and compaction tails are synthetic
2618
+ // prompts: the update waits for the next plain user turn.
2619
+ plain: !resume && !compactionResume && late.length === 0,
2620
+ });
2621
+ if (sysPlan.capped && !sysCapWarned.has(key)) {
2622
+ sysCapWarned.add(key);
2623
+ deps.log?.("sysprompt-update-capped", { key, updates: existing?.systemPromptUpdates }, "warn");
2624
+ }
2625
+ }
2626
+ const shipSys = sysPlan !== undefined && (sysPlan.ship === "fresh" || sysPlan.ship === "update");
2627
+ let sysPrompt = shipSys ? rawSysPrompt : undefined;
2499
2628
  let agent = config.agent;
2500
2629
  if (deps.engine !== "acp") {
2501
- if (rawSysPrompt && !config.agent) {
2630
+ if (sysPrompt && !config.agent) {
2502
2631
  const stagedBody = [
2503
2632
  SYSTEM_PROMPT_PREAMBLE,
2504
2633
  rawSysPrompt,
@@ -2516,14 +2645,14 @@ async function runTurnDriver(
2516
2645
  }
2517
2646
  // Staging failed: inline fallback. The silent-drop guard below
2518
2647
  // keeps the resulting cap failure visible instead of quiet.
2519
- } else if (rawSysPrompt && config.agent && !warnedUserAgentConflict) {
2648
+ } else if (sysPrompt && config.agent && !warnedUserAgentConflict) {
2520
2649
  warnedUserAgentConflict = true;
2521
2650
  deps.log?.(
2522
2651
  "sysprompt-agent-conflict",
2523
2652
  { agent: config.agent, effect: "system prompt ships inline in the prompt (over-cap drop risk)" },
2524
2653
  "warn",
2525
2654
  );
2526
- } else if (!rawSysPrompt && !config.agent && existing?.conversationId) {
2655
+ } else if (!sysPrompt && !config.agent && existing?.conversationId) {
2527
2656
  // Gate closed (bound conversation): pass the carrier staged for
2528
2657
  // THIS conversation, if any, so the driver profile never drifts on
2529
2658
  // "agent" and a respawned process reloads its own instructions.
@@ -2575,8 +2704,14 @@ async function runTurnDriver(
2575
2704
  const fullPrompt =
2576
2705
  (late.length > 0 && !freshLate
2577
2706
  ? buildLateResultPrompt(late, deliveredPrompt || undefined)
2578
- : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, { codemodeOnly: codemodeNote, acpToolsDirect, lean }) +
2579
- (freshLate ? `\n\n${buildLateResultPrompt(late)}` : "")) +
2707
+ : buildFullPrompt(sysPrompt, embeddedDigest ? "" : digestFinal, deliveredPrompt, {
2708
+ codemodeOnly: codemodeNote,
2709
+ acpToolsDirect,
2710
+ lean,
2711
+ // Inert unless sysPrompt is set (update ship): the preamble
2712
+ // swap only applies inside a shipped block.
2713
+ sysPromptUpdate: sysPlan?.ship === "update",
2714
+ }) + (freshLate ? `\n\n${buildLateResultPrompt(late)}` : "")) +
2580
2715
  stageImageNote(runImages);
2581
2716
  if (!syncTurn) {
2582
2717
  try {
@@ -2630,8 +2765,11 @@ async function runTurnDriver(
2630
2765
  // the cumulative task dir never re-reports older turns' logs.
2631
2766
  const turnStartMs = Date.now();
2632
2767
  let nativeBackgroundSeen = false;
2633
- // Issue #16 guard: quota reclassification applies to text-only turns only.
2768
+ // Issue #16 guard: after thought/tool activity only the strict agy notice
2769
+ // signature reclassifies, checked against the text emitted after the last
2770
+ // non-text activity (tailText); text-only turns keep the loose detection.
2634
2771
  let sawToolOrThought = false;
2772
+ let tailText = "";
2635
2773
  const feats: ActivityFeatures = {
2636
2774
  replay: deps.replay,
2637
2775
  nativeActive: deps.nativeActive,
@@ -2649,7 +2787,12 @@ async function runTurnDriver(
2649
2787
  for (;;) {
2650
2788
  const activity = await h.next();
2651
2789
  if (!activity) break;
2652
- if (activity.type !== "text" && activity.type !== "usage") sawToolOrThought = true;
2790
+ if (activity.type === "text") {
2791
+ tailText += activity.delta;
2792
+ } else if (activity.type !== "usage") {
2793
+ sawToolOrThought = true;
2794
+ tailText = "";
2795
+ }
2653
2796
  if (consumeActivity(stream, blocks, activity, diffCtx, cwd, feats) === "parked") return "parked";
2654
2797
  }
2655
2798
  };
@@ -2661,8 +2804,10 @@ async function runTurnDriver(
2661
2804
  // into. Only when no record exists: an unbound run() cannot have
2662
2805
  // recreated a conversation, so the snapshot id is the real one, and
2663
2806
  // the staged agent must move with the binding or a stream-json resume
2664
- // re-runs without its carrier-agent profile.
2665
- if (!ephemeral && !rotationGuardArmed() && (syncTurn || !existing)) {
2807
+ // re-runs without its carrier-agent profile. A bound ACP turn that
2808
+ // shipped an update block also claims its hash here: the park proves
2809
+ // the prompt reached the conversation (issue #45).
2810
+ if (!ephemeral && !rotationGuardArmed()) {
2666
2811
  const parkedConv = deps.driver.snapshot().conversationId;
2667
2812
  if (parkedConv) {
2668
2813
  if (syncTurn) {
@@ -2671,18 +2816,23 @@ async function runTurnDriver(
2671
2816
  // as history, so the latch has no second consumer.
2672
2817
  syncTurn.adoptBinding(parkedConv);
2673
2818
  const rec = syncTurn.record();
2674
- if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId });
2819
+ if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId, ...sysRecordFields(true) });
2675
2820
  if (syncTurn.freshConversation) deps.pendingCompactionHandoff?.delete(key);
2676
- } else {
2821
+ } else if (!existing) {
2677
2822
  store.set(key, {
2678
2823
  conversationId: parkedConv,
2679
2824
  lastStepIdx: -1,
2680
2825
  lastMessageCount: nextCount,
2681
2826
  digestBoundary: nextBoundary,
2682
2827
  digestSummaryId: settleSummaryId,
2828
+ ...sysRecordFields(true),
2683
2829
  });
2684
2830
  deps.pendingCompactionHandoff?.delete(key);
2685
2831
  if (stagedAgentName) stagedAgentByConversation.set(parkedConv, stagedAgentName);
2832
+ } else if (sysPlan?.ship === "update" && parkedConv === existing.conversationId) {
2833
+ // A park proves the prompt reached the conversation: claim the
2834
+ // update so the continuation settle never re-ships it.
2835
+ store.set(key, { ...existing, conversationId: parkedConv, ...sysRecordFields(true) });
2686
2836
  }
2687
2837
  }
2688
2838
  }
@@ -2740,18 +2890,31 @@ async function runTurnDriver(
2740
2890
  }
2741
2891
  // Issue #16: agy streams the account quota notice as agent text and ends
2742
2892
  // the turn OK; settle it as a retryable error so provider failover fires.
2743
- // Text-only turns only, and the binding is untouched below: the
2744
- // conversation itself is healthy, unlike the silentDrop signature above.
2745
- if (outcome.status === "OK" && !outcome.aborted && !sawToolOrThought) {
2746
- const quota = detectQuotaNotice(outcome.response);
2893
+ // Loose detection on text-only turns, strict signature after thought/tool
2894
+ // activity; the full response backs up tailText when a stray activity
2895
+ // wiped it. Accepted limit: a notice preceded by prose on the same
2896
+ // post-activity text run leaves the start anchor unmet and stays a reply
2897
+ // (scanning for the signature anywhere would reclassify real quota
2898
+ // prose). The binding is untouched below: the conversation itself is
2899
+ // healthy, unlike the silentDrop signature above.
2900
+ if (outcome.status === "OK" && !outcome.aborted) {
2901
+ const quota = sawToolOrThought
2902
+ ? detectStrictQuotaNotice(tailText) || detectStrictQuotaNotice(outcome.response)
2903
+ : detectQuotaNotice(outcome.response);
2747
2904
  if (quota) {
2748
2905
  deps.log?.("turn-error", { reason: "quota-exhausted", resetsIn: quota.resetsIn ?? null }, "error");
2749
2906
  finalize(stream, blocks, "error", quotaErrorMessage(quota));
2750
2907
  return;
2751
2908
  }
2752
2909
  // 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)) {
2910
+ // as notice text with end_turn instead of a driver error. Post-activity
2911
+ // detection adds a vendor-marker gate (work reports legitimately start
2912
+ // with the same phrases); auth settles fail-fast (login is a human
2913
+ // action, no failover).
2914
+ const auth = sawToolOrThought
2915
+ ? detectStrictAuthNotice(tailText) || detectStrictAuthNotice(outcome.response)
2916
+ : detectAuthNotice(outcome.response);
2917
+ if (auth) {
2755
2918
  deps.log?.("turn-error", { reason: "auth-expired" }, "error");
2756
2919
  finalize(stream, blocks, "error", authErrorMessage());
2757
2920
  return;
@@ -2922,7 +3085,7 @@ async function runTurnDriver(
2922
3085
  );
2923
3086
  const record = settleSync.record();
2924
3087
  if (record.conversationId && !rotationGuardArmed()) {
2925
- store.set(key, { ...record, conversationId: record.conversationId });
3088
+ store.set(key, { ...record, conversationId: record.conversationId, ...sysRecordFields(outcome.status === "OK" && !outcome.aborted) });
2926
3089
  // A rebuild shipped the compaction summary as history; the one-shot
2927
3090
  // latch has no second consumer.
2928
3091
  if (settleSync.freshConversation) deps.pendingCompactionHandoff?.delete(key);
@@ -2960,6 +3123,7 @@ async function runTurnDriver(
2960
3123
  lastMessageCount: nextCount,
2961
3124
  digestBoundary: nextBoundary,
2962
3125
  digestSummaryId: settleSummaryId,
3126
+ ...sysRecordFields(true),
2963
3127
  // The churn latch must survive digest turns (store.set
2964
3128
  // replaces the record), or the gate re-opens next turn and
2965
3129
  // the session alternates rebuild/digest forever.
@@ -35,6 +35,19 @@ export function detectQuotaNotice(response: string): QuotaNotice | undefined {
35
35
  return resetsIn ? { resetsIn } : {};
36
36
  }
37
37
 
38
+ // Signature shared by every known agy copy (Individual, Third-party). Only
39
+ // this stricter form may reclassify a turn that ran thought/tool activity,
40
+ // where a loose "quota reached" sentence is far likelier to be real prose.
41
+ const STRICT_SIGNATURE = /upgrade your subscription to increase your limits/i;
42
+
43
+ /** Strict variant of detectQuotaNotice: same shape gate plus the agy notice
44
+ * signature. Used for turns with thought/tool activity. */
45
+ export function detectStrictQuotaNotice(response: string): QuotaNotice | undefined {
46
+ const notice = detectQuotaNotice(response);
47
+ if (!notice) return undefined;
48
+ return STRICT_SIGNATURE.test(response) ? notice : undefined;
49
+ }
50
+
38
51
  /** Retryable-classified pi errorMessage for a detected notice. */
39
52
  export function quotaErrorMessage(notice: QuotaNotice): string {
40
53
  const reset = notice.resetsIn ? `; resets in ${notice.resetsIn}` : "";
package/src/sessions.ts CHANGED
@@ -36,6 +36,14 @@ export interface AgySession {
36
36
  * builder neither re-injects that summary nor restarts its window on
37
37
  * it. Optional/absent when no compaction existed at write time. */
38
38
  digestSummaryId?: string;
39
+ /** SHA-256 of the pi system prompt last delivered to this conversation,
40
+ * fresh block or update (issue #45). Absent on records predating the
41
+ * field: the provider adopts the current prompt as the baseline instead
42
+ * of re-shipping the block to every existing conversation. */
43
+ systemPromptHash?: string;
44
+ /** How many system prompt update blocks this conversation has accepted.
45
+ * Gates the per-conversation update cap (prompt churn guard). */
46
+ systemPromptUpdates?: number;
39
47
  /** History-sync protocol journal (handoff = "sync"). Absent on digest
40
48
  * records and on records predating the sync mode. Zeroed digest
41
49
  * watermark fields accompany it (the sync persist contract), so a
@@ -62,6 +70,8 @@ function narrowStoreMap(parsed: unknown): StoreMap {
62
70
  const mc = (value as { lastMessageCount?: unknown }).lastMessageCount;
63
71
  const db = (value as { digestBoundary?: unknown }).digestBoundary;
64
72
  const dci = (value as { digestSummaryId?: unknown }).digestSummaryId;
73
+ const sph = (value as { systemPromptHash?: unknown }).systemPromptHash;
74
+ const spu = (value as { systemPromptUpdates?: unknown }).systemPromptUpdates;
65
75
  // Malformed sync journals narrow to an invalid-sync-state marker
66
76
  // (never throws; self-heals via a named rebuild), so the field is
67
77
  // kept but flagged.
@@ -72,6 +82,8 @@ function narrowStoreMap(parsed: unknown): StoreMap {
72
82
  lastMessageCount: typeof mc === "number" && Number.isFinite(mc) ? mc : 0,
73
83
  ...(typeof db === "string" ? { digestBoundary: db } : {}),
74
84
  ...(typeof dci === "string" ? { digestSummaryId: dci } : {}),
85
+ ...(typeof sph === "string" ? { systemPromptHash: sph } : {}),
86
+ ...(typeof spu === "number" && Number.isFinite(spu) ? { systemPromptUpdates: spu } : {}),
75
87
  ...(sync ? { sync } : {}),
76
88
  };
77
89
  }
@@ -116,6 +128,8 @@ export class SessionStore {
116
128
  lastMessageCount: s.lastMessageCount ?? 0,
117
129
  ...(s.digestBoundary !== undefined ? { digestBoundary: s.digestBoundary } : {}),
118
130
  ...(s.digestSummaryId !== undefined ? { digestSummaryId: s.digestSummaryId } : {}),
131
+ ...(s.systemPromptHash !== undefined ? { systemPromptHash: s.systemPromptHash } : {}),
132
+ ...(s.systemPromptUpdates !== undefined ? { systemPromptUpdates: s.systemPromptUpdates } : {}),
119
133
  ...(s.sync !== undefined ? { sync: structuredClone(s.sync) } : {}),
120
134
  };
121
135
  }