@genesislcap/ai-assistant 15.110.4 → 15.111.1-GENC-1962.4

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.
@@ -42446,6 +42446,38 @@
42446
42446
  "endIndex": 6
42447
42447
  }
42448
42448
  },
42449
+ {
42450
+ "kind": "PropertySignature",
42451
+ "canonicalReference": "@genesislcap/ai-assistant!StatefulAgentInit#tailContextMode:member",
42452
+ "docComment": "/**\n * Whether `tailContext` is sent fresh on every call or stored in history when it changes. See `AgentConfig.tailContextMode`.\n */\n",
42453
+ "excerptTokens": [
42454
+ {
42455
+ "kind": "Content",
42456
+ "text": "tailContextMode?: "
42457
+ },
42458
+ {
42459
+ "kind": "Reference",
42460
+ "text": "AgentConfig",
42461
+ "canonicalReference": "@genesislcap/ai-assistant!AgentConfig:type"
42462
+ },
42463
+ {
42464
+ "kind": "Content",
42465
+ "text": "['tailContextMode']"
42466
+ },
42467
+ {
42468
+ "kind": "Content",
42469
+ "text": ";"
42470
+ }
42471
+ ],
42472
+ "isReadonly": false,
42473
+ "isOptional": true,
42474
+ "releaseTag": "Beta",
42475
+ "name": "tailContextMode",
42476
+ "propertyTypeTokenRange": {
42477
+ "startIndex": 1,
42478
+ "endIndex": 3
42479
+ }
42480
+ },
42449
42481
  {
42450
42482
  "kind": "PropertySignature",
42451
42483
  "canonicalReference": "@genesislcap/ai-assistant!StatefulAgentInit#temperature:member",
@@ -2514,6 +2514,28 @@ declare interface BaseAgentConfig {
2514
2514
  * @beta
2515
2515
  */
2516
2516
  tailContext?: TailContextInput;
2517
+ /**
2518
+ * Where {@link BaseAgentConfig.tailContext} goes on the wire (GENC-1962).
2519
+ *
2520
+ * - `'volatile'` (the default): appended to every request and never stored. Cheapest on the cache,
2521
+ * but on a model with preserved thinking (Anthropic's 5.5 family) a request that carried a tail
2522
+ * produces thinking that no later request can replay: the tail is gone by the next request, so
2523
+ * the prefix the thinking was made against is never rebuilt, and the transport leaves it out.
2524
+ * - `'stored'`: stored in history as a hidden note (`driverNote: 'agent-context'`), and only when it
2525
+ * differs from the agent's last stored note. History then only grows at the end, so thinking
2526
+ * produced within a tool loop stays replayable for as long as the system prompt and tools do.
2527
+ * The note says it replaces earlier ones; it is sent only to the agent that wrote it. Earlier
2528
+ * notes stay in history while the agent's system prompt and tools hold, and are removed on the
2529
+ * first call where either has changed, since nothing before that call can be replayed or read
2530
+ * from the cache. Costs history: one copy per change within a stable run, cached after its first
2531
+ * read.
2532
+ *
2533
+ * The framework's own volatile additions (fold suffix, retry nudges) stay a volatile tail in both
2534
+ * modes. Read once when the agent is installed.
2535
+ *
2536
+ * @beta
2537
+ */
2538
+ tailContextMode?: 'volatile' | 'stored';
2517
2539
  /**
2518
2540
  * Structured-output schema for this agent. When resolved to a schema on a turn, the model's
2519
2541
  * final (non-tool) answer is constrained to it instead of free text. Composes with `tools`;
@@ -3223,6 +3245,14 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
3223
3245
  * the resolved string in a `<system-reminder>` marker and injects it at the message tail.
3224
3246
  */
3225
3247
  private activeTailContextInput?;
3248
+ /** Whether the active agent's tail context is stored in history (`tailContextMode: 'stored'`). */
3249
+ private activeTailContextStored;
3250
+ /**
3251
+ * Per agent with a stored tail, a digest of the system prompt and tools its last call was sent
3252
+ * with. When the next call's differs, nothing before it can be replayed or read from the cache,
3253
+ * so that agent's superseded context notes are dropped (see `storeAgentContext`).
3254
+ */
3255
+ private readonly storedContextHeaders;
3226
3256
  /**
3227
3257
  * Active agent's structured-output schema selector (static value or per-turn resolver).
3228
3258
  * When it resolves to a schema, the model's final answer is constrained to it this turn.
@@ -4162,6 +4192,39 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
4162
4192
  */
4163
4193
  private appendDriverNotice;
4164
4194
  private appendToHistory;
4195
+ /** Stamp a message for history: its timestamp (unless it has one) and the active agent. */
4196
+ private tagMessage;
4197
+ /**
4198
+ * Write the active agent's tail context into history as a hidden note (`tailContextMode:
4199
+ * 'stored'`, GENC-1962), unless it is the same as the last one this agent stored. A tail that
4200
+ * resolves to nothing after there was one stores a note saying so, or the old one would still
4201
+ * read as current. `beforePendingUser`: the turn's first call, which sends the newest message (the
4202
+ * user's) separately, so the note goes in ahead of it. While the system prompt and tools hold,
4203
+ * the history only grows where the next request already ends, which is what keeps earlier
4204
+ * thinking replayable.
4205
+ *
4206
+ * `header` is this call's system prompt and tools (`requestHeaderDigest`). When it differs from
4207
+ * the agent's previous call, the cache and every earlier thinking block are lost anyway, so the
4208
+ * agent's superseded notes are removed and only the current one is kept: otherwise every change
4209
+ * of state stays in history for the rest of the conversation (measured on a Create bootstrap,
4210
+ * 39 notes and about 41K tokens on every call).
4211
+ */
4212
+ private storeAgentContext;
4213
+ /**
4214
+ * The parent's history as a sub-agent inherits it, capped by `historyCap`.
4215
+ *
4216
+ * The current in-flight assistant message (the one with tool calls that triggered this invocation)
4217
+ * is left out: it has unresolved tool calls that would confuse the sub-agent into thinking it needs
4218
+ * to handle tools it doesn't own. It is found by its unanswered calls, not by being last: a widget
4219
+ * the batch showed can come after it.
4220
+ *
4221
+ * The parent's stored context notes go too, before the cap: the child never reads them (its own
4222
+ * agent name differs), so counted against `historyCap` a note would take the place of a recent
4223
+ * message the child would have been sent in full (GENC-1962).
4224
+ */
4225
+ private subAgentHistory;
4226
+ /** A digest of what a request sends ahead of its messages: the system prompt and the tools. */
4227
+ private requestHeaderDigest;
4165
4228
  /** Announce the current history to the host. */
4166
4229
  private notifyHistoryUpdated;
4167
4230
  }
@@ -10321,6 +10384,8 @@ export declare interface StatefulAgentInit<S> {
10321
10384
  * content; the framework frames it. Omit, or return an empty string, for none.
10322
10385
  */
10323
10386
  tailContext?: string | ((ctx: StatefulAgentContext<S>) => string | Promise<string>);
10387
+ /** Whether `tailContext` is sent fresh on every call or stored in history when it changes. See `AgentConfig.tailContextMode`. */
10388
+ tailContextMode?: AgentConfig['tailContextMode'];
10324
10389
  /**
10325
10390
  * Hook consulted when the model calls a tool that isn't dispatchable in the
10326
10391
  * current state — a *stale* tool (valid in an earlier state of this agent) or
@@ -5348,7 +5348,7 @@ var DEBUG_LOG_README = [
5348
5348
  "Timestamps are millisecond-resolution; entries that share the same millisecond are ordered by a fixed kind rank (event, then turn, then message), which is a heuristic and may not reflect exact causal order within that millisecond \u2014 e.g. a user message and the turn it triggered, or a final assistant message and its turn.end event, can appear in either order depending on whether they landed in the same millisecond. Read the logical structure of a turn rather than over-interpreting the micro-ordering of co-timestamped entries of different kinds.",
5349
5349
  "kind:'message' \u2014 the conversation. `role` is user/assistant/tool/system-event/synthetic-user; `agentName` says which agent produced it; `toolCalls`/`toolResult`/`interaction` carry tool and widget activity; `inputTokens`/`outputTokens`/`cost` are per-message LLM usage, where `inputTokens` is the WHOLE prompt for that request and `cacheReadTokens`/`cacheWriteTokens` BREAK IT DOWN rather than add to it \u2014 uncached input is `inputTokens` minus those two, and adding the cache fields to `inputTokens` counts the prompt twice. The cache fields are absent on providers that report no cache split (Gemini reports reads only, since implicit caching bills no write) and on messages persisted before they existed, so read them as 0 when missing. Each bucket bills at a different rate \u2014 cache reads a fraction of uncached input, cache writes a premium, output highest \u2014 so a large token count at a small cost means the prompt was mostly cache hits. `externalCostUsd` is any non-LLM cost a widget reported for its own external service calls (folded into the session cost total alongside `cost`). On model-produced assistant messages, `model` is the concrete model id that generated it (e.g. 'gemini-2.5-flash-lite') and `providerName` is the registry slot it resolved under (e.g. a tier name like 'high'/'low', or the default); together they attribute the message \u2014 and any tool calls it carries \u2014 to an exact model even across a mid-session vendor/tier switch, where one slot name can map to different models before and after the switch. Both are undefined on any entry that is NOT an LLM response: non-assistant roles (user/tool/system-event) and 'synthetic-user' echoes; assistant interaction/widget entries (empty content carrying an `interaction` \u2014 a rendered widget, not a model turn); driver-authored assistant fallbacks (the timeout, repeated-malformed-call, and empty-response apology messages); and messages restored from a session persisted before these fields existed. One partial case: on a genuine model turn whose provider exposes no `getStatus` (or reports no model), `providerName` is still set but `model` alone is undefined. A 'synthetic-user' message is a display-only echo of an interaction outcome (e.g. the answer a widget reported): it renders on the user's side of the chat and `agentName` is the agent that created it, but it is never sent to the LLM \u2014 so it has no matching 'turn' and the model learns the outcome only from the corresponding tool result. An echo of an answer an interceptor (such as an autopilot) gave is NOT synthetic-user: see the delegated-messages paragraph.",
5350
5350
  "The autopilot (GENC-1660) runs on a driver of its own, and everything it did is harvested into this log: entries with delegate: autopilot and an agentName ending in \u203A Autopilot are its turns (the decision message it was sent is the user message of its turn, so what it was shown is there verbatim; its systemPrompt is its grounding, such as the brief), its tool calls (widget_read, widget_act, hand_back, any read-only tools of its own, and its widget tools \u2014 reads with parameters that a widget type declares, routed to the interaction of that type being decided and refused with a reason when none is, offered on every decision so its tool list never changes; while one is open its tail starts with a line naming them) and their results (a read, view or widget tool, is capped at about 20,000 characters, cut with a note asking for less, and leaves its history at the end of the decision as a one-line note), and its own events. Its cost is already in the session total: it is booked as externalCostUsd on the interaction each decision answered, or, for a written question it answered, on the user message it sent on the user behalf (delegate: autopilot), so do not add its turns to that total. Spend that reached no message is recorded as autopilot.cost-dropped instead.",
5351
- "Delegated messages (GENC-1660): a message with a `delegate` field was written or sent ON THE USER'S BEHALF by a driver decorator, and `delegate` names it (e.g. autopilot). The platform stamps it; nothing else can. It renders as the assistant whatever its role. A delegated `user` message was NOT typed by the user: it is an answer given on their behalf, and the model read it with `delegateFraming` in brackets in front of the content (the stored `content` is the bare text). A delegated `assistant` message is display-only (`excludeFromProvider`): the decorator's narration note, or, when its answer carried no note, the widget's own echo of the answer (its `userMessage`), shown as the assistant and never as the person. A widget answer a decorator gave with a note is not echoed at all: the note already says what was chosen. To tell what the person decided from what was decided for them, read `interaction.answeredBy` and these fields, never the role alone. Driver notes: a `user` message with a `driverNote` field was written by the driver for the model, never by the user, and is hidden from the transcript; `driverNote: 'finish-guard'` is the agent's finishGuard holding the turn open after a prose reply, its content the guard's note in a `<system-reminder>`, and it follows a turn.finish-guard event; `driverNote: 'completion-nudge'` is the driver asking a sub-agent that replied in prose to call its completion tool; `driverNote: 'forced-tool-nudge'` is the driver asking a parent agent for the tool call its forced turn required, after a model that rejects forcing (responseMeta.toolChoiceDowngraded) replied in prose.",
5351
+ "Delegated messages (GENC-1660): a message with a `delegate` field was written or sent ON THE USER'S BEHALF by a driver decorator, and `delegate` names it (e.g. autopilot). The platform stamps it; nothing else can. It renders as the assistant whatever its role. A delegated `user` message was NOT typed by the user: it is an answer given on their behalf, and the model read it with `delegateFraming` in brackets in front of the content (the stored `content` is the bare text). A delegated `assistant` message is display-only (`excludeFromProvider`): the decorator's narration note, or, when its answer carried no note, the widget's own echo of the answer (its `userMessage`), shown as the assistant and never as the person. A widget answer a decorator gave with a note is not echoed at all: the note already says what was chosen. To tell what the person decided from what was decided for them, read `interaction.answeredBy` and these fields, never the role alone. Driver notes: a `user` message with a `driverNote` field was written by the driver for the model, never by the user, and is hidden from the transcript; `driverNote: 'finish-guard'` is the agent's finishGuard holding the turn open after a prose reply, its content the guard's note in a `<system-reminder>`, and it follows a turn.finish-guard event; `driverNote: 'completion-nudge'` is the driver asking a sub-agent that replied in prose to call its completion tool; `driverNote: 'forced-tool-nudge'` is the driver asking a parent agent for the tool call its forced turn required, after a model that rejects forcing (responseMeta.toolChoiceDowngraded) replied in prose. `driverNote: 'agent-context'` is an agent's tail context stored in history rather than sent as a volatile tail (the agent set tailContextMode: 'stored'): written only when it changes, so the latest one before a call is what that call's context was, and it is sent only to the agent named in its agentName. An agent's earlier notes are removed from history on the first call where its system prompt or tools changed, so the history keeps only the notes written since then.",
5352
5352
  "Sub-agent messages appear inline. When a tool delegates to a sub-agent (via `requestSubAgent`), the sub-agent's whole conversation \u2014 its own assistant/tool messages, each with their own `content`/`thinking`/`toolCalls`/`toolResult` and per-message `model`/`providerName`/`inputTokens`/`outputTokens`/`cacheReadTokens`/`cacheWriteTokens`/`cost` \u2014 is hoisted into the timeline as ordinary kind:'message' entries, interleaved by timestamp right after the tool call that spawned them (so you read the delegation top-to-bottom). A hoisted entry is marked: `subAgentDepth` is its delegation depth (1 for a sub-agent, 2 for a sub-agent's sub-agent, \u2026), `subAgentOf` is the id of the parent tool call that spawned it (correlates it back even when two sub-agents run in one parent turn), `subAgentName` is the sub-agent's own name, and `agentName` is rewritten to a `\"<parent> \u203A <sub-agent>\"` breadcrumb (composing when nested, e.g. `\"UI Builder \u203A Planner \u203A Grounding\"`). The sub-agent's per-LLM-call snapshots also surface as kind:'turn' entries with a `<parentTurn>-<subAgentNo>.<childTurn>` `turnIndex` (see the kind:'turn' paragraph), and subagent.started/completed (or subagent.failed) events bracket the run. Per-message `cost` on hoisted entries is already part of the session total (it is summed from the un-flattened history), so summing the top-level timeline does NOT double-count.",
5353
5353
  "kind:'turn' \u2014 one LLM call. `turnIndex` is a string: a top-level turn is the bare counter ('0', '1', \u2026); a sub-agent's turns are labelled '<parentTurn>-<subAgentNo>.<childTurn>': the parent turn that activated it, the sub-agent's number (1-based, in the order the sub-agents started within that parent turn, so it matches the order of the subagent.started events; two sub-agents in one parent turn never share a number, even when they run in parallel or share a name), and the sub-agent's own turn position (1-based) \u2014 e.g. '3-2.1', '3-2.2' are the first two turns of the second sub-agent started in parent turn 3, and a sub-agent nested under its turn '3-2.2' contributes '3-2.2-1.1', \u2026 ('.' joins the parts of one level, '-' separates levels). The `<parentTurn>-<subAgentNo>` part is the sub-agent's `turnPrefix`: the same value is stamped on its subagent.started/completed/failed events and on its harvested events as `detail.turnPrefix`, so match events to turns by value (a turn belongs to the sub-agent whose `turnPrefix` its `turnIndex` begins with) \u2014 and `agentName` names the agent that ran the turn. `systemPrompt` and `toolNames` are what the model saw. A systemPrompt of '<repeated \u2014 identical to turn N>' was byte-identical to turn N and de-duplicated; the full prompt is shown whenever it changes (often because a stateful agent advanced), so prompt evolution is visible.",
5354
5354
  "kind:'turn'.`model`/`providerName`/`provider` \u2014 which model ran that call: the concrete model id, the registry slot it resolved under (a tier name like 'high'/'low', or the default), and the vendor. Recorded per CALL, so an agent whose `provider` selector varies by state \u2014 a flow that plans on a high tier and executes on a low one \u2014 has every step attributed, including calls that produced no message. `model` is the SERVING model where the provider reports one, so a turn answered by a server-side fallback names the model that answered rather than the one requested; it always matches the `model` on the message that call produced. Absent when the provider exposes no `getStatus` and the transport stamped nothing.",
@@ -5365,6 +5365,59 @@ var DEBUG_LOG_README = [
5365
5365
  "To debug a failure: find the last turn.error or tool.failed, then read upward for the user message, the turn(s), and the agent/provider/state events that led into it. For a turn that went to the wrong agent, read its routing.decided first \u2014 `decision` says whether anything was actually asked."
5366
5366
  ];
5367
5367
 
5368
+ // src/state/persistence/diagnostics.ts
5369
+ var FNV_OFFSET_BASIS2 = 2166136261;
5370
+ var FNV_PRIME2 = 16777619;
5371
+ var DIGEST_RADIX = 36;
5372
+ function configDigest(json) {
5373
+ let a = FNV_OFFSET_BASIS2;
5374
+ let b = FNV_PRIME2;
5375
+ for (let i = 0; i < json.length; i += 1) {
5376
+ const c = json.charCodeAt(i);
5377
+ a = Math.imul(a ^ c, FNV_PRIME2) >>> 0;
5378
+ b = Math.imul(b ^ c, FNV_OFFSET_BASIS2) >>> 0;
5379
+ }
5380
+ return [json.length, a, b].map((n) => n.toString(DIGEST_RADIX)).join("-");
5381
+ }
5382
+ function turnIdentity(entry) {
5383
+ return `turn::${String(entry.turnIndex ?? "")}::${entry.timestamp ?? ""}::${String(entry.agentName ?? "")}`;
5384
+ }
5385
+ var KIND_RANK = { event: 0, turn: 1, message: 2 };
5386
+ var UNKNOWN_KIND_RANK = 99;
5387
+ function assembleDebugLog(entries, readme) {
5388
+ const seenAt = /* @__PURE__ */ new Map();
5389
+ let latestMeta;
5390
+ const timeline = [];
5391
+ for (const entry of entries) {
5392
+ if (entry.kind === "meta-snapshot") {
5393
+ if (!latestMeta || (entry.timestamp ?? "") >= (latestMeta.timestamp ?? "")) {
5394
+ latestMeta = entry;
5395
+ }
5396
+ continue;
5397
+ }
5398
+ const id = entry.kind === "turn" ? turnIdentity(entry) : JSON.stringify(entry);
5399
+ const at = seenAt.get(id);
5400
+ if (at !== void 0) {
5401
+ if (entry.usage && !timeline[at].usage) timeline[at] = entry;
5402
+ continue;
5403
+ }
5404
+ seenAt.set(id, timeline.length);
5405
+ timeline.push(entry);
5406
+ }
5407
+ timeline.sort((a, b) => {
5408
+ const ta = a.timestamp ?? "";
5409
+ const tb = b.timestamp ?? "";
5410
+ if (ta < tb) return -1;
5411
+ if (ta > tb) return 1;
5412
+ return (KIND_RANK[a.kind] ?? UNKNOWN_KIND_RANK) - (KIND_RANK[b.kind] ?? UNKNOWN_KIND_RANK);
5413
+ });
5414
+ const context = latestMeta?.meta?.context;
5415
+ return { readme, sessionUsage: context?.sessionUsage, timeline, meta: latestMeta?.meta };
5416
+ }
5417
+ function withFreshMetaSnapshot(stored, fresh) {
5418
+ return [...stored.filter((e) => e.kind !== "meta-snapshot"), fresh];
5419
+ }
5420
+
5368
5421
  // src/utils/delegated-message.ts
5369
5422
  var DEFAULT_DELEGATE_FRAMING = "Sent on the user's behalf.";
5370
5423
  function delegatedFields(options) {
@@ -5394,6 +5447,15 @@ ${note.trim()}
5394
5447
  driverNote: kind
5395
5448
  };
5396
5449
  }
5450
+ var AGENT_CONTEXT_PREAMBLE = "The current state, as of this point in the conversation. It replaces any earlier note like this one: where they differ, this one is right.";
5451
+ var NO_CONTEXT = "There is nothing to note at the moment.";
5452
+ function agentContextNote(body) {
5453
+ return `<system-reminder>
5454
+ ${AGENT_CONTEXT_PREAMBLE}
5455
+
5456
+ ${body.trim() || NO_CONTEXT}
5457
+ </system-reminder>`;
5458
+ }
5397
5459
 
5398
5460
  // src/utils/preserved-user-messages.ts
5399
5461
  function freshUserMessages(toCompact) {
@@ -6033,7 +6095,7 @@ function renderMessageForSummary(m) {
6033
6095
  }
6034
6096
  }
6035
6097
  function buildCompactionSummaryPrompt(toCompact) {
6036
- const transcript = toCompact.filter((m) => !m.excludeFromProvider).map(renderMessageForSummary).filter(Boolean).join("\n");
6098
+ const transcript = toCompact.filter((m) => !m.excludeFromProvider && m.driverNote !== "agent-context").map(renderMessageForSummary).filter(Boolean).join("\n");
6037
6099
  const systemPrompt = "You compress a conversation transcript into a concise summary that lets an AI assistant continue the conversation seamlessly. Preserve key facts, decisions, what the user wants, entity names and IDs, and any unresolved threads. Write plain prose. Never roleplay or continue the conversation.";
6038
6100
  const userMessage = `<conversation_history>
6039
6101
  ${transcript}
@@ -8541,6 +8603,14 @@ var ChatDriver = class _ChatDriver extends EventTarget {
8541
8603
  this.messageController = new AbortController();
8542
8604
  /** Capabilities provided on this driver by decorators (GENC-1660). Only the root's are used. */
8543
8605
  this.handlerCapabilities = /* @__PURE__ */ new Map();
8606
+ /** Whether the active agent's tail context is stored in history (`tailContextMode: 'stored'`). */
8607
+ this.activeTailContextStored = false;
8608
+ /**
8609
+ * Per agent with a stored tail, a digest of the system prompt and tools its last call was sent
8610
+ * with. When the next call's differs, nothing before it can be replayed or read from the cache,
8611
+ * so that agent's superseded context notes are dropped (see `storeAgentContext`).
8612
+ */
8613
+ this.storedContextHeaders = /* @__PURE__ */ new Map();
8544
8614
  /**
8545
8615
  * Caches validated provider lookups per name within the current agent. Cleared
8546
8616
  * by `installAgent` so each new agent's static/function-resolved names are
@@ -9214,6 +9284,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
9214
9284
  this.activeCachePolicyInput = config.cachePolicy;
9215
9285
  this.activeThinkingPolicyInput = config.thinkingPolicy;
9216
9286
  this.activeTailContextInput = config.tailContext;
9287
+ this.activeTailContextStored = config.tailContextMode === "stored";
9217
9288
  this.activeResponseSchemaInput = config.responseSchema;
9218
9289
  this.activeFallbacks = config.fallbacks;
9219
9290
  this.activeOnUnresolvedTool = config.onUnresolvedTool;
@@ -10333,8 +10404,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
10333
10404
  const noteIdle = () => idle?.touch();
10334
10405
  let snapshotHistory = [];
10335
10406
  if (inheritHistory !== false) {
10336
- const baseHistory = this.history.slice(0, inFlightToolCallsAt(this.history));
10337
- snapshotHistory = historyCap != null ? applyHistoryCap(baseHistory, historyCap) : [...baseHistory];
10407
+ snapshotHistory = this.subAgentHistory(historyCap);
10338
10408
  }
10339
10409
  const contextMessages = context ? [{ role: "user", content: `[Sub-agent context]: ${JSON.stringify(context)}` }] : [];
10340
10410
  const effectivePrimer = [
@@ -10641,11 +10711,21 @@ ${tailNote}` : "";
10641
10711
 
10642
10712
  ${closing}` : "";
10643
10713
  const frameworkSystemSuffix = `${foldSuffix}${firstCallNote}${closingNote}${retryNudge}`;
10644
- const primer = normalizeForProvider([
10645
- ...this.primerHistory ?? [],
10646
- ...transientPrimer ?? []
10647
- ]);
10648
- const baseHistory = firstLlmCall ? this.history.slice(0, -1) : this.history;
10714
+ if (this.activeTailContextStored) {
10715
+ const storedTail = await resolveTurnInput(this.activeTailContextInput, promptCtx);
10716
+ this.storeAgentContext(
10717
+ storedTail,
10718
+ firstLlmCall,
10719
+ this.requestHeaderDigest(resolvedSystemPrompt)
10720
+ );
10721
+ }
10722
+ const ownContext = (m) => m.driverNote !== "agent-context" || this.activeTailContextStored && m.agentName === this.activeAgentName;
10723
+ const primer = normalizeForProvider(
10724
+ [...this.primerHistory ?? [], ...transientPrimer ?? []].filter(ownContext)
10725
+ );
10726
+ const baseHistory = (firstLlmCall ? this.history.slice(0, -1) : this.history).filter(
10727
+ ownContext
10728
+ );
10649
10729
  firstLlmCall = false;
10650
10730
  const suspended = this.suspendedClocks();
10651
10731
  const condensedHistory = applyCondensation(
@@ -10681,7 +10761,8 @@ ${closing}` : "";
10681
10761
  resolveTurnInput(this.activeTemperatureInput, promptCtx),
10682
10762
  resolveTurnInput(this.activeToolChoiceInput, promptCtx),
10683
10763
  resolveTurnInput(this.activeCachePolicyInput, promptCtx),
10684
- resolveTurnInput(this.activeTailContextInput, promptCtx),
10764
+ // A stored tail was resolved and written into history above; only a volatile one is sent.
10765
+ this.activeTailContextStored ? Promise.resolve(void 0) : resolveTurnInput(this.activeTailContextInput, promptCtx),
10685
10766
  resolveTurnInput(this.activeResponseSchemaInput, promptCtx),
10686
10767
  // Only consulted on the first iteration (see `pinnedThinkingPolicy`); resolved
10687
10768
  // alongside the others so a resolver still sees the same turn context.
@@ -11389,7 +11470,12 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
11389
11470
  this.appendToHistory({ role: "assistant", content, excludeFromProvider: true });
11390
11471
  }
11391
11472
  appendToHistory(message) {
11392
- const tagged = {
11473
+ this.history = [...this.history, this.tagMessage(message)];
11474
+ this.notifyHistoryUpdated();
11475
+ }
11476
+ /** Stamp a message for history: its timestamp (unless it has one) and the active agent. */
11477
+ tagMessage(message) {
11478
+ return {
11393
11479
  ...message,
11394
11480
  // Stamp on first append; preserve any caller-supplied timestamp.
11395
11481
  timestamp: message.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
@@ -11399,9 +11485,71 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
11399
11485
  agentLabel: this.activeAgentLabel
11400
11486
  } : {}
11401
11487
  };
11402
- this.history = [...this.history, tagged];
11488
+ }
11489
+ /**
11490
+ * Write the active agent's tail context into history as a hidden note (`tailContextMode:
11491
+ * 'stored'`, GENC-1962), unless it is the same as the last one this agent stored. A tail that
11492
+ * resolves to nothing after there was one stores a note saying so, or the old one would still
11493
+ * read as current. `beforePendingUser`: the turn's first call, which sends the newest message (the
11494
+ * user's) separately, so the note goes in ahead of it. While the system prompt and tools hold,
11495
+ * the history only grows where the next request already ends, which is what keeps earlier
11496
+ * thinking replayable.
11497
+ *
11498
+ * `header` is this call's system prompt and tools (`requestHeaderDigest`). When it differs from
11499
+ * the agent's previous call, the cache and every earlier thinking block are lost anyway, so the
11500
+ * agent's superseded notes are removed and only the current one is kept: otherwise every change
11501
+ * of state stays in history for the rest of the conversation (measured on a Create bootstrap,
11502
+ * 39 notes and about 41K tokens on every call).
11503
+ */
11504
+ storeAgentContext(tail, beforePendingUser, header) {
11505
+ const agent = this.activeAgentName ?? "";
11506
+ const previousHeader = this.storedContextHeaders.get(agent);
11507
+ this.storedContextHeaders.set(agent, header);
11508
+ const prefixBroken = previousHeader !== void 0 && previousHeader !== header;
11509
+ const isOwnNote = (m) => m.driverNote === "agent-context" && m.agentName === this.activeAgentName;
11510
+ const body = (tail ?? "").trim();
11511
+ const previous = [...this.history].reverse().find(isOwnNote);
11512
+ const content = agentContextNote(body);
11513
+ const append = Boolean(body || previous) && previous?.content !== content;
11514
+ const superseded = this.history.filter((m) => isOwnNote(m) && (append || m !== previous));
11515
+ if (!append && !(prefixBroken && superseded.length > 0)) return;
11516
+ let history = this.history;
11517
+ if (prefixBroken) history = history.filter((m) => !superseded.includes(m));
11518
+ if (append) {
11519
+ const note = this.tagMessage({ role: "user", content, driverNote: "agent-context" });
11520
+ const at = beforePendingUser && history.length > 0 ? history.length - 1 : history.length;
11521
+ history = [...history.slice(0, at), note, ...history.slice(at)];
11522
+ }
11523
+ this.history = history;
11403
11524
  this.notifyHistoryUpdated();
11404
11525
  }
11526
+ /**
11527
+ * The parent's history as a sub-agent inherits it, capped by `historyCap`.
11528
+ *
11529
+ * The current in-flight assistant message (the one with tool calls that triggered this invocation)
11530
+ * is left out: it has unresolved tool calls that would confuse the sub-agent into thinking it needs
11531
+ * to handle tools it doesn't own. It is found by its unanswered calls, not by being last: a widget
11532
+ * the batch showed can come after it.
11533
+ *
11534
+ * The parent's stored context notes go too, before the cap: the child never reads them (its own
11535
+ * agent name differs), so counted against `historyCap` a note would take the place of a recent
11536
+ * message the child would have been sent in full (GENC-1962).
11537
+ */
11538
+ subAgentHistory(historyCap) {
11539
+ const baseHistory = this.history.slice(0, inFlightToolCallsAt(this.history)).filter((m) => m.driverNote !== "agent-context");
11540
+ return historyCap != null ? applyHistoryCap(baseHistory, historyCap) : baseHistory;
11541
+ }
11542
+ /** A digest of what a request sends ahead of its messages: the system prompt and the tools. */
11543
+ requestHeaderDigest(systemPrompt) {
11544
+ return configDigest(
11545
+ JSON.stringify([
11546
+ systemPrompt ?? "",
11547
+ // `enforceSchema` too: the Anthropic transport's replay fingerprint includes it, so toggling it
11548
+ // breaks replay just as a changed schema does.
11549
+ this.toolDefinitions.map((t) => [t.name, t.description, t.parameters, !!t.enforceSchema])
11550
+ ])
11551
+ );
11552
+ }
11405
11553
  /** Announce the current history to the host. */
11406
11554
  notifyHistoryUpdated() {
11407
11555
  this.dispatchEvent(
@@ -12694,6 +12842,18 @@ function bindStateOrDefault(hook, getState) {
12694
12842
  return hook({ ...ctx, state });
12695
12843
  };
12696
12844
  }
12845
+ function forwardedOptions(opts) {
12846
+ return {
12847
+ primerHistory: opts.primerHistory,
12848
+ subAgents: opts.subAgents,
12849
+ manualSelection: opts.manualSelection,
12850
+ chatInputDuringExecution: opts.chatInputDuringExecution,
12851
+ tailContextMode: opts.tailContextMode,
12852
+ notResumableMessage: opts.notResumableMessage,
12853
+ resumeOnRestore: opts.resumeOnRestore,
12854
+ contextReserve: opts.contextReserve
12855
+ };
12856
+ }
12697
12857
  function defineStatefulAgent(opts) {
12698
12858
  let state;
12699
12859
  const assertNoFolds = (handlers) => {
@@ -12795,10 +12955,7 @@ function defineStatefulAgent(opts) {
12795
12955
  const base = {
12796
12956
  name: opts.name,
12797
12957
  displayName: wrappedDisplayName,
12798
- primerHistory: opts.primerHistory,
12799
- subAgents: opts.subAgents,
12800
- manualSelection: opts.manualSelection,
12801
- chatInputDuringExecution: opts.chatInputDuringExecution,
12958
+ ...forwardedOptions(opts),
12802
12959
  toolDefinitions: wrappedTools,
12803
12960
  toolHandlers: wrappedHandlers,
12804
12961
  provider: wrappedProvider,
@@ -12810,9 +12967,6 @@ function defineStatefulAgent(opts) {
12810
12967
  onUnresolvedTool: wrappedOnUnresolvedTool,
12811
12968
  finishGuard: wrappedFinishGuard,
12812
12969
  resumable: wrappedResumable,
12813
- notResumableMessage: opts.notResumableMessage,
12814
- resumeOnRestore: opts.resumeOnRestore,
12815
- contextReserve: opts.contextReserve,
12816
12970
  // Bound to the live state, so the autopilot's resolvers see what this agent's do (GENC-1660).
12817
12971
  ...opts.autopilot && {
12818
12972
  autopilot: {
@@ -13171,59 +13325,6 @@ function describeInteraction(input) {
13171
13325
  };
13172
13326
  }
13173
13327
 
13174
- // src/state/persistence/diagnostics.ts
13175
- var FNV_OFFSET_BASIS2 = 2166136261;
13176
- var FNV_PRIME2 = 16777619;
13177
- var DIGEST_RADIX = 36;
13178
- function configDigest(json) {
13179
- let a = FNV_OFFSET_BASIS2;
13180
- let b = FNV_PRIME2;
13181
- for (let i = 0; i < json.length; i += 1) {
13182
- const c = json.charCodeAt(i);
13183
- a = Math.imul(a ^ c, FNV_PRIME2) >>> 0;
13184
- b = Math.imul(b ^ c, FNV_OFFSET_BASIS2) >>> 0;
13185
- }
13186
- return [json.length, a, b].map((n) => n.toString(DIGEST_RADIX)).join("-");
13187
- }
13188
- function turnIdentity(entry) {
13189
- return `turn::${String(entry.turnIndex ?? "")}::${entry.timestamp ?? ""}::${String(entry.agentName ?? "")}`;
13190
- }
13191
- var KIND_RANK = { event: 0, turn: 1, message: 2 };
13192
- var UNKNOWN_KIND_RANK = 99;
13193
- function assembleDebugLog(entries, readme) {
13194
- const seenAt = /* @__PURE__ */ new Map();
13195
- let latestMeta;
13196
- const timeline = [];
13197
- for (const entry of entries) {
13198
- if (entry.kind === "meta-snapshot") {
13199
- if (!latestMeta || (entry.timestamp ?? "") >= (latestMeta.timestamp ?? "")) {
13200
- latestMeta = entry;
13201
- }
13202
- continue;
13203
- }
13204
- const id = entry.kind === "turn" ? turnIdentity(entry) : JSON.stringify(entry);
13205
- const at = seenAt.get(id);
13206
- if (at !== void 0) {
13207
- if (entry.usage && !timeline[at].usage) timeline[at] = entry;
13208
- continue;
13209
- }
13210
- seenAt.set(id, timeline.length);
13211
- timeline.push(entry);
13212
- }
13213
- timeline.sort((a, b) => {
13214
- const ta = a.timestamp ?? "";
13215
- const tb = b.timestamp ?? "";
13216
- if (ta < tb) return -1;
13217
- if (ta > tb) return 1;
13218
- return (KIND_RANK[a.kind] ?? UNKNOWN_KIND_RANK) - (KIND_RANK[b.kind] ?? UNKNOWN_KIND_RANK);
13219
- });
13220
- const context = latestMeta?.meta?.context;
13221
- return { readme, sessionUsage: context?.sessionUsage, timeline, meta: latestMeta?.meta };
13222
- }
13223
- function withFreshMetaSnapshot(stored, fresh) {
13224
- return [...stored.filter((e) => e.kind !== "meta-snapshot"), fresh];
13225
- }
13226
-
13227
13328
  // src/utils/strip-agent-handlers.ts
13228
13329
  function stripAgentHandlers(agent) {
13229
13330
  const serializable = {};