@genesislcap/ai-assistant 15.99.1 → 15.99.2-GENC-1962.3

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.
@@ -42307,6 +42307,38 @@
42307
42307
  "endIndex": 6
42308
42308
  }
42309
42309
  },
42310
+ {
42311
+ "kind": "PropertySignature",
42312
+ "canonicalReference": "@genesislcap/ai-assistant!StatefulAgentInit#tailContextMode:member",
42313
+ "docComment": "/**\n * Whether `tailContext` is sent fresh on every call or stored in history when it changes. See `AgentConfig.tailContextMode`.\n */\n",
42314
+ "excerptTokens": [
42315
+ {
42316
+ "kind": "Content",
42317
+ "text": "tailContextMode?: "
42318
+ },
42319
+ {
42320
+ "kind": "Reference",
42321
+ "text": "AgentConfig",
42322
+ "canonicalReference": "@genesislcap/ai-assistant!AgentConfig:type"
42323
+ },
42324
+ {
42325
+ "kind": "Content",
42326
+ "text": "['tailContextMode']"
42327
+ },
42328
+ {
42329
+ "kind": "Content",
42330
+ "text": ";"
42331
+ }
42332
+ ],
42333
+ "isReadonly": false,
42334
+ "isOptional": true,
42335
+ "releaseTag": "Beta",
42336
+ "name": "tailContextMode",
42337
+ "propertyTypeTokenRange": {
42338
+ "startIndex": 1,
42339
+ "endIndex": 3
42340
+ }
42341
+ },
42310
42342
  {
42311
42343
  "kind": "PropertySignature",
42312
42344
  "canonicalReference": "@genesislcap/ai-assistant!StatefulAgentInit#temperature:member",
@@ -2492,6 +2492,28 @@ declare interface BaseAgentConfig {
2492
2492
  * @beta
2493
2493
  */
2494
2494
  tailContext?: TailContextInput;
2495
+ /**
2496
+ * Where {@link BaseAgentConfig.tailContext} goes on the wire (GENC-1962).
2497
+ *
2498
+ * - `'volatile'` (the default): appended to every request and never stored. Cheapest on the cache,
2499
+ * but on a model with preserved thinking (Anthropic's 5.5 family) a request that carried a tail
2500
+ * produces thinking that no later request can replay: the tail is gone by the next request, so
2501
+ * the prefix the thinking was made against is never rebuilt, and the transport leaves it out.
2502
+ * - `'stored'`: stored in history as a hidden note (`driverNote: 'agent-context'`), and only when it
2503
+ * differs from the agent's last stored note. History then only grows at the end, so thinking
2504
+ * produced within a tool loop stays replayable for as long as the system prompt and tools do.
2505
+ * The note says it replaces earlier ones; it is sent only to the agent that wrote it. Earlier
2506
+ * notes stay in history while the agent's system prompt and tools hold, and are removed on the
2507
+ * first call where either has changed, since nothing before that call can be replayed or read
2508
+ * from the cache. Costs history: one copy per change within a stable run, cached after its first
2509
+ * read.
2510
+ *
2511
+ * The framework's own volatile additions (fold suffix, retry nudges) stay a volatile tail in both
2512
+ * modes. Read once when the agent is installed.
2513
+ *
2514
+ * @beta
2515
+ */
2516
+ tailContextMode?: 'volatile' | 'stored';
2495
2517
  /**
2496
2518
  * Structured-output schema for this agent. When resolved to a schema on a turn, the model's
2497
2519
  * final (non-tool) answer is constrained to it instead of free text. Composes with `tools`;
@@ -3201,6 +3223,14 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
3201
3223
  * the resolved string in a `<system-reminder>` marker and injects it at the message tail.
3202
3224
  */
3203
3225
  private activeTailContextInput?;
3226
+ /** Whether the active agent's tail context is stored in history (`tailContextMode: 'stored'`). */
3227
+ private activeTailContextStored;
3228
+ /**
3229
+ * Per agent with a stored tail, a digest of the system prompt and tools its last call was sent
3230
+ * with. When the next call's differs, nothing before it can be replayed or read from the cache,
3231
+ * so that agent's superseded context notes are dropped (see `storeAgentContext`).
3232
+ */
3233
+ private readonly storedContextHeaders;
3204
3234
  /**
3205
3235
  * Active agent's structured-output schema selector (static value or per-turn resolver).
3206
3236
  * When it resolves to a schema, the model's final answer is constrained to it this turn.
@@ -4138,6 +4168,26 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
4138
4168
  */
4139
4169
  private appendDriverNotice;
4140
4170
  private appendToHistory;
4171
+ /** Stamp a message for history: its timestamp (unless it has one) and the active agent. */
4172
+ private tagMessage;
4173
+ /**
4174
+ * Write the active agent's tail context into history as a hidden note (`tailContextMode:
4175
+ * 'stored'`, GENC-1962), unless it is the same as the last one this agent stored. A tail that
4176
+ * resolves to nothing after there was one stores a note saying so, or the old one would still
4177
+ * read as current. `beforePendingUser`: the turn's first call, which sends the newest message (the
4178
+ * user's) separately, so the note goes in ahead of it. While the system prompt and tools hold,
4179
+ * the history only grows where the next request already ends, which is what keeps earlier
4180
+ * thinking replayable.
4181
+ *
4182
+ * `header` is this call's system prompt and tools (`requestHeaderDigest`). When it differs from
4183
+ * the agent's previous call, the cache and every earlier thinking block are lost anyway, so the
4184
+ * agent's superseded notes are removed and only the current one is kept: otherwise every change
4185
+ * of state stays in history for the rest of the conversation (measured on a Create bootstrap,
4186
+ * 39 notes and about 41K tokens on every call).
4187
+ */
4188
+ private storeAgentContext;
4189
+ /** A digest of what a request sends ahead of its messages: the system prompt and the tools. */
4190
+ private requestHeaderDigest;
4141
4191
  /** Announce the current history to the host. */
4142
4192
  private notifyHistoryUpdated;
4143
4193
  }
@@ -10252,6 +10302,8 @@ export declare interface StatefulAgentInit<S> {
10252
10302
  * content; the framework frames it. Omit, or return an empty string, for none.
10253
10303
  */
10254
10304
  tailContext?: string | ((ctx: StatefulAgentContext<S>) => string | Promise<string>);
10305
+ /** Whether `tailContext` is sent fresh on every call or stored in history when it changes. See `AgentConfig.tailContextMode`. */
10306
+ tailContextMode?: AgentConfig['tailContextMode'];
10255
10307
  /**
10256
10308
  * Hook consulted when the model calls a tool that isn't dispatchable in the
10257
10309
  * current state — a *stale* tool (valid in an earlier state of this agent) or
@@ -5299,7 +5299,7 @@ var DEBUG_LOG_README = [
5299
5299
  "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.",
5300
5300
  "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.",
5301
5301
  "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.",
5302
- "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.",
5302
+ "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.",
5303
5303
  "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 an N-M `turnIndex`, 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.",
5304
5304
  "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 numbered under the parent turn that activated them ('3-1', '3-2', \u2026, and a nested sub-agent contributes '3-2-1', \u2026), 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.",
5305
5305
  "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.",
@@ -5316,6 +5316,59 @@ var DEBUG_LOG_README = [
5316
5316
  "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."
5317
5317
  ];
5318
5318
 
5319
+ // src/state/persistence/diagnostics.ts
5320
+ var FNV_OFFSET_BASIS2 = 2166136261;
5321
+ var FNV_PRIME2 = 16777619;
5322
+ var DIGEST_RADIX = 36;
5323
+ function configDigest(json) {
5324
+ let a = FNV_OFFSET_BASIS2;
5325
+ let b = FNV_PRIME2;
5326
+ for (let i = 0; i < json.length; i += 1) {
5327
+ const c = json.charCodeAt(i);
5328
+ a = Math.imul(a ^ c, FNV_PRIME2) >>> 0;
5329
+ b = Math.imul(b ^ c, FNV_OFFSET_BASIS2) >>> 0;
5330
+ }
5331
+ return [json.length, a, b].map((n) => n.toString(DIGEST_RADIX)).join("-");
5332
+ }
5333
+ function turnIdentity(entry) {
5334
+ return `turn::${String(entry.turnIndex ?? "")}::${entry.timestamp ?? ""}::${String(entry.agentName ?? "")}`;
5335
+ }
5336
+ var KIND_RANK = { event: 0, turn: 1, message: 2 };
5337
+ var UNKNOWN_KIND_RANK = 99;
5338
+ function assembleDebugLog(entries, readme) {
5339
+ const seenAt = /* @__PURE__ */ new Map();
5340
+ let latestMeta;
5341
+ const timeline = [];
5342
+ for (const entry of entries) {
5343
+ if (entry.kind === "meta-snapshot") {
5344
+ if (!latestMeta || (entry.timestamp ?? "") >= (latestMeta.timestamp ?? "")) {
5345
+ latestMeta = entry;
5346
+ }
5347
+ continue;
5348
+ }
5349
+ const id = entry.kind === "turn" ? turnIdentity(entry) : JSON.stringify(entry);
5350
+ const at = seenAt.get(id);
5351
+ if (at !== void 0) {
5352
+ if (entry.usage && !timeline[at].usage) timeline[at] = entry;
5353
+ continue;
5354
+ }
5355
+ seenAt.set(id, timeline.length);
5356
+ timeline.push(entry);
5357
+ }
5358
+ timeline.sort((a, b) => {
5359
+ const ta = a.timestamp ?? "";
5360
+ const tb = b.timestamp ?? "";
5361
+ if (ta < tb) return -1;
5362
+ if (ta > tb) return 1;
5363
+ return (KIND_RANK[a.kind] ?? UNKNOWN_KIND_RANK) - (KIND_RANK[b.kind] ?? UNKNOWN_KIND_RANK);
5364
+ });
5365
+ const context = latestMeta?.meta?.context;
5366
+ return { readme, sessionUsage: context?.sessionUsage, timeline, meta: latestMeta?.meta };
5367
+ }
5368
+ function withFreshMetaSnapshot(stored, fresh) {
5369
+ return [...stored.filter((e) => e.kind !== "meta-snapshot"), fresh];
5370
+ }
5371
+
5319
5372
  // src/utils/delegated-message.ts
5320
5373
  var DEFAULT_DELEGATE_FRAMING = "Sent on the user's behalf.";
5321
5374
  function delegatedFields(options) {
@@ -5345,6 +5398,15 @@ ${note.trim()}
5345
5398
  driverNote: kind
5346
5399
  };
5347
5400
  }
5401
+ 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.";
5402
+ var NO_CONTEXT = "There is nothing to note at the moment.";
5403
+ function agentContextNote(body) {
5404
+ return `<system-reminder>
5405
+ ${AGENT_CONTEXT_PREAMBLE}
5406
+
5407
+ ${body.trim() || NO_CONTEXT}
5408
+ </system-reminder>`;
5409
+ }
5348
5410
 
5349
5411
  // src/utils/preserved-user-messages.ts
5350
5412
  function freshUserMessages(toCompact) {
@@ -8456,6 +8518,14 @@ var ChatDriver = class _ChatDriver extends EventTarget {
8456
8518
  this.messageController = new AbortController();
8457
8519
  /** Capabilities provided on this driver by decorators (GENC-1660). Only the root's are used. */
8458
8520
  this.handlerCapabilities = /* @__PURE__ */ new Map();
8521
+ /** Whether the active agent's tail context is stored in history (`tailContextMode: 'stored'`). */
8522
+ this.activeTailContextStored = false;
8523
+ /**
8524
+ * Per agent with a stored tail, a digest of the system prompt and tools its last call was sent
8525
+ * with. When the next call's differs, nothing before it can be replayed or read from the cache,
8526
+ * so that agent's superseded context notes are dropped (see `storeAgentContext`).
8527
+ */
8528
+ this.storedContextHeaders = /* @__PURE__ */ new Map();
8459
8529
  /**
8460
8530
  * Caches validated provider lookups per name within the current agent. Cleared
8461
8531
  * by `installAgent` so each new agent's static/function-resolved names are
@@ -9127,6 +9197,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
9127
9197
  this.activeCachePolicyInput = config.cachePolicy;
9128
9198
  this.activeThinkingPolicyInput = config.thinkingPolicy;
9129
9199
  this.activeTailContextInput = config.tailContext;
9200
+ this.activeTailContextStored = config.tailContextMode === "stored";
9130
9201
  this.activeResponseSchemaInput = config.responseSchema;
9131
9202
  this.activeFallbacks = config.fallbacks;
9132
9203
  this.activeOnUnresolvedTool = config.onUnresolvedTool;
@@ -10551,11 +10622,21 @@ ${tailNote}` : "";
10551
10622
 
10552
10623
  ${closing}` : "";
10553
10624
  const frameworkSystemSuffix = `${foldSuffix}${firstCallNote}${closingNote}${retryNudge}`;
10554
- const primer = normalizeForProvider([
10555
- ...this.primerHistory ?? [],
10556
- ...transientPrimer ?? []
10557
- ]);
10558
- const baseHistory = firstLlmCall ? this.history.slice(0, -1) : this.history;
10625
+ if (this.activeTailContextStored) {
10626
+ const storedTail = await resolveTurnInput(this.activeTailContextInput, promptCtx);
10627
+ this.storeAgentContext(
10628
+ storedTail,
10629
+ firstLlmCall,
10630
+ this.requestHeaderDigest(resolvedSystemPrompt)
10631
+ );
10632
+ }
10633
+ const ownContext = (m) => m.driverNote !== "agent-context" || m.agentName === this.activeAgentName;
10634
+ const primer = normalizeForProvider(
10635
+ [...this.primerHistory ?? [], ...transientPrimer ?? []].filter(ownContext)
10636
+ );
10637
+ const baseHistory = (firstLlmCall ? this.history.slice(0, -1) : this.history).filter(
10638
+ ownContext
10639
+ );
10559
10640
  firstLlmCall = false;
10560
10641
  const suspended = this.suspendedClocks();
10561
10642
  const condensedHistory = applyCondensation(
@@ -10591,7 +10672,8 @@ ${closing}` : "";
10591
10672
  resolveTurnInput(this.activeTemperatureInput, promptCtx),
10592
10673
  resolveTurnInput(this.activeToolChoiceInput, promptCtx),
10593
10674
  resolveTurnInput(this.activeCachePolicyInput, promptCtx),
10594
- resolveTurnInput(this.activeTailContextInput, promptCtx),
10675
+ // A stored tail was resolved and written into history above; only a volatile one is sent.
10676
+ this.activeTailContextStored ? Promise.resolve(void 0) : resolveTurnInput(this.activeTailContextInput, promptCtx),
10595
10677
  resolveTurnInput(this.activeResponseSchemaInput, promptCtx),
10596
10678
  // Only consulted on the first iteration (see `pinnedThinkingPolicy`); resolved
10597
10679
  // alongside the others so a resolver still sees the same turn context.
@@ -11299,7 +11381,12 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
11299
11381
  this.appendToHistory({ role: "assistant", content, excludeFromProvider: true });
11300
11382
  }
11301
11383
  appendToHistory(message) {
11302
- const tagged = {
11384
+ this.history = [...this.history, this.tagMessage(message)];
11385
+ this.notifyHistoryUpdated();
11386
+ }
11387
+ /** Stamp a message for history: its timestamp (unless it has one) and the active agent. */
11388
+ tagMessage(message) {
11389
+ return {
11303
11390
  ...message,
11304
11391
  // Stamp on first append; preserve any caller-supplied timestamp.
11305
11392
  timestamp: message.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
@@ -11309,9 +11396,53 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
11309
11396
  agentLabel: this.activeAgentLabel
11310
11397
  } : {}
11311
11398
  };
11312
- this.history = [...this.history, tagged];
11399
+ }
11400
+ /**
11401
+ * Write the active agent's tail context into history as a hidden note (`tailContextMode:
11402
+ * 'stored'`, GENC-1962), unless it is the same as the last one this agent stored. A tail that
11403
+ * resolves to nothing after there was one stores a note saying so, or the old one would still
11404
+ * read as current. `beforePendingUser`: the turn's first call, which sends the newest message (the
11405
+ * user's) separately, so the note goes in ahead of it. While the system prompt and tools hold,
11406
+ * the history only grows where the next request already ends, which is what keeps earlier
11407
+ * thinking replayable.
11408
+ *
11409
+ * `header` is this call's system prompt and tools (`requestHeaderDigest`). When it differs from
11410
+ * the agent's previous call, the cache and every earlier thinking block are lost anyway, so the
11411
+ * agent's superseded notes are removed and only the current one is kept: otherwise every change
11412
+ * of state stays in history for the rest of the conversation (measured on a Create bootstrap,
11413
+ * 39 notes and about 41K tokens on every call).
11414
+ */
11415
+ storeAgentContext(tail, beforePendingUser, header) {
11416
+ const agent = this.activeAgentName ?? "";
11417
+ const previousHeader = this.storedContextHeaders.get(agent);
11418
+ this.storedContextHeaders.set(agent, header);
11419
+ const prefixBroken = previousHeader !== void 0 && previousHeader !== header;
11420
+ const isOwnNote = (m) => m.driverNote === "agent-context" && m.agentName === this.activeAgentName;
11421
+ const body = (tail ?? "").trim();
11422
+ const previous = [...this.history].reverse().find(isOwnNote);
11423
+ const content = agentContextNote(body);
11424
+ const append = Boolean(body || previous) && previous?.content !== content;
11425
+ const superseded = this.history.filter((m) => isOwnNote(m) && (append || m !== previous));
11426
+ if (!append && !(prefixBroken && superseded.length > 0)) return;
11427
+ let history = this.history;
11428
+ if (prefixBroken) history = history.filter((m) => !superseded.includes(m));
11429
+ if (append) {
11430
+ const note = this.tagMessage({ role: "user", content, driverNote: "agent-context" });
11431
+ const at = beforePendingUser && history.length > 0 ? history.length - 1 : history.length;
11432
+ history = [...history.slice(0, at), note, ...history.slice(at)];
11433
+ }
11434
+ this.history = history;
11313
11435
  this.notifyHistoryUpdated();
11314
11436
  }
11437
+ /** A digest of what a request sends ahead of its messages: the system prompt and the tools. */
11438
+ requestHeaderDigest(systemPrompt) {
11439
+ return configDigest(
11440
+ JSON.stringify([
11441
+ systemPrompt ?? "",
11442
+ this.toolDefinitions.map((t) => [t.name, t.description, t.parameters])
11443
+ ])
11444
+ );
11445
+ }
11315
11446
  /** Announce the current history to the host. */
11316
11447
  notifyHistoryUpdated() {
11317
11448
  this.dispatchEvent(
@@ -12603,6 +12734,18 @@ function bindStateOrDefault(hook, getState) {
12603
12734
  return hook({ ...ctx, state });
12604
12735
  };
12605
12736
  }
12737
+ function forwardedOptions(opts) {
12738
+ return {
12739
+ primerHistory: opts.primerHistory,
12740
+ subAgents: opts.subAgents,
12741
+ manualSelection: opts.manualSelection,
12742
+ chatInputDuringExecution: opts.chatInputDuringExecution,
12743
+ tailContextMode: opts.tailContextMode,
12744
+ notResumableMessage: opts.notResumableMessage,
12745
+ resumeOnRestore: opts.resumeOnRestore,
12746
+ contextReserve: opts.contextReserve
12747
+ };
12748
+ }
12606
12749
  function defineStatefulAgent(opts) {
12607
12750
  let state;
12608
12751
  const assertNoFolds = (handlers) => {
@@ -12704,10 +12847,7 @@ function defineStatefulAgent(opts) {
12704
12847
  const base = {
12705
12848
  name: opts.name,
12706
12849
  displayName: wrappedDisplayName,
12707
- primerHistory: opts.primerHistory,
12708
- subAgents: opts.subAgents,
12709
- manualSelection: opts.manualSelection,
12710
- chatInputDuringExecution: opts.chatInputDuringExecution,
12850
+ ...forwardedOptions(opts),
12711
12851
  toolDefinitions: wrappedTools,
12712
12852
  toolHandlers: wrappedHandlers,
12713
12853
  provider: wrappedProvider,
@@ -12719,9 +12859,6 @@ function defineStatefulAgent(opts) {
12719
12859
  onUnresolvedTool: wrappedOnUnresolvedTool,
12720
12860
  finishGuard: wrappedFinishGuard,
12721
12861
  resumable: wrappedResumable,
12722
- notResumableMessage: opts.notResumableMessage,
12723
- resumeOnRestore: opts.resumeOnRestore,
12724
- contextReserve: opts.contextReserve,
12725
12862
  // Bound to the live state, so the autopilot's resolvers see what this agent's do (GENC-1660).
12726
12863
  ...opts.autopilot && {
12727
12864
  autopilot: {
@@ -13076,59 +13213,6 @@ function describeInteraction(input) {
13076
13213
  };
13077
13214
  }
13078
13215
 
13079
- // src/state/persistence/diagnostics.ts
13080
- var FNV_OFFSET_BASIS2 = 2166136261;
13081
- var FNV_PRIME2 = 16777619;
13082
- var DIGEST_RADIX = 36;
13083
- function configDigest(json) {
13084
- let a = FNV_OFFSET_BASIS2;
13085
- let b = FNV_PRIME2;
13086
- for (let i = 0; i < json.length; i += 1) {
13087
- const c = json.charCodeAt(i);
13088
- a = Math.imul(a ^ c, FNV_PRIME2) >>> 0;
13089
- b = Math.imul(b ^ c, FNV_OFFSET_BASIS2) >>> 0;
13090
- }
13091
- return [json.length, a, b].map((n) => n.toString(DIGEST_RADIX)).join("-");
13092
- }
13093
- function turnIdentity(entry) {
13094
- return `turn::${String(entry.turnIndex ?? "")}::${entry.timestamp ?? ""}::${String(entry.agentName ?? "")}`;
13095
- }
13096
- var KIND_RANK = { event: 0, turn: 1, message: 2 };
13097
- var UNKNOWN_KIND_RANK = 99;
13098
- function assembleDebugLog(entries, readme) {
13099
- const seenAt = /* @__PURE__ */ new Map();
13100
- let latestMeta;
13101
- const timeline = [];
13102
- for (const entry of entries) {
13103
- if (entry.kind === "meta-snapshot") {
13104
- if (!latestMeta || (entry.timestamp ?? "") >= (latestMeta.timestamp ?? "")) {
13105
- latestMeta = entry;
13106
- }
13107
- continue;
13108
- }
13109
- const id = entry.kind === "turn" ? turnIdentity(entry) : JSON.stringify(entry);
13110
- const at = seenAt.get(id);
13111
- if (at !== void 0) {
13112
- if (entry.usage && !timeline[at].usage) timeline[at] = entry;
13113
- continue;
13114
- }
13115
- seenAt.set(id, timeline.length);
13116
- timeline.push(entry);
13117
- }
13118
- timeline.sort((a, b) => {
13119
- const ta = a.timestamp ?? "";
13120
- const tb = b.timestamp ?? "";
13121
- if (ta < tb) return -1;
13122
- if (ta > tb) return 1;
13123
- return (KIND_RANK[a.kind] ?? UNKNOWN_KIND_RANK) - (KIND_RANK[b.kind] ?? UNKNOWN_KIND_RANK);
13124
- });
13125
- const context = latestMeta?.meta?.context;
13126
- return { readme, sessionUsage: context?.sessionUsage, timeline, meta: latestMeta?.meta };
13127
- }
13128
- function withFreshMetaSnapshot(stored, fresh) {
13129
- return [...stored.filter((e) => e.kind !== "meta-snapshot"), fresh];
13130
- }
13131
-
13132
13216
  // src/utils/strip-agent-handlers.ts
13133
13217
  function stripAgentHandlers(agent) {
13134
13218
  const serializable = {};