@genesislcap/ai-assistant 15.82.0 → 15.84.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 +2811 -233
- package/dist/ai-assistant.d.ts +835 -93
- package/dist/chat-driver.cjs +452 -99
- package/dist/chat-driver.cjs.map +4 -4
- package/dist/chat-driver.mjs +452 -99
- package/dist/chat-driver.mjs.map +4 -4
- package/dist/custom-elements.json +1903 -907
- package/dist/dts/autopilot/autopilot-driver.d.ts +117 -11
- package/dist/dts/autopilot/autopilot-driver.d.ts.map +1 -1
- package/dist/dts/autopilot/autopilot-session.d.ts +55 -7
- package/dist/dts/autopilot/autopilot-session.d.ts.map +1 -1
- package/dist/dts/autopilot/autopilot-tools.d.ts +3 -2
- package/dist/dts/autopilot/autopilot-tools.d.ts.map +1 -1
- package/dist/dts/autopilot/decision-message.d.ts +35 -3
- package/dist/dts/autopilot/decision-message.d.ts.map +1 -1
- package/dist/dts/autopilot/hand-back/hand-back.controller.d.ts +2 -2
- package/dist/dts/autopilot/hand-back/hand-back.controller.d.ts.map +1 -1
- package/dist/dts/autopilot/hand-back/hand-back.d.ts +2 -2
- package/dist/dts/autopilot/hand-back/hand-back.d.ts.map +1 -1
- package/dist/dts/autopilot/index.d.ts +1 -0
- package/dist/dts/autopilot/index.d.ts.map +1 -1
- package/dist/dts/autopilot/widget-tools.d.ts +95 -0
- package/dist/dts/autopilot/widget-tools.d.ts.map +1 -0
- package/dist/dts/channel/ai-activity-channel.d.ts +10 -0
- package/dist/dts/channel/ai-activity-channel.d.ts.map +1 -1
- package/dist/dts/components/ai-driver/ai-driver.d.ts +25 -6
- package/dist/dts/components/ai-driver/ai-driver.d.ts.map +1 -1
- package/dist/dts/components/ai-driver/base-driver-decorator.d.ts +2 -0
- package/dist/dts/components/ai-driver/base-driver-decorator.d.ts.map +1 -1
- package/dist/dts/components/chat-driver/chat-driver.d.ts +14 -2
- package/dist/dts/components/chat-driver/chat-driver.d.ts.map +1 -1
- package/dist/dts/components/chat-driver/interaction-controller.d.ts +61 -17
- package/dist/dts/components/chat-driver/interaction-controller.d.ts.map +1 -1
- package/dist/dts/config/config.d.ts +31 -6
- package/dist/dts/config/config.d.ts.map +1 -1
- package/dist/dts/config/define-stateful-agent.d.ts +5 -1
- package/dist/dts/config/define-stateful-agent.d.ts.map +1 -1
- package/dist/dts/genesis/write-outcome.d.ts.map +1 -1
- package/dist/dts/index.d.ts +4 -2
- package/dist/dts/index.d.ts.map +1 -1
- package/dist/dts/main/main.d.ts +11 -0
- package/dist/dts/main/main.d.ts.map +1 -1
- package/dist/dts/main/main.template.d.ts.map +1 -1
- package/dist/dts/notifications/agent-notifications.d.ts +6 -2
- package/dist/dts/notifications/agent-notifications.d.ts.map +1 -1
- package/dist/dts/notifications/agent-notifier.d.ts +26 -4
- package/dist/dts/notifications/agent-notifier.d.ts.map +1 -1
- package/dist/dts/state/decision-surface.d.ts +22 -4
- package/dist/dts/state/decision-surface.d.ts.map +1 -1
- package/dist/dts/state/interaction-context.d.ts +23 -4
- package/dist/dts/state/interaction-context.d.ts.map +1 -1
- package/dist/dts/state/interaction-registry.d.ts +55 -6
- package/dist/dts/state/interaction-registry.d.ts.map +1 -1
- package/dist/dts/state/live-interactions.d.ts +28 -0
- package/dist/dts/state/live-interactions.d.ts.map +1 -0
- package/dist/dts/state/persistence/session-persister.d.ts.map +1 -1
- package/dist/dts/state/persistence/session-snapshot.d.ts +16 -5
- package/dist/dts/state/persistence/session-snapshot.d.ts.map +1 -1
- package/dist/dts/state/test-interaction-context.d.ts +93 -0
- package/dist/dts/state/test-interaction-context.d.ts.map +1 -0
- package/dist/dts/types/ai-chat-widget.d.ts +7 -6
- package/dist/dts/types/ai-chat-widget.d.ts.map +1 -1
- package/dist/dts/types/interaction-context.d.ts +128 -17
- package/dist/dts/types/interaction-context.d.ts.map +1 -1
- package/dist/dts/types/interaction-interceptor.d.ts +48 -6
- package/dist/dts/types/interaction-interceptor.d.ts.map +1 -1
- package/dist/dts/types/interaction-surface.d.ts +145 -23
- package/dist/dts/types/interaction-surface.d.ts.map +1 -1
- package/dist/esm/autopilot/autopilot-driver.js +313 -60
- package/dist/esm/autopilot/autopilot-session.js +219 -40
- package/dist/esm/autopilot/autopilot-tools.js +11 -7
- package/dist/esm/autopilot/decision-message.js +105 -26
- package/dist/esm/autopilot/hand-back/hand-back.controller.js +2 -1
- package/dist/esm/autopilot/index.js +1 -0
- package/dist/esm/autopilot/widget-tools.js +39 -0
- package/dist/esm/components/ai-driver/base-driver-decorator.js +17 -0
- package/dist/esm/components/chat-driver/chat-driver.js +18 -2
- package/dist/esm/components/chat-driver/interaction-controller.js +232 -71
- package/dist/esm/components/settings-modal/settings-modal.template.js +2 -2
- package/dist/esm/config/define-stateful-agent.js +22 -1
- package/dist/esm/genesis/write-outcome.js +8 -4
- package/dist/esm/index.js +2 -0
- package/dist/esm/main/main.js +39 -3
- package/dist/esm/main/main.template.js +4 -1
- package/dist/esm/notifications/agent-notifications.js +11 -1
- package/dist/esm/notifications/agent-notifier.js +41 -7
- package/dist/esm/state/debug-event-log.js +5 -5
- package/dist/esm/state/decision-surface.js +137 -54
- package/dist/esm/state/interaction-context.js +41 -8
- package/dist/esm/state/interaction-registry.js +11 -0
- package/dist/esm/state/live-interactions.js +36 -0
- package/dist/esm/state/persistence/session-persister.js +44 -17
- package/dist/esm/state/persistence/session-snapshot.js +2 -2
- package/dist/esm/state/test-interaction-context.js +99 -0
- package/docs/notifications.md +55 -5
- package/docs/styling.md +33 -0
- package/package.json +19 -19
- package/sandbox/README.md +3 -2
- package/sandbox/autopilot.ts +26 -6
- package/sandbox/sandbox.ts +2 -0
- /package/dist/{tsdoc-metadata.json → dts/tsdoc-metadata.json} +0 -0
|
@@ -628,13 +628,16 @@ ${(tc) => { var _a; return (((_a = tc.foldPath) === null || _a === void 0 ? void
|
|
|
628
628
|
// it is filled the way the person's own bubble is while it runs, since it is filling in for them.
|
|
629
629
|
// A toggle: `aria-pressed` carries its state, so its accessible name is constant (the pill's own
|
|
630
630
|
// label) and what the click does — Pause / Resume — leads its tooltip instead.
|
|
631
|
+
// While on it carries a second part name, `autopilot-toggle-on`, as the conversation carries
|
|
632
|
+
// `conversation-has-stepper`: `::part()` cannot select a class or an attribute, so without it a
|
|
633
|
+
// host could restyle the pill but not its on state, e.g. to fill it with its own user-bubble token.
|
|
631
634
|
const autopilotToggleTemplate = html `
|
|
632
635
|
<${buttonTag}
|
|
633
636
|
class="${(x) => classNames('composer-pill', 'composer-pill-labelled', 'autopilot-toggle', [
|
|
634
637
|
'is-on',
|
|
635
638
|
x.autopilotCanPause,
|
|
636
639
|
])}"
|
|
637
|
-
part="autopilot-toggle"
|
|
640
|
+
part="${(x) => (x.autopilotCanPause ? 'autopilot-toggle autopilot-toggle-on' : 'autopilot-toggle')}"
|
|
638
641
|
appearance="stealth"
|
|
639
642
|
aria-pressed="${(x) => (x.autopilotCanPause ? 'true' : 'false')}"
|
|
640
643
|
title="${(x) => x.autopilotToggleTitle}"
|
|
@@ -44,12 +44,22 @@ export const levelOffered = (level, config) => notificationsOffered(config) && (
|
|
|
44
44
|
* @internal
|
|
45
45
|
*/
|
|
46
46
|
export const effectiveNotificationLevel = (stored, config) => (levelOffered(stored, config) ? stored : 'off');
|
|
47
|
+
/**
|
|
48
|
+
* The lowest level that notifies for each kind. Keyed by the union, so a new kind is a compile
|
|
49
|
+
* error here rather than one every level silently shows or hides.
|
|
50
|
+
*/
|
|
51
|
+
const KIND_LEVEL = {
|
|
52
|
+
'autopilot-handed-back': 'autopilot',
|
|
53
|
+
'autopilot-stopped': 'autopilot',
|
|
54
|
+
'widget-needs-input': 'needs-input',
|
|
55
|
+
'turn-ended': 'needs-input',
|
|
56
|
+
};
|
|
47
57
|
/**
|
|
48
58
|
* Whether a level notifies for a kind of event.
|
|
49
59
|
*
|
|
50
60
|
* @internal
|
|
51
61
|
*/
|
|
52
|
-
export const levelAllows = (level, kind) => level === 'needs-input' || (level === 'autopilot' && kind
|
|
62
|
+
export const levelAllows = (level, kind) => level === 'needs-input' || (level === 'autopilot' && KIND_LEVEL[kind] === 'autopilot');
|
|
53
63
|
/**
|
|
54
64
|
* Whether an event's session is `sessionKey` or one of its sub-agents' sessions.
|
|
55
65
|
*
|
|
@@ -2,8 +2,8 @@ import { logger } from '../utils/logger';
|
|
|
2
2
|
import { agentNotificationPermission, DEFAULT_AGENT_NOTIFICATION_MESSAGE, levelAllows, } from './agent-notifications';
|
|
3
3
|
/**
|
|
4
4
|
* How long a notification with a given tag holds off another with the same tag. Two sources can
|
|
5
|
-
* report one moment — the autopilot
|
|
6
|
-
*
|
|
5
|
+
* report one moment — the autopilot handing a widget back, and that widget asking for attention
|
|
6
|
+
* just after — and the second should not alert again. It may still improve the text: see
|
|
7
7
|
* `AgentNotifier.notify`.
|
|
8
8
|
*/
|
|
9
9
|
const REPEAT_WINDOW_MS = 5000;
|
|
@@ -19,19 +19,23 @@ const browserEnv = {
|
|
|
19
19
|
notification.close();
|
|
20
20
|
onClick();
|
|
21
21
|
};
|
|
22
|
+
return notification;
|
|
22
23
|
},
|
|
23
24
|
now: () => Date.now(),
|
|
24
25
|
};
|
|
26
|
+
/** One interaction's tag, whichever report it came from. */
|
|
27
|
+
const interactionTag = (interactionId) => `ai-assistant:${interactionId}`;
|
|
25
28
|
/**
|
|
26
29
|
* The tag a notification carries. The browser replaces a notification that has the same tag, so
|
|
27
30
|
* windows that share a session never stack copies. Interaction ids are unique, so one interaction
|
|
28
31
|
* gets one notification whichever session reported it (a sub-agent's or its parent's); everything
|
|
29
|
-
* else the autopilot
|
|
32
|
+
* else shares one per session — the autopilot's stop, and a turn ending (GENC-1660), which can
|
|
33
|
+
* report the same moment when the turn that ends the flow stops the autopilot.
|
|
30
34
|
*
|
|
31
35
|
* @internal
|
|
32
36
|
*/
|
|
33
37
|
export const agentNotificationTag = (detail) => detail.interactionId
|
|
34
|
-
?
|
|
38
|
+
? interactionTag(detail.interactionId)
|
|
35
39
|
: `ai-assistant:${detail.sessionKey}:autopilot`;
|
|
36
40
|
/**
|
|
37
41
|
* Decides whether an `agent-attention` event becomes a browser notification, and shows it
|
|
@@ -40,8 +44,11 @@ export const agentNotificationTag = (detail) => detail.interactionId
|
|
|
40
44
|
* Shows nothing when the level does not cover the event, when permission is not granted, while
|
|
41
45
|
* the person is looking at the page (the in-page UI covers that), or when the same tag was just
|
|
42
46
|
* shown — unless the repeat brings a widget's own message the first lacked. That one replaces the
|
|
43
|
-
* notification under the same tag, silently: the autopilot
|
|
44
|
-
*
|
|
47
|
+
* notification under the same tag, silently: the autopilot hands a widget back before the
|
|
48
|
+
* widget's own request is reported, and the widget's words are the better ones.
|
|
49
|
+
*
|
|
50
|
+
* A notification about an interaction is closed once that interaction stops waiting on the person
|
|
51
|
+
* (`close`), so a stale one does not linger (GENC-1660).
|
|
45
52
|
*
|
|
46
53
|
* @internal
|
|
47
54
|
*/
|
|
@@ -50,6 +57,8 @@ export class AgentNotifier {
|
|
|
50
57
|
this.env = env;
|
|
51
58
|
/** Each tag shown within the repeat window: when, and whether it carried a widget's message. */
|
|
52
59
|
this.shown = new Map();
|
|
60
|
+
/** The notification showing for each interaction's tag, until it is closed. */
|
|
61
|
+
this.open = new Map();
|
|
53
62
|
}
|
|
54
63
|
/** Show a notification for `detail` if it should be shown. Returns whether it was. */
|
|
55
64
|
notify(detail, context) {
|
|
@@ -71,8 +80,9 @@ export class AgentNotifier {
|
|
|
71
80
|
const replacing = !!previous && !previous.message && !!detail.message;
|
|
72
81
|
if (previous && !replacing)
|
|
73
82
|
return false;
|
|
83
|
+
let handle;
|
|
74
84
|
try {
|
|
75
|
-
this.env.show(context.title, Object.assign({ body: detail.message || context.message || DEFAULT_AGENT_NOTIFICATION_MESSAGE, tag }, (replacing ? { silent: true } : {})), context.onClick);
|
|
85
|
+
handle = this.env.show(context.title, Object.assign({ body: detail.message || context.message || DEFAULT_AGENT_NOTIFICATION_MESSAGE, tag }, (replacing ? { silent: true } : {})), context.onClick);
|
|
76
86
|
}
|
|
77
87
|
catch (e) {
|
|
78
88
|
// Some browsers (Chrome on Android) only allow notifications from a service worker, and
|
|
@@ -81,6 +91,30 @@ export class AgentNotifier {
|
|
|
81
91
|
return false;
|
|
82
92
|
}
|
|
83
93
|
this.shown.set(tag, { at: (_a = previous === null || previous === void 0 ? void 0 : previous.at) !== null && _a !== void 0 ? _a : now, message: !!detail.message });
|
|
94
|
+
// Only an interaction's: the session's own (a stop, a turn ending) has nothing to go stale on.
|
|
95
|
+
if (detail.interactionId && handle)
|
|
96
|
+
this.open.set(tag, handle);
|
|
97
|
+
return true;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Close the notification showing for `interactionId`, if one is: the interaction no longer waits
|
|
101
|
+
* on the person, because it settled or a claimant took it (GENC-1660). Its tag is forgotten too,
|
|
102
|
+
* so if the interaction comes back to the person (a claimant hands it back), that notifies anew.
|
|
103
|
+
* Returns whether one was closed.
|
|
104
|
+
*/
|
|
105
|
+
close(interactionId) {
|
|
106
|
+
const tag = interactionTag(interactionId);
|
|
107
|
+
this.shown.delete(tag);
|
|
108
|
+
const handle = this.open.get(tag);
|
|
109
|
+
if (!handle)
|
|
110
|
+
return false;
|
|
111
|
+
this.open.delete(tag);
|
|
112
|
+
try {
|
|
113
|
+
handle.close();
|
|
114
|
+
}
|
|
115
|
+
catch (e) {
|
|
116
|
+
logger.warn('AgentNotifier: could not close a notification', e);
|
|
117
|
+
}
|
|
84
118
|
return true;
|
|
85
119
|
}
|
|
86
120
|
}
|
|
@@ -78,8 +78,8 @@ export const META_EVENT_IMPORTANCE = {
|
|
|
78
78
|
'interaction.outcome-dropped': 'high',
|
|
79
79
|
// A long action's step starting, finishing, or skipped on resume because it was already done.
|
|
80
80
|
'interaction.step': 'low',
|
|
81
|
-
// A cut checkpoint taken over after a reload, refused (by sameWork,
|
|
82
|
-
// at flow end.
|
|
81
|
+
// A cut checkpoint taken over after a reload, refused (by sameWork, and kept for a later request;
|
|
82
|
+
// or as malformed), or dropped at flow end, as is the live one.
|
|
83
83
|
'interaction.checkpoint': 'normal',
|
|
84
84
|
// A claimant handing a pending interaction to the person, or taking it back.
|
|
85
85
|
'interaction.held': 'normal',
|
|
@@ -253,8 +253,8 @@ export const DEBUG_LOG_README = [
|
|
|
253
253
|
'`timeline` is the entire session as one array, already sorted chronologically by `timestamp` (ISO 8601). Every entry has a `kind`.',
|
|
254
254
|
'Timestamps are millisecond-resolution; entries that share the same millisecond are ordered by a fixed kind rank (event, then turn, then message), which is a heuristic and may not reflect exact causal order within that millisecond — e.g. a user message and the turn it triggered, or a final assistant message and its turn.end event, can appear in either order depending on whether they landed in the same millisecond. Read the logical structure of a turn rather than over-interpreting the micro-ordering of co-timestamped entries of different kinds.',
|
|
255
255
|
"kind:'message' — the conversation. `role` is user/assistant/tool/system-event/synthetic-user; `agentName` says which agent produced it; `toolCalls`/`toolResult`/`interaction` carry tool and widget activity; `inputTokens`/`outputTokens`/`cost` are per-message LLM usage, where `inputTokens` is the WHOLE prompt for that request and `cacheReadTokens`/`cacheWriteTokens` BREAK IT DOWN rather than add to it — uncached input is `inputTokens` minus those two, and adding the cache fields to `inputTokens` counts the prompt twice. The cache fields are absent on providers that report no cache split (Gemini reports reads only, since implicit caching bills no write) and on messages persisted before they existed, so read them as 0 when missing. Each bucket bills at a different rate — cache reads a fraction of uncached input, cache writes a premium, output highest — so a large token count at a small cost means the prompt was mostly cache hits. `externalCostUsd` is any non-LLM cost a widget reported for its own external service calls (folded into the session cost total alongside `cost`). On model-produced assistant messages, `model` is the concrete model id that generated it (e.g. 'gemini-2.5-flash-lite') and `providerName` is the registry slot it resolved under (e.g. a tier name like 'high'/'low', or the default); together they attribute the message — and any tool calls it carries — to an exact model even across a mid-session vendor/tier switch, where one slot name can map to different models before and after the switch. Both are undefined on any entry that is NOT an LLM response: non-assistant roles (user/tool/system-event) and 'synthetic-user' echoes; assistant interaction/widget entries (empty content carrying an `interaction` — a rendered widget, not a model turn); driver-authored assistant fallbacks (the timeout, repeated-malformed-call, and empty-response apology messages); and messages restored from a session persisted before these fields existed. One partial case: on a genuine model turn whose provider exposes no `getStatus` (or reports no model), `providerName` is still set but `model` alone is undefined. A 'synthetic-user' message is a display-only echo of an interaction outcome (e.g. the answer a widget reported): it renders on the user's side of the chat and `agentName` is the agent that created it, but it is never sent to the LLM — so it has no matching 'turn' and the model learns the outcome only from the corresponding tool result. An echo of an answer an interceptor (such as an autopilot) gave is NOT synthetic-user: see the delegated-messages paragraph.",
|
|
256
|
-
'The autopilot (GENC-1660) runs on a driver of its own, and everything it did is harvested into this log: entries with delegate: autopilot and an agentName ending in › Autopilot are its turns (the decision message it was sent is the user message of its turn, so what it was shown is there verbatim; its systemPrompt is its grounding, such as the brief), its tool calls (widget_read, widget_act, hand_back) and their results, and its own events. Its cost is already in the session total: it is booked as externalCostUsd on the interaction each decision answered, or, for a written question it answered, on the user message it sent on the user behalf (delegate: autopilot), so do not add its turns to that total. Spend that reached no message is recorded as autopilot.cost-dropped instead.',
|
|
257
|
-
"Delegated messages (GENC-1660): a message with a `delegate` field was written or sent ON THE USER'S BEHALF by a driver decorator, and `delegate` names it (e.g. autopilot). The platform stamps it; nothing else can. It renders as the assistant whatever its role. A delegated `user` message was NOT typed by the user: it is an answer given on their behalf, and the model read it with `delegateFraming` in brackets in front of the content (the stored `content` is the bare text). A delegated `assistant` message is display-only (`excludeFromProvider`): the decorator's narration, or the echo of
|
|
256
|
+
'The autopilot (GENC-1660) runs on a driver of its own, and everything it did is harvested into this log: entries with delegate: autopilot and an agentName ending in › Autopilot are its turns (the decision message it was sent is the user message of its turn, so what it was shown is there verbatim; its systemPrompt is its grounding, such as the brief), its tool calls (widget_read, widget_act, hand_back, any read-only tools of its own, and its widget tools — reads with parameters that a widget type declares, routed to the interaction of that type being decided and refused with a reason when none is, offered on every decision so its tool list never changes; while one is open its tail starts with a line naming them) and their results (a read, view or widget tool, is capped at about 20,000 characters, cut with a note asking for less, and leaves its history at the end of the decision as a one-line note), and its own events. Its cost is already in the session total: it is booked as externalCostUsd on the interaction each decision answered, or, for a written question it answered, on the user message it sent on the user behalf (delegate: autopilot), so do not add its turns to that total. Spend that reached no message is recorded as autopilot.cost-dropped instead.',
|
|
257
|
+
"Delegated messages (GENC-1660): a message with a `delegate` field was written or sent ON THE USER'S BEHALF by a driver decorator, and `delegate` names it (e.g. autopilot). The platform stamps it; nothing else can. It renders as the assistant whatever its role. A delegated `user` message was NOT typed by the user: it is an answer given on their behalf, and the model read it with `delegateFraming` in brackets in front of the content (the stored `content` is the bare text). A delegated `assistant` message is display-only (`excludeFromProvider`): the decorator's narration note, or, when its answer carried no note, the widget's own echo of the answer (its `userMessage`), shown as the assistant and never as the person. A widget answer a decorator gave with a note is not echoed at all: the note already says what was chosen. To tell what the person decided from what was decided for them, read `interaction.answeredBy` and these fields, never the role alone.",
|
|
258
258
|
"Sub-agent messages appear inline. When a tool delegates to a sub-agent (via `requestSubAgent`), the sub-agent's whole conversation — its own assistant/tool messages, each with their own `content`/`thinking`/`toolCalls`/`toolResult` and per-message `model`/`providerName`/`inputTokens`/`outputTokens`/`cacheReadTokens`/`cacheWriteTokens`/`cost` — is hoisted into the timeline as ordinary kind:'message' entries, interleaved by timestamp right after the tool call that spawned them (so you read the delegation top-to-bottom). A hoisted entry is marked: `subAgentDepth` is its delegation depth (1 for a sub-agent, 2 for a sub-agent's sub-agent, …), `subAgentOf` is the id of the parent tool call that spawned it (correlates it back even when two sub-agents run in one parent turn), `subAgentName` is the sub-agent's own name, and `agentName` is rewritten to a `\"<parent> › <sub-agent>\"` breadcrumb (composing when nested, e.g. `\"UI Builder › Planner › Grounding\"`). The sub-agent's per-LLM-call snapshots also surface as kind:'turn' entries with an N-M `turnIndex`, and subagent.started/completed (or subagent.failed) events bracket the run. Per-message `cost` on hoisted entries is already part of the session total (it is summed from the un-flattened history), so summing the top-level timeline does NOT double-count.",
|
|
259
259
|
"kind:'turn' — one LLM call. `turnIndex` is a string: a top-level turn is the bare counter ('0', '1', …); a sub-agent's turns are numbered under the parent turn that activated them ('3-1', '3-2', …, and a nested sub-agent contributes '3-2-1', …), and `agentName` names the agent that ran the turn. `systemPrompt` and `toolNames` are what the model saw. A systemPrompt of '<repeated — identical to turn N>' was byte-identical to turn N and de-duplicated; the full prompt is shown whenever it changes (often because a stateful agent advanced), so prompt evolution is visible.",
|
|
260
260
|
"kind:'turn'.`model`/`providerName`/`provider` — which model ran that call: the concrete model id, the registry slot it resolved under (a tier name like 'high'/'low', or the default), and the vendor. Recorded per CALL, so an agent whose `provider` selector varies by state — a flow that plans on a high tier and executes on a low one — has every step attributed, including calls that produced no message. `model` is the SERVING model where the provider reports one, so a turn answered by a server-side fallback names the model that answered rather than the one requested; it always matches the `model` on the message that call produced. Absent when the provider exposes no `getStatus` and the transport stamped nothing.",
|
|
@@ -262,7 +262,7 @@ export const DEBUG_LOG_README = [
|
|
|
262
262
|
"kind:'turn'.`agentSnapshot` — the active agent's own view of its internal state, captured at that turn. An agent opts into this by exposing a `getDebugSnapshot()` that returns JSON-serializable per-state info; stateful/flow agents wire it automatically, so you can watch a flow advance turn-by-turn (e.g. current step, cursor, collected fields, pending changes). Absent for agents that don't expose one.",
|
|
263
263
|
"kind:'event' — a meta/lifecycle event. `type` names it (see below); `detail` carries structured data. `detail.placement` is the emitting UI instance: 'bubble' (collapsed), 'panel' (popped-out), or 'standalone'.",
|
|
264
264
|
"Each 'event' also has an `importance`: 'high' (failures/limits — turn.error, tool.failed, subagent.failed, file.read-failed, suggestions.failed, context.threshold-crossed), 'normal' (session flow — connects, turns, retries, handoffs, agent/provider changes, interactions, sub-agent start/complete), or 'low' (skippable UI/bookkeeping noise — panel.toggled, attachment.added, driver.wired/unwired, context.updated, context.condensed). To skim, ignore importance:'low'; to triage a failure, filter to importance:'high' then read the nearby messages and turns. A 'high' turn.error is often preceded by one or more 'normal' turn.retry events for the same reason — read them together to see how many attempts were made before bailing. 'message' and 'turn' entries carry no importance — they are the substance, always read them.",
|
|
265
|
-
'Event types: assistant.connected/disconnected (mount + placement + whether the session was created or restored), assistant.popout/popin (window placement), driver.created/wired/unwired (which driver is live and why it stops/starts responding across a popout), state.changed (idle↔loading), turn.start/turn.end (turn boundary; turn.end carries durationMs), turn.retry (a recoverable in-turn retry — detail.reason plus attempt/maxAttempts; for malformed calls also finishMessage; for empty responses also the provider finishReason + thoughtsTokens + parts breakdown), turn.error (a turn failed or hit a guardrail — detail.reason is one of exception/malformed-function-call/empty-response/unknown-tool-limit/max-iterations/response-truncated/refusal/budget-exhausted/provider-refused/context-exhausted/ai-service-error, plus reason-specific diagnostics: attempts (for empty-response also finishReason + thoughtsTokens + a parts breakdown, distinguishing a thinking-only STOP from a truly empty turn), finishMessage, for response-truncated the model + maxTokens + outputTokens + tools, unknownTools (split into staleTools — real earlier this activation but retired by the current state or hidden behind an open exclusive fold — and hallucinatedTools — never advertised) + availableTools, iterations + limit, for budget-exhausted the budgetUsd + spentUsd figures reported by the proxy plus the resolved vendor, for provider-refused the kind (spend|auth) plus the upstream status and error type — the vendor refusing the ACCOUNT rather than us refusing to spend, so the remedy is a top-up or a key rotation rather than a raised cap, and the kind is the only place that distinction survives because the user-facing copy is deliberately cause-free, for context-exhausted the estimated contextTokens against the guard that stopped the turn plus the iterations reached — the driver ending a runaway tool loop at the edge of the context window rather than issuing a request the provider would reject, so the transcript survives intact and can still be compacted, for ai-service-error the code (one of AI_SERVICE_ERROR_CODES, e.g. NO_API_KEY) and the status the AI service answered with — its own text goes to the browser console only, or name + message for exceptions), tool.failed (a tool threw), tool.unresolved (the model called a tool that could not be dispatched — detail.kind is folded/fold-hidden/stale/unknown, plus tool + agent and, for the counted kinds, the consecutive streak; the recurring lead-up to an unknown-tool-limit turn.error), subagent.started/completed/failed (the lifecycle of a `requestSubAgent` delegation — detail.agent names the sub-agent; these bracket the sub-agent turns that appear as kind:turn entries with an N-M `turnIndex`; subagent.failed also carries detail.reason, one of max_iterations/malformed_tool_call/empty_response/unknown_tool_limit/timeout/response_truncated/refusal/budget_exhausted/provider_refused/context_exhausted/ai_service_error; budget_exhausted and provider_refused are terminal for the PARENT turn too, and so is ai_service_error when the refusal is about the service rather than the request and came from the vendor the parent calls — the parent stops rather than calling the model again into the same wall; after context_exhausted the parent goes on, but its own next call is likely to stop on the same guard), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), routing.decided (ONE PER ROUTING DECISION — see its own paragraph below), provider.selected (the resolved provider for the upcoming turns — detail.provider is the registry SLOT/tier name, detail.model the concrete model behind it and detail.vendor its vendor; emitted only when the slot CHANGES, so read the per-turn `model` for the model of any given call rather than assuming the nearest event still applies), interaction.requested/resolved (blocking user widgets — explain quiet gaps; note that when a sub-agent opens a widget, detail.agent — and the agentName on the interaction message — is the HOST agent that owns the widget, NOT the sub-agent that asked, because widgets render and resolve on the host driver; detail.ownerPath names the agents that actually asked, outermost first, the last being the one whose tool requested it, and detail.heldBy says who held it when it opened: user, or the id of the interceptor that claimed it, such as autopilot; on interaction.resolved, detail.answeredBy is who answered — the claimant id when it settled through its own hold, user for any other answer (a click counts as the person even on a widget a claimant held) — absent when it closed unanswered (a timeout or a stop); the same value is stamped on the interaction message as answeredBy, and when it is not user the tool result that interaction returned carries a decidedOnUsersBehalf record, so the model was told the choice was not made by the person; detail.edits, present only when non-zero, counts the editing actions a claimant ran on the widget before it was settled, whoever settled it, and those edits are stamped on the interaction message as edits, each with by, action, choice and args when it had some, in the order they ran, while a decidedOnUsersBehalf record carries their choice texts as edits, and when the person settled it after such edits the tool result carries an editedOnUsersBehalf record instead — the framing and those choice texts — so the model knows the widget was changed on the user behalf before the user answered, and that the user then confirmed it by finishing it), interaction.held (a claimant moved a pending interaction to the person or back to itself — detail.heldBy is the new holder, detail.claimant the interceptor; a widget held by anything but user was not answered by the person), interaction.claim-refused (a claim on a userOnly interaction, which stays with the person — detail.claimant + reason), autopilot.* (the autopilot, a decorator that answers interactions on behalf of the user — autopilot.claimed / autopilot.declined say whether it took each interaction and, for a decline, detail.reason: paused, other-flow, no-autopilot, unavailable, userOnly, policy or no-controller; autopilot.decision-sent is what it was sent (detail.chars); autopilot.acted is what it did (detail.action, detail.note, detail.finished); autopilot.handed-back is a decision it gave to the person (detail.reason and detail.trigger: model, no-decision or error); autopilot.paused / autopilot.resumed are mode changes (detail.scope, detail.trigger, detail.decideYourself when the person resumed during a hand-back; detail.trigger is restored when the mode came back with the session after a reload, applied once its flow re-activated, which starts nothing by itself); autopilot.error is the wrapper itself failing; autopilot.refinement counts a written answer against its step (detail.stepKey, detail.count, detail.limitReached, after which reply is withdrawn for that step); autopilot.handback-presented is the turn-level hand-back, shown when a working turn ended needing the person with no widget to hand over (detail.why: max-iterations, context-exhausted, failure or question; detail.options; detail.choice once answered); autopilot.catch-up is the autopilot being given the whole visible transcript at once (detail.why: first, for its first decision in a flow or after a reload; size, when its own history passed its budget and was rebuilt short — detail.ownChars; or compacted, when a compaction removed the last message it had seen, so it reads the summary and everything since, short; in each, what it had sent on the user behalf is included and labelled as its own, since its own history does not hold it); autopilot.cost-dropped is autopilot spend that no message carries, so it is NOT in the session total (detail.costUsd and detail.why: handed-back, aborted or stale for a written question it answered that no reply was sent for — stale when a pause, a resume, a new turn or the end of its flow came before the answer landed, which then went nowhere — or no-recorder when the driver had no way to book a decision to its interaction); a hand-back trigger can also be budget (the decision passed its spend cap), watchdog (its work went quiet: no ready surface and no heartbeat, or its own decision stalled with no model call landing, which stops that decision) or detached (the autopilot was removed while it held the interaction, which went to the person with no reason shown). To debug one autopilot decision, follow its interactionId: interaction.requested (heldBy), autopilot.claimed, autopilot.decision-sent, autopilot.acted or autopilot.handed-back, interaction.invoked, interaction.resolved (answeredBy), then the next turn of the working agent), interaction.invoked (a claimant ran one of the actions the widget itself exposes, through its hold, the same code the button runs — detail.claimant, detail.action (an option id, select or reply) and detail.finished, whether that settled the interaction, and when it did not, the run is recorded as an edit; the choice and narration it recorded reach the result of the tool that asked as decidedOnUsersBehalf), interaction.step (a long action run as named steps through runSteps, which survive a reload — detail.step and detail.outcome: started, done, skipped when the step was already done before a reload, or resumed when it started before a reload and runs again with what it saved part-way, such as a job id it re-attaches to), interaction.checkpoint (the one checkpoint a conversation keeps for its long action — detail.action: resumed when a reload cut the work and the next request of the same widget type took it over, refused when the registration sameWork said the new request is different work (detail.saved is the identity it kept) or when runSteps found the handed-over checkpoint malformed and started fresh (detail.reason, detail.saved), or cleared when its flow ended with nothing taking it over), context.updated/threshold-crossed (token + cost), context.condensed (a stale tool payload was collapsed out of the model-bound history by a `condenseWhen` declaration on the tool — detail.tool + toolCallId, target args|response, trigger (superseded:<key> or age:<n>), stubLen, and an estimated tokensSaved; stored history and this log keep the FULL payload, so the model-visible slice at any point is the full history minus the condensations recorded up to then), panel.toggled, attachment.added, file.read-failed, suggestions.failed.',
|
|
265
|
+
'Event types: assistant.connected/disconnected (mount + placement + whether the session was created or restored), assistant.popout/popin (window placement), driver.created/wired/unwired (which driver is live and why it stops/starts responding across a popout), state.changed (idle↔loading), turn.start/turn.end (turn boundary; turn.end carries durationMs), turn.retry (a recoverable in-turn retry — detail.reason plus attempt/maxAttempts; for malformed calls also finishMessage; for empty responses also the provider finishReason + thoughtsTokens + parts breakdown), turn.error (a turn failed or hit a guardrail — detail.reason is one of exception/malformed-function-call/empty-response/unknown-tool-limit/max-iterations/response-truncated/refusal/budget-exhausted/provider-refused/context-exhausted/ai-service-error, plus reason-specific diagnostics: attempts (for empty-response also finishReason + thoughtsTokens + a parts breakdown, distinguishing a thinking-only STOP from a truly empty turn), finishMessage, for response-truncated the model + maxTokens + outputTokens + tools, unknownTools (split into staleTools — real earlier this activation but retired by the current state or hidden behind an open exclusive fold — and hallucinatedTools — never advertised) + availableTools, iterations + limit, for budget-exhausted the budgetUsd + spentUsd figures reported by the proxy plus the resolved vendor, for provider-refused the kind (spend|auth) plus the upstream status and error type — the vendor refusing the ACCOUNT rather than us refusing to spend, so the remedy is a top-up or a key rotation rather than a raised cap, and the kind is the only place that distinction survives because the user-facing copy is deliberately cause-free, for context-exhausted the estimated contextTokens against the guard that stopped the turn plus the iterations reached — the driver ending a runaway tool loop at the edge of the context window rather than issuing a request the provider would reject, so the transcript survives intact and can still be compacted, for ai-service-error the code (one of AI_SERVICE_ERROR_CODES, e.g. NO_API_KEY) and the status the AI service answered with — its own text goes to the browser console only, or name + message for exceptions), tool.failed (a tool threw), tool.unresolved (the model called a tool that could not be dispatched — detail.kind is folded/fold-hidden/stale/unknown, plus tool + agent and, for the counted kinds, the consecutive streak; the recurring lead-up to an unknown-tool-limit turn.error), subagent.started/completed/failed (the lifecycle of a `requestSubAgent` delegation — detail.agent names the sub-agent; these bracket the sub-agent turns that appear as kind:turn entries with an N-M `turnIndex`; subagent.failed also carries detail.reason, one of max_iterations/malformed_tool_call/empty_response/unknown_tool_limit/timeout/response_truncated/refusal/budget_exhausted/provider_refused/context_exhausted/ai_service_error; budget_exhausted and provider_refused are terminal for the PARENT turn too, and so is ai_service_error when the refusal is about the service rather than the request and came from the vendor the parent calls — the parent stops rather than calling the model again into the same wall; after context_exhausted the parent goes on, but its own next call is likely to stop on the same guard), agent.handoff (routing; from=null is the initial activation), agent.pinned/unpinned (forced routing), routing.decided (ONE PER ROUTING DECISION — see its own paragraph below), provider.selected (the resolved provider for the upcoming turns — detail.provider is the registry SLOT/tier name, detail.model the concrete model behind it and detail.vendor its vendor; emitted only when the slot CHANGES, so read the per-turn `model` for the model of any given call rather than assuming the nearest event still applies), interaction.requested/resolved (blocking user widgets — explain quiet gaps; note that when a sub-agent opens a widget, detail.agent — and the agentName on the interaction message — is the HOST agent that owns the widget, NOT the sub-agent that asked, because widgets render and resolve on the host driver; detail.ownerPath names the agents that actually asked, outermost first, the last being the one whose tool requested it, and detail.heldBy says who held it when it opened: user, or the id of the interceptor that claimed it, such as autopilot; on interaction.resolved, detail.answeredBy is who answered — the claimant id when it settled through its own hold, user for any other answer (a click counts as the person even on a widget a claimant held) — absent when it closed unanswered (a timeout or a stop), and absent too when it settled by itself other than through the hold of a claimant — a widget registered resolvesItself (one that does its work and settles on its own, asking the person nothing, such as a generation run), or one outcome its controller said settled itself (ctx.resolve with resolvedItself, such as a generation phase that failed outright before its review gate ever asked anything) — which then carries detail.resolvedItself: true instead, as the interaction message does — nobody answered it, and the platform cannot tell it finishing from the person interrupting it (a Skip), so only the result of the widget itself can say which; the same value is stamped on the interaction message as answeredBy and on the result the asking tool handler receives (absent there in the same cases), and when it is not user the tool result that interaction returned carries a decidedOnUsersBehalf record, so the model was told the choice was not made by the person; detail.edits, present only when non-zero, counts the editing actions a claimant ran on the widget before it was settled, whoever settled it, and those edits are stamped on the interaction message as edits, each with by, action, choice and args when it had some, in the order they ran, while a decidedOnUsersBehalf record carries their choice texts as edits, and when the person settled it after such edits the tool result carries an editedOnUsersBehalf record instead — the framing and those choice texts — so the model knows the widget was changed on the user behalf before the user answered, and that the user then confirmed it by finishing it), interaction.held (a claimant moved a pending interaction to the person or back to itself — detail.heldBy is the new holder, detail.claimant the interceptor; detail.late: true is an interceptor that declined it when it opened claiming it afterwards, such as the autopilot resumed while it was open; a widget held by anything but user was not answered by the person), interaction.claim-refused (a claim on a userOnly interaction, which stays with the person — detail.claimant + reason), autopilot.* (the autopilot, a decorator that answers interactions on behalf of the user — autopilot.claimed / autopilot.declined say whether it took each interaction and, for a decline, detail.reason: paused, other-flow, no-autopilot, unavailable, userOnly, policy or no-controller; one declined as paused that is still open when the person resumes the autopilot is looked at again, and the autopilot.claimed or autopilot.declined recorded for it then carries detail.onResume: true (a decline then can also be claimed-elsewhere, another interceptor having claimed it first); a restored mode looks at nothing; autopilot.decision-sent is what it was sent (detail.chars; detail.nothingEnabled: true when every action on the widget was unavailable — a gate whose controller said it was asking, such as a failed build the autopilot may not cancel — so it could only hand it back, which it may then do even after the person asked it to decide it itself; a widget whose controller says it is working (ctx.setWorking) is never sent a decision until it says it is asking, even when an action is enabled or the person resumes the autopilot); autopilot.acted is what it did (detail.action, detail.note, detail.finished); autopilot.handed-back is a decision it gave to the person (detail.reason and detail.trigger: model, no-decision or error); autopilot.paused / autopilot.resumed are mode changes (detail.scope, detail.trigger, detail.decideYourself when the person resumed during a hand-back; detail.trigger is restored when the mode came back with the session after a reload, applied once its flow re-activated, which starts nothing by itself); autopilot.error is the wrapper itself failing; autopilot.refinement counts a refining action against its step — a written answer (reply) or a widget action declared refines, such as a regenerate with instructions, counted together (detail.action, detail.stepKey, detail.count, detail.limitReached, after which every refining action is withdrawn for that step: not listed, and refused; the decision and every relisting of its actions say how many are left at the step, as a line Refinements left at this step: N, wherever the widget has a refining action); autopilot.handback-presented is the turn-level hand-back, shown when a working turn ended needing the person with no widget to hand over (detail.why: max-iterations, context-exhausted, failure or question; detail.options; detail.choice once answered); autopilot.catch-up is the autopilot being given the whole visible transcript at once (detail.why: first, for its first decision in a flow or after a reload; size, when its own history passed its budget and was rebuilt short — detail.ownChars; or compacted, when a compaction removed the last message it had seen, so it reads the summary and everything since, short; in each, what it had sent on the user behalf is included and labelled as its own, since its own history does not hold it); autopilot.cost-dropped is autopilot spend that no message carries, so it is NOT in the session total (detail.costUsd and detail.why: handed-back, aborted or stale for a written question it answered that no reply was sent for — stale when a pause, a resume, a new turn or the end of its flow came before the answer landed, which then went nowhere — or no-recorder when the driver had no way to book a decision to its interaction); a hand-back trigger can also be budget (the decision passed its spend cap), watchdog (its work went quiet: no ready surface and no heartbeat, or its own decision stalled with no model call landing, which stops that decision) or detached (the autopilot was removed while it held the interaction, which went to the person with no reason shown). To debug one autopilot decision, follow its interactionId: interaction.requested (heldBy), autopilot.claimed, autopilot.decision-sent, autopilot.acted or autopilot.handed-back, interaction.invoked, interaction.resolved (answeredBy), then the next turn of the working agent), interaction.invoked (a claimant ran one of the actions the widget itself exposes, through its hold, the same code the button runs — detail.claimant, detail.action (an option id, select or reply) and detail.finished, whether that settled the interaction, and when it did not, the run is recorded as an edit; the choice and narration it recorded reach the result of the tool that asked as decidedOnUsersBehalf), interaction.step (a long action run as named steps through runSteps, which survive a reload — detail.step and detail.outcome: started, done, skipped when the step was already done before a reload, or resumed when it started before a reload and runs again with what it saved part-way, such as a job id it re-attaches to), interaction.checkpoint (the checkpoints a conversation keeps for its long actions: the one in flight, and each one a reload cut, held apart until a request of its own widget type takes it over, so a resumed flow that opens other long widgets first, which save their own, loses nothing — detail.action: resumed when a reload cut the work and a request of the same widget type that the registration sameWork agrees is the same work took it over, refused when sameWork said a new request is different work (detail.saved is the identity it kept; detail.kept: true, since it stays for a later request of that type, and is offered to every one until one agrees) or when runSteps found the handed-over checkpoint malformed and started fresh (detail.reason, detail.saved), or cleared when its flow ended, once per checkpoint, with detail.cut: true for one a reload cut that nothing took over), context.updated/threshold-crossed (token + cost), context.condensed (a stale tool payload was collapsed out of the model-bound history by a `condenseWhen` declaration on the tool — detail.tool + toolCallId, target args|response, trigger (superseded:<key> or age:<n>), stubLen, and an estimated tokensSaved; stored history and this log keep the FULL payload, so the model-visible slice at any point is the full history minus the condensations recorded up to then), panel.toggled, attachment.added, file.read-failed, suggestions.failed.',
|
|
266
266
|
'Sub-agent meta events: a sub-agent\'s own turn.retry/turn.error/tool.failed/tool.unresolved events are merged into this same timeline, tagged with `detail.subAgent` — a `"<parent> › <sub-agent>"` breadcrumb that composes when nested (e.g. `"UI Builder › Planner › Grounding"`) — and interleaved by their original timestamps within the subagent.started→completed/failed bracket. These are the per-attempt/per-failure signals that do NOT appear among the sub-agent\'s (hoisted) messages: a malformed/empty attempt that gets retried produces no message, and the stale-vs-hallucinated split and streak counts live only on the event. A sub-agent\'s high-volume, message-derivable events (turn.start/turn.end, provider.selected, context.updated) are intentionally NOT merged — read its hoisted messages for model/tokens/cost and turn-by-turn activity, and the bracketing subagent.* events for the run\'s span.',
|
|
267
267
|
"`meta` holds context captured at export time: agentSummary (full agent configs), context (active model, contextTokens/contextLimit/contextUsagePercent for the last call, and the session totals — sessionCostUsd, sessionTokensConsumed, and the four-bucket sessionUsage lifted to the top of this log), activeDebugSnapshot (the active agent's `getDebugSnapshot()` taken fresh at export — reflects state NOW, which may have advanced beyond the last turn's agentSnapshot), debug (optional host-supplied debug state), host, and the export timestamp.",
|
|
268
268
|
'Note the two different scopes in `meta.context`: `contextTokens` is the prompt size of the LAST call (against `contextLimit`, the model context window), while `sessionUsage`/`sessionTokensConsumed` are cumulative BILLED throughput. Every turn resends the conversation, so the cumulative figure counts each turn’s prompt again in the next turn’s and is expected to dwarf the context size — that is not double-counting.',
|
|
@@ -6,23 +6,45 @@ const normalise = (option) => {
|
|
|
6
6
|
var _a;
|
|
7
7
|
return typeof option === 'string'
|
|
8
8
|
? { id: option, label: option }
|
|
9
|
-
: { id: (_a = option.id) !== null && _a !== void 0 ? _a : option.label, label: option.label,
|
|
9
|
+
: { id: (_a = option.id) !== null && _a !== void 0 ? _a : option.label, label: option.label, unavailable: option.unavailable };
|
|
10
10
|
};
|
|
11
|
-
|
|
12
|
-
|
|
11
|
+
/** What an unavailable thing says when its guard gives no reason (an empty one, or a throw). */
|
|
12
|
+
export const GENERIC_UNAVAILABLE = 'not available in this state';
|
|
13
|
+
/**
|
|
14
|
+
* Why something cannot be used right now, from its `unavailable` guard, or `undefined` when it can
|
|
15
|
+
* (GENC-1660). One rule for options, actions and widget tools: absent means available; an empty
|
|
16
|
+
* reason, or a guard that throws, counts as unavailable with a generic reason, since a guard that
|
|
17
|
+
* cannot say why cannot vouch for its button either.
|
|
18
|
+
*/
|
|
19
|
+
export function unavailableReason(guard, ...args) {
|
|
20
|
+
if (!guard)
|
|
21
|
+
return undefined;
|
|
13
22
|
try {
|
|
14
|
-
|
|
23
|
+
const reason = guard(...args);
|
|
24
|
+
if (reason === undefined)
|
|
25
|
+
return undefined;
|
|
26
|
+
// Without a closing full stop, so a message that ends the sentence itself never shows two.
|
|
27
|
+
return reason.trim().replace(/\.+$/, '') || GENERIC_UNAVAILABLE;
|
|
15
28
|
}
|
|
16
|
-
catch (
|
|
17
|
-
|
|
18
|
-
return false;
|
|
29
|
+
catch (_a) {
|
|
30
|
+
return GENERIC_UNAVAILABLE;
|
|
19
31
|
}
|
|
20
|
-
}
|
|
32
|
+
}
|
|
33
|
+
const reasonFor = (option) => unavailableReason(option.unavailable);
|
|
34
|
+
const isEnabled = (option) => reasonFor(option) === undefined;
|
|
35
|
+
/** Each view's description, by name: what the model is told a surface's views hold. */
|
|
36
|
+
const describeViews = (views) => Object.fromEntries(Object.entries(views).map(([name, v]) => [name, v.description]));
|
|
37
|
+
/**
|
|
38
|
+
* Read one named view. Own views only: a name from the model such as `constructor` must not reach
|
|
39
|
+
* the record's prototype. A view it does not have reads as nothing; the autopilot refuses one before
|
|
40
|
+
* it gets here.
|
|
41
|
+
*/
|
|
42
|
+
const readView = (views, view) => Object.prototype.hasOwnProperty.call(views, view) ? views[view].read() : undefined;
|
|
21
43
|
/**
|
|
22
44
|
* Build the surface for a short-form decision (GENC-1660). Its actions are its options (by id),
|
|
23
|
-
* plus `select` for a multi-select and `reply` for a written answer; all of them finish.
|
|
24
|
-
* read — facts, actions, enabled-ness — is taken
|
|
25
|
-
* widget as it is now.
|
|
45
|
+
* plus `select` for a multi-select and `reply` for a written answer; all of them finish. Its views,
|
|
46
|
+
* if it has any, are read by name. Every read — facts, views, actions, enabled-ness — is taken
|
|
47
|
+
* fresh, so the surface always describes the widget as it is now.
|
|
26
48
|
*
|
|
27
49
|
* Throws if an option's id collides with another or with a platform-owned name, which is a bug in
|
|
28
50
|
* the widget rather than something to recover from.
|
|
@@ -42,12 +64,10 @@ export function buildDecisionSurface(spec) {
|
|
|
42
64
|
const actions = () => {
|
|
43
65
|
const enabled = options.filter(isEnabled);
|
|
44
66
|
return [
|
|
45
|
-
...options.map((o) =>
|
|
46
|
-
|
|
47
|
-
label: o.label,
|
|
48
|
-
|
|
49
|
-
enabled: isEnabled(o),
|
|
50
|
-
})),
|
|
67
|
+
...options.map((o) => {
|
|
68
|
+
const unavailable = reasonFor(o);
|
|
69
|
+
return Object.assign({ name: o.id, label: o.label, finishes: true, enabled: unavailable === undefined }, (unavailable !== undefined ? { unavailable } : {}));
|
|
70
|
+
}),
|
|
51
71
|
...(spec.multi
|
|
52
72
|
? [
|
|
53
73
|
{
|
|
@@ -58,18 +78,27 @@ export function buildDecisionSurface(spec) {
|
|
|
58
78
|
},
|
|
59
79
|
]
|
|
60
80
|
: []),
|
|
61
|
-
...(spec.freeText
|
|
62
|
-
? [{ name: REPLY_ACTION, finishes: true, enabled: true, args: 'text' }]
|
|
63
|
-
: []),
|
|
81
|
+
...(spec.freeText ? [replyAction()] : []),
|
|
64
82
|
];
|
|
65
83
|
};
|
|
84
|
+
const replyReason = () => unavailableReason(spec.freeTextUnavailable);
|
|
85
|
+
const replyAction = () => {
|
|
86
|
+
const unavailable = replyReason();
|
|
87
|
+
return Object.assign(Object.assign({ name: REPLY_ACTION, finishes: true, enabled: unavailable === undefined }, (unavailable !== undefined ? { unavailable } : {})), { args: 'text', refines: true });
|
|
88
|
+
};
|
|
66
89
|
const answer = (a) => () => spec.choose(a);
|
|
67
|
-
return {
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
90
|
+
const facts = () => { var _a, _b; return (_b = (_a = spec.facts) === null || _a === void 0 ? void 0 : _a.call(spec)) !== null && _b !== void 0 ? _b : {}; };
|
|
91
|
+
// Views, where it has any, read as a full-form surface's do: by name, the default being what a
|
|
92
|
+
// read without one returned before views existed (the facts). An empty record is no views, so a
|
|
93
|
+
// decision without them keeps the surface it always had, `read` absent.
|
|
94
|
+
const views = spec.views && Object.keys(spec.views).length ? spec.views : undefined;
|
|
95
|
+
const readable = views
|
|
96
|
+
? {
|
|
97
|
+
views: describeViews(views),
|
|
98
|
+
read: (view) => (view === undefined ? facts() : readView(views, view)),
|
|
99
|
+
}
|
|
100
|
+
: {};
|
|
101
|
+
return Object.assign(Object.assign({ prompt: spec.prompt, facts }, readable), { actions, isReady: () => actions().some((a) => a.finishes && a.enabled), prepare(name, args) {
|
|
73
102
|
if (spec.multi && name === SELECT_ACTION) {
|
|
74
103
|
const picked = args === null || args === void 0 ? void 0 : args.options;
|
|
75
104
|
if (!Array.isArray(picked) || picked.length === 0) {
|
|
@@ -87,7 +116,7 @@ export function buildDecisionSurface(spec) {
|
|
|
87
116
|
if (disabled.length) {
|
|
88
117
|
return {
|
|
89
118
|
error: 'disabled',
|
|
90
|
-
message: `Not available right now: ${disabled.map((o) => o.label).join(', ')}.`,
|
|
119
|
+
message: `Not available right now: ${disabled.map((o) => `${o.label} (${reasonFor(o)})`).join(', ')}.`,
|
|
91
120
|
};
|
|
92
121
|
}
|
|
93
122
|
const picks = chosen;
|
|
@@ -98,6 +127,10 @@ export function buildDecisionSurface(spec) {
|
|
|
98
127
|
};
|
|
99
128
|
}
|
|
100
129
|
if (spec.freeText && name === REPLY_ACTION) {
|
|
130
|
+
const why = replyReason();
|
|
131
|
+
if (why !== undefined) {
|
|
132
|
+
return { error: 'disabled', message: `"reply" is not available right now: ${why}.` };
|
|
133
|
+
}
|
|
101
134
|
const text = args === null || args === void 0 ? void 0 : args.text;
|
|
102
135
|
if (typeof text !== 'string' || !text.trim()) {
|
|
103
136
|
return { error: 'invalid-args', message: '`reply` takes { text: string }, not empty.' };
|
|
@@ -108,16 +141,19 @@ export function buildDecisionSurface(spec) {
|
|
|
108
141
|
if (!option) {
|
|
109
142
|
return { error: 'unknown-action', message: `No action "${name}" here.` };
|
|
110
143
|
}
|
|
111
|
-
|
|
112
|
-
|
|
144
|
+
const why = reasonFor(option);
|
|
145
|
+
if (why !== undefined) {
|
|
146
|
+
return {
|
|
147
|
+
error: 'disabled',
|
|
148
|
+
message: `"${option.label}" is not available right now: ${why}.`,
|
|
149
|
+
};
|
|
113
150
|
}
|
|
114
151
|
return {
|
|
115
152
|
choice: option.label,
|
|
116
153
|
finishes: true,
|
|
117
154
|
run: answer({ kind: 'option', option: option.id }),
|
|
118
155
|
};
|
|
119
|
-
}
|
|
120
|
-
};
|
|
156
|
+
} });
|
|
121
157
|
}
|
|
122
158
|
/** How long a choice's text may run in a `decidedOnUsersBehalf` record, in characters. */
|
|
123
159
|
const CHOICE_CHARS = 300;
|
|
@@ -161,30 +197,62 @@ export function checkArgs(args, schema) {
|
|
|
161
197
|
.map(([key, prop]) => `${key} should be ${String(prop === null || prop === void 0 ? void 0 : prop.type)}`);
|
|
162
198
|
return wrong.length ? `${wrong.join('; ')}.` : undefined;
|
|
163
199
|
}
|
|
200
|
+
/**
|
|
201
|
+
* An example of arguments that fit `schema`, for a refusal to show the model: each property with a
|
|
202
|
+
* placeholder of its declared type, required ones first. Shallow, like {@link checkArgs}.
|
|
203
|
+
*/
|
|
204
|
+
export function exampleArgs(schema) {
|
|
205
|
+
var _a, _b;
|
|
206
|
+
const properties = ((_a = schema.properties) !== null && _a !== void 0 ? _a : {});
|
|
207
|
+
const required = new Set((_b = schema.required) !== null && _b !== void 0 ? _b : []);
|
|
208
|
+
const placeholder = (type) => {
|
|
209
|
+
switch (type) {
|
|
210
|
+
case 'string':
|
|
211
|
+
return '…';
|
|
212
|
+
case 'number':
|
|
213
|
+
case 'integer':
|
|
214
|
+
return 0;
|
|
215
|
+
case 'boolean':
|
|
216
|
+
return false;
|
|
217
|
+
case 'array':
|
|
218
|
+
return [];
|
|
219
|
+
case 'object':
|
|
220
|
+
return {};
|
|
221
|
+
default:
|
|
222
|
+
return null;
|
|
223
|
+
}
|
|
224
|
+
};
|
|
225
|
+
const names = Object.keys(properties).sort((a, b) => Number(required.has(b)) - Number(required.has(a)));
|
|
226
|
+
return Object.fromEntries(names.map((name) => { var _a; return [name, placeholder((_a = properties[name]) === null || _a === void 0 ? void 0 : _a.type)]; }));
|
|
227
|
+
}
|
|
164
228
|
/**
|
|
165
229
|
* Build the surface for a full-form spec (GENC-1660 §4.2): named actions, some editing and some
|
|
166
|
-
* finishing, each guarded and
|
|
230
|
+
* finishing, each guarded and checked (a text action's text, a form's fields against its schema); a
|
|
231
|
+
* description; described views to read, one of them the preview. Every read is fresh.
|
|
232
|
+
*
|
|
233
|
+
* Throws if an action declares both `text` and `argsSchema`, or the preview is not one of the
|
|
234
|
+
* views: a bug in the widget rather than something to recover from.
|
|
167
235
|
*/
|
|
168
236
|
export function buildFullSurface(spec) {
|
|
169
|
-
const
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
return (_a = enabledWhen === null || enabledWhen === void 0 ? void 0 : enabledWhen()) !== null && _a !== void 0 ? _a : true;
|
|
173
|
-
}
|
|
174
|
-
catch (_b) {
|
|
175
|
-
return false;
|
|
237
|
+
for (const [name, action] of Object.entries(spec.actions)) {
|
|
238
|
+
if (action.text && action.argsSchema) {
|
|
239
|
+
throw new Error(`exposeSurface: action "${name}" takes \`text\` or \`argsSchema\`, not both.`);
|
|
176
240
|
}
|
|
177
|
-
}
|
|
178
|
-
const
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
241
|
+
}
|
|
242
|
+
const views = spec.views && Object.keys(spec.views).length ? spec.views : undefined;
|
|
243
|
+
if (spec.preview !== undefined &&
|
|
244
|
+
!(views && Object.prototype.hasOwnProperty.call(views, spec.preview))) {
|
|
245
|
+
throw new Error(`exposeSurface: the preview "${spec.preview}" is not one of its views.`);
|
|
246
|
+
}
|
|
247
|
+
const actions = () => Object.entries(spec.actions).map(([name, a]) => {
|
|
248
|
+
const unavailable = unavailableReason(a.unavailable);
|
|
249
|
+
return Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({ name, finishes: !!a.finishes, enabled: unavailable === undefined }, (unavailable !== undefined ? { unavailable } : {})), { description: a.description }), (a.text ? { args: 'text' } : {})), (a.argsSchema ? { args: 'fields', argsSchema: a.argsSchema } : {})), (a.refines ? { refines: true } : {}));
|
|
250
|
+
});
|
|
251
|
+
return Object.assign(Object.assign({ prompt: spec.prompt, facts: () => ({}), describe: () => spec.describe() }, (views
|
|
252
|
+
? Object.assign(Object.assign({ views: describeViews(views) }, (spec.preview !== undefined ? { preview: spec.preview } : {})), { read: (view) => {
|
|
253
|
+
const name = view !== null && view !== void 0 ? view : spec.preview;
|
|
254
|
+
return name === undefined ? undefined : readView(views, name);
|
|
255
|
+
} }) : {})), { actions, isReady: () => actions().some((a) => a.enabled), prepare(name, args) {
|
|
188
256
|
// Own actions only: a name from the model such as `constructor` or `toString` must not reach
|
|
189
257
|
// the object's prototype.
|
|
190
258
|
const action = Object.prototype.hasOwnProperty.call(spec.actions, name)
|
|
@@ -192,8 +260,24 @@ export function buildFullSurface(spec) {
|
|
|
192
260
|
: undefined;
|
|
193
261
|
if (!action)
|
|
194
262
|
return { error: 'unknown-action', message: `No action "${name}" here.` };
|
|
195
|
-
|
|
196
|
-
|
|
263
|
+
const why = unavailableReason(action.unavailable);
|
|
264
|
+
if (why !== undefined) {
|
|
265
|
+
return { error: 'disabled', message: `"${name}" is not available right now: ${why}.` };
|
|
266
|
+
}
|
|
267
|
+
if (action.text) {
|
|
268
|
+
const text = args === null || args === void 0 ? void 0 : args.text;
|
|
269
|
+
if (typeof text !== 'string' || !text.trim()) {
|
|
270
|
+
return {
|
|
271
|
+
error: 'invalid-args',
|
|
272
|
+
message: `"${name}" takes its argument as \`text\`, not empty.`,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
const trimmed = text.trim();
|
|
276
|
+
return {
|
|
277
|
+
choice: `${name}: ${trimmed}`.slice(0, CHOICE_CHARS),
|
|
278
|
+
finishes: !!action.finishes,
|
|
279
|
+
run: () => action.run(trimmed),
|
|
280
|
+
};
|
|
197
281
|
}
|
|
198
282
|
const problem = checkArgs(args !== null && args !== void 0 ? args : {}, action.argsSchema);
|
|
199
283
|
if (problem)
|
|
@@ -204,6 +288,5 @@ export function buildFullSurface(spec) {
|
|
|
204
288
|
finishes: !!action.finishes,
|
|
205
289
|
run: () => action.run(args !== null && args !== void 0 ? args : {}),
|
|
206
290
|
};
|
|
207
|
-
}
|
|
208
|
-
};
|
|
291
|
+
} });
|
|
209
292
|
}
|
|
@@ -21,22 +21,33 @@ export function createInteractionContext(interactionId, deps = {}) {
|
|
|
21
21
|
let surface;
|
|
22
22
|
let lastActivityAt = Date.now();
|
|
23
23
|
let checkpoint = deps.checkpoint;
|
|
24
|
+
let working;
|
|
24
25
|
// GENC-1676: the widget's first `requestAttention`, held until who holds the interaction is
|
|
25
|
-
// decided (`markOffered`), then reported once — or
|
|
26
|
+
// decided (`markOffered`), then reported once — or not at all, if a claimant holds it. Its message
|
|
27
|
+
// is kept either way, for the claimant's hand-back to report (GENC-1660).
|
|
26
28
|
let offered = false;
|
|
27
29
|
let attention;
|
|
28
30
|
let attentionDone = false;
|
|
31
|
+
// GENC-1660: set while an interceptor reports the request in the driver's place (`takeAttention`).
|
|
32
|
+
let attentionTaker;
|
|
29
33
|
const reportAttention = () => {
|
|
30
34
|
var _a;
|
|
31
35
|
if (!offered || !attention || attentionDone || disposed || settled)
|
|
32
36
|
return;
|
|
33
37
|
attentionDone = true;
|
|
34
|
-
// A claimant's: its own hand-back reports, if it gives the interaction back.
|
|
38
|
+
// A claimant's: its own hand-back reports, with the message, if it gives the interaction back.
|
|
35
39
|
if (heldBy !== 'user')
|
|
36
40
|
return;
|
|
37
|
-
(_a = deps.requestAttention) === null || _a === void 0 ? void 0 : _a
|
|
41
|
+
(_a = (attentionTaker !== null && attentionTaker !== void 0 ? attentionTaker : deps.requestAttention)) === null || _a === void 0 ? void 0 : _a(attention.message);
|
|
38
42
|
};
|
|
39
|
-
/**
|
|
43
|
+
/**
|
|
44
|
+
* The surface as the context reports it: readiness follows what the controller said it is doing
|
|
45
|
+
* (`setWorking`) before the surface's own rule. Working: not ready, whatever is enabled. Asking:
|
|
46
|
+
* ready, even with nothing enabled, since what it exposed is the decision to make now. Never said:
|
|
47
|
+
* the surface's own rule, as before.
|
|
48
|
+
*/
|
|
49
|
+
const reporting = (built) => (Object.assign(Object.assign({}, built), { isReady: () => working === false || (working !== true && built.isReady()) }));
|
|
50
|
+
/** Fire every waiting `onSurfaceReady` once a decision is due (see `reporting`). */
|
|
40
51
|
const checkReady = () => {
|
|
41
52
|
if (disposed || !surface || readyListeners.size === 0 || !surface.isReady())
|
|
42
53
|
return;
|
|
@@ -69,6 +80,16 @@ export function createInteractionContext(interactionId, deps = {}) {
|
|
|
69
80
|
get checkpoint() {
|
|
70
81
|
return checkpoint;
|
|
71
82
|
},
|
|
83
|
+
get working() {
|
|
84
|
+
return working;
|
|
85
|
+
},
|
|
86
|
+
setWorking(next) {
|
|
87
|
+
if (disposed || next === working)
|
|
88
|
+
return;
|
|
89
|
+
working = next;
|
|
90
|
+
// Status and readiness both read it, so subscribers re-read and a gate that just opened fires.
|
|
91
|
+
context.notify();
|
|
92
|
+
},
|
|
72
93
|
saveCheckpoint(next) {
|
|
73
94
|
var _a;
|
|
74
95
|
if (disposed)
|
|
@@ -123,23 +144,23 @@ export function createInteractionContext(interactionId, deps = {}) {
|
|
|
123
144
|
}
|
|
124
145
|
disposers.add(fn);
|
|
125
146
|
},
|
|
126
|
-
resolve(result) {
|
|
147
|
+
resolve(result, options) {
|
|
127
148
|
var _a;
|
|
128
149
|
if (settled || disposed)
|
|
129
150
|
return;
|
|
130
151
|
settled = true;
|
|
131
|
-
(_a = deps.resolve) === null || _a === void 0 ? void 0 : _a.call(deps, result);
|
|
152
|
+
(_a = deps.resolve) === null || _a === void 0 ? void 0 : _a.call(deps, result, options);
|
|
132
153
|
},
|
|
133
154
|
exposeDecision(decision) {
|
|
134
155
|
if (disposed)
|
|
135
156
|
return;
|
|
136
|
-
surface = buildDecisionSurface(decision);
|
|
157
|
+
surface = reporting(buildDecisionSurface(decision));
|
|
137
158
|
context.notify();
|
|
138
159
|
},
|
|
139
160
|
exposeSurface(spec) {
|
|
140
161
|
if (disposed)
|
|
141
162
|
return;
|
|
142
|
-
surface = buildFullSurface(spec);
|
|
163
|
+
surface = reporting(buildFullSurface(spec));
|
|
143
164
|
context.notify();
|
|
144
165
|
},
|
|
145
166
|
onSurfaceReady(fn) {
|
|
@@ -201,6 +222,18 @@ export function createInteractionContext(interactionId, deps = {}) {
|
|
|
201
222
|
offered = true;
|
|
202
223
|
reportAttention();
|
|
203
224
|
},
|
|
225
|
+
get attentionMessage() {
|
|
226
|
+
return attention === null || attention === void 0 ? void 0 : attention.message;
|
|
227
|
+
},
|
|
228
|
+
takeAttention(onRequest) {
|
|
229
|
+
if (attentionDone || disposed || settled || attentionTaker)
|
|
230
|
+
return undefined;
|
|
231
|
+
attentionTaker = onRequest;
|
|
232
|
+
return () => {
|
|
233
|
+
if (attentionTaker === onRequest)
|
|
234
|
+
attentionTaker = undefined;
|
|
235
|
+
};
|
|
236
|
+
},
|
|
204
237
|
get surface() {
|
|
205
238
|
return surface;
|
|
206
239
|
},
|