@genesislcap/ai-assistant 15.35.3 → 15.35.4-FUI-0.9

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.
Files changed (43) hide show
  1. package/dist/ai-assistant.api.json +483 -0
  2. package/dist/ai-assistant.d.ts +213 -0
  3. package/dist/chat-driver.cjs +221 -4
  4. package/dist/chat-driver.cjs.map +2 -2
  5. package/dist/chat-driver.mjs +221 -4
  6. package/dist/chat-driver.mjs.map +2 -2
  7. package/dist/custom-elements.json +1189 -827
  8. package/dist/dts/components/ai-driver/ai-driver.d.ts +31 -0
  9. package/dist/dts/components/ai-driver/ai-driver.d.ts.map +1 -1
  10. package/dist/dts/components/chat-bubble/chat-bubble.d.ts.map +1 -1
  11. package/dist/dts/components/chat-bubble/chat-bubble.template.d.ts.map +1 -1
  12. package/dist/dts/components/chat-driver/chat-driver.d.ts +93 -0
  13. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  14. package/dist/dts/components/chat-markdown/chat-markdown.d.ts +29 -0
  15. package/dist/dts/components/chat-markdown/chat-markdown.d.ts.map +1 -1
  16. package/dist/dts/components/halo-overlay.d.ts +30 -0
  17. package/dist/dts/components/halo-overlay.d.ts.map +1 -1
  18. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +17 -0
  19. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
  20. package/dist/dts/main/main.template.d.ts.map +1 -1
  21. package/dist/dts/state/persistence/index.d.ts +1 -0
  22. package/dist/dts/state/persistence/index.d.ts.map +1 -1
  23. package/dist/dts/state/persistence/session-persister.d.ts +12 -0
  24. package/dist/dts/state/persistence/session-persister.d.ts.map +1 -1
  25. package/dist/dts/state/persistence/session-snapshot.d.ts +14 -0
  26. package/dist/dts/state/persistence/session-snapshot.d.ts.map +1 -1
  27. package/dist/dts/suggestions/chat-suggestions.d.ts +7 -0
  28. package/dist/dts/suggestions/chat-suggestions.d.ts.map +1 -1
  29. package/dist/dts/utils/condense-history.d.ts +114 -0
  30. package/dist/dts/utils/condense-history.d.ts.map +1 -1
  31. package/dist/esm/components/chat-bubble/chat-bubble.js +8 -0
  32. package/dist/esm/components/chat-bubble/chat-bubble.template.js +5 -3
  33. package/dist/esm/components/chat-driver/chat-driver.js +140 -17
  34. package/dist/esm/components/chat-markdown/chat-markdown.js +132 -1
  35. package/dist/esm/components/halo-overlay.js +96 -8
  36. package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +17 -0
  37. package/dist/esm/main/main.template.js +95 -45
  38. package/dist/esm/state/persistence/session-persister.js +63 -15
  39. package/dist/esm/state/persistence/session-snapshot.js +2 -17
  40. package/dist/esm/suggestions/chat-suggestions.js +11 -3
  41. package/dist/esm/utils/condense-history.js +123 -0
  42. package/docs/styling.md +120 -0
  43. package/package.json +18 -18
@@ -18,6 +18,7 @@ import type { ChatThinkingPolicy } from '@genesislcap/foundation-ai';
18
18
  import type { ChatToolChoice } from '@genesislcap/foundation-ai';
19
19
  import type { ChatToolDefinition } from '@genesislcap/foundation-ai';
20
20
  import type { ChatToolHandlers } from '@genesislcap/foundation-ai';
21
+ import type { CondensePolicy } from '@genesislcap/foundation-ai';
21
22
  import { Container } from '@genesislcap/web-core';
22
23
  import { ElementStyles } from '@genesislcap/web-core';
23
24
  import { GenesisElement } from '@genesislcap/web-core';
@@ -650,6 +651,27 @@ export declare class AiChatMarkdown extends GenesisElement {
650
651
  content: string;
651
652
  /** @internal */
652
653
  renderMarkdown(): string;
654
+ /**
655
+ * Tag the generated elements with shadow parts so an embedding app can style them.
656
+ *
657
+ * Takes the tree DOMPurify built rather than re-parsing its serialised output: `content` changes
658
+ * on every streamed chunk, so a second parse/serialise round trip would run per chunk over the
659
+ * whole message, and the string the browser finally parses is then serialised straight from the
660
+ * tree DOMPurify checked. Parse/serialise mismatches are where mXSS bypasses have historically
661
+ * lived, and this walk has no need to introduce one.
662
+ *
663
+ * Only ever *adds* attributes, to DOM that has already been cleared - so it is not itself
664
+ * sanitiser surface.
665
+ *
666
+ * Lists additionally carry a level: a top-level list is `md-ul md-ul-level-1`, a list nested
667
+ * inside it is `md-ul-level-2`, and an `li` takes the level of the list holding it. Levels are
668
+ * clamped at `MAX_LIST_LEVEL`, so a list deeper than that answers to the deepest level
669
+ * rather than to a name no host forwards. Chat markdown rarely nests, so this is a safety valve
670
+ * rather than a feature - without it, every list at every depth would answer to one selector and
671
+ * there would be no way to tell them apart afterwards. Depth comes from walking the tree rather
672
+ * than from marked's renderers, which are invoked innermost-first and so cannot count downwards.
673
+ */
674
+ private annotateParts;
653
675
  }
654
676
 
655
677
  /**
@@ -779,6 +801,36 @@ export declare interface AiDriver extends EventTarget {
779
801
  * to project, and a caller falls back to {@link AiDriver.getRawHistory}.
780
802
  */
781
803
  getHistoryForPersistence?(): ChatMessage[];
804
+ /**
805
+ * The `condenseWhen` policies that have NOT fired yet, for the tool calls in `messages` — the
806
+ * transcript being persisted — in a clock-independent form a later
807
+ * {@link AiDriver.restoreCondensePolicies} can re-register (GENC-1632). The companion of
808
+ * {@link AiDriver.getHistoryForPersistence}: that stores already-collapsed payloads as stubs;
809
+ * this keeps the not-yet-collapsed ones collapsible across a reload, where they would otherwise
810
+ * ride every provider call for the rest of the session. Optional, like its companion — a driver
811
+ * without condensation has none.
812
+ *
813
+ * @beta
814
+ */
815
+ getCondensePoliciesForPersistence?(messages: readonly ChatMessage[]): PersistedCondensePolicy[];
816
+ /**
817
+ * Re-register policies from {@link AiDriver.getCondensePoliciesForPersistence} against a restored
818
+ * transcript (GENC-1632). Call after {@link AiDriver.loadHistory}: entries whose tool call is not
819
+ * in the loaded history are dropped. Tolerates `undefined` and malformed entries (an older or
820
+ * damaged snapshot), which are ignored.
821
+ *
822
+ * Returns how many entries were actually re-armed (`restored`) and how many of those are parked
823
+ * pending the next agent activation (`awaitingReactivation`) — narrower than `entries.length`,
824
+ * which counts what was offered, not what was accepted (a malformed entry, a trimmed-away call, or
825
+ * a first-wins duplicate is dropped silently). A caller logging the outcome needs this split to
826
+ * tell "all re-armed" from "none did".
827
+ *
828
+ * @beta
829
+ */
830
+ restoreCondensePolicies?(entries: readonly unknown[] | undefined): {
831
+ restored: number;
832
+ awaitingReactivation: number;
833
+ };
782
834
  /**
783
835
  * The live `AgentConfig` currently active in the driver — the instance whose
784
836
  * `onActivate` ran, so its `serialize`/`getDebugSnapshot` closures hold live
@@ -1524,8 +1576,29 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
1524
1576
  * provider call to collapse stale payloads from the model-bound history only.
1525
1577
  * Accumulates across agents on a shared driver (a superseded read collapses no
1526
1578
  * matter which agent made it) and is never cleared — it dies with the driver.
1579
+ *
1580
+ * "Dies with the driver" used to mean a page reload silently disarmed every policy that had
1581
+ * not fired yet: the restored transcript carried the full payload and nothing was left to
1582
+ * collapse it, so it rode every later provider call (GENC-1632). The unfired entries are now
1583
+ * persisted with the session and re-registered on restore — see
1584
+ * {@link ChatDriver.getCondensePoliciesForPersistence} and
1585
+ * {@link ChatDriver.restoreCondensePolicies}.
1527
1586
  */
1528
1587
  private readonly condensePolicies;
1588
+ /**
1589
+ * Restored policies whose owning activation was still live at save time, waiting for that agent
1590
+ * to be re-installed so they can be stamped with the activation it resumes in (GENC-1632).
1591
+ *
1592
+ * They cannot be stamped at restore time. On a fresh page `activeAgentName` is unset, so the
1593
+ * first `installAgent` after the reload is a "name change" and advances `currentActivation` —
1594
+ * which is exactly the `agentEnd` signal. An entry stamped before that bump reads as belonging
1595
+ * to an activation that has ended, and it and every `phaseEnd` entry (through the `agentEnd`
1596
+ * backstop) collapse on the first provider call after the reload, mid-flow. For Create's
1597
+ * Planning phase that is the uploaded scope document vanishing the moment the user carries on
1598
+ * talking about it — a worse failure than the one being fixed. So the stamp is deferred to that
1599
+ * `installAgent`, and consumed there once whichever agent it installs.
1600
+ */
1601
+ private readonly condenseAwaitingReactivation;
1529
1602
  /**
1530
1603
  * Monotonic model-call counter for the driver's whole lifetime — the age clock
1531
1604
  * for `condenseWhen({ on: { kind: 'age' } })`. The per-`sendMessage` `iterations`
@@ -2132,6 +2205,77 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
2132
2205
  * unaffected — which is what makes the elision recoverable.
2133
2206
  */
2134
2207
  getHistoryForPersistence(): ChatMessage[];
2208
+ /** The four condensation clocks as they read now. */
2209
+ private condenseClocks;
2210
+ /**
2211
+ * The `condenseWhen` policies that have not fired yet, for the calls in `messages`, in the
2212
+ * clock-independent form {@link ChatDriver.restoreCondensePolicies} re-registers. See
2213
+ * {@link AiDriver.getCondensePoliciesForPersistence}.
2214
+ *
2215
+ * The other half of {@link ChatDriver.getHistoryForPersistence} (GENC-1632). That stores the
2216
+ * payloads the model has already stopped seeing as their stubs; this stores the policies for the
2217
+ * ones it has NOT stopped seeing yet, so a reload does not strand them at full size for the rest
2218
+ * of the session. Only entries whose call is in `messages` — the transcript actually being
2219
+ * written — are returned, so a frozen (non-resumable) or compacted save carries no policy for a
2220
+ * call it does not contain.
2221
+ *
2222
+ * @beta
2223
+ */
2224
+ getCondensePoliciesForPersistence(messages: readonly ChatMessage[]): PersistedCondensePolicy[];
2225
+ /**
2226
+ * Re-register policies saved by {@link ChatDriver.getCondensePoliciesForPersistence} against
2227
+ * the restored transcript. See {@link AiDriver.restoreCondensePolicies}.
2228
+ *
2229
+ * Call AFTER {@link ChatDriver.loadHistory} has seeded the restored transcript: an entry is
2230
+ * re-registered only if its tool call is in the driver's history, so one whose call the
2231
+ * restorable-boundary trim cut away (an orphaned trailing `tool_use`) is dropped rather than
2232
+ * resurrected against nothing.
2233
+ *
2234
+ * First-wins still holds per call: an entry is skipped if a policy is already registered for its
2235
+ * tool call — a restore never overrides what a live handler declared. `superseded` needs no
2236
+ * special handling — survivors are resolved from HISTORY order on every pass, so a restored entry
2237
+ * and a later call on the same `by` key resolve exactly as two live ones would.
2238
+ *
2239
+ * Clocks are rebased so each trigger is exactly as far from firing as it was at save time (see
2240
+ * `rebaseRestoredCondensePolicy`), with one deferral. An entry owned by the activation that was
2241
+ * live at save time, whose agent is not the one installed right now — the normal case on a
2242
+ * fresh page, where nothing is installed yet — is parked in
2243
+ * `condenseAwaitingReactivation` and stamped by the next `installAgent`: with
2244
+ * that agent's resumed activation if it is the same agent, or left behind (so it reads as
2245
+ * ended, which it has) if a different agent took over.
2246
+ *
2247
+ * A host with no agent to re-activate (a bare driver built from a static config) loses nothing
2248
+ * by this: the entry's owner (`undefined`) matches the installed agent (`undefined`), so it is
2249
+ * stamped live straight away and ends when the driver's single activation does — on
2250
+ * `releaseAgent` / `completeSubAgent`, exactly as a policy registered live would.
2251
+ *
2252
+ * Returns how many entries were actually re-armed, split from how many were merely present in
2253
+ * `entries` (review follow-up, GENC-1632): a malformed entry, one whose call the restorable-
2254
+ * boundary trim removed, or a first-wins duplicate is silently dropped, so the caller's own count
2255
+ * of `entries` can't tell "all of them came back" from "none did". `restored` is every entry that
2256
+ * reached `condensePolicies`; `awaitingReactivation` is the subset of those parked pending the
2257
+ * next `installAgent` rather than stamped live immediately.
2258
+ *
2259
+ * @beta
2260
+ */
2261
+ restoreCondensePolicies(entries: readonly unknown[] | undefined): {
2262
+ restored: number;
2263
+ awaitingReactivation: number;
2264
+ };
2265
+ /**
2266
+ * Stamp the restored entries parked in `condenseAwaitingReactivation` now that
2267
+ * `installAgent` has advanced the activation clock for `agentName` (GENC-1632).
2268
+ *
2269
+ * Same agent → the flow the entry belonged to is resuming, so it takes the new activation and
2270
+ * stays full until THAT activation ends (and, for `phaseEnd`, until the next `endPhase()`).
2271
+ * Different agent → its owner did not come back; its activation is over, so it keeps the stamp
2272
+ * it was restored with, which is now behind the clock, and collapses on the next provider call
2273
+ * exactly as a live `agentEnd` payload does on a swap.
2274
+ *
2275
+ * One-shot: the set is emptied whatever the outcome, because only the FIRST activation after the
2276
+ * restore can be the resumption. Any later swap is an ordinary activation boundary.
2277
+ */
2278
+ private resumeRestoredCondensePolicies;
2135
2279
  /**
2136
2280
  * {@inheritDoc AiDriver.getSuggestions}
2137
2281
  *
@@ -5064,6 +5208,22 @@ export declare class OrchestratingDriver extends EventTarget implements AiDriver
5064
5208
  * tests passed, and the feature did nothing.
5065
5209
  */
5066
5210
  getHistoryForPersistence(): ChatMessage[];
5211
+ /**
5212
+ * Delegates to the inner {@link ChatDriver}, which owns the condensation registry and clocks
5213
+ * (GENC-1632). The forward matters for the same reason as `getHistoryForPersistence` above: the
5214
+ * persister reaches it through `?.`, so a missing forward would compile, pass the ChatDriver
5215
+ * tests, and do nothing for every orchestrated host — which is every host with an agents array.
5216
+ */
5217
+ getCondensePoliciesForPersistence(messages: readonly ChatMessage[]): PersistedCondensePolicy[];
5218
+ /**
5219
+ * Delegates to the inner {@link ChatDriver} (GENC-1632). The deferred activation stamp it
5220
+ * performs is taken by the inner driver's `installAgent`, which this driver's own
5221
+ * `installAgent` always reaches, so nothing extra is needed here.
5222
+ */
5223
+ restoreCondensePolicies(entries: readonly unknown[] | undefined): {
5224
+ restored: number;
5225
+ awaitingReactivation: number;
5226
+ };
5067
5227
  /** {@inheritDoc AiDriver.setContextGuard} */
5068
5228
  setContextGuard(policy?: ContextGuardPolicy): void;
5069
5229
  /** {@inheritDoc AiDriver.compact} */
@@ -5165,6 +5325,47 @@ export declare class OrchestratingDriver extends EventTarget implements AiDriver
5165
5325
  */
5166
5326
  export declare const PERSISTED_SESSION_VERSION = 1;
5167
5327
 
5328
+ /**
5329
+ * A `condenseWhen` policy that had NOT fired when the session was saved, in the shape it is
5330
+ * persisted in (GENC-1632).
5331
+ *
5332
+ * The clocks are stored as **elapsed counts, never raw values**, and that is the whole design. All
5333
+ * four driver clocks restart at 0 on a page reload, so a raw stamp means nothing to the driver that
5334
+ * reads it back, and it is wrong in whichever direction the arithmetic happens to fall. A phase
5335
+ * epoch of 1 restored against a fresh driver's 0 needs TWO `endPhase()` calls to fire, so the
5336
+ * Planning-phase document it guards is never shed at the end of Planning; an activation stamp
5337
+ * that lands below the fresh driver's clock reads as "a later activation began" — the `agentEnd`
5338
+ * trigger — and collapses the payload on the first provider call after the reload, mid-phase.
5339
+ * "How far each clock had moved past the call when it was saved" survives any reset, because it
5340
+ * is re-applied relative to whatever the new driver's clocks happen to read.
5341
+ *
5342
+ * Only unfired entries are persisted: a fired one has already been rendered into the stored
5343
+ * transcript as the stub the model was sent (GENC-1566), so there is nothing left for it to do.
5344
+ *
5345
+ * @public
5346
+ */
5347
+ export declare interface PersistedCondensePolicy {
5348
+ /** The tool call the policy is registered against. */
5349
+ toolCallId: string;
5350
+ /** The policy exactly as the tool declared it. */
5351
+ policy: CondensePolicy;
5352
+ /** Name of the agent whose activation made the call; absent on a driver with no installed agent. */
5353
+ agent?: string;
5354
+ /**
5355
+ * How far each clock had advanced past the call's stamp at save time. `0` means "still the
5356
+ * current one": the call's turn / activation / phase was the live one when the session was
5357
+ * saved. A positive count means that boundary had already passed, so the trigger keyed on it
5358
+ * fires on the first provider call after restore (it would have fired on the next call anyway;
5359
+ * it only had not been latched because no call had happened since).
5360
+ */
5361
+ elapsed: {
5362
+ modelCalls: number;
5363
+ turns: number;
5364
+ activations: number;
5365
+ phases: number;
5366
+ };
5367
+ }
5368
+
5168
5369
  /**
5169
5370
  * A durable, restorable snapshot of one chat session — the *restorable core* of
5170
5371
  * the debug log (GENC-1351 §5.1/D1), captured losslessly and independently of
@@ -5208,6 +5409,18 @@ export declare interface PersistedSession {
5208
5409
  * value shape is the agent's own, hence `unknown`.
5209
5410
  */
5210
5411
  agentSnapshots: Record<string, unknown>;
5412
+ /**
5413
+ * `condenseWhen` policies that had not fired yet when the session was saved, for tool calls in
5414
+ * {@link PersistedSession.messages} (GENC-1632). Handed back to the driver on restore so those
5415
+ * payloads still collapse when their trigger fires, instead of riding every provider call for the
5416
+ * rest of the resumed session at full size. Payloads that HAD already collapsed need no entry:
5417
+ * `messages` already stores them as the stubs the model was sent (GENC-1566).
5418
+ *
5419
+ * Optional and additive, so the schema `version` is unchanged: a snapshot written before this
5420
+ * field existed restores exactly as it always did (nothing to re-register), and a reader that
5421
+ * predates it ignores it. Omitted rather than written empty when there is nothing to carry.
5422
+ */
5423
+ condensePolicies?: PersistedCondensePolicy[];
5211
5424
  /**
5212
5425
  * Interrupted-flow marker (GENC-1351 §5.9). Present when the session was saved
5213
5426
  * while an agent declared its current state non-resumable (`resumable === false`).
@@ -4083,6 +4083,79 @@ function projectCompaction(history, cut, summaryTokens = COMPACTION_SUMMARY_TOKE
4083
4083
  // src/utils/condense-history.ts
4084
4084
  var CONDENSE_MIN_CHARS = 1e3;
4085
4085
  var CONDENSED_ARGS_KEY = "condensed";
4086
+ function isValidCondenseTrigger(t) {
4087
+ if (t?.kind === "superseded") return typeof t.by === "string" && t.by.length > 0;
4088
+ if (t?.kind === "age") return typeof t.turns === "number" && t.turns >= 1;
4089
+ return t?.kind === "turnEnd" || t?.kind === "agentEnd" || t?.kind === "phaseEnd";
4090
+ }
4091
+ function isValidCondenseResult(r) {
4092
+ if (r === "pointer" || r === "drop") return true;
4093
+ return !!r && typeof r === "object" && typeof r.replaceWith === "string";
4094
+ }
4095
+ function toolCallIdsIn(history) {
4096
+ const ids = /* @__PURE__ */ new Set();
4097
+ for (const msg of history) {
4098
+ for (const tc of msg.toolCalls ?? []) ids.add(tc.id);
4099
+ }
4100
+ return ids;
4101
+ }
4102
+ function snapshotCondensePolicies(policies, clocks, history) {
4103
+ if (policies.size === 0) return [];
4104
+ const present = toolCallIdsIn(history);
4105
+ const out = [];
4106
+ for (const [toolCallId, entry] of policies) {
4107
+ if (entry.firedTrigger || !present.has(toolCallId)) continue;
4108
+ out.push({
4109
+ toolCallId,
4110
+ policy: entry.policy,
4111
+ ...entry.agent !== void 0 && { agent: entry.agent },
4112
+ elapsed: {
4113
+ // `max(0, …)`: every clock is monotonic, so these are never negative on a live driver;
4114
+ // the clamp only stops a malformed entry from being written out as "the future".
4115
+ modelCalls: Math.max(0, clocks.modelCall - entry.iteration),
4116
+ turns: Math.max(0, clocks.turn - entry.turn),
4117
+ activations: Math.max(0, clocks.activation - entry.activation),
4118
+ phases: Math.max(0, clocks.phaseEpoch - entry.phaseEpoch)
4119
+ }
4120
+ });
4121
+ }
4122
+ return out;
4123
+ }
4124
+ function parsePersistedCondensePolicy(value) {
4125
+ if (!value || typeof value !== "object") return void 0;
4126
+ const v = value;
4127
+ if (typeof v.toolCallId !== "string" || !v.toolCallId) return void 0;
4128
+ const policy = v.policy;
4129
+ if (!policy || typeof policy !== "object") return void 0;
4130
+ const triggers = Array.isArray(policy.on) ? policy.on : [policy.on];
4131
+ if (triggers.length === 0 || !triggers.every(isValidCondenseTrigger)) return void 0;
4132
+ if (policy.args === void 0 && policy.response === void 0) return void 0;
4133
+ if (policy.args !== void 0 && !isValidCondenseResult(policy.args)) return void 0;
4134
+ if (policy.response !== void 0 && !isValidCondenseResult(policy.response)) return void 0;
4135
+ const count = (n) => typeof n === "number" && Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
4136
+ const e = v.elapsed ?? {};
4137
+ return {
4138
+ toolCallId: v.toolCallId,
4139
+ policy,
4140
+ ...typeof v.agent === "string" && { agent: v.agent },
4141
+ elapsed: {
4142
+ modelCalls: count(e.modelCalls),
4143
+ turns: count(e.turns),
4144
+ activations: count(e.activations),
4145
+ phases: count(e.phases)
4146
+ }
4147
+ };
4148
+ }
4149
+ function rebaseRestoredCondensePolicy(entry, clocks) {
4150
+ return {
4151
+ policy: entry.policy,
4152
+ iteration: clocks.modelCall - entry.elapsed.modelCalls,
4153
+ turn: clocks.turn - entry.elapsed.turns,
4154
+ activation: clocks.activation - entry.elapsed.activations,
4155
+ phaseEpoch: clocks.phaseEpoch - entry.elapsed.phases,
4156
+ ...entry.agent !== void 0 && { agent: entry.agent }
4157
+ };
4158
+ }
4086
4159
  function triggerReason(trigger) {
4087
4160
  switch (trigger.kind) {
4088
4161
  case "age":
@@ -5370,8 +5443,29 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5370
5443
  * provider call to collapse stale payloads from the model-bound history only.
5371
5444
  * Accumulates across agents on a shared driver (a superseded read collapses no
5372
5445
  * matter which agent made it) and is never cleared — it dies with the driver.
5446
+ *
5447
+ * "Dies with the driver" used to mean a page reload silently disarmed every policy that had
5448
+ * not fired yet: the restored transcript carried the full payload and nothing was left to
5449
+ * collapse it, so it rode every later provider call (GENC-1632). The unfired entries are now
5450
+ * persisted with the session and re-registered on restore — see
5451
+ * {@link ChatDriver.getCondensePoliciesForPersistence} and
5452
+ * {@link ChatDriver.restoreCondensePolicies}.
5373
5453
  */
5374
5454
  this.condensePolicies = /* @__PURE__ */ new Map();
5455
+ /**
5456
+ * Restored policies whose owning activation was still live at save time, waiting for that agent
5457
+ * to be re-installed so they can be stamped with the activation it resumes in (GENC-1632).
5458
+ *
5459
+ * They cannot be stamped at restore time. On a fresh page `activeAgentName` is unset, so the
5460
+ * first `installAgent` after the reload is a "name change" and advances `currentActivation` —
5461
+ * which is exactly the `agentEnd` signal. An entry stamped before that bump reads as belonging
5462
+ * to an activation that has ended, and it and every `phaseEnd` entry (through the `agentEnd`
5463
+ * backstop) collapse on the first provider call after the reload, mid-flow. For Create's
5464
+ * Planning phase that is the uploaded scope document vanishing the moment the user carries on
5465
+ * talking about it — a worse failure than the one being fixed. So the stamp is deferred to that
5466
+ * `installAgent`, and consumed there once whichever agent it installs.
5467
+ */
5468
+ this.condenseAwaitingReactivation = /* @__PURE__ */ new Set();
5375
5469
  /**
5376
5470
  * Monotonic model-call counter for the driver's whole lifetime — the age clock
5377
5471
  * for `condenseWhen({ on: { kind: 'age' } })`. The per-`sendMessage` `iterations`
@@ -5846,7 +5940,10 @@ var ChatDriver = class _ChatDriver extends EventTarget {
5846
5940
  * whether the hooks should fire is the whole difference between this and `activateAgent`.
5847
5941
  */
5848
5942
  installAgent(config) {
5849
- if (config.name !== this.activeAgentName) this.currentActivation += 1;
5943
+ if (config.name !== this.activeAgentName) {
5944
+ this.currentActivation += 1;
5945
+ this.resumeRestoredCondensePolicies(config.name);
5946
+ }
5850
5947
  this.systemPrompt = config.systemPrompt;
5851
5948
  if (typeof config.toolDefinitions === "function") {
5852
5949
  this.toolDefinitionsFactory = config.toolDefinitions;
@@ -6159,6 +6256,109 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6159
6256
  getHistoryForPersistence() {
6160
6257
  return condenseForPersistence([...this.history], this.condensePolicies);
6161
6258
  }
6259
+ /** The four condensation clocks as they read now. */
6260
+ condenseClocks() {
6261
+ return {
6262
+ modelCall: this.modelCallSeq,
6263
+ turn: this.turnSeq,
6264
+ activation: this.currentActivation,
6265
+ phaseEpoch: this.currentPhaseEpoch
6266
+ };
6267
+ }
6268
+ /**
6269
+ * The `condenseWhen` policies that have not fired yet, for the calls in `messages`, in the
6270
+ * clock-independent form {@link ChatDriver.restoreCondensePolicies} re-registers. See
6271
+ * {@link AiDriver.getCondensePoliciesForPersistence}.
6272
+ *
6273
+ * The other half of {@link ChatDriver.getHistoryForPersistence} (GENC-1632). That stores the
6274
+ * payloads the model has already stopped seeing as their stubs; this stores the policies for the
6275
+ * ones it has NOT stopped seeing yet, so a reload does not strand them at full size for the rest
6276
+ * of the session. Only entries whose call is in `messages` — the transcript actually being
6277
+ * written — are returned, so a frozen (non-resumable) or compacted save carries no policy for a
6278
+ * call it does not contain.
6279
+ *
6280
+ * @beta
6281
+ */
6282
+ getCondensePoliciesForPersistence(messages) {
6283
+ return snapshotCondensePolicies(this.condensePolicies, this.condenseClocks(), messages);
6284
+ }
6285
+ /**
6286
+ * Re-register policies saved by {@link ChatDriver.getCondensePoliciesForPersistence} against
6287
+ * the restored transcript. See {@link AiDriver.restoreCondensePolicies}.
6288
+ *
6289
+ * Call AFTER {@link ChatDriver.loadHistory} has seeded the restored transcript: an entry is
6290
+ * re-registered only if its tool call is in the driver's history, so one whose call the
6291
+ * restorable-boundary trim cut away (an orphaned trailing `tool_use`) is dropped rather than
6292
+ * resurrected against nothing.
6293
+ *
6294
+ * First-wins still holds per call: an entry is skipped if a policy is already registered for its
6295
+ * tool call — a restore never overrides what a live handler declared. `superseded` needs no
6296
+ * special handling — survivors are resolved from HISTORY order on every pass, so a restored entry
6297
+ * and a later call on the same `by` key resolve exactly as two live ones would.
6298
+ *
6299
+ * Clocks are rebased so each trigger is exactly as far from firing as it was at save time (see
6300
+ * `rebaseRestoredCondensePolicy`), with one deferral. An entry owned by the activation that was
6301
+ * live at save time, whose agent is not the one installed right now — the normal case on a
6302
+ * fresh page, where nothing is installed yet — is parked in
6303
+ * `condenseAwaitingReactivation` and stamped by the next `installAgent`: with
6304
+ * that agent's resumed activation if it is the same agent, or left behind (so it reads as
6305
+ * ended, which it has) if a different agent took over.
6306
+ *
6307
+ * A host with no agent to re-activate (a bare driver built from a static config) loses nothing
6308
+ * by this: the entry's owner (`undefined`) matches the installed agent (`undefined`), so it is
6309
+ * stamped live straight away and ends when the driver's single activation does — on
6310
+ * `releaseAgent` / `completeSubAgent`, exactly as a policy registered live would.
6311
+ *
6312
+ * Returns how many entries were actually re-armed, split from how many were merely present in
6313
+ * `entries` (review follow-up, GENC-1632): a malformed entry, one whose call the restorable-
6314
+ * boundary trim removed, or a first-wins duplicate is silently dropped, so the caller's own count
6315
+ * of `entries` can't tell "all of them came back" from "none did". `restored` is every entry that
6316
+ * reached `condensePolicies`; `awaitingReactivation` is the subset of those parked pending the
6317
+ * next `installAgent` rather than stamped live immediately.
6318
+ *
6319
+ * @beta
6320
+ */
6321
+ restoreCondensePolicies(entries) {
6322
+ if (!Array.isArray(entries) || entries.length === 0)
6323
+ return { restored: 0, awaitingReactivation: 0 };
6324
+ const present = toolCallIdsIn(this.history);
6325
+ const clocks = this.condenseClocks();
6326
+ let restored = 0;
6327
+ let awaitingReactivation = 0;
6328
+ for (const raw of entries) {
6329
+ const entry = parsePersistedCondensePolicy(raw);
6330
+ if (!entry || !present.has(entry.toolCallId)) continue;
6331
+ if (this.condensePolicies.has(entry.toolCallId)) continue;
6332
+ this.condensePolicies.set(entry.toolCallId, rebaseRestoredCondensePolicy(entry, clocks));
6333
+ restored += 1;
6334
+ if (entry.elapsed.activations === 0 && entry.agent !== this.activeAgentName) {
6335
+ this.condenseAwaitingReactivation.add(entry.toolCallId);
6336
+ awaitingReactivation += 1;
6337
+ }
6338
+ }
6339
+ return { restored, awaitingReactivation };
6340
+ }
6341
+ /**
6342
+ * Stamp the restored entries parked in `condenseAwaitingReactivation` now that
6343
+ * `installAgent` has advanced the activation clock for `agentName` (GENC-1632).
6344
+ *
6345
+ * Same agent → the flow the entry belonged to is resuming, so it takes the new activation and
6346
+ * stays full until THAT activation ends (and, for `phaseEnd`, until the next `endPhase()`).
6347
+ * Different agent → its owner did not come back; its activation is over, so it keeps the stamp
6348
+ * it was restored with, which is now behind the clock, and collapses on the next provider call
6349
+ * exactly as a live `agentEnd` payload does on a swap.
6350
+ *
6351
+ * One-shot: the set is emptied whatever the outcome, because only the FIRST activation after the
6352
+ * restore can be the resumption. Any later swap is an ordinary activation boundary.
6353
+ */
6354
+ resumeRestoredCondensePolicies(agentName) {
6355
+ if (this.condenseAwaitingReactivation.size === 0) return;
6356
+ for (const toolCallId of this.condenseAwaitingReactivation) {
6357
+ const entry = this.condensePolicies.get(toolCallId);
6358
+ if (entry && entry.agent === agentName) entry.activation = this.currentActivation;
6359
+ }
6360
+ this.condenseAwaitingReactivation.clear();
6361
+ }
6162
6362
  /**
6163
6363
  * {@inheritDoc AiDriver.getSuggestions}
6164
6364
  *
@@ -6474,8 +6674,7 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6474
6674
  return;
6475
6675
  }
6476
6676
  const triggers = Array.isArray(policy.on) ? policy.on : [policy.on];
6477
- const validTrigger = (t) => t?.kind === "superseded" ? typeof t.by === "string" && t.by.length > 0 : t?.kind === "age" ? typeof t.turns === "number" && t.turns >= 1 : t?.kind === "turnEnd" || t?.kind === "agentEnd" || t?.kind === "phaseEnd";
6478
- if (triggers.length === 0 || !triggers.every(validTrigger)) {
6677
+ if (triggers.length === 0 || !triggers.every(isValidCondenseTrigger)) {
6479
6678
  logger2.warn(
6480
6679
  `ChatDriver(${this.activeAgentName ?? "unknown"}): condenseWhen called with an invalid trigger \u2014 ignoring`
6481
6680
  );
@@ -6492,7 +6691,8 @@ var ChatDriver = class _ChatDriver extends EventTarget {
6492
6691
  iteration: this.modelCallSeq,
6493
6692
  turn: this.turnSeq,
6494
6693
  activation: this.currentActivation,
6495
- phaseEpoch: this.currentPhaseEpoch
6694
+ phaseEpoch: this.currentPhaseEpoch,
6695
+ ...this.activeAgentName !== void 0 && { agent: this.activeAgentName }
6496
6696
  });
6497
6697
  }
6498
6698
  };
@@ -7665,6 +7865,23 @@ var OrchestratingDriver = class extends EventTarget {
7665
7865
  getHistoryForPersistence() {
7666
7866
  return this.chatDriver.getHistoryForPersistence();
7667
7867
  }
7868
+ /**
7869
+ * Delegates to the inner {@link ChatDriver}, which owns the condensation registry and clocks
7870
+ * (GENC-1632). The forward matters for the same reason as `getHistoryForPersistence` above: the
7871
+ * persister reaches it through `?.`, so a missing forward would compile, pass the ChatDriver
7872
+ * tests, and do nothing for every orchestrated host — which is every host with an agents array.
7873
+ */
7874
+ getCondensePoliciesForPersistence(messages) {
7875
+ return this.chatDriver.getCondensePoliciesForPersistence(messages);
7876
+ }
7877
+ /**
7878
+ * Delegates to the inner {@link ChatDriver} (GENC-1632). The deferred activation stamp it
7879
+ * performs is taken by the inner driver's `installAgent`, which this driver's own
7880
+ * `installAgent` always reaches, so nothing extra is needed here.
7881
+ */
7882
+ restoreCondensePolicies(entries) {
7883
+ return this.chatDriver.restoreCondensePolicies(entries);
7884
+ }
7668
7885
  /** {@inheritDoc AiDriver.setContextGuard} */
7669
7886
  setContextGuard(policy) {
7670
7887
  this.chatDriver.setContextGuard(policy);