@genesislcap/ai-assistant 15.6.2 → 15.7.0
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.
- package/dist/ai-assistant.api.json +391 -5
- package/dist/ai-assistant.d.ts +613 -6
- package/dist/chat-driver.cjs +285 -26
- package/dist/chat-driver.cjs.map +3 -3
- package/dist/chat-driver.mjs +285 -26
- package/dist/chat-driver.mjs.map +3 -3
- package/dist/custom-elements.json +254 -10
- package/dist/dts/channel/ai-activity-channel.d.ts +51 -1
- package/dist/dts/channel/ai-activity-channel.d.ts.map +1 -1
- package/dist/dts/components/chat-driver/chat-driver.d.ts +99 -1
- package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
- package/dist/dts/components/chat-driver/chat-driver.test.d.ts.map +1 -1
- package/dist/dts/components/orchestrating-driver/orchestrating-driver.budget.test.d.ts +2 -0
- package/dist/dts/components/orchestrating-driver/orchestrating-driver.budget.test.d.ts.map +1 -0
- package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts +14 -0
- package/dist/dts/components/orchestrating-driver/orchestrating-driver.d.ts.map +1 -1
- package/dist/dts/main/blocked-state.test.d.ts +2 -0
- package/dist/dts/main/blocked-state.test.d.ts.map +1 -0
- package/dist/dts/main/main.d.ts +394 -6
- package/dist/dts/main/main.d.ts.map +1 -1
- package/dist/dts/main/main.styles.d.ts.map +1 -1
- package/dist/dts/main/main.styles.test.d.ts +2 -0
- package/dist/dts/main/main.styles.test.d.ts.map +1 -0
- package/dist/dts/main/main.template.d.ts +53 -0
- package/dist/dts/main/main.template.d.ts.map +1 -1
- package/dist/dts/state/ai-assistant-slice.d.ts +162 -6
- package/dist/dts/state/ai-assistant-slice.d.ts.map +1 -1
- package/dist/dts/state/debug-event-log.d.ts +6 -1
- package/dist/dts/state/debug-event-log.d.ts.map +1 -1
- package/dist/dts/state/session-store.d.ts +11 -0
- package/dist/dts/state/session-store.d.ts.map +1 -1
- package/dist/esm/components/chat-driver/chat-driver.js +263 -21
- package/dist/esm/components/chat-driver/chat-driver.test.js +464 -1
- package/dist/esm/components/orchestrating-driver/orchestrating-driver.budget.test.js +312 -0
- package/dist/esm/components/orchestrating-driver/orchestrating-driver.js +89 -4
- package/dist/esm/main/blocked-state.test.js +969 -0
- package/dist/esm/main/main.js +704 -16
- package/dist/esm/main/main.styles.js +47 -0
- package/dist/esm/main/main.styles.test.js +86 -0
- package/dist/esm/main/main.template.js +121 -4
- package/dist/esm/state/ai-assistant-slice.js +145 -7
- package/dist/esm/state/ai-assistant-slice.test.js +138 -1
- package/dist/esm/state/debug-event-log.js +7 -2
- package/dist/esm/state/debug-event-log.test.js +49 -1
- package/dist/esm/state/persistence/session-snapshot.test.js +18 -0
- package/dist/tsconfig.tsbuildinfo +1 -1
- package/docs/migration-GENC-1464.md +562 -0
- package/docs/sub_agent.md +20 -3
- package/package.json +17 -17
- package/src/channel/ai-activity-channel.ts +56 -2
- package/src/components/chat-driver/chat-driver.test.ts +549 -0
- package/src/components/chat-driver/chat-driver.ts +324 -14
- package/src/components/orchestrating-driver/orchestrating-driver.budget.test.ts +438 -0
- package/src/components/orchestrating-driver/orchestrating-driver.ts +101 -6
- package/src/main/blocked-state.test.ts +1316 -0
- package/src/main/main.styles.test.ts +103 -0
- package/src/main/main.styles.ts +47 -0
- package/src/main/main.template.ts +131 -4
- package/src/main/main.ts +704 -10
- package/src/state/ai-assistant-slice.test.ts +215 -0
- package/src/state/ai-assistant-slice.ts +218 -8
- package/src/state/debug-event-log.test.ts +63 -0
- package/src/state/debug-event-log.ts +7 -2
- package/src/state/persistence/session-snapshot.test.ts +22 -0
package/src/main/main.ts
CHANGED
|
@@ -24,12 +24,22 @@
|
|
|
24
24
|
import type {
|
|
25
25
|
AggregateUsage,
|
|
26
26
|
AIProviderRegistryStatusEntry,
|
|
27
|
+
AIProviderType,
|
|
27
28
|
ChatAttachment,
|
|
28
29
|
ChatConfig,
|
|
30
|
+
ChatDriverResult,
|
|
29
31
|
ChatInputDuringExecutionMode,
|
|
30
32
|
ChatMessage,
|
|
33
|
+
TurnFailureReason,
|
|
34
|
+
} from '@genesislcap/foundation-ai';
|
|
35
|
+
import {
|
|
36
|
+
AIProviderRegistry,
|
|
37
|
+
BUDGETED_VENDORS,
|
|
38
|
+
DEFAULT_BUDGET_EXHAUSTED_MESSAGE,
|
|
39
|
+
isObservableAIProviderRegistry,
|
|
40
|
+
VENDOR_LABELS,
|
|
41
|
+
vendorTypeOfLabel,
|
|
31
42
|
} from '@genesislcap/foundation-ai';
|
|
32
|
-
import { AIProviderRegistry, isObservableAIProviderRegistry } from '@genesislcap/foundation-ai';
|
|
33
43
|
import { showNotificationDialog } from '@genesislcap/foundation-notifications';
|
|
34
44
|
import { avoidTreeShaking } from '@genesislcap/foundation-utils';
|
|
35
45
|
import type { Modal } from '@genesislcap/rapid-design-system';
|
|
@@ -208,6 +218,88 @@ const COMPOSER_MAX_HEIGHT_PX = 400;
|
|
|
208
218
|
/** Keep at least this much of the message list visible while growing the composer. */
|
|
209
219
|
const COMPOSER_MIN_MESSAGES_PX = 80;
|
|
210
220
|
|
|
221
|
+
/**
|
|
222
|
+
* Composer placeholder while the assistant is blocked (GENC-1464). Deliberately
|
|
223
|
+
* fixed and short, and NOT host-overridable — the banner directly above it
|
|
224
|
+
* carries the detail, and that one IS overridable via `setBlocked(true, reason)`.
|
|
225
|
+
* The banner's own default copy is `DEFAULT_BUDGET_EXHAUSTED_MESSAGE`, read
|
|
226
|
+
* straight from `foundation-ai` so the banner and the driver's transcript bubble
|
|
227
|
+
* cannot drift apart.
|
|
228
|
+
*/
|
|
229
|
+
const BLOCKED_PLACEHOLDER = 'AI usage limit reached';
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Closing sentence for a wall the user cannot route around. Singular/plural
|
|
233
|
+
* variants because the banner names one vendor or several.
|
|
234
|
+
*/
|
|
235
|
+
const RAISE_LIMIT_ACTION = 'Contact your administrator to raise it.';
|
|
236
|
+
const RAISE_LIMITS_ACTION = 'Contact your administrator to raise them.';
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Banner copy built from the figures a 402 actually reported, or `undefined`
|
|
240
|
+
* when the proxy sent none.
|
|
241
|
+
*
|
|
242
|
+
* `undefined` is the meaningful return, not a fallback: paired with the
|
|
243
|
+
* slice's "a re-latch without a reason keeps the existing explanation" rule, it
|
|
244
|
+
* makes a figureless driver latch leave a host-supplied reason intact rather
|
|
245
|
+
* than blanking it back to the default at the exact moment the wall is hit.
|
|
246
|
+
*
|
|
247
|
+
* Exported for the unit test that pins the formatting; not part of the element
|
|
248
|
+
* API.
|
|
249
|
+
*
|
|
250
|
+
* @internal
|
|
251
|
+
*/
|
|
252
|
+
export function formatBlockedReason(
|
|
253
|
+
budget?: Extract<ChatDriverResult, { reason: 'done' }>['budget'],
|
|
254
|
+
vendor?: AIProviderType,
|
|
255
|
+
): string | undefined {
|
|
256
|
+
if (!budget || (budget.budgetUsd == null && budget.spentUsd == null)) return undefined;
|
|
257
|
+
const money = (v?: number) => (v == null ? 'an unknown amount' : `$${v.toFixed(2)}`);
|
|
258
|
+
const figures = `(${money(budget.spentUsd)} of ${money(budget.budgetUsd)})`;
|
|
259
|
+
// A per-vendor statement carries NO action clause, because the right action is
|
|
260
|
+
// not knowable at latch time: whether "switch vendor" or "contact your
|
|
261
|
+
// administrator" is the honest advice depends on whether any OTHER vendor still
|
|
262
|
+
// has headroom, which only the composing getter can see. The vendor-agnostic
|
|
263
|
+
// form keeps its historical trailing sentence — nothing composes onto it.
|
|
264
|
+
return vendor
|
|
265
|
+
? `${vendorDisplayName(vendor)}'s AI usage limit is reached ${figures}.`
|
|
266
|
+
: `AI usage limit reached ${figures}. Contact your administrator to raise it.`;
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
/**
|
|
270
|
+
* Human-readable name for a vendor, falling back to its raw type.
|
|
271
|
+
*
|
|
272
|
+
* `'none'` needs no special case: it is the "no provider configured" sentinel,
|
|
273
|
+
* it is filtered out of {@link FoundationAiAssistant.reachableVendors}, the latch
|
|
274
|
+
* refuses to attribute a wall to it, and
|
|
275
|
+
* {@link FoundationAiAssistant.setVendorBlocked} rejects it at the boundary — so
|
|
276
|
+
* nothing can put it in front of this function. The `?? vendor` fallback is for a
|
|
277
|
+
* vendor type added to `AIProviderType` without a label, which would print the
|
|
278
|
+
* type rather than nothing.
|
|
279
|
+
*/
|
|
280
|
+
function vendorDisplayName(vendor: AIProviderType): string {
|
|
281
|
+
return (VENDOR_LABELS as Partial<Record<AIProviderType, string>>)[vendor] ?? vendor;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* `a`, `a and b`, `a, b and c`.
|
|
286
|
+
*
|
|
287
|
+
* The general joiner is kept rather than hardcoded to a pair because the list
|
|
288
|
+
* is `BUDGETED_VENDORS`-shaped, and that list is a cross-repo contract owned by
|
|
289
|
+
* the proxy (today `anthropic` and `gemini`; `openai` is refused up front with
|
|
290
|
+
* 400 UNSUPPORTED_PROVIDER and can never be walled) — a vendor added there must
|
|
291
|
+
* not require an edit here. Its upper bound is not an assertion in a comment — it is
|
|
292
|
+
* the key count of `VENDOR_LABELS`, since every element of every list passed here
|
|
293
|
+
* comes from `blockedVendors` or `reachableVendors`, both of which hold
|
|
294
|
+
* `AIProviderType` values, and the type has five members of which `'none'` is
|
|
295
|
+
* excluded from both.
|
|
296
|
+
*/
|
|
297
|
+
function formatVendorList(vendors: readonly AIProviderType[]): string {
|
|
298
|
+
const names = vendors.map(vendorDisplayName);
|
|
299
|
+
if (names.length <= 1) return names[0] ?? '';
|
|
300
|
+
return `${names.slice(0, -1).join(', ')} and ${names[names.length - 1]}`;
|
|
301
|
+
}
|
|
302
|
+
|
|
211
303
|
// Register supporting components when the main component module is imported.
|
|
212
304
|
avoidTreeShaking(
|
|
213
305
|
AiChatMarkdown,
|
|
@@ -425,14 +517,26 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
425
517
|
|
|
426
518
|
/**
|
|
427
519
|
* True when a new send must be refused: a turn is running (`busy`), a page-reload
|
|
428
|
-
* restore is loading history that would clobber it (`restoring`),
|
|
429
|
-
* compaction is rewriting history (`compacting`)
|
|
430
|
-
*
|
|
431
|
-
*
|
|
432
|
-
*
|
|
520
|
+
* restore is loading history that would clobber it (`restoring`), a manual
|
|
521
|
+
* compaction is rewriting history (`compacting`), or a backend condition has
|
|
522
|
+
* locked the assistant outright (`blocked` — e.g. an exhausted AI budget).
|
|
523
|
+
* Mirrors the composer's `?disabled` gate so a **programmatic**
|
|
524
|
+
* `send`/`submitMessage` (e.g. a host's custom input while the built-in composer
|
|
525
|
+
* is hidden) can't slip past it and have its message wiped when the
|
|
526
|
+
* restored/compacted history lands (GENC-1351 §6).
|
|
433
527
|
*/
|
|
434
528
|
private get sendBlocked(): boolean {
|
|
435
|
-
return this.busy || this.restoring || this.compacting;
|
|
529
|
+
return this.busy || this.restoring || this.compacting || this.blocked;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/**
|
|
533
|
+
* Why a programmatic send was refused, for `submitMessage`'s `errors`. A
|
|
534
|
+
* backend block is called out distinctly because — unlike the transient
|
|
535
|
+
* "busy" cases — waiting and retrying will never clear it, and a caller
|
|
536
|
+
* looping on "Assistant is busy" would spin forever.
|
|
537
|
+
*/
|
|
538
|
+
private sendRefusalReason(): string {
|
|
539
|
+
return this.blocked ? this.effectiveBlockedReason : 'Assistant is busy';
|
|
436
540
|
}
|
|
437
541
|
|
|
438
542
|
/**
|
|
@@ -604,6 +708,545 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
604
708
|
this._sessionRef?.actions.aiAssistant.setRestoring(value);
|
|
605
709
|
}
|
|
606
710
|
|
|
711
|
+
/**
|
|
712
|
+
* Whether the assistant is blocked by a backend condition and cannot send —
|
|
713
|
+
* today, an exhausted AI-spend budget (GENC-1464). While true the composer is
|
|
714
|
+
* disabled, `send`/`submitMessage` refuse, suggestions stop being fetched, and
|
|
715
|
+
* a persistent banner (`part="blocked-banner"`) sits above the composer
|
|
716
|
+
* explaining why. The transcript stays visible and scrollable throughout —
|
|
717
|
+
* unlike `compacting` and `restoring`, this does not replace the conversation.
|
|
718
|
+
*
|
|
719
|
+
* **Latched.** Nothing in the element clears it: not a new turn, not "Clear"
|
|
720
|
+
* / "New chat", not a pop-in/out. It stays set until the host writes
|
|
721
|
+
* `false` — because nothing the user can do inside the assistant refills a
|
|
722
|
+
* budget. Hosts typically set it from their own pre-flight budget check on
|
|
723
|
+
* mount, and clear it once a later check shows headroom again.
|
|
724
|
+
*
|
|
725
|
+
* The driver also latches it automatically when a turn ends with the
|
|
726
|
+
* `'budget-exhausted'` failure reason — off the `tool-loop-end` activity bus
|
|
727
|
+
* (which also covers a sub-agent wall, a turn this element did not start, and
|
|
728
|
+
* an element swapped in mid-turn) and off the driver's return value (which
|
|
729
|
+
* covers a wall hit during multi-agent classification, where no tool loop ran
|
|
730
|
+
* and so no bus event fires). So a host that does no pre-flight at all still
|
|
731
|
+
* gets a correct locked UI the moment the first 402 lands. The bus topic is
|
|
732
|
+
* tab-scoped, so a wall hit in a popped-out window latches the main window
|
|
733
|
+
* too — correct for a shared spend cap.
|
|
734
|
+
*
|
|
735
|
+
* **Lifetime — read this before relying on it as your source of truth.** The
|
|
736
|
+
* latch is in-memory and per-`stateKey`:
|
|
737
|
+
*
|
|
738
|
+
* - It does **not** survive `switchSession`. Switching away tears the outgoing
|
|
739
|
+
* session's store down entirely, so switching back yields a fresh, unblocked
|
|
740
|
+
* store.
|
|
741
|
+
* - It does **not** survive a page reload. It is deliberately absent from the
|
|
742
|
+
* persisted session snapshot: the snapshot is long-lived, so a persisted
|
|
743
|
+
* latch would outlive an out-of-band budget raise with no in-element way to
|
|
744
|
+
* clear it — a stale lock is worse than re-deriving the state.
|
|
745
|
+
*
|
|
746
|
+
* The durable source of truth is therefore the **host's pre-flight**, which
|
|
747
|
+
* should run on mount and on every session switch. See
|
|
748
|
+
* `docs/migration-GENC-1464.md` §"How to adopt", Option B.
|
|
749
|
+
*
|
|
750
|
+
* @beta
|
|
751
|
+
*/
|
|
752
|
+
@volatile
|
|
753
|
+
get blocked(): boolean {
|
|
754
|
+
const session = this._sessionRef?.store.aiAssistant;
|
|
755
|
+
if (!session) return false;
|
|
756
|
+
if (session.blocked) return true;
|
|
757
|
+
// Byte-identical to the old stored read for every host that never adopts the
|
|
758
|
+
// per-vendor API — which is what makes this derivation non-breaking.
|
|
759
|
+
if (session.blockedVendors.length === 0) return false;
|
|
760
|
+
// Unknown reachability (statuses not loaded yet, or providers that report no
|
|
761
|
+
// status) fails SAFE — any wall blocks everything, exactly today's semantics —
|
|
762
|
+
// and needs no clause of its own: `every` on the empty set is vacuously true.
|
|
763
|
+
return this.reachableVendors.every((v) => session.blockedVendors.includes(v));
|
|
764
|
+
}
|
|
765
|
+
set blocked(value: boolean) {
|
|
766
|
+
this._sessionRef?.actions.aiAssistant.setBlocked({ blocked: value });
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* The distinct vendors the registry can currently reach, from the provider
|
|
771
|
+
* statuses this element already loads on connect and refreshes on every
|
|
772
|
+
* observable-registry change.
|
|
773
|
+
*
|
|
774
|
+
* This is the element's answer to "which vendor would the next turn use" — a
|
|
775
|
+
* question that has **no** correct answer and deliberately gets no API. The
|
|
776
|
+
* provider is resolved per turn AND per agent: `activeProviderInput` may be an
|
|
777
|
+
* async function of the turn's context, an orchestrated turn picks its agent
|
|
778
|
+
* with an LLM `classify()` call, and sub-agents resolve their own providers.
|
|
779
|
+
* Any pre-turn "peek" would therefore be a guess that is wrong precisely on the
|
|
780
|
+
* multi-agent hosts per-vendor budgets exist for.
|
|
781
|
+
*
|
|
782
|
+
* Asking instead which vendors are REACHABLE is answerable, synchronous, and
|
|
783
|
+
* free — and it is enough: the composer must stay live while any reachable
|
|
784
|
+
* vendor has headroom, and must lock when none does. It also makes vendor-switch
|
|
785
|
+
* recovery a derivation rather than a mutation: a host that swaps its registry
|
|
786
|
+
* to another vendor fires the observable, the statuses reload, the walled vendor
|
|
787
|
+
* drops out of this set, and `blocked` goes false with every latch left intact.
|
|
788
|
+
*
|
|
789
|
+
* @beta
|
|
790
|
+
*/
|
|
791
|
+
@volatile
|
|
792
|
+
get reachableVendors(): readonly AIProviderType[] {
|
|
793
|
+
const seen = new Set<AIProviderType>();
|
|
794
|
+
for (const entry of this.providerStatuses) {
|
|
795
|
+
const provider = entry.status?.provider;
|
|
796
|
+
if (!provider || provider === 'none') continue;
|
|
797
|
+
// Reachable means "can serve the next turn", and `chat()` is OPTIONAL on
|
|
798
|
+
// `AIProvider` — the shipped `ChromeProvider` and `OpenAIProvider`
|
|
799
|
+
// implement `getStatus()` only. Counting a chat-less provider here made
|
|
800
|
+
// every consumer wrong at once: it was headroom for the `blocked`
|
|
801
|
+
// derivation (so `otherVendorAvailable: false` failed to lock the
|
|
802
|
+
// composer and each send burned another doomed 402), and it was a switch
|
|
803
|
+
// target for the banner ("Switch to Chrome to keep going" toward a
|
|
804
|
+
// provider that cannot chat).
|
|
805
|
+
//
|
|
806
|
+
// The gate is CAPABILITY, not vendor identity, so a host's custom
|
|
807
|
+
// chat-capable OpenAI provider still counts — the same distinction
|
|
808
|
+
// `validate-providers.ts` already enforces by throwing. And it drops a
|
|
809
|
+
// vendor only on positive evidence: statuses normally come from
|
|
810
|
+
// `providerRegistry.listStatuses()`, whose `name` always resolves, but a
|
|
811
|
+
// host (or test) that assigns `providerStatuses` directly may have no
|
|
812
|
+
// matching registry entry, and an unresolvable name must not silently
|
|
813
|
+
// erase a vendor the status layer vouched for.
|
|
814
|
+
const registered = this.providerRegistry?.get(entry.name);
|
|
815
|
+
if (registered && typeof registered.chat !== 'function') continue;
|
|
816
|
+
seen.add(provider);
|
|
817
|
+
}
|
|
818
|
+
return [...seen];
|
|
819
|
+
}
|
|
820
|
+
|
|
821
|
+
/**
|
|
822
|
+
* Vendors currently walled by the AI-spend budget, in the order they were
|
|
823
|
+
* walled. Empty for a host that never adopts the per-vendor API.
|
|
824
|
+
*
|
|
825
|
+
* May include a vendor this registry cannot reach — either because the registry
|
|
826
|
+
* moved on after the wall was latched, or because a 402's
|
|
827
|
+
* `otherVendorAvailable: false` walls every vendor the proxy meters (which is
|
|
828
|
+
* what that verdict is a statement about; see
|
|
829
|
+
* {@link FoundationAiAssistant.latchBlockedFrom}). Neither costs anything
|
|
830
|
+
* internally — {@link FoundationAiAssistant.blocked} asks only about the
|
|
831
|
+
* reachable set, and the banner reads the reachability-filtered
|
|
832
|
+
* {@link FoundationAiAssistant.relevantBlockedVendors} — but a host rendering
|
|
833
|
+
* this list itself should filter it against its own registry.
|
|
834
|
+
*
|
|
835
|
+
* Read-only on purpose: a settable array would let a host write a partial list
|
|
836
|
+
* and silently orphan the per-vendor banner copy.
|
|
837
|
+
* {@link FoundationAiAssistant.setVendorBlocked} is the write path.
|
|
838
|
+
*
|
|
839
|
+
* @beta
|
|
840
|
+
*/
|
|
841
|
+
get blockedVendors(): readonly AIProviderType[] {
|
|
842
|
+
return this._sessionRef?.store.aiAssistant.blockedVendors ?? [];
|
|
843
|
+
}
|
|
844
|
+
|
|
845
|
+
/**
|
|
846
|
+
* Whether this specific vendor's budget is walled — regardless of whether any
|
|
847
|
+
* other vendor still has headroom.
|
|
848
|
+
*
|
|
849
|
+
* @beta
|
|
850
|
+
*/
|
|
851
|
+
isVendorBlocked(vendor: AIProviderType): boolean {
|
|
852
|
+
return this.blockedVendors.includes(vendor);
|
|
853
|
+
}
|
|
854
|
+
|
|
855
|
+
/**
|
|
856
|
+
* Wall (or release) one vendor's budget, optionally with banner copy for it.
|
|
857
|
+
* The per-vendor mirror of {@link FoundationAiAssistant.setBlocked}.
|
|
858
|
+
*
|
|
859
|
+
* Walling a vendor does **not** on its own disable the composer: while another
|
|
860
|
+
* reachable vendor has headroom the assistant stays usable and the banner tells
|
|
861
|
+
* the user to switch. Only when every reachable vendor is walled does `blocked`
|
|
862
|
+
* become true.
|
|
863
|
+
*
|
|
864
|
+
* `reason` is composed into the banner sentence for that vendor, **however many
|
|
865
|
+
* vendors are walled** — see {@link FoundationAiAssistant.effectiveBlockedReason}.
|
|
866
|
+
* It is per-vendor copy, not a whole-banner override; {@link FoundationAiAssistant.blockedReason}
|
|
867
|
+
* is the override. Omitting it keeps whatever explanation that vendor already
|
|
868
|
+
* carried, so a driver latch landing after a host one cannot blank it.
|
|
869
|
+
*
|
|
870
|
+
* `'none'` is rejected with a warning rather than accepted: it is the "no
|
|
871
|
+
* provider configured" sentinel, not a vendor. Latching it would put the raw
|
|
872
|
+
* sentinel in the banner ("none's AI usage limit is reached") and could never
|
|
873
|
+
* be undone by derivation, because `'none'` never appears in
|
|
874
|
+
* {@link FoundationAiAssistant.reachableVendors} — so `blocked` could never
|
|
875
|
+
* become derivable from it either. Use {@link FoundationAiAssistant.setBlocked}
|
|
876
|
+
* for a vendor-agnostic block.
|
|
877
|
+
*
|
|
878
|
+
* @beta
|
|
879
|
+
*/
|
|
880
|
+
/** Whether this vendor's wall came from the sweep alone — see the slice's `sweptVendors`. */
|
|
881
|
+
private isVendorSwept(vendor: AIProviderType): boolean {
|
|
882
|
+
return (this._sessionRef?.store.aiAssistant.sweptVendors ?? []).includes(vendor);
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
setVendorBlocked(vendor: AIProviderType, blocked: boolean, reason?: string | null): void {
|
|
886
|
+
if (vendor === 'none') {
|
|
887
|
+
logger.warn(
|
|
888
|
+
"FoundationAiAssistant.setVendorBlocked: 'none' is the no-provider sentinel, not a vendor — " +
|
|
889
|
+
'ignoring. Use setBlocked() for a vendor-agnostic block.',
|
|
890
|
+
);
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
this._sessionRef?.actions.aiAssistant.setVendorBlocked({ vendor, blocked, reason });
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
/**
|
|
897
|
+
* The walled vendors the user can still be routed to — i.e.
|
|
898
|
+
* {@link FoundationAiAssistant.blockedVendors} narrowed to the reachable set,
|
|
899
|
+
* which is the only set the banner may name.
|
|
900
|
+
*
|
|
901
|
+
* A wall the registry can no longer reach is not news: it cannot be hit, and
|
|
902
|
+
* naming it puts a vendor in front of the user that is not theirs. The concrete
|
|
903
|
+
* failure this exists to stop: a host ships Anthropic-only, Anthropic walls, the
|
|
904
|
+
* host swaps its registry to Gemini, Gemini walls — and the banner reads "AI
|
|
905
|
+
* usage limits are reached for Anthropic and Gemini" to a user who has never
|
|
906
|
+
* had an Anthropic key. The spurious second name also flips the copy onto the
|
|
907
|
+
* plural branch, so even the closing sentence is wrong.
|
|
908
|
+
*
|
|
909
|
+
* When nothing is reachable YET (the statuses are still loading — the exact
|
|
910
|
+
* window the pre-flight and the cross-tab bus latch into), the fallback keeps
|
|
911
|
+
* every wall for LOCKING (`blocked` still derives true) but names only the
|
|
912
|
+
* vendors walled by a REFUSAL, dropping the ones the `otherVendorAvailable`
|
|
913
|
+
* sweep added. A refusal is a fact about a vendor this user just used; a sweep
|
|
914
|
+
* entry is the proxy's headroom verdict about a vendor the host may not even
|
|
915
|
+
* ship — naming it here reproduced the exact failure above from the other
|
|
916
|
+
* direction ("Gemini's AI usage limit is reached" to an Anthropic-only user),
|
|
917
|
+
* and flipped the copy onto the plural branch with it. Self-corrects when the
|
|
918
|
+
* statuses land: from then on reachability, not provenance, decides.
|
|
919
|
+
*
|
|
920
|
+
* @internal
|
|
921
|
+
*/
|
|
922
|
+
@volatile
|
|
923
|
+
private get relevantBlockedVendors(): readonly AIProviderType[] {
|
|
924
|
+
const walled = this.blockedVendors;
|
|
925
|
+
const reachable = this.reachableVendors;
|
|
926
|
+
if (reachable.length === 0) {
|
|
927
|
+
const swept = this._sessionRef?.store.aiAssistant.sweptVendors ?? [];
|
|
928
|
+
return walled.filter((v) => !swept.includes(v));
|
|
929
|
+
}
|
|
930
|
+
return walled.filter((v) => reachable.includes(v));
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/**
|
|
934
|
+
* Whether the blocked banner has anything to say — a vendor-agnostic block, OR
|
|
935
|
+
* at least one walled vendor the registry can still reach. Broader than
|
|
936
|
+
* {@link FoundationAiAssistant.blocked} on purpose: partial exhaustion leaves
|
|
937
|
+
* the composer live but still needs to be announced, because the next turn may
|
|
938
|
+
* route to the walled vendor and fail.
|
|
939
|
+
*
|
|
940
|
+
* Reads the reachability-filtered list for the same reason the copy does — a
|
|
941
|
+
* host that has swapped its registry away from the walled vendor has nothing
|
|
942
|
+
* left to announce, and would otherwise get a banner that falls through to the
|
|
943
|
+
* generic default copy over a perfectly usable composer.
|
|
944
|
+
*
|
|
945
|
+
* @internal
|
|
946
|
+
*/
|
|
947
|
+
@volatile
|
|
948
|
+
get bannerVisible(): boolean {
|
|
949
|
+
return this.blocked || this.relevantBlockedVendors.length > 0;
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
/**
|
|
953
|
+
* Whether a suggestions fetch would hit a wall.
|
|
954
|
+
*
|
|
955
|
+
* Unlike a chat turn, this one CAN be resolved exactly: both suggestion paths
|
|
956
|
+
* go to the registry **default** and never to a per-agent override
|
|
957
|
+
* (`ChatDriver.getSuggestions` calls `providerRegistry.default()`, and
|
|
958
|
+
* `OrchestratingDriver.getSuggestions` just delegates to it). So the vendor a
|
|
959
|
+
* suggestions call would use is knowable, and this is the one place in the
|
|
960
|
+
* feature where that is true.
|
|
961
|
+
*
|
|
962
|
+
* Same rationale as the guard it replaces: a doomed suggestions call burns a
|
|
963
|
+
* `suggestions.failed` meta event and parks a raw transport error in
|
|
964
|
+
* `suggestionsState` for hosts to find.
|
|
965
|
+
*
|
|
966
|
+
* @internal
|
|
967
|
+
*/
|
|
968
|
+
@volatile
|
|
969
|
+
get suggestionsBlocked(): boolean {
|
|
970
|
+
if (this.blocked) return true;
|
|
971
|
+
const defaultVendor = this.providerStatuses.find((e) => e.isDefault)?.status?.provider;
|
|
972
|
+
return !!defaultVendor && defaultVendor !== 'none' && this.isVendorBlocked(defaultVendor);
|
|
973
|
+
}
|
|
974
|
+
|
|
975
|
+
/**
|
|
976
|
+
* Explanation shown in the blocked banner, or `null` for the element's default
|
|
977
|
+
* copy. Only meaningful while {@link FoundationAiAssistant.blocked} is true;
|
|
978
|
+
* setting `blocked = false` clears it.
|
|
979
|
+
*
|
|
980
|
+
* Writable, and symmetric with every other store-backed accessor on this
|
|
981
|
+
* class: writing it re-latches with the CURRENT `blocked` value, so it changes
|
|
982
|
+
* the copy without disturbing the flag. Assigning `null` clears the
|
|
983
|
+
* explanation while staying blocked (the banner falls back to the default
|
|
984
|
+
* copy). {@link FoundationAiAssistant.setBlocked} remains the way to write
|
|
985
|
+
* both in one atomic action.
|
|
986
|
+
*
|
|
987
|
+
* @beta
|
|
988
|
+
*/
|
|
989
|
+
get blockedReason(): string | null {
|
|
990
|
+
return this._sessionRef?.store.aiAssistant.blockedReason ?? null;
|
|
991
|
+
}
|
|
992
|
+
set blockedReason(value: string | null) {
|
|
993
|
+
// Deliberately NOT `setBlocked({ blocked: this.blocked, reason })`: `blocked`
|
|
994
|
+
// is derived now, so re-latching with it would pass `false` for a partially
|
|
995
|
+
// walled session and clear every per-vendor latch as a side effect of setting
|
|
996
|
+
// a string.
|
|
997
|
+
this._sessionRef?.actions.aiAssistant.setBlockedReason(value);
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
/**
|
|
1001
|
+
* Latch the backend block off a turn outcome. The single decision point for
|
|
1002
|
+
* both latch sites (the `tool-loop-end` bus subscription and `send()`'s
|
|
1003
|
+
* return-value check), so the rule cannot diverge between them.
|
|
1004
|
+
*
|
|
1005
|
+
* Idempotent and one-way **per vendor**: it never unblocks, and it never
|
|
1006
|
+
* re-writes an existing wall. That guard is load-bearing, not just an
|
|
1007
|
+
* optimisation — the bus fires from the driver's `finally`, i.e. BEFORE
|
|
1008
|
+
* `sendMessage()` resolves, so a host subscribed to `tool-loop-end` (what the
|
|
1009
|
+
* migration guide's Option C recommends) sets its own detailed reason and the
|
|
1010
|
+
* return-value latch would otherwise land a moment later and blank it.
|
|
1011
|
+
*
|
|
1012
|
+
* The guard being per-vendor rather than global is the whole difference. A
|
|
1013
|
+
* single global "already blocked, do nothing" would swallow a second vendor's
|
|
1014
|
+
* wall — so a session walled on Anthropic could never record that Gemini went
|
|
1015
|
+
* too, and under a mixed registry an Anthropic-only wall would lock a composer
|
|
1016
|
+
* that Gemini could still serve.
|
|
1017
|
+
*
|
|
1018
|
+
* **Which field is authoritative**, in order:
|
|
1019
|
+
*
|
|
1020
|
+
* 1. `budget.vendorLabel` — stamped by the transport that was actually refused,
|
|
1021
|
+
* so it can never be stale. But it is a static per-transport string, so a
|
|
1022
|
+
* white-labelled or multiplexing gateway fronting several upstreams leaves
|
|
1023
|
+
* it unclaimed by any vendor.
|
|
1024
|
+
* 2. `budget.vendor` — which the driver resolved from the label where it could,
|
|
1025
|
+
* and otherwise from the proxy's own `vendor` field on the 402. It is
|
|
1026
|
+
* therefore NOT simply `vendorLabel` normalised, and the two can disagree;
|
|
1027
|
+
* that fallback is the only attribution on offer for the gateway case above.
|
|
1028
|
+
* 3. `vendorHint` — the bus detail's top-level vendor, i.e. the driver's
|
|
1029
|
+
* last-resolved provider. Last resort because it CAN be stale: an
|
|
1030
|
+
* orchestrated turn classifies against the registry default, a provider the
|
|
1031
|
+
* chat driver may never have resolved, so its last-resolved provider there is
|
|
1032
|
+
* the previous turn's vendor or nothing at all.
|
|
1033
|
+
*
|
|
1034
|
+
* A wall that names no recognised vendor falls back to the vendor-agnostic
|
|
1035
|
+
* block — fail-safe, and identical to the pre-per-vendor behaviour.
|
|
1036
|
+
*
|
|
1037
|
+
* **`otherVendorAvailable: false` is server-known truth and outranks every
|
|
1038
|
+
* inference made here.** The proxy meters the pots, so only it can say whether
|
|
1039
|
+
* anything else has headroom; this element can only observe which vendors the
|
|
1040
|
+
* registry can REACH, which says nothing about their remaining spend. So when
|
|
1041
|
+
* the proxy says no, every other *budgeted* vendor is walled in the same pass.
|
|
1042
|
+
* That is what makes `blocked` derive true — locking the composer on the first
|
|
1043
|
+
* response instead of after a second doomed turn — and what empties the "free"
|
|
1044
|
+
* set the banner would otherwise have advised switching to.
|
|
1045
|
+
*
|
|
1046
|
+
* The sweep runs over `BUDGETED_VENDORS`, deliberately **not** over
|
|
1047
|
+
* {@link FoundationAiAssistant.reachableVendors}. Reachability is loaded
|
|
1048
|
+
* asynchronously (`activateSession` kicks off `loadProviderStatuses()` and does
|
|
1049
|
+
* not await it), so a wall landing before the statuses resolve would have swept
|
|
1050
|
+
* an empty set — silently discarding the one fact on the 402 the client cannot
|
|
1051
|
+
* re-derive, with nothing to re-run it when the statuses arrived. Worse, it let
|
|
1052
|
+
* the verdict effectively un-latch: the single wall derived `blocked` only
|
|
1053
|
+
* while the reachable set was empty, so the moment the statuses landed the
|
|
1054
|
+
* composer came back to life against a budget the proxy had already said was
|
|
1055
|
+
* gone. Sweeping the metered vendor list instead makes the verdict independent
|
|
1056
|
+
* of load order and of registry membership, which is exactly what it is: a
|
|
1057
|
+
* statement about the proxy's pots, not about this user's registry.
|
|
1058
|
+
*
|
|
1059
|
+
* Walling a vendor the registry cannot reach costs nothing: `blocked` only asks
|
|
1060
|
+
* whether every REACHABLE vendor is walled, and the banner reads
|
|
1061
|
+
* {@link FoundationAiAssistant.relevantBlockedVendors}, which filters the walls
|
|
1062
|
+
* back down to the reachable set before naming any of them.
|
|
1063
|
+
*
|
|
1064
|
+
* One boundary remains on the sweep: it walls only vendors the proxy meters,
|
|
1065
|
+
* enforced structurally by iterating `BUDGETED_VENDORS` itself rather than
|
|
1066
|
+
* filtering a wider set through a predicate. Chrome runs on-device with no pot
|
|
1067
|
+
* to exhaust, so "no other vendor has budget" is not a statement about it, and
|
|
1068
|
+
* "Switch to Chrome to keep going." stays honest advice.
|
|
1069
|
+
*
|
|
1070
|
+
* The sweep runs last but sits OUTSIDE the per-vendor idempotence guard, and
|
|
1071
|
+
* both halves of that matter. Last, so the vendor that actually refused this
|
|
1072
|
+
* turn heads the wall order the multi-vendor banner reads. Outside the guard,
|
|
1073
|
+
* because the verdict can arrive on a LATER 402 for a vendor that is already
|
|
1074
|
+
* walled — turn 1 walls Anthropic while Gemini still has headroom, turn 2 walls
|
|
1075
|
+
* it again and reports that Gemini has since gone too — and an early return
|
|
1076
|
+
* would drop exactly the news the second turn was there to deliver.
|
|
1077
|
+
*
|
|
1078
|
+
* @param reason - the turn's failure reason; anything but `'budget-exhausted'` is ignored.
|
|
1079
|
+
* @param ref - session store to write through; defaults to the live one. `send()`
|
|
1080
|
+
* passes the ref it captured before its awaits, since a lifecycle event during the
|
|
1081
|
+
* turn may already have cleared `_sessionRef`.
|
|
1082
|
+
* @param budget - what the 402 reported: figures when the proxy sent any, the
|
|
1083
|
+
* refusing vendor, and its `otherVendorAvailable` verdict.
|
|
1084
|
+
* @param vendorHint - the `tool-loop-end` detail's top-level vendor, used only
|
|
1085
|
+
* when the budget payload names none.
|
|
1086
|
+
*
|
|
1087
|
+
* @internal
|
|
1088
|
+
*/
|
|
1089
|
+
private latchBlockedFrom(
|
|
1090
|
+
reason?: TurnFailureReason,
|
|
1091
|
+
ref = this._sessionRef,
|
|
1092
|
+
budget?: Extract<ChatDriverResult, { reason: 'done' }>['budget'],
|
|
1093
|
+
vendorHint?: AIProviderType,
|
|
1094
|
+
): void {
|
|
1095
|
+
if (reason !== 'budget-exhausted') return;
|
|
1096
|
+
const vendor = vendorTypeOfLabel(budget?.vendorLabel) ?? budget?.vendor ?? vendorHint;
|
|
1097
|
+
if (!vendor || vendor === 'none') {
|
|
1098
|
+
if (!this.blocked) {
|
|
1099
|
+
ref?.actions.aiAssistant.setBlocked({ blocked: true, reason: formatBlockedReason(budget) });
|
|
1100
|
+
}
|
|
1101
|
+
} else if (!this.isVendorBlocked(vendor) || this.isVendorSwept(vendor)) {
|
|
1102
|
+
// The idempotence guard protects a host-supplied reason from being
|
|
1103
|
+
// overwritten by this latch's boilerplate — but a SWEPT wall cannot carry
|
|
1104
|
+
// one (the sweep writes no reason, and any host call clears the swept
|
|
1105
|
+
// mark), so upgrading it on a first-hand refusal clobbers nothing and
|
|
1106
|
+
// gains the vendor its own figures plus a place in the early-window
|
|
1107
|
+
// banner (see `relevantBlockedVendors`).
|
|
1108
|
+
if (this.reachableVendors.length === 0) {
|
|
1109
|
+
// Not fatal — `blocked` still derives to true, so the UI is correct — but
|
|
1110
|
+
// the host gets no per-vendor benefit and would otherwise have no signal.
|
|
1111
|
+
logger.warn(
|
|
1112
|
+
`FoundationAiAssistant: ${vendor} hit its AI budget, but no registered provider counts ` +
|
|
1113
|
+
'as reachable, so per-vendor blocking degrades to blocking everything. Two causes: no ' +
|
|
1114
|
+
'provider reports a status (implement AIProvider.getStatus()), or every provider that ' +
|
|
1115
|
+
'does is chat-less and so cannot serve a turn (implement chat() on at least one).',
|
|
1116
|
+
);
|
|
1117
|
+
}
|
|
1118
|
+
ref?.actions.aiAssistant.setVendorBlocked({
|
|
1119
|
+
vendor,
|
|
1120
|
+
blocked: true,
|
|
1121
|
+
reason: formatBlockedReason(budget, vendor),
|
|
1122
|
+
});
|
|
1123
|
+
}
|
|
1124
|
+
// Last, so the vendor that actually refused this turn heads the wall order the
|
|
1125
|
+
// multi-vendor banner reads — and unconditionally, NOT under the per-vendor
|
|
1126
|
+
// idempotence guard above, because the verdict can arrive on a later 402 for a
|
|
1127
|
+
// vendor that is already walled.
|
|
1128
|
+
if (budget?.otherVendorAvailable !== false) return;
|
|
1129
|
+
// Over the metered vendor list, NOT the reachable set: the statuses load
|
|
1130
|
+
// asynchronously, so a reachability-scoped sweep dropped the verdict entirely
|
|
1131
|
+
// when the wall beat them home. `relevantBlockedVendors` decides what the
|
|
1132
|
+
// banner may NAME — reachability-filtered when the statuses are in, and
|
|
1133
|
+
// refusals-only while they are not, which is what `swept: true` records.
|
|
1134
|
+
for (const other of BUDGETED_VENDORS) {
|
|
1135
|
+
if (other === vendor || this.isVendorBlocked(other)) continue;
|
|
1136
|
+
// No reason: the slice's "an omitted reason keeps the existing explanation"
|
|
1137
|
+
// rule applies, and there are no figures for this vendor — only the proxy's
|
|
1138
|
+
// word that it has nothing left. `swept: true` records exactly that
|
|
1139
|
+
// provenance, so the unknown-reachability banner can decline to name it.
|
|
1140
|
+
ref?.actions.aiAssistant.setVendorBlocked({ vendor: other, blocked: true, swept: true });
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
/**
|
|
1145
|
+
* Block or unblock the assistant, optionally with custom banner copy.
|
|
1146
|
+
* Equivalent to the {@link FoundationAiAssistant.blocked} setter, plus the
|
|
1147
|
+
* reason in one atomic write.
|
|
1148
|
+
*
|
|
1149
|
+
* Blocking writes the **vendor-agnostic** block — what a host with one budget
|
|
1150
|
+
* pot means — and does not populate
|
|
1151
|
+
* {@link FoundationAiAssistant.blockedVendors}. Unblocking clears the
|
|
1152
|
+
* per-vendor walls as well, so a host asserting "the wall is gone" after its
|
|
1153
|
+
* own pre-flight cannot be silently overruled by a driver latch it never saw.
|
|
1154
|
+
*
|
|
1155
|
+
* @beta
|
|
1156
|
+
*/
|
|
1157
|
+
setBlocked(blocked: boolean, reason?: string | null): void {
|
|
1158
|
+
this._sessionRef?.actions.aiAssistant.setBlocked({ blocked, reason });
|
|
1159
|
+
}
|
|
1160
|
+
|
|
1161
|
+
/**
|
|
1162
|
+
* Copy shown in the blocked banner, in ascending specificity:
|
|
1163
|
+
*
|
|
1164
|
+
* 1. the host's `blockedReason` — a whole-banner override, unchanged;
|
|
1165
|
+
* 2. copy composed from the walled vendors (their per-vendor reasons when set,
|
|
1166
|
+
* otherwise their names) plus the action that is actually available;
|
|
1167
|
+
* 3. the default budget-exhaustion message.
|
|
1168
|
+
*
|
|
1169
|
+
* The action clause is computed here rather than stored, because whether
|
|
1170
|
+
* "switch vendor" or "contact your administrator" is honest depends on whether
|
|
1171
|
+
* another reachable vendor still has headroom — which changes when the registry
|
|
1172
|
+
* changes, long after the wall was latched. Telling a user to switch to a
|
|
1173
|
+
* vendor that is also exhausted is worse than saying nothing.
|
|
1174
|
+
*
|
|
1175
|
+
* The `free` set is a client-side inference — "reachable and not known to be
|
|
1176
|
+
* walled" — and it is only ever allowed to be one. Where the proxy has told us
|
|
1177
|
+
* otherwise (`otherVendorAvailable: false`) the latch has already walled those
|
|
1178
|
+
* vendors, so they are not in `free` here and no "switch to X" clause can be
|
|
1179
|
+
* composed from them. Both lists are filtered by reachability, so the copy
|
|
1180
|
+
* names only vendors this user's registry can actually route to.
|
|
1181
|
+
*
|
|
1182
|
+
* **Per-vendor copy is composed however many vendors are walled**, which is
|
|
1183
|
+
* what {@link FoundationAiAssistant.setVendorBlocked} and
|
|
1184
|
+
* `docs/migration-GENC-1464.md` both promise. It previously reached only the
|
|
1185
|
+
* single-vendor branch, so a host that had carefully set copy for each of its
|
|
1186
|
+
* vendors watched all of it vanish the moment a second one walled — replaced by
|
|
1187
|
+
* generic copy, at the exact moment the situation got worse.
|
|
1188
|
+
*
|
|
1189
|
+
* The compact "AI usage limits are reached for A and B." list is kept for the
|
|
1190
|
+
* case it was written for: NO walled vendor carries copy, so a statement per
|
|
1191
|
+
* vendor would just repeat one boilerplate sentence per name. As soon as any of
|
|
1192
|
+
* them does carry copy, the branch lists one statement per vendor instead —
|
|
1193
|
+
* falling back to that same boilerplate for the ones that have none, so the
|
|
1194
|
+
* sentence set stays complete rather than silently naming a subset.
|
|
1195
|
+
*
|
|
1196
|
+
* @internal
|
|
1197
|
+
*/
|
|
1198
|
+
@volatile
|
|
1199
|
+
get effectiveBlockedReason(): string {
|
|
1200
|
+
if (this.blockedReason) return this.blockedReason;
|
|
1201
|
+
|
|
1202
|
+
const walled = this.relevantBlockedVendors;
|
|
1203
|
+
if (walled.length === 0) return DEFAULT_BUDGET_EXHAUSTED_MESSAGE;
|
|
1204
|
+
|
|
1205
|
+
const free = this.reachableVendors.filter((v) => !walled.includes(v));
|
|
1206
|
+
const action = free.length
|
|
1207
|
+
? `Switch to ${formatVendorList(free)} to keep going.`
|
|
1208
|
+
: walled.length > 1
|
|
1209
|
+
? RAISE_LIMITS_ACTION
|
|
1210
|
+
: RAISE_LIMIT_ACTION;
|
|
1211
|
+
|
|
1212
|
+
const reasons = this._sessionRef?.store.aiAssistant.blockedVendorReasons;
|
|
1213
|
+
const statementFor = (v: AIProviderType) =>
|
|
1214
|
+
reasons?.[v] ?? `${vendorDisplayName(v)}'s AI usage limit is reached.`;
|
|
1215
|
+
|
|
1216
|
+
if (walled.length === 1) return `${statementFor(walled[0])} ${action}`;
|
|
1217
|
+
// Several walled vendors carry several sets of figures, which do not fit one
|
|
1218
|
+
// sentence. With no per-vendor copy to preserve, name them in a list rather
|
|
1219
|
+
// than repeat the same boilerplate sentence per vendor.
|
|
1220
|
+
if (!walled.some((v) => reasons?.[v])) {
|
|
1221
|
+
return `AI usage limits are reached for ${formatVendorList(walled)}. ${action}`;
|
|
1222
|
+
}
|
|
1223
|
+
return `${walled.map(statementFor).join(' ')} ${action}`;
|
|
1224
|
+
}
|
|
1225
|
+
|
|
1226
|
+
/**
|
|
1227
|
+
* Copy the driver writes into the TRANSCRIPT when a turn hits the budget wall.
|
|
1228
|
+
*
|
|
1229
|
+
* A host-set `blockedReason` still wins, so a white-labelled host does not read
|
|
1230
|
+
* its own explanation in the banner and the shipped default directly below it —
|
|
1231
|
+
* that is the whole reason the driver takes this at all.
|
|
1232
|
+
*
|
|
1233
|
+
* What it deliberately is NOT is
|
|
1234
|
+
* {@link FoundationAiAssistant.effectiveBlockedReason}. That getter
|
|
1235
|
+
* composes advice — `"…Switch to Gemini to keep going."` — which is true only
|
|
1236
|
+
* while that vendor has headroom, and the transcript is a permanent record. The
|
|
1237
|
+
* driver reads this once at CONSTRUCTION, and `getOrCreateDriver` keys on the
|
|
1238
|
+
* agents list, so an agents swap *after* a wall re-runs `createDriver` and would
|
|
1239
|
+
* freeze that sentence into every later turn's bubble. Reading the latch's own
|
|
1240
|
+
* copy instead is structurally incapable of carrying the advice: the only
|
|
1241
|
+
* writer of `blockedReason` is the vendor-agnostic branch of
|
|
1242
|
+
* `latchBlockedFrom`, whose `formatBlockedReason(budget)` form has no switch
|
|
1243
|
+
* clause. Per-vendor copy lives in `blockedVendorReasons` and reaches the
|
|
1244
|
+
* banner alone.
|
|
1245
|
+
*/
|
|
1246
|
+
private get transcriptBudgetExhaustedMessage(): string {
|
|
1247
|
+
return this.blockedReason ?? DEFAULT_BUDGET_EXHAUSTED_MESSAGE;
|
|
1248
|
+
}
|
|
1249
|
+
|
|
607
1250
|
/**
|
|
608
1251
|
* Name of the agent the user has pinned via the agent picker. `null` means
|
|
609
1252
|
* automatic routing (Auto). Persisted on the session store, so it survives
|
|
@@ -1187,6 +1830,8 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
1187
1830
|
private driverCleanup?: () => void;
|
|
1188
1831
|
private loadingTimer: ReturnType<typeof setTimeout> | undefined;
|
|
1189
1832
|
private unsubBus?: () => void;
|
|
1833
|
+
/** Unsubscribe handle for the `tool-loop-end` budget latch (GENC-1464). */
|
|
1834
|
+
private _unsubBudgetLatch?: () => void;
|
|
1190
1835
|
/** Unsubscribe handle for the provider-registry change listener (observable registries only). */
|
|
1191
1836
|
private unsubProviderRegistry?: () => void;
|
|
1192
1837
|
/** Unsubscribe handle for {@link (AssistantAppSettingsProvider:interface).subscribe}. */
|
|
@@ -1570,6 +2215,7 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
1570
2215
|
maxFoldOperations: agent.maxFoldOperations,
|
|
1571
2216
|
maxTurnSnapshots: agent.maxTurnSnapshots,
|
|
1572
2217
|
activityBus: agenticActivityBus,
|
|
2218
|
+
budgetExhaustedMessage: this.transcriptBudgetExhaustedMessage,
|
|
1573
2219
|
});
|
|
1574
2220
|
}
|
|
1575
2221
|
|
|
@@ -1579,6 +2225,7 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
1579
2225
|
maxTurnSnapshots: agent.maxTurnSnapshots,
|
|
1580
2226
|
sessionKey: this.getStateKey() ?? '',
|
|
1581
2227
|
activityBus: agenticActivityBus,
|
|
2228
|
+
budgetExhaustedMessage: this.transcriptBudgetExhaustedMessage,
|
|
1582
2229
|
});
|
|
1583
2230
|
}
|
|
1584
2231
|
|
|
@@ -1942,6 +2589,19 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
1942
2589
|
});
|
|
1943
2590
|
}
|
|
1944
2591
|
this.wireAppSettingsProvider();
|
|
2592
|
+
// Latch the backend block off the activity bus (GENC-1464). This is the primary
|
|
2593
|
+
// seam: it fires for a turn this element did not start, for a sub-agent's
|
|
2594
|
+
// wall (the child inherits the parent's bus and publishes its own
|
|
2595
|
+
// `tool-loop-end`), and it writes through whichever element is connected NOW
|
|
2596
|
+
// rather than the one that happened to call `send()`. Re-subscribed per
|
|
2597
|
+
// connect (docking/popout remounts); balanced in `disconnectedCallback`.
|
|
2598
|
+
this._unsubBudgetLatch?.();
|
|
2599
|
+
this._unsubBudgetLatch = agenticActivityBus.subscribe('tool-loop-end', (d) =>
|
|
2600
|
+
// Pass the figures through: this seam wins the latch for an in-loop wall (the
|
|
2601
|
+
// common case), so dropping them here would render the generic banner copy in
|
|
2602
|
+
// exactly the path `ChatDriverResult.budget` was widened to serve.
|
|
2603
|
+
this.latchBlockedFrom(d?.failureReason, undefined, d?.budget, d?.vendor),
|
|
2604
|
+
);
|
|
1945
2605
|
if (this.messagesEl) {
|
|
1946
2606
|
this._scrollListener = () => {
|
|
1947
2607
|
this._userScrolledAway =
|
|
@@ -2048,6 +2708,8 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
2048
2708
|
this.unwireDriver();
|
|
2049
2709
|
this.unsubBus?.();
|
|
2050
2710
|
this.unsubBus = undefined;
|
|
2711
|
+
this._unsubBudgetLatch?.();
|
|
2712
|
+
this._unsubBudgetLatch = undefined;
|
|
2051
2713
|
this.unsubProviderRegistry?.();
|
|
2052
2714
|
this.unsubProviderRegistry = undefined;
|
|
2053
2715
|
this.unwireAppSettingsProvider();
|
|
@@ -2995,6 +3657,9 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
2995
3657
|
*/
|
|
2996
3658
|
@volatile
|
|
2997
3659
|
get effectivePlaceholder(): string {
|
|
3660
|
+
// The block outranks the agent pin: while blocked the composer is disabled
|
|
3661
|
+
// anyway, so naming the pinned agent would only imply a send is possible.
|
|
3662
|
+
if (this.blocked) return BLOCKED_PLACEHOLDER;
|
|
2998
3663
|
if (this.pinnedAgentName) return `Message ${this.pinnedAgentName}...`;
|
|
2999
3664
|
return this.placeholder;
|
|
3000
3665
|
}
|
|
@@ -3389,6 +4054,10 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
3389
4054
|
}
|
|
3390
4055
|
|
|
3391
4056
|
handleSuggestionClick(suggestion: string) {
|
|
4057
|
+
// Belt-and-braces with the template gate that hides the chips while blocked:
|
|
4058
|
+
// `send()` refuses, but `inputValue` would already have been written, leaving
|
|
4059
|
+
// the chip's text stranded in a disabled textarea the user cannot clear.
|
|
4060
|
+
if (this.sendBlocked) return;
|
|
3392
4061
|
this.inputValue = suggestion;
|
|
3393
4062
|
this.send();
|
|
3394
4063
|
}
|
|
@@ -3416,7 +4085,7 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
3416
4085
|
*/
|
|
3417
4086
|
async submitMessage(input: { text?: string; files?: File[] }): Promise<SubmitMessageResult> {
|
|
3418
4087
|
if (this.sendBlocked) {
|
|
3419
|
-
return { ok: false, errors: [
|
|
4088
|
+
return { ok: false, errors: [this.sendRefusalReason()] };
|
|
3420
4089
|
}
|
|
3421
4090
|
|
|
3422
4091
|
let nextAttachments: ChatAttachment[] = [];
|
|
@@ -3430,7 +4099,7 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
3430
4099
|
// (Cast widens through TS's narrowing of `this.state` from the earlier
|
|
3431
4100
|
// early-return; the getter can return a different value across an await.)
|
|
3432
4101
|
if (this.sendBlocked) {
|
|
3433
|
-
return { ok: false, errors: [
|
|
4102
|
+
return { ok: false, errors: [this.sendRefusalReason()] };
|
|
3434
4103
|
}
|
|
3435
4104
|
if (errors.length) {
|
|
3436
4105
|
this.attachmentErrors = errors;
|
|
@@ -3462,6 +4131,22 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
3462
4131
|
return;
|
|
3463
4132
|
}
|
|
3464
4133
|
|
|
4134
|
+
// A guaranteed 402. This runs from the post-turn `finally` (the turn that
|
|
4135
|
+
// just latched), from `connectedCallback` (a pop-in against a blocked store),
|
|
4136
|
+
// and from the `pinnedAgentName` setter — which resets `suggestionsState`
|
|
4137
|
+
// first, defeating the already-fetched guard below. So without this a blocked
|
|
4138
|
+
// session still fires one doomed request per turn, per pop-in and per pin
|
|
4139
|
+
// change, each one burning a `suggestions.failed` meta event and parking a
|
|
4140
|
+
// raw transport-error string in `suggestionsState.message`.
|
|
4141
|
+
//
|
|
4142
|
+
// Resolved against the registry DEFAULT, not the whole composer gate: both
|
|
4143
|
+
// suggestion paths call `providerRegistry.default()`, so under partial
|
|
4144
|
+
// exhaustion this is knowable exactly — and suggestions stay available when
|
|
4145
|
+
// the default vendor is the one with headroom.
|
|
4146
|
+
if (this.suggestionsBlocked) {
|
|
4147
|
+
return;
|
|
4148
|
+
}
|
|
4149
|
+
|
|
3465
4150
|
if (suggestionsConfig.behavior === 'initial' && this.messages.length > 0) {
|
|
3466
4151
|
return;
|
|
3467
4152
|
}
|
|
@@ -3551,7 +4236,16 @@ export class FoundationAiAssistant extends GenesisElement {
|
|
|
3551
4236
|
? `${input}\n\n*Attached: ${pendingAttachments.map((a) => a.name).join(', ')}*`
|
|
3552
4237
|
: input;
|
|
3553
4238
|
try {
|
|
3554
|
-
await this.driver?.sendMessage(displayInput, pendingAttachments);
|
|
4239
|
+
const result = await this.driver?.sendMessage(displayInput, pendingAttachments);
|
|
4240
|
+
// Latch the backend block the moment the driver reports it, so the composer
|
|
4241
|
+
// locks without waiting on the host's next pre-flight. The bus subscription
|
|
4242
|
+
// in `connectedCallback` covers most walls; this covers the one it cannot —
|
|
4243
|
+
// a wall hit during multi-agent classification, where no tool loop ran and
|
|
4244
|
+
// so no `tool-loop-end` was published. `latchBlockedFrom` is idempotent, so
|
|
4245
|
+
// the two seams overlapping is harmless.
|
|
4246
|
+
if (result?.reason === 'done') {
|
|
4247
|
+
this.latchBlockedFrom(result.failureReason, capturedSessionRef, result.budget);
|
|
4248
|
+
}
|
|
3555
4249
|
} finally {
|
|
3556
4250
|
this.stopLoadingTimer();
|
|
3557
4251
|
this._pendingSendPrompt = undefined;
|