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

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,25 @@ 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, since they stay in history; it is sent only to the
2506
+ * agent that wrote it. Costs history: one copy per change, cached after its first read.
2507
+ *
2508
+ * The framework's own volatile additions (fold suffix, retry nudges) stay a volatile tail in both
2509
+ * modes. Read once when the agent is installed.
2510
+ *
2511
+ * @beta
2512
+ */
2513
+ tailContextMode?: 'volatile' | 'stored';
2495
2514
  /**
2496
2515
  * Structured-output schema for this agent. When resolved to a schema on a turn, the model's
2497
2516
  * final (non-tool) answer is constrained to it instead of free text. Composes with `tools`;
@@ -3201,6 +3220,8 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
3201
3220
  * the resolved string in a `<system-reminder>` marker and injects it at the message tail.
3202
3221
  */
3203
3222
  private activeTailContextInput?;
3223
+ /** Whether the active agent's tail context is stored in history (`tailContextMode: 'stored'`). */
3224
+ private activeTailContextStored;
3204
3225
  /**
3205
3226
  * Active agent's structured-output schema selector (static value or per-turn resolver).
3206
3227
  * When it resolves to a schema, the model's final answer is constrained to it this turn.
@@ -4138,6 +4159,17 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
4138
4159
  */
4139
4160
  private appendDriverNotice;
4140
4161
  private appendToHistory;
4162
+ /** Stamp a message for history: its timestamp (unless it has one) and the active agent. */
4163
+ private tagMessage;
4164
+ /**
4165
+ * Write the active agent's tail context into history as a hidden note (`tailContextMode:
4166
+ * 'stored'`, GENC-1962), unless it is the same as the last one this agent stored. A tail that
4167
+ * resolves to nothing after there was one stores a note saying so, or the old one would still
4168
+ * read as current. `beforePendingUser`: the turn's first call, which sends the newest message (the
4169
+ * user's) separately, so the note goes in ahead of it. Either way the history only grows where
4170
+ * the next request already ends, which is what keeps earlier thinking replayable.
4171
+ */
4172
+ private storeAgentContext;
4141
4173
  /** Announce the current history to the host. */
4142
4174
  private notifyHistoryUpdated;
4143
4175
  }
@@ -10252,6 +10284,8 @@ export declare interface StatefulAgentInit<S> {
10252
10284
  * content; the framework frames it. Omit, or return an empty string, for none.
10253
10285
  */
10254
10286
  tailContext?: string | ((ctx: StatefulAgentContext<S>) => string | Promise<string>);
10287
+ /** Whether `tailContext` is sent fresh on every call or stored in history when it changes. See `AgentConfig.tailContextMode`. */
10288
+ tailContextMode?: AgentConfig['tailContextMode'];
10255
10289
  /**
10256
10290
  * Hook consulted when the model calls a tool that isn't dispatchable in the
10257
10291
  * 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.",
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.",
@@ -5345,6 +5345,15 @@ ${note.trim()}
5345
5345
  driverNote: kind
5346
5346
  };
5347
5347
  }
5348
+ 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.";
5349
+ var NO_CONTEXT = "There is nothing to note at the moment.";
5350
+ function agentContextNote(body) {
5351
+ return `<system-reminder>
5352
+ ${AGENT_CONTEXT_PREAMBLE}
5353
+
5354
+ ${body.trim() || NO_CONTEXT}
5355
+ </system-reminder>`;
5356
+ }
5348
5357
 
5349
5358
  // src/utils/preserved-user-messages.ts
5350
5359
  function freshUserMessages(toCompact) {
@@ -8456,6 +8465,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
8456
8465
  this.messageController = new AbortController();
8457
8466
  /** Capabilities provided on this driver by decorators (GENC-1660). Only the root's are used. */
8458
8467
  this.handlerCapabilities = /* @__PURE__ */ new Map();
8468
+ /** Whether the active agent's tail context is stored in history (`tailContextMode: 'stored'`). */
8469
+ this.activeTailContextStored = false;
8459
8470
  /**
8460
8471
  * Caches validated provider lookups per name within the current agent. Cleared
8461
8472
  * by `installAgent` so each new agent's static/function-resolved names are
@@ -9127,6 +9138,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
9127
9138
  this.activeCachePolicyInput = config.cachePolicy;
9128
9139
  this.activeThinkingPolicyInput = config.thinkingPolicy;
9129
9140
  this.activeTailContextInput = config.tailContext;
9141
+ this.activeTailContextStored = config.tailContextMode === "stored";
9130
9142
  this.activeResponseSchemaInput = config.responseSchema;
9131
9143
  this.activeFallbacks = config.fallbacks;
9132
9144
  this.activeOnUnresolvedTool = config.onUnresolvedTool;
@@ -10551,11 +10563,17 @@ ${tailNote}` : "";
10551
10563
 
10552
10564
  ${closing}` : "";
10553
10565
  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;
10566
+ if (this.activeTailContextStored) {
10567
+ const storedTail = await resolveTurnInput(this.activeTailContextInput, promptCtx);
10568
+ this.storeAgentContext(storedTail, firstLlmCall);
10569
+ }
10570
+ const ownContext = (m) => m.driverNote !== "agent-context" || m.agentName === this.activeAgentName;
10571
+ const primer = normalizeForProvider(
10572
+ [...this.primerHistory ?? [], ...transientPrimer ?? []].filter(ownContext)
10573
+ );
10574
+ const baseHistory = (firstLlmCall ? this.history.slice(0, -1) : this.history).filter(
10575
+ ownContext
10576
+ );
10559
10577
  firstLlmCall = false;
10560
10578
  const suspended = this.suspendedClocks();
10561
10579
  const condensedHistory = applyCondensation(
@@ -10591,7 +10609,8 @@ ${closing}` : "";
10591
10609
  resolveTurnInput(this.activeTemperatureInput, promptCtx),
10592
10610
  resolveTurnInput(this.activeToolChoiceInput, promptCtx),
10593
10611
  resolveTurnInput(this.activeCachePolicyInput, promptCtx),
10594
- resolveTurnInput(this.activeTailContextInput, promptCtx),
10612
+ // A stored tail was resolved and written into history above; only a volatile one is sent.
10613
+ this.activeTailContextStored ? Promise.resolve(void 0) : resolveTurnInput(this.activeTailContextInput, promptCtx),
10595
10614
  resolveTurnInput(this.activeResponseSchemaInput, promptCtx),
10596
10615
  // Only consulted on the first iteration (see `pinnedThinkingPolicy`); resolved
10597
10616
  // alongside the others so a resolver still sees the same turn context.
@@ -11299,7 +11318,12 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
11299
11318
  this.appendToHistory({ role: "assistant", content, excludeFromProvider: true });
11300
11319
  }
11301
11320
  appendToHistory(message) {
11302
- const tagged = {
11321
+ this.history = [...this.history, this.tagMessage(message)];
11322
+ this.notifyHistoryUpdated();
11323
+ }
11324
+ /** Stamp a message for history: its timestamp (unless it has one) and the active agent. */
11325
+ tagMessage(message) {
11326
+ return {
11303
11327
  ...message,
11304
11328
  // Stamp on first append; preserve any caller-supplied timestamp.
11305
11329
  timestamp: message.timestamp ?? (/* @__PURE__ */ new Date()).toISOString(),
@@ -11309,7 +11333,24 @@ RECOVERY: this tool failed once \u2014 you may retry it, or take a different val
11309
11333
  agentLabel: this.activeAgentLabel
11310
11334
  } : {}
11311
11335
  };
11312
- this.history = [...this.history, tagged];
11336
+ }
11337
+ /**
11338
+ * Write the active agent's tail context into history as a hidden note (`tailContextMode:
11339
+ * 'stored'`, GENC-1962), unless it is the same as the last one this agent stored. A tail that
11340
+ * resolves to nothing after there was one stores a note saying so, or the old one would still
11341
+ * read as current. `beforePendingUser`: the turn's first call, which sends the newest message (the
11342
+ * user's) separately, so the note goes in ahead of it. Either way the history only grows where
11343
+ * the next request already ends, which is what keeps earlier thinking replayable.
11344
+ */
11345
+ storeAgentContext(tail, beforePendingUser) {
11346
+ const body = (tail ?? "").trim();
11347
+ const previous = [...this.history].reverse().find((m) => m.driverNote === "agent-context" && m.agentName === this.activeAgentName);
11348
+ if (!body && !previous) return;
11349
+ const content = agentContextNote(body);
11350
+ if (previous?.content === content) return;
11351
+ const note = this.tagMessage({ role: "user", content, driverNote: "agent-context" });
11352
+ const at = beforePendingUser && this.history.length > 0 ? this.history.length - 1 : this.history.length;
11353
+ this.history = [...this.history.slice(0, at), note, ...this.history.slice(at)];
11313
11354
  this.notifyHistoryUpdated();
11314
11355
  }
11315
11356
  /** Announce the current history to the host. */
@@ -12603,6 +12644,18 @@ function bindStateOrDefault(hook, getState) {
12603
12644
  return hook({ ...ctx, state });
12604
12645
  };
12605
12646
  }
12647
+ function forwardedOptions(opts) {
12648
+ return {
12649
+ primerHistory: opts.primerHistory,
12650
+ subAgents: opts.subAgents,
12651
+ manualSelection: opts.manualSelection,
12652
+ chatInputDuringExecution: opts.chatInputDuringExecution,
12653
+ tailContextMode: opts.tailContextMode,
12654
+ notResumableMessage: opts.notResumableMessage,
12655
+ resumeOnRestore: opts.resumeOnRestore,
12656
+ contextReserve: opts.contextReserve
12657
+ };
12658
+ }
12606
12659
  function defineStatefulAgent(opts) {
12607
12660
  let state;
12608
12661
  const assertNoFolds = (handlers) => {
@@ -12704,10 +12757,7 @@ function defineStatefulAgent(opts) {
12704
12757
  const base = {
12705
12758
  name: opts.name,
12706
12759
  displayName: wrappedDisplayName,
12707
- primerHistory: opts.primerHistory,
12708
- subAgents: opts.subAgents,
12709
- manualSelection: opts.manualSelection,
12710
- chatInputDuringExecution: opts.chatInputDuringExecution,
12760
+ ...forwardedOptions(opts),
12711
12761
  toolDefinitions: wrappedTools,
12712
12762
  toolHandlers: wrappedHandlers,
12713
12763
  provider: wrappedProvider,
@@ -12719,9 +12769,6 @@ function defineStatefulAgent(opts) {
12719
12769
  onUnresolvedTool: wrappedOnUnresolvedTool,
12720
12770
  finishGuard: wrappedFinishGuard,
12721
12771
  resumable: wrappedResumable,
12722
- notResumableMessage: opts.notResumableMessage,
12723
- resumeOnRestore: opts.resumeOnRestore,
12724
- contextReserve: opts.contextReserve,
12725
12772
  // Bound to the live state, so the autopilot's resolvers see what this agent's do (GENC-1660).
12726
12773
  ...opts.autopilot && {
12727
12774
  autopilot: {