@genesislcap/ai-assistant 15.35.3 → 15.35.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. package/dist/ai-assistant.api.json +483 -0
  2. package/dist/ai-assistant.d.ts +192 -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 +1616 -1350
  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-driver/chat-driver.d.ts +93 -0
  11. package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
  12. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +17 -0
  13. package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
  14. package/dist/dts/state/persistence/index.d.ts +1 -0
  15. package/dist/dts/state/persistence/index.d.ts.map +1 -1
  16. package/dist/dts/state/persistence/session-persister.d.ts +12 -0
  17. package/dist/dts/state/persistence/session-persister.d.ts.map +1 -1
  18. package/dist/dts/state/persistence/session-snapshot.d.ts +14 -0
  19. package/dist/dts/state/persistence/session-snapshot.d.ts.map +1 -1
  20. package/dist/dts/utils/condense-history.d.ts +114 -0
  21. package/dist/dts/utils/condense-history.d.ts.map +1 -1
  22. package/dist/esm/components/chat-driver/chat-driver.js +140 -17
  23. package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +17 -0
  24. package/dist/esm/state/persistence/session-persister.js +63 -15
  25. package/dist/esm/state/persistence/session-snapshot.js +2 -17
  26. package/dist/esm/utils/condense-history.js +123 -0
  27. 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';
@@ -779,6 +780,36 @@ export declare interface AiDriver extends EventTarget {
779
780
  * to project, and a caller falls back to {@link AiDriver.getRawHistory}.
780
781
  */
781
782
  getHistoryForPersistence?(): ChatMessage[];
783
+ /**
784
+ * The `condenseWhen` policies that have NOT fired yet, for the tool calls in `messages` — the
785
+ * transcript being persisted — in a clock-independent form a later
786
+ * {@link AiDriver.restoreCondensePolicies} can re-register (GENC-1632). The companion of
787
+ * {@link AiDriver.getHistoryForPersistence}: that stores already-collapsed payloads as stubs;
788
+ * this keeps the not-yet-collapsed ones collapsible across a reload, where they would otherwise
789
+ * ride every provider call for the rest of the session. Optional, like its companion — a driver
790
+ * without condensation has none.
791
+ *
792
+ * @beta
793
+ */
794
+ getCondensePoliciesForPersistence?(messages: readonly ChatMessage[]): PersistedCondensePolicy[];
795
+ /**
796
+ * Re-register policies from {@link AiDriver.getCondensePoliciesForPersistence} against a restored
797
+ * transcript (GENC-1632). Call after {@link AiDriver.loadHistory}: entries whose tool call is not
798
+ * in the loaded history are dropped. Tolerates `undefined` and malformed entries (an older or
799
+ * damaged snapshot), which are ignored.
800
+ *
801
+ * Returns how many entries were actually re-armed (`restored`) and how many of those are parked
802
+ * pending the next agent activation (`awaitingReactivation`) — narrower than `entries.length`,
803
+ * which counts what was offered, not what was accepted (a malformed entry, a trimmed-away call, or
804
+ * a first-wins duplicate is dropped silently). A caller logging the outcome needs this split to
805
+ * tell "all re-armed" from "none did".
806
+ *
807
+ * @beta
808
+ */
809
+ restoreCondensePolicies?(entries: readonly unknown[] | undefined): {
810
+ restored: number;
811
+ awaitingReactivation: number;
812
+ };
782
813
  /**
783
814
  * The live `AgentConfig` currently active in the driver — the instance whose
784
815
  * `onActivate` ran, so its `serialize`/`getDebugSnapshot` closures hold live
@@ -1524,8 +1555,29 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
1524
1555
  * provider call to collapse stale payloads from the model-bound history only.
1525
1556
  * Accumulates across agents on a shared driver (a superseded read collapses no
1526
1557
  * matter which agent made it) and is never cleared — it dies with the driver.
1558
+ *
1559
+ * "Dies with the driver" used to mean a page reload silently disarmed every policy that had
1560
+ * not fired yet: the restored transcript carried the full payload and nothing was left to
1561
+ * collapse it, so it rode every later provider call (GENC-1632). The unfired entries are now
1562
+ * persisted with the session and re-registered on restore — see
1563
+ * {@link ChatDriver.getCondensePoliciesForPersistence} and
1564
+ * {@link ChatDriver.restoreCondensePolicies}.
1527
1565
  */
1528
1566
  private readonly condensePolicies;
1567
+ /**
1568
+ * Restored policies whose owning activation was still live at save time, waiting for that agent
1569
+ * to be re-installed so they can be stamped with the activation it resumes in (GENC-1632).
1570
+ *
1571
+ * They cannot be stamped at restore time. On a fresh page `activeAgentName` is unset, so the
1572
+ * first `installAgent` after the reload is a "name change" and advances `currentActivation` —
1573
+ * which is exactly the `agentEnd` signal. An entry stamped before that bump reads as belonging
1574
+ * to an activation that has ended, and it and every `phaseEnd` entry (through the `agentEnd`
1575
+ * backstop) collapse on the first provider call after the reload, mid-flow. For Create's
1576
+ * Planning phase that is the uploaded scope document vanishing the moment the user carries on
1577
+ * talking about it — a worse failure than the one being fixed. So the stamp is deferred to that
1578
+ * `installAgent`, and consumed there once whichever agent it installs.
1579
+ */
1580
+ private readonly condenseAwaitingReactivation;
1529
1581
  /**
1530
1582
  * Monotonic model-call counter for the driver's whole lifetime — the age clock
1531
1583
  * for `condenseWhen({ on: { kind: 'age' } })`. The per-`sendMessage` `iterations`
@@ -2132,6 +2184,77 @@ export declare class ChatDriver extends EventTarget implements AiDriver {
2132
2184
  * unaffected — which is what makes the elision recoverable.
2133
2185
  */
2134
2186
  getHistoryForPersistence(): ChatMessage[];
2187
+ /** The four condensation clocks as they read now. */
2188
+ private condenseClocks;
2189
+ /**
2190
+ * The `condenseWhen` policies that have not fired yet, for the calls in `messages`, in the
2191
+ * clock-independent form {@link ChatDriver.restoreCondensePolicies} re-registers. See
2192
+ * {@link AiDriver.getCondensePoliciesForPersistence}.
2193
+ *
2194
+ * The other half of {@link ChatDriver.getHistoryForPersistence} (GENC-1632). That stores the
2195
+ * payloads the model has already stopped seeing as their stubs; this stores the policies for the
2196
+ * ones it has NOT stopped seeing yet, so a reload does not strand them at full size for the rest
2197
+ * of the session. Only entries whose call is in `messages` — the transcript actually being
2198
+ * written — are returned, so a frozen (non-resumable) or compacted save carries no policy for a
2199
+ * call it does not contain.
2200
+ *
2201
+ * @beta
2202
+ */
2203
+ getCondensePoliciesForPersistence(messages: readonly ChatMessage[]): PersistedCondensePolicy[];
2204
+ /**
2205
+ * Re-register policies saved by {@link ChatDriver.getCondensePoliciesForPersistence} against
2206
+ * the restored transcript. See {@link AiDriver.restoreCondensePolicies}.
2207
+ *
2208
+ * Call AFTER {@link ChatDriver.loadHistory} has seeded the restored transcript: an entry is
2209
+ * re-registered only if its tool call is in the driver's history, so one whose call the
2210
+ * restorable-boundary trim cut away (an orphaned trailing `tool_use`) is dropped rather than
2211
+ * resurrected against nothing.
2212
+ *
2213
+ * First-wins still holds per call: an entry is skipped if a policy is already registered for its
2214
+ * tool call — a restore never overrides what a live handler declared. `superseded` needs no
2215
+ * special handling — survivors are resolved from HISTORY order on every pass, so a restored entry
2216
+ * and a later call on the same `by` key resolve exactly as two live ones would.
2217
+ *
2218
+ * Clocks are rebased so each trigger is exactly as far from firing as it was at save time (see
2219
+ * `rebaseRestoredCondensePolicy`), with one deferral. An entry owned by the activation that was
2220
+ * live at save time, whose agent is not the one installed right now — the normal case on a
2221
+ * fresh page, where nothing is installed yet — is parked in
2222
+ * `condenseAwaitingReactivation` and stamped by the next `installAgent`: with
2223
+ * that agent's resumed activation if it is the same agent, or left behind (so it reads as
2224
+ * ended, which it has) if a different agent took over.
2225
+ *
2226
+ * A host with no agent to re-activate (a bare driver built from a static config) loses nothing
2227
+ * by this: the entry's owner (`undefined`) matches the installed agent (`undefined`), so it is
2228
+ * stamped live straight away and ends when the driver's single activation does — on
2229
+ * `releaseAgent` / `completeSubAgent`, exactly as a policy registered live would.
2230
+ *
2231
+ * Returns how many entries were actually re-armed, split from how many were merely present in
2232
+ * `entries` (review follow-up, GENC-1632): a malformed entry, one whose call the restorable-
2233
+ * boundary trim removed, or a first-wins duplicate is silently dropped, so the caller's own count
2234
+ * of `entries` can't tell "all of them came back" from "none did". `restored` is every entry that
2235
+ * reached `condensePolicies`; `awaitingReactivation` is the subset of those parked pending the
2236
+ * next `installAgent` rather than stamped live immediately.
2237
+ *
2238
+ * @beta
2239
+ */
2240
+ restoreCondensePolicies(entries: readonly unknown[] | undefined): {
2241
+ restored: number;
2242
+ awaitingReactivation: number;
2243
+ };
2244
+ /**
2245
+ * Stamp the restored entries parked in `condenseAwaitingReactivation` now that
2246
+ * `installAgent` has advanced the activation clock for `agentName` (GENC-1632).
2247
+ *
2248
+ * Same agent → the flow the entry belonged to is resuming, so it takes the new activation and
2249
+ * stays full until THAT activation ends (and, for `phaseEnd`, until the next `endPhase()`).
2250
+ * Different agent → its owner did not come back; its activation is over, so it keeps the stamp
2251
+ * it was restored with, which is now behind the clock, and collapses on the next provider call
2252
+ * exactly as a live `agentEnd` payload does on a swap.
2253
+ *
2254
+ * One-shot: the set is emptied whatever the outcome, because only the FIRST activation after the
2255
+ * restore can be the resumption. Any later swap is an ordinary activation boundary.
2256
+ */
2257
+ private resumeRestoredCondensePolicies;
2135
2258
  /**
2136
2259
  * {@inheritDoc AiDriver.getSuggestions}
2137
2260
  *
@@ -5064,6 +5187,22 @@ export declare class OrchestratingDriver extends EventTarget implements AiDriver
5064
5187
  * tests passed, and the feature did nothing.
5065
5188
  */
5066
5189
  getHistoryForPersistence(): ChatMessage[];
5190
+ /**
5191
+ * Delegates to the inner {@link ChatDriver}, which owns the condensation registry and clocks
5192
+ * (GENC-1632). The forward matters for the same reason as `getHistoryForPersistence` above: the
5193
+ * persister reaches it through `?.`, so a missing forward would compile, pass the ChatDriver
5194
+ * tests, and do nothing for every orchestrated host — which is every host with an agents array.
5195
+ */
5196
+ getCondensePoliciesForPersistence(messages: readonly ChatMessage[]): PersistedCondensePolicy[];
5197
+ /**
5198
+ * Delegates to the inner {@link ChatDriver} (GENC-1632). The deferred activation stamp it
5199
+ * performs is taken by the inner driver's `installAgent`, which this driver's own
5200
+ * `installAgent` always reaches, so nothing extra is needed here.
5201
+ */
5202
+ restoreCondensePolicies(entries: readonly unknown[] | undefined): {
5203
+ restored: number;
5204
+ awaitingReactivation: number;
5205
+ };
5067
5206
  /** {@inheritDoc AiDriver.setContextGuard} */
5068
5207
  setContextGuard(policy?: ContextGuardPolicy): void;
5069
5208
  /** {@inheritDoc AiDriver.compact} */
@@ -5165,6 +5304,47 @@ export declare class OrchestratingDriver extends EventTarget implements AiDriver
5165
5304
  */
5166
5305
  export declare const PERSISTED_SESSION_VERSION = 1;
5167
5306
 
5307
+ /**
5308
+ * A `condenseWhen` policy that had NOT fired when the session was saved, in the shape it is
5309
+ * persisted in (GENC-1632).
5310
+ *
5311
+ * The clocks are stored as **elapsed counts, never raw values**, and that is the whole design. All
5312
+ * four driver clocks restart at 0 on a page reload, so a raw stamp means nothing to the driver that
5313
+ * reads it back, and it is wrong in whichever direction the arithmetic happens to fall. A phase
5314
+ * epoch of 1 restored against a fresh driver's 0 needs TWO `endPhase()` calls to fire, so the
5315
+ * Planning-phase document it guards is never shed at the end of Planning; an activation stamp
5316
+ * that lands below the fresh driver's clock reads as "a later activation began" — the `agentEnd`
5317
+ * trigger — and collapses the payload on the first provider call after the reload, mid-phase.
5318
+ * "How far each clock had moved past the call when it was saved" survives any reset, because it
5319
+ * is re-applied relative to whatever the new driver's clocks happen to read.
5320
+ *
5321
+ * Only unfired entries are persisted: a fired one has already been rendered into the stored
5322
+ * transcript as the stub the model was sent (GENC-1566), so there is nothing left for it to do.
5323
+ *
5324
+ * @public
5325
+ */
5326
+ export declare interface PersistedCondensePolicy {
5327
+ /** The tool call the policy is registered against. */
5328
+ toolCallId: string;
5329
+ /** The policy exactly as the tool declared it. */
5330
+ policy: CondensePolicy;
5331
+ /** Name of the agent whose activation made the call; absent on a driver with no installed agent. */
5332
+ agent?: string;
5333
+ /**
5334
+ * How far each clock had advanced past the call's stamp at save time. `0` means "still the
5335
+ * current one": the call's turn / activation / phase was the live one when the session was
5336
+ * saved. A positive count means that boundary had already passed, so the trigger keyed on it
5337
+ * fires on the first provider call after restore (it would have fired on the next call anyway;
5338
+ * it only had not been latched because no call had happened since).
5339
+ */
5340
+ elapsed: {
5341
+ modelCalls: number;
5342
+ turns: number;
5343
+ activations: number;
5344
+ phases: number;
5345
+ };
5346
+ }
5347
+
5168
5348
  /**
5169
5349
  * A durable, restorable snapshot of one chat session — the *restorable core* of
5170
5350
  * the debug log (GENC-1351 §5.1/D1), captured losslessly and independently of
@@ -5208,6 +5388,18 @@ export declare interface PersistedSession {
5208
5388
  * value shape is the agent's own, hence `unknown`.
5209
5389
  */
5210
5390
  agentSnapshots: Record<string, unknown>;
5391
+ /**
5392
+ * `condenseWhen` policies that had not fired yet when the session was saved, for tool calls in
5393
+ * {@link PersistedSession.messages} (GENC-1632). Handed back to the driver on restore so those
5394
+ * payloads still collapse when their trigger fires, instead of riding every provider call for the
5395
+ * rest of the resumed session at full size. Payloads that HAD already collapsed need no entry:
5396
+ * `messages` already stores them as the stubs the model was sent (GENC-1566).
5397
+ *
5398
+ * Optional and additive, so the schema `version` is unchanged: a snapshot written before this
5399
+ * field existed restores exactly as it always did (nothing to re-register), and a reader that
5400
+ * predates it ignores it. Omitted rather than written empty when there is nothing to carry.
5401
+ */
5402
+ condensePolicies?: PersistedCondensePolicy[];
5211
5403
  /**
5212
5404
  * Interrupted-flow marker (GENC-1351 §5.9). Present when the session was saved
5213
5405
  * 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);