@estebanforge/pi-antigravity-bridge 1.20.2 → 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,12 @@
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
+
5
11
  ## [1.20.2] - 2026-12-05
6
12
 
7
13
  ### 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.2",
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",
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,7 +42,7 @@ 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 { SessionStore, type AgySession } from "./sessions.js";
45
46
  import { detectQuotaNotice, detectStrictQuotaNotice, quotaErrorMessage } from "./quota-notice.js";
46
47
  import { authErrorMessage, detectAuthNotice, detectStrictAuthNotice, isAuthErrorMessage } from "./auth-state.js";
47
48
  import { redactText } from "./redact.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 {
@@ -2669,8 +2804,10 @@ async function runTurnDriver(
2669
2804
  // into. Only when no record exists: an unbound run() cannot have
2670
2805
  // recreated a conversation, so the snapshot id is the real one, and
2671
2806
  // the staged agent must move with the binding or a stream-json resume
2672
- // re-runs without its carrier-agent profile.
2673
- 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()) {
2674
2811
  const parkedConv = deps.driver.snapshot().conversationId;
2675
2812
  if (parkedConv) {
2676
2813
  if (syncTurn) {
@@ -2679,18 +2816,23 @@ async function runTurnDriver(
2679
2816
  // as history, so the latch has no second consumer.
2680
2817
  syncTurn.adoptBinding(parkedConv);
2681
2818
  const rec = syncTurn.record();
2682
- if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId });
2819
+ if (rec.conversationId) store.set(key, { ...rec, conversationId: rec.conversationId, ...sysRecordFields(true) });
2683
2820
  if (syncTurn.freshConversation) deps.pendingCompactionHandoff?.delete(key);
2684
- } else {
2821
+ } else if (!existing) {
2685
2822
  store.set(key, {
2686
2823
  conversationId: parkedConv,
2687
2824
  lastStepIdx: -1,
2688
2825
  lastMessageCount: nextCount,
2689
2826
  digestBoundary: nextBoundary,
2690
2827
  digestSummaryId: settleSummaryId,
2828
+ ...sysRecordFields(true),
2691
2829
  });
2692
2830
  deps.pendingCompactionHandoff?.delete(key);
2693
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) });
2694
2836
  }
2695
2837
  }
2696
2838
  }
@@ -2943,7 +3085,7 @@ async function runTurnDriver(
2943
3085
  );
2944
3086
  const record = settleSync.record();
2945
3087
  if (record.conversationId && !rotationGuardArmed()) {
2946
- store.set(key, { ...record, conversationId: record.conversationId });
3088
+ store.set(key, { ...record, conversationId: record.conversationId, ...sysRecordFields(outcome.status === "OK" && !outcome.aborted) });
2947
3089
  // A rebuild shipped the compaction summary as history; the one-shot
2948
3090
  // latch has no second consumer.
2949
3091
  if (settleSync.freshConversation) deps.pendingCompactionHandoff?.delete(key);
@@ -2981,6 +3123,7 @@ async function runTurnDriver(
2981
3123
  lastMessageCount: nextCount,
2982
3124
  digestBoundary: nextBoundary,
2983
3125
  digestSummaryId: settleSummaryId,
3126
+ ...sysRecordFields(true),
2984
3127
  // The churn latch must survive digest turns (store.set
2985
3128
  // replaces the record), or the gate re-opens next turn and
2986
3129
  // the session alternates rebuild/digest forever.
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
  }