@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
@@ -42,6 +42,13 @@ export interface RegisteredCondensePolicy {
42
42
  activation: number;
43
43
  /** App-controlled phase epoch when the call was made — the `phaseEnd` clock. */
44
44
  phaseEpoch: number;
45
+ /**
46
+ * Name of the agent whose activation made the call (`undefined` on a driver with no installed
47
+ * agent). Not read by any trigger — `activation` is the clock — but a restored entry needs it to
48
+ * tell whether the agent re-activated after a reload is the one that owned the call, or a
49
+ * different one that has taken over (GENC-1632, see {@link rebaseRestoredCondensePolicy}).
50
+ */
51
+ agent?: string;
45
52
  /** `context.condensed` already emitted for the args payload (fire-once). */
46
53
  reportedArgs?: boolean;
47
54
  /** `context.condensed` already emitted for the response payload (fire-once). */
@@ -105,6 +112,113 @@ export interface CondenseContext {
105
112
  */
106
113
  batchCalls?: number;
107
114
  }
115
+ /**
116
+ * The driver's four condensation clocks as raw values — what {@link RegisteredCondensePolicy}
117
+ * stamps at `condenseWhen` time, and what a persisted entry is re-expressed against on the way out
118
+ * and rebased onto on the way back in (GENC-1632).
119
+ */
120
+ export interface CondenseClocks {
121
+ modelCall: number;
122
+ turn: number;
123
+ activation: number;
124
+ phaseEpoch: number;
125
+ }
126
+ /**
127
+ * A `condenseWhen` policy that had NOT fired when the session was saved, in the shape it is
128
+ * persisted in (GENC-1632).
129
+ *
130
+ * The clocks are stored as **elapsed counts, never raw values**, and that is the whole design. All
131
+ * four driver clocks restart at 0 on a page reload, so a raw stamp means nothing to the driver that
132
+ * reads it back, and it is wrong in whichever direction the arithmetic happens to fall. A phase
133
+ * epoch of 1 restored against a fresh driver's 0 needs TWO `endPhase()` calls to fire, so the
134
+ * Planning-phase document it guards is never shed at the end of Planning; an activation stamp
135
+ * that lands below the fresh driver's clock reads as "a later activation began" — the `agentEnd`
136
+ * trigger — and collapses the payload on the first provider call after the reload, mid-phase.
137
+ * "How far each clock had moved past the call when it was saved" survives any reset, because it
138
+ * is re-applied relative to whatever the new driver's clocks happen to read.
139
+ *
140
+ * Only unfired entries are persisted: a fired one has already been rendered into the stored
141
+ * transcript as the stub the model was sent (GENC-1566), so there is nothing left for it to do.
142
+ *
143
+ * @public
144
+ */
145
+ export interface PersistedCondensePolicy {
146
+ /** The tool call the policy is registered against. */
147
+ toolCallId: string;
148
+ /** The policy exactly as the tool declared it. */
149
+ policy: CondensePolicy;
150
+ /** Name of the agent whose activation made the call; absent on a driver with no installed agent. */
151
+ agent?: string;
152
+ /**
153
+ * How far each clock had advanced past the call's stamp at save time. `0` means "still the
154
+ * current one": the call's turn / activation / phase was the live one when the session was
155
+ * saved. A positive count means that boundary had already passed, so the trigger keyed on it
156
+ * fires on the first provider call after restore (it would have fired on the next call anyway;
157
+ * it only had not been latched because no call had happened since).
158
+ */
159
+ elapsed: {
160
+ modelCalls: number;
161
+ turns: number;
162
+ activations: number;
163
+ phases: number;
164
+ };
165
+ }
166
+ /** Whether `t` is a well-formed trigger — the same rule `condenseWhen` enforces on registration. */
167
+ export declare function isValidCondenseTrigger(t: CondenseTrigger | undefined): boolean;
168
+ /**
169
+ * Every tool-call id carried by an assistant message in `history`. Exported so the save side
170
+ * ({@link snapshotCondensePolicies}) and the restore side (`ChatDriver.restoreCondensePolicies`)
171
+ * compute "is this call still present?" from one definition — GENC-1632 review: the two had drifted
172
+ * into separate copies of the same loop.
173
+ */
174
+ export declare function toolCallIdsIn(history: readonly ChatMessage[]): Set<string>;
175
+ /**
176
+ * The entries to PERSIST alongside `history` (GENC-1632): every registered policy that has not
177
+ * fired yet and whose tool call is still in the transcript being saved, re-expressed as elapsed
178
+ * clock counts (see {@link PersistedCondensePolicy}).
179
+ *
180
+ * `history` is the transcript actually being written, not the driver's live one, because the two
181
+ * can differ: a non-resumable save freezes at the last user message, and a compaction may have
182
+ * summarised a call away. An entry whose call is not in the saved transcript has nothing to
183
+ * collapse after a reload, so it is not written.
184
+ *
185
+ * Pure, no writes to the registry — safe on a save path that runs on every autosave.
186
+ */
187
+ export declare function snapshotCondensePolicies(policies: ReadonlyMap<string, RegisteredCondensePolicy>, clocks: CondenseClocks, history: readonly ChatMessage[]): PersistedCondensePolicy[];
188
+ /**
189
+ * Validate one persisted entry read back from storage. Returns `undefined` for anything that is not
190
+ * a well-formed {@link PersistedCondensePolicy} — the blob came off a disk or a network, and a
191
+ * policy that cannot be evaluated must be dropped rather than reach `applyCondensation`, which
192
+ * trusts its registry. A missing or malformed `elapsed` count reads as `0` (the boundary had not
193
+ * passed), which errs towards keeping a payload visible rather than eliding it.
194
+ */
195
+ export declare function parsePersistedCondensePolicy(value: unknown): PersistedCondensePolicy | undefined;
196
+ /**
197
+ * Re-register a persisted entry against a (typically fresh) driver's clocks (GENC-1632): each
198
+ * stamp is the current clock minus the elapsed count, so every trigger stands exactly as far from
199
+ * firing as it did when the session was saved.
200
+ *
201
+ * Per clock, what that means after a reload:
202
+ * - `age` — exact. The model-call distance is preserved, so a result seen twice of its three
203
+ * allowed looks gets one more. The rebased `iteration` is usually negative (the call predates
204
+ * this driver's first model call), which the trigger arithmetic is indifferent to; it does
205
+ * surface as a negative `turn` on the eventual `context.condensed` event.
206
+ * - `turnEnd` — a call from the turn that was running at save time collapses on the next
207
+ * `sendMessage`. That is the original intent, not an approximation: a reload ends the turn.
208
+ * - `phaseEnd` — collapses at the next `endPhase()`, or at once if the phase had already ended.
209
+ * - `agentEnd` (and `phaseEnd`'s backstop) — an entry whose activation had already ended collapses
210
+ * at once. One owned by the activation live at save time is stamped with the CURRENT
211
+ * activation, which reads as live; but the driver will very likely advance its activation clock
212
+ * when the agent is re-installed after the reload, so this stamp is provisional and the driver
213
+ * must re-stamp it at that point — see `ChatDriver.installAgent`. Leaving it here would collapse
214
+ * the payload the moment the flow resumes, which is the failure this whole mechanism exists to
215
+ * avoid.
216
+ *
217
+ * The `reported*` latches start clear, so the eventual full→stub transition reports once, like any
218
+ * other entry. The stored transcript cannot hold a stub for an unfired entry, so there is no
219
+ * earlier report to duplicate.
220
+ */
221
+ export declare function rebaseRestoredCondensePolicy(entry: PersistedCondensePolicy, clocks: CondenseClocks): RegisteredCondensePolicy;
108
222
  /**
109
223
  * Structured detail for a `context.condensed` meta-event. The index signature
110
224
  * lets it satisfy `recordMetaEvent`'s `Record<string, unknown>` detail param
@@ -1 +1 @@
1
- {"version":3,"file":"condense-history.d.ts","sourceRoot":"","sources":["../../../src/utils/condense-history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG/F;;;;;;;;;;;;;GAaG;AAEH;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,OAAO,CAAC;AAEvC,uFAAuF;AACvF,eAAO,MAAM,kBAAkB,cAAc,CAAC;AAE9C;;;;;GAKG;AACH,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,cAAc,CAAC;IACvB;;;;;OAKG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,+EAA+E;IAC/E,UAAU,EAAE,MAAM,CAAC;IACnB,gFAAgF;IAChF,UAAU,EAAE,MAAM,CAAC;IACnB,4EAA4E;IAC5E,YAAY,CAAC,EAAE,OAAO,CAAC;I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EACtB,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,wBAAwB,CAAC,GACtD,WAAW,EAAE,CA8Df"}
1
+ {"version":3,"file":"condense-history.d.ts","sourceRoot":"","sources":["../../../src/utils/condense-history.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,cAAc,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAG/F;;;;;;;;;;;;;GAaG;AAEH;;;;GAIG;AACH,eAAO,MAAM,kBAAkB,OAAO,CAAC;AAEvC,uFAAuF;AACvF,eAAO,MAAM,kBAAkB,cAAc,CAAC;AAE9C;;;;;GAKG;AACH,MAAM,WAAW,wBAAwB;IACvC,MAAM,EAAE,cAAc,CAAC;IACvB;;;;;OAKG;IACH,SAAS,EAAE,MAAM,CAAC;IAClB,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,+EAA+E;IAC/E,UAAU,EAAE,MAAM,CAAC;IACnB,gFAAgF;IAChF,UAAU,EAAE,MAAM,CAAC;IACnB;;;;;OAKG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,4EAA4E;IAC5E,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,gFAAgF;IAChF,gBAAgB,CAAC,EAAE,OAAO,CAAC;IAC3B;;;;;;;;;;;;;;;;;;;;OAoBG;IACH,YAAY,CAAC,EAAE,eAAe,CAAC;CAChC;AAED;;;;GAIG;AACH,MAAM,WAAW,eAAe;IAC9B,2DAA2D;IAC3D,SAAS,EAAE,MAAM,CAAC;IAClB,yEAAyE;IACzE,IAAI,EAAE,MAAM,CAAC;IACb,4FAA4F;IAC5F,eAAe,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC;IACjD;;;OAGG;IACH,UAAU,EAAE,CAAC,UAAU,EAAE,MAAM,KAAK,OAAO,CAAC;IAC5C;;;;;;;;;;;;;;;;OAgBG;IACH,UAAU,CAAC,EAAE,MAAM,CAAC;CACrB;AAED;;;;GAIG;AAC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,0DAA0D;IAC1D,IAAI,EAAE,MAAM,CAAC;IACb,UAAU,EAAE,MAAM,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,GAAG,UAAU,CAAC;IAC5B,oEAAoE;IACpE,OAAO,EAAE,MAAM,CAAC;IAChB,sCAAsC;IACtC,OAAO,EAAE,MAAM,CAAC;IAChB,mFAAmF;IACnF,WAAW,EAAE,MAAM,CAAC;CACrB;AAiID;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAsCG;AACH,wBAAgB,iBAAiB,CAC/B,OAAO,EAAE,WAAW,EAAE,EACtB,QAAQ,EAAE,GAAG,CAAC,MAAM,EAAE,wBAAwB,CAAC,EAC/C,GAAG,EAAE,eAAe,EACpB,WAAW,EAAE,CAAC,MAAM,EAAE,oBAAoB,KAAK,IAAI,GAClD,WAAW,EAAE,CAyKf;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAiCG;AACH,wBAAgB,sBAAsB,CACpC,OAAO,EAAE,WAAW,EAAE,EACtB,QAAQ,EAAE,WAAW,CAAC,MAAM,EAAE,wBAAwB,CAAC,GACtD,WAAW,EAAE,CA8Df"}
@@ -329,6 +329,14 @@ let AiChatBubble = class AiChatBubble extends GenesisElement {
329
329
  }
330
330
  this.closeAbort = new AbortController();
331
331
  this.dialogEl.classList.add('closing');
332
+ // `dialog` is an exposed part, so an app can legitimately cancel the exit animation
333
+ // (`::part(dialog) { animation: none }` to drop the bounce, say). Without this the close would
334
+ // then wait on an `animationend` that never arrives and the dialog would never go away.
335
+ // getAnimations() flushes style, so the class added above is already accounted for.
336
+ if (this.dialogEl.getAnimations().length === 0) {
337
+ this.dialogOpen = false;
338
+ return;
339
+ }
332
340
  this.dialogEl.addEventListener('animationend', () => {
333
341
  this.dialogOpen = false;
334
342
  }, {
@@ -17,6 +17,7 @@ export const AiChatBubbleTemplate = () => {
17
17
  ${when((x) => !x.dialogOpen, html `
18
18
  <div
19
19
  class="bubble ${(x) => (x.hovered ? 'hovered' : '')}"
20
+ part="bubble"
20
21
  style="${(x) => `translate: ${x.bubbleLeft}px ${x.bubbleTop}px`}"
21
22
  ${ref('bubbleEl')}
22
23
  @mousedown="${(x, c) => x.onBubbleMouseDown(c.event)}"
@@ -27,8 +28,8 @@ export const AiChatBubbleTemplate = () => {
27
28
  <img src="${(x) => x.imageSrc}" alt="AI" draggable="false" />
28
29
  `)}
29
30
  ${when((x) => !x.imageSrc, genesisIconTemplate)}
30
- <div class="pulse-ring"></div>
31
- <div class="tooltip" style="${(x) => x.tooltipStyle}" ${ref('tooltipEl')}>
31
+ <div class="pulse-ring" part="pulse-ring"></div>
32
+ <div class="tooltip" part="tooltip" style="${(x) => x.tooltipStyle}" ${ref('tooltipEl')}>
32
33
  ${(x) => x.title}
33
34
  </div>
34
35
  </div>
@@ -41,11 +42,12 @@ export const AiChatBubbleTemplate = () => {
41
42
  (x) => (x.dialogOpen ? [x] : []), html `
42
43
  <div
43
44
  class="dialog"
45
+ part="dialog"
44
46
  style="${(x) => `translate: ${x.dialogLeft}px ${x.dialogTop}px; width: ${x.dialogWidth}px; height: ${x.dialogHeight}px`}"
45
47
  @chat-header-mousedown="${(x, c) => x.onDialogHeaderMouseDown(c.event)}"
46
48
  ${ref('dialogEl')}
47
49
  >
48
- <div class="dialog-content">
50
+ <div class="dialog-content" part="dialog-content">
49
51
  <slot name="dialog-content" ${slotted('dialogContent')}></slot>
50
52
  </div>
51
53
  </div>
@@ -4,7 +4,7 @@ import { NOOP_ACTIVITY_BUS } from '../../channel/ai-activity-bus';
4
4
  import { resolveChatProvider } from '../../config/validate-providers';
5
5
  import { clearSession, getMetaEvents, mergeMetaEvents, recordMetaEvent, recordTurnError, recordTurnRetry, } from '../../state/debug-event-log';
6
6
  import { generateSuggestions } from '../../suggestions/generate-suggestions';
7
- import { applyCondensation, condenseForPersistence, } from '../../utils/condense-history';
7
+ import { applyCondensation, condenseForPersistence, isValidCondenseTrigger, parsePersistedCondensePolicy, rebaseRestoredCondensePolicy, snapshotCondensePolicies, toolCallIdsIn, } from '../../utils/condense-history';
8
8
  import { estimatePreambleTokens, estimateRequestTokens, } from '../../utils/context-tokens';
9
9
  import { applyHistoryCap, buildCompactionSummaryPrompt, planCompaction, normalizeForProvider, } from '../../utils/history-transform';
10
10
  import { logger } from '../../utils/logger';
@@ -92,8 +92,29 @@ export class ChatDriver extends EventTarget {
92
92
  * provider call to collapse stale payloads from the model-bound history only.
93
93
  * Accumulates across agents on a shared driver (a superseded read collapses no
94
94
  * matter which agent made it) and is never cleared — it dies with the driver.
95
+ *
96
+ * "Dies with the driver" used to mean a page reload silently disarmed every policy that had
97
+ * not fired yet: the restored transcript carried the full payload and nothing was left to
98
+ * collapse it, so it rode every later provider call (GENC-1632). The unfired entries are now
99
+ * persisted with the session and re-registered on restore — see
100
+ * {@link ChatDriver.getCondensePoliciesForPersistence} and
101
+ * {@link ChatDriver.restoreCondensePolicies}.
95
102
  */
96
103
  this.condensePolicies = new Map();
104
+ /**
105
+ * Restored policies whose owning activation was still live at save time, waiting for that agent
106
+ * to be re-installed so they can be stamped with the activation it resumes in (GENC-1632).
107
+ *
108
+ * They cannot be stamped at restore time. On a fresh page `activeAgentName` is unset, so the
109
+ * first `installAgent` after the reload is a "name change" and advances `currentActivation` —
110
+ * which is exactly the `agentEnd` signal. An entry stamped before that bump reads as belonging
111
+ * to an activation that has ended, and it and every `phaseEnd` entry (through the `agentEnd`
112
+ * backstop) collapse on the first provider call after the reload, mid-flow. For Create's
113
+ * Planning phase that is the uploaded scope document vanishing the moment the user carries on
114
+ * talking about it — a worse failure than the one being fixed. So the stamp is deferred to that
115
+ * `installAgent`, and consumed there once whichever agent it installs.
116
+ */
117
+ this.condenseAwaitingReactivation = new Set();
97
118
  /**
98
119
  * Monotonic model-call counter for the driver's whole lifetime — the age clock
99
120
  * for `condenseWhen({ on: { kind: 'age' } })`. The per-`sendMessage` `iterations`
@@ -625,8 +646,10 @@ export class ChatDriver extends EventTarget {
625
646
  // flow is over, so its `agentEnd`-tagged payloads become collapsible. Guarded
626
647
  // on a name change so re-applying the same agent (e.g. a per-turn re-resolve)
627
648
  // does not spuriously advance the clock and prematurely drop its payloads.
628
- if (config.name !== this.activeAgentName)
649
+ if (config.name !== this.activeAgentName) {
629
650
  this.currentActivation += 1;
651
+ this.resumeRestoredCondensePolicies(config.name);
652
+ }
630
653
  this.systemPrompt = config.systemPrompt;
631
654
  if (typeof config.toolDefinitions === 'function') {
632
655
  this.toolDefinitionsFactory = config.toolDefinitions;
@@ -997,6 +1020,113 @@ export class ChatDriver extends EventTarget {
997
1020
  getHistoryForPersistence() {
998
1021
  return condenseForPersistence([...this.history], this.condensePolicies);
999
1022
  }
1023
+ /** The four condensation clocks as they read now. */
1024
+ condenseClocks() {
1025
+ return {
1026
+ modelCall: this.modelCallSeq,
1027
+ turn: this.turnSeq,
1028
+ activation: this.currentActivation,
1029
+ phaseEpoch: this.currentPhaseEpoch,
1030
+ };
1031
+ }
1032
+ /**
1033
+ * The `condenseWhen` policies that have not fired yet, for the calls in `messages`, in the
1034
+ * clock-independent form {@link ChatDriver.restoreCondensePolicies} re-registers. See
1035
+ * {@link AiDriver.getCondensePoliciesForPersistence}.
1036
+ *
1037
+ * The other half of {@link ChatDriver.getHistoryForPersistence} (GENC-1632). That stores the
1038
+ * payloads the model has already stopped seeing as their stubs; this stores the policies for the
1039
+ * ones it has NOT stopped seeing yet, so a reload does not strand them at full size for the rest
1040
+ * of the session. Only entries whose call is in `messages` — the transcript actually being
1041
+ * written — are returned, so a frozen (non-resumable) or compacted save carries no policy for a
1042
+ * call it does not contain.
1043
+ *
1044
+ * @beta
1045
+ */
1046
+ getCondensePoliciesForPersistence(messages) {
1047
+ return snapshotCondensePolicies(this.condensePolicies, this.condenseClocks(), messages);
1048
+ }
1049
+ /**
1050
+ * Re-register policies saved by {@link ChatDriver.getCondensePoliciesForPersistence} against
1051
+ * the restored transcript. See {@link AiDriver.restoreCondensePolicies}.
1052
+ *
1053
+ * Call AFTER {@link ChatDriver.loadHistory} has seeded the restored transcript: an entry is
1054
+ * re-registered only if its tool call is in the driver's history, so one whose call the
1055
+ * restorable-boundary trim cut away (an orphaned trailing `tool_use`) is dropped rather than
1056
+ * resurrected against nothing.
1057
+ *
1058
+ * First-wins still holds per call: an entry is skipped if a policy is already registered for its
1059
+ * tool call — a restore never overrides what a live handler declared. `superseded` needs no
1060
+ * special handling — survivors are resolved from HISTORY order on every pass, so a restored entry
1061
+ * and a later call on the same `by` key resolve exactly as two live ones would.
1062
+ *
1063
+ * Clocks are rebased so each trigger is exactly as far from firing as it was at save time (see
1064
+ * `rebaseRestoredCondensePolicy`), with one deferral. An entry owned by the activation that was
1065
+ * live at save time, whose agent is not the one installed right now — the normal case on a
1066
+ * fresh page, where nothing is installed yet — is parked in
1067
+ * `condenseAwaitingReactivation` and stamped by the next `installAgent`: with
1068
+ * that agent's resumed activation if it is the same agent, or left behind (so it reads as
1069
+ * ended, which it has) if a different agent took over.
1070
+ *
1071
+ * A host with no agent to re-activate (a bare driver built from a static config) loses nothing
1072
+ * by this: the entry's owner (`undefined`) matches the installed agent (`undefined`), so it is
1073
+ * stamped live straight away and ends when the driver's single activation does — on
1074
+ * `releaseAgent` / `completeSubAgent`, exactly as a policy registered live would.
1075
+ *
1076
+ * Returns how many entries were actually re-armed, split from how many were merely present in
1077
+ * `entries` (review follow-up, GENC-1632): a malformed entry, one whose call the restorable-
1078
+ * boundary trim removed, or a first-wins duplicate is silently dropped, so the caller's own count
1079
+ * of `entries` can't tell "all of them came back" from "none did". `restored` is every entry that
1080
+ * reached `condensePolicies`; `awaitingReactivation` is the subset of those parked pending the
1081
+ * next `installAgent` rather than stamped live immediately.
1082
+ *
1083
+ * @beta
1084
+ */
1085
+ restoreCondensePolicies(entries) {
1086
+ if (!Array.isArray(entries) || entries.length === 0)
1087
+ return { restored: 0, awaitingReactivation: 0 };
1088
+ const present = toolCallIdsIn(this.history);
1089
+ const clocks = this.condenseClocks();
1090
+ let restored = 0;
1091
+ let awaitingReactivation = 0;
1092
+ for (const raw of entries) {
1093
+ const entry = parsePersistedCondensePolicy(raw);
1094
+ if (!entry || !present.has(entry.toolCallId))
1095
+ continue;
1096
+ if (this.condensePolicies.has(entry.toolCallId))
1097
+ continue;
1098
+ this.condensePolicies.set(entry.toolCallId, rebaseRestoredCondensePolicy(entry, clocks));
1099
+ restored += 1;
1100
+ if (entry.elapsed.activations === 0 && entry.agent !== this.activeAgentName) {
1101
+ this.condenseAwaitingReactivation.add(entry.toolCallId);
1102
+ awaitingReactivation += 1;
1103
+ }
1104
+ }
1105
+ return { restored, awaitingReactivation };
1106
+ }
1107
+ /**
1108
+ * Stamp the restored entries parked in `condenseAwaitingReactivation` now that
1109
+ * `installAgent` has advanced the activation clock for `agentName` (GENC-1632).
1110
+ *
1111
+ * Same agent → the flow the entry belonged to is resuming, so it takes the new activation and
1112
+ * stays full until THAT activation ends (and, for `phaseEnd`, until the next `endPhase()`).
1113
+ * Different agent → its owner did not come back; its activation is over, so it keeps the stamp
1114
+ * it was restored with, which is now behind the clock, and collapses on the next provider call
1115
+ * exactly as a live `agentEnd` payload does on a swap.
1116
+ *
1117
+ * One-shot: the set is emptied whatever the outcome, because only the FIRST activation after the
1118
+ * restore can be the resumption. Any later swap is an ordinary activation boundary.
1119
+ */
1120
+ resumeRestoredCondensePolicies(agentName) {
1121
+ if (this.condenseAwaitingReactivation.size === 0)
1122
+ return;
1123
+ for (const toolCallId of this.condenseAwaitingReactivation) {
1124
+ const entry = this.condensePolicies.get(toolCallId);
1125
+ if (entry && entry.agent === agentName)
1126
+ entry.activation = this.currentActivation;
1127
+ }
1128
+ this.condenseAwaitingReactivation.clear();
1129
+ }
1000
1130
  /**
1001
1131
  * {@inheritDoc AiDriver.getSuggestions}
1002
1132
  *
@@ -1338,12 +1468,9 @@ export class ChatDriver extends EventTarget {
1338
1468
  return;
1339
1469
  }
1340
1470
  const triggers = Array.isArray(policy.on) ? policy.on : [policy.on];
1341
- const validTrigger = (t) => (t === null || t === void 0 ? void 0 : t.kind) === 'superseded'
1342
- ? typeof t.by === 'string' && t.by.length > 0
1343
- : (t === null || t === void 0 ? void 0 : t.kind) === 'age'
1344
- ? typeof t.turns === 'number' && t.turns >= 1
1345
- : (t === null || t === void 0 ? void 0 : t.kind) === 'turnEnd' || (t === null || t === void 0 ? void 0 : t.kind) === 'agentEnd' || (t === null || t === void 0 ? void 0 : t.kind) === 'phaseEnd';
1346
- if (triggers.length === 0 || !triggers.every(validTrigger)) {
1471
+ // Shared with the restore path's validation (GENC-1632), so a policy that could not be
1472
+ // registered live can never be re-registered from a stored session either.
1473
+ if (triggers.length === 0 || !triggers.every(isValidCondenseTrigger)) {
1347
1474
  logger.warn(`ChatDriver(${(_b = this.activeAgentName) !== null && _b !== void 0 ? _b : 'unknown'}): condenseWhen called with an invalid trigger — ignoring`);
1348
1475
  return;
1349
1476
  }
@@ -1353,15 +1480,11 @@ export class ChatDriver extends EventTarget {
1353
1480
  logger.error(`ChatDriver(${(_c = this.activeAgentName) !== null && _c !== void 0 ? _c : 'unknown'}): condenseWhen called more than once for the same tool call — keeping the first policy, ignoring this one`);
1354
1481
  return;
1355
1482
  }
1356
- // Stamp the three clocks NOW (read straight off the driver — the handler
1357
- // runs during the current model-call's tool batch).
1358
- this.condensePolicies.set(activeToolCallId, {
1359
- policy,
1360
- iteration: this.modelCallSeq,
1361
- turn: this.turnSeq,
1362
- activation: this.currentActivation,
1363
- phaseEpoch: this.currentPhaseEpoch,
1364
- });
1483
+ // Stamp the four clocks NOW (read straight off the driver — the handler
1484
+ // runs during the current model-call's tool batch). `agent` is not a clock; it is
1485
+ // recorded so a persisted entry can tell, after a reload, whether the agent that
1486
+ // re-activates is the one that owned the call (GENC-1632).
1487
+ this.condensePolicies.set(activeToolCallId, Object.assign({ policy, iteration: this.modelCallSeq, turn: this.turnSeq, activation: this.currentActivation, phaseEpoch: this.currentPhaseEpoch }, (this.activeAgentName !== undefined && { agent: this.activeAgentName })));
1365
1488
  } });
1366
1489
  }
1367
1490
  /**
@@ -68,6 +68,92 @@ const styles = css `
68
68
  font-weight: 600;
69
69
  }
70
70
  `;
71
+ /**
72
+ * Element tag -> the shadow part it is exposed as.
73
+ *
74
+ * Markdown is rendered from a string at runtime, so there is no template on which to author
75
+ * `part=` attributes - which is why this component previously exposed nothing at all and an
76
+ * embedding app could only reach it through whichever global design tokens the rules below happen
77
+ * to use. Annotating the generated DOM gives an app ordinary CSS over each element type
78
+ * (`ai-chat-markdown::part(md-li) { ... }`) instead of a per-property token API that would have to
79
+ * grow every time someone wants to style something new.
80
+ *
81
+ * The vocabulary is deliberately a fixed list of element kinds rather than anything derived from
82
+ * the content: it is a public API surface, so it should change only when this map does. That also
83
+ * makes it enumerable, which {@link MARKDOWN_EXPORTPARTS} relies on.
84
+ */
85
+ const MARKDOWN_PARTS = {
86
+ P: 'md-p',
87
+ UL: 'md-ul',
88
+ OL: 'md-ol',
89
+ LI: 'md-li',
90
+ PRE: 'md-pre',
91
+ CODE: 'md-code',
92
+ A: 'md-link',
93
+ BLOCKQUOTE: 'md-quote',
94
+ TABLE: 'md-table',
95
+ THEAD: 'md-thead',
96
+ TBODY: 'md-tbody',
97
+ TR: 'md-tr',
98
+ TH: 'md-th',
99
+ TD: 'md-td',
100
+ HR: 'md-hr',
101
+ IMG: 'md-img',
102
+ STRONG: 'md-strong',
103
+ EM: 'md-em',
104
+ H1: 'md-h1',
105
+ H2: 'md-h2',
106
+ H3: 'md-h3',
107
+ H4: 'md-h4',
108
+ H5: 'md-h5',
109
+ H6: 'md-h6',
110
+ };
111
+ /** Tags whose part is also emitted with a nesting level (see {@link AiChatMarkdown.annotateParts}). */
112
+ const DEPTH_TAGGED = ['UL', 'OL', 'LI'];
113
+ const DEPTH_TAGGED_SET = new Set(DEPTH_TAGGED);
114
+ /**
115
+ * Deepest list level with a part of its own; anything deeper is tagged as this level.
116
+ *
117
+ * `exportparts` has no wildcard, so every level a host forwards has to be named. An uncapped
118
+ * scheme would therefore have a forwarding list that can never be complete, and any list deeper
119
+ * than it happened to enumerate would be silently unstyleable. Capping keeps the exported
120
+ * vocabulary finite and makes the deepest level mean "this deep or deeper", which is a contract
121
+ * that can actually be honoured.
122
+ */
123
+ const MAX_LIST_LEVEL = 3;
124
+ /**
125
+ * The two `code` flavours, emitted alongside `md-code`.
126
+ *
127
+ * `::part()` takes no descendant combinators, so `md-code` alone cannot distinguish inline code
128
+ * from the `code` inside a `pre`: an app giving it a background for inline spans would paint every
129
+ * code block too, and the `pre code` reset in this component's own styles loses to an outer
130
+ * `::part` rule in the cascade, so there would be nothing to undo it with.
131
+ */
132
+ const CODE_BLOCK_PART = 'md-code-block';
133
+ const CODE_INLINE_PART = 'md-code-inline';
134
+ /**
135
+ * Every part this component exposes, as an `exportparts` value.
136
+ *
137
+ * `::part()` crosses exactly one shadow boundary, so a host that renders `<ai-chat-markdown>` in
138
+ * its own shadow root has to forward these for an app to reach them at all. Built from the map
139
+ * above rather than written out, so the forwarded list cannot drift from what is emitted.
140
+ */
141
+ export const MARKDOWN_EXPORTPARTS = [
142
+ ...Object.values(MARKDOWN_PARTS),
143
+ CODE_BLOCK_PART,
144
+ CODE_INLINE_PART,
145
+ ...DEPTH_TAGGED.flatMap((tag) => Array.from({ length: MAX_LIST_LEVEL }, (_, i) => `${MARKDOWN_PARTS[tag]}-level-${i + 1}`)),
146
+ ].join(', ');
147
+ /** The part attribute for one generated element, given the list depth it sits at. */
148
+ function partFor(el, base, listDepth) {
149
+ var _a;
150
+ if (DEPTH_TAGGED_SET.has(el.tagName))
151
+ return `${base} ${base}-level-${listDepth}`;
152
+ if (el.tagName === 'CODE') {
153
+ return `${base} ${((_a = el.parentElement) === null || _a === void 0 ? void 0 : _a.tagName) === 'PRE' ? CODE_BLOCK_PART : CODE_INLINE_PART}`;
154
+ }
155
+ return base;
156
+ }
71
157
  let AiChatMarkdown = class AiChatMarkdown extends GenesisElement {
72
158
  constructor() {
73
159
  super(...arguments);
@@ -79,7 +165,52 @@ let AiChatMarkdown = class AiChatMarkdown extends GenesisElement {
79
165
  if (!this.content)
80
166
  return '';
81
167
  const rawHtml = marked.parse(this.content);
82
- return DOMPurify.sanitize(rawHtml);
168
+ // `part`/`exportparts` are on DOMPurify's default allow-list, so a model emitting
169
+ // `<span part="md-link">` would otherwise land a name in this component's part namespace that
170
+ // MARKDOWN_PARTS never granted. Forbidding them keeps the vocabulary exactly what this file
171
+ // says it is, whatever the content claims.
172
+ return this.annotateParts(DOMPurify.sanitize(rawHtml, {
173
+ FORBID_ATTR: ['part', 'exportparts'],
174
+ RETURN_DOM_FRAGMENT: true,
175
+ }));
176
+ }
177
+ /**
178
+ * Tag the generated elements with shadow parts so an embedding app can style them.
179
+ *
180
+ * Takes the tree DOMPurify built rather than re-parsing its serialised output: `content` changes
181
+ * on every streamed chunk, so a second parse/serialise round trip would run per chunk over the
182
+ * whole message, and the string the browser finally parses is then serialised straight from the
183
+ * tree DOMPurify checked. Parse/serialise mismatches are where mXSS bypasses have historically
184
+ * lived, and this walk has no need to introduce one.
185
+ *
186
+ * Only ever *adds* attributes, to DOM that has already been cleared - so it is not itself
187
+ * sanitiser surface.
188
+ *
189
+ * Lists additionally carry a level: a top-level list is `md-ul md-ul-level-1`, a list nested
190
+ * inside it is `md-ul-level-2`, and an `li` takes the level of the list holding it. Levels are
191
+ * clamped at `MAX_LIST_LEVEL`, so a list deeper than that answers to the deepest level
192
+ * rather than to a name no host forwards. Chat markdown rarely nests, so this is a safety valve
193
+ * rather than a feature - without it, every list at every depth would answer to one selector and
194
+ * there would be no way to tell them apart afterwards. Depth comes from walking the tree rather
195
+ * than from marked's renderers, which are invoked innermost-first and so cannot count downwards.
196
+ */
197
+ annotateParts(fragment) {
198
+ const walk = (parent, listDepth) => {
199
+ for (const el of Array.from(parent.children)) {
200
+ const base = MARKDOWN_PARTS[el.tagName];
201
+ // A list opens the next level; everything else sits at its parent list's level.
202
+ const depth = el.tagName === 'UL' || el.tagName === 'OL'
203
+ ? Math.min(listDepth + 1, MAX_LIST_LEVEL)
204
+ : listDepth;
205
+ if (base)
206
+ el.setAttribute('part', partFor(el, base, depth));
207
+ walk(el, depth);
208
+ }
209
+ };
210
+ walk(fragment, 0);
211
+ const container = document.createElement('div');
212
+ container.append(fragment);
213
+ return container.innerHTML;
83
214
  }
84
215
  };
85
216
  __decorate([