driverkit 0.0.0-stage → 0.0.1
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/CONTROLS.md +578 -0
- package/REACT.md +477 -0
- package/README.md +104 -2
- package/dist/agent/backend.d.ts +69 -0
- package/dist/agent/backend.d.ts.map +1 -0
- package/dist/agent/backend.js +130 -0
- package/dist/agent/backend.js.map +1 -0
- package/dist/agent/control.d.ts +148 -0
- package/dist/agent/control.d.ts.map +1 -0
- package/dist/agent/control.js +342 -0
- package/dist/agent/control.js.map +1 -0
- package/dist/agent/index.d.ts +9 -0
- package/dist/agent/index.d.ts.map +1 -0
- package/dist/agent/index.js +6 -0
- package/dist/agent/index.js.map +1 -0
- package/dist/agent/loop.d.ts +136 -0
- package/dist/agent/loop.d.ts.map +1 -0
- package/dist/agent/loop.js +824 -0
- package/dist/agent/loop.js.map +1 -0
- package/dist/agent/render.d.ts +173 -0
- package/dist/agent/render.d.ts.map +1 -0
- package/dist/agent/render.js +425 -0
- package/dist/agent/render.js.map +1 -0
- package/dist/agent/tools.d.ts +138 -0
- package/dist/agent/tools.d.ts.map +1 -0
- package/dist/agent/tools.js +622 -0
- package/dist/agent/tools.js.map +1 -0
- package/dist/agent/types.d.ts +566 -0
- package/dist/agent/types.d.ts.map +1 -0
- package/dist/agent/types.js +32 -0
- package/dist/agent/types.js.map +1 -0
- package/dist/browser/budget.d.ts +92 -0
- package/dist/browser/budget.d.ts.map +1 -0
- package/dist/browser/budget.js +151 -0
- package/dist/browser/budget.js.map +1 -0
- package/dist/browser/connect.d.ts +368 -0
- package/dist/browser/connect.d.ts.map +1 -0
- package/dist/browser/connect.js +1038 -0
- package/dist/browser/connect.js.map +1 -0
- package/dist/browser/elsewhere.d.ts +89 -0
- package/dist/browser/elsewhere.d.ts.map +1 -0
- package/dist/browser/elsewhere.js +91 -0
- package/dist/browser/elsewhere.js.map +1 -0
- package/dist/browser/frames.d.ts +85 -0
- package/dist/browser/frames.d.ts.map +1 -0
- package/dist/browser/frames.js +11 -0
- package/dist/browser/frames.js.map +1 -0
- package/dist/browser/index.d.ts +8 -0
- package/dist/browser/index.d.ts.map +1 -0
- package/dist/browser/index.js +9 -0
- package/dist/browser/index.js.map +1 -0
- package/dist/check/check.d.ts +171 -0
- package/dist/check/check.d.ts.map +1 -0
- package/dist/check/check.js +666 -0
- package/dist/check/check.js.map +1 -0
- package/dist/check/index.d.ts +3 -0
- package/dist/check/index.d.ts.map +1 -0
- package/dist/check/index.js +2 -0
- package/dist/check/index.js.map +1 -0
- package/dist/check/types.d.ts +149 -0
- package/dist/check/types.d.ts.map +1 -0
- package/dist/check/types.js +29 -0
- package/dist/check/types.js.map +1 -0
- package/dist/controls/controls.d.ts +198 -0
- package/dist/controls/controls.d.ts.map +1 -0
- package/dist/controls/controls.js +742 -0
- package/dist/controls/controls.js.map +1 -0
- package/dist/controls/dom.d.ts +108 -0
- package/dist/controls/dom.d.ts.map +1 -0
- package/dist/controls/dom.js +56 -0
- package/dist/controls/dom.js.map +1 -0
- package/dist/controls/index.d.ts +26 -0
- package/dist/controls/index.d.ts.map +1 -0
- package/dist/controls/index.js +23 -0
- package/dist/controls/index.js.map +1 -0
- package/dist/controls/rows.d.ts +66 -0
- package/dist/controls/rows.d.ts.map +1 -0
- package/dist/controls/rows.js +127 -0
- package/dist/controls/rows.js.map +1 -0
- package/dist/core/index.d.ts +3 -0
- package/dist/core/index.d.ts.map +1 -0
- package/dist/core/index.js +15 -0
- package/dist/core/index.js.map +1 -0
- package/dist/core/registry.d.ts +192 -0
- package/dist/core/registry.d.ts.map +1 -0
- package/dist/core/registry.js +2799 -0
- package/dist/core/registry.js.map +1 -0
- package/dist/core/types.d.ts +2468 -0
- package/dist/core/types.d.ts.map +1 -0
- package/dist/core/types.js +19 -0
- package/dist/core/types.js.map +1 -0
- package/dist/otel/index.d.ts +122 -0
- package/dist/otel/index.d.ts.map +1 -0
- package/dist/otel/index.js +157 -0
- package/dist/otel/index.js.map +1 -0
- package/dist/react/index.d.ts +191 -0
- package/dist/react/index.d.ts.map +1 -0
- package/dist/react/index.js +547 -0
- package/dist/react/index.js.map +1 -0
- package/dist/react/runtime.d.ts +95 -0
- package/dist/react/runtime.d.ts.map +1 -0
- package/dist/react/runtime.js +54 -0
- package/dist/react/runtime.js.map +1 -0
- package/dist/react/store.d.ts +333 -0
- package/dist/react/store.d.ts.map +1 -0
- package/dist/react/store.js +695 -0
- package/dist/react/store.js.map +1 -0
- package/dist/relay/auth.d.ts +244 -0
- package/dist/relay/auth.d.ts.map +1 -0
- package/dist/relay/auth.js +391 -0
- package/dist/relay/auth.js.map +1 -0
- package/dist/relay/frames.d.ts +141 -0
- package/dist/relay/frames.d.ts.map +1 -0
- package/dist/relay/frames.js +20 -0
- package/dist/relay/frames.js.map +1 -0
- package/dist/relay/index.d.ts +8 -0
- package/dist/relay/index.d.ts.map +1 -0
- package/dist/relay/index.js +4 -0
- package/dist/relay/index.js.map +1 -0
- package/dist/relay/relay.d.ts +277 -0
- package/dist/relay/relay.d.ts.map +1 -0
- package/dist/relay/relay.js +1026 -0
- package/dist/relay/relay.js.map +1 -0
- package/dist/relay/serve.d.ts +33 -0
- package/dist/relay/serve.d.ts.map +1 -0
- package/dist/relay/serve.js +86 -0
- package/dist/relay/serve.js.map +1 -0
- package/dist/widget/chat.d.ts +290 -0
- package/dist/widget/chat.d.ts.map +1 -0
- package/dist/widget/chat.js +486 -0
- package/dist/widget/chat.js.map +1 -0
- package/dist/widget/css.d.ts +49 -0
- package/dist/widget/css.d.ts.map +1 -0
- package/dist/widget/css.js +532 -0
- package/dist/widget/css.js.map +1 -0
- package/dist/widget/dom.d.ts +143 -0
- package/dist/widget/dom.d.ts.map +1 -0
- package/dist/widget/dom.js +27 -0
- package/dist/widget/dom.js.map +1 -0
- package/dist/widget/highlight.d.ts +64 -0
- package/dist/widget/highlight.d.ts.map +1 -0
- package/dist/widget/highlight.js +136 -0
- package/dist/widget/highlight.js.map +1 -0
- package/dist/widget/index.d.ts +9 -0
- package/dist/widget/index.d.ts.map +1 -0
- package/dist/widget/index.js +20 -0
- package/dist/widget/index.js.map +1 -0
- package/dist/widget/position.d.ts +166 -0
- package/dist/widget/position.d.ts.map +1 -0
- package/dist/widget/position.js +497 -0
- package/dist/widget/position.js.map +1 -0
- package/dist/widget/settings.d.ts +116 -0
- package/dist/widget/settings.d.ts.map +1 -0
- package/dist/widget/settings.js +117 -0
- package/dist/widget/settings.js.map +1 -0
- package/dist/widget/widget.d.ts +442 -0
- package/dist/widget/widget.d.ts.map +1 -0
- package/dist/widget/widget.js +2005 -0
- package/dist/widget/widget.js.map +1 -0
- package/package.json +144 -4
|
@@ -0,0 +1,486 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Surviving a page reload: restore everything, resume nothing.
|
|
3
|
+
*
|
|
4
|
+
* Today a reload destroys the drive loop, the transcript, and everything the
|
|
5
|
+
* agent knows. Settings and the panel's position are remembered — see
|
|
6
|
+
* `settings.ts` and `position.ts` — and the conversation, which is the only
|
|
7
|
+
* thing in the panel anybody would miss, was not.
|
|
8
|
+
*
|
|
9
|
+
* **THE RULE, AND WHY IT IS NOT "RESUME WHERE WE LEFT OFF".** A page can die
|
|
10
|
+
* mid-commit. Five steps in, `accept-selected` in flight on 3,412 rows, the tab
|
|
11
|
+
* reloads. Storage can record that the call was STARTED. It cannot record
|
|
12
|
+
* whether it LANDED — that answer is on the server, and the page that was
|
|
13
|
+
* waiting for it is gone. A run that auto-resumed would either repeat a commit
|
|
14
|
+
* that already happened or skip one that did not, and those two are precisely
|
|
15
|
+
* what the plan token was built to prevent. So on return the transcript is
|
|
16
|
+
* there, and the panel says plainly that a call was in flight and may or may
|
|
17
|
+
* not have landed, naming the verb, before anything else happens.
|
|
18
|
+
*
|
|
19
|
+
* **WHAT IS PERSISTED: THE MODEL TURNS, AND THE RENDERED LINES ARE REBUILT FROM
|
|
20
|
+
* THEM.** Those were the two candidates and only one of them is a conversation.
|
|
21
|
+
* Persisting the rendered lines is cheaper and gives the person their history
|
|
22
|
+
* back — and leaves the model with amnesia, so the panel reads "I accepted
|
|
23
|
+
* 1,000 contacts" above an input box where "undo that" is unanswerable. That is
|
|
24
|
+
* a worse lie than an empty panel, because it looks like it worked. Persisting
|
|
25
|
+
* the turns gives both: the conversation continues coherently AND a readable
|
|
26
|
+
* transcript can be drawn from it, out of one source of truth. Two stored
|
|
27
|
+
* copies of one conversation is two things that come to disagree, which is the
|
|
28
|
+
* same argument the core makes for building an `AuditEvent` off the `Result`
|
|
29
|
+
* rather than from a second look at the app.
|
|
30
|
+
*
|
|
31
|
+
* Note what "resume nothing" does and does not mean. The run does not restart:
|
|
32
|
+
* no step is retried, no verb is called, nothing happens until the person types
|
|
33
|
+
* something. The CONVERSATION is continuous, which is the point of keeping it.
|
|
34
|
+
*
|
|
35
|
+
* **WHERE IT GOES: `sessionStorage`, NOT `localStorage`, AND THE SCOPE IS THE
|
|
36
|
+
* PRIVACY ANSWER AS WELL AS THE CORRECTNESS ONE.** A transcript holds the
|
|
37
|
+
* person's instructions and the model's prose about their records. That is a
|
|
38
|
+
* different privacy class from a remembered pane position, on a machine that
|
|
39
|
+
* may be shared, and `localStorage` would keep it until somebody cleared site
|
|
40
|
+
* data. `sessionStorage` is per TAB, survives a reload, and is discarded when
|
|
41
|
+
* the tab closes — so the conversation lives exactly as long as the sitting it
|
|
42
|
+
* was had in. It also settles scoping for free, which `localStorage` could not:
|
|
43
|
+
* two tabs of one app are two conversations and must not stomp each other, and
|
|
44
|
+
* a per-tab key in `localStorage` would need a tab id and would leave a key
|
|
45
|
+
* behind for every tab ever opened, which nothing can sweep up because
|
|
46
|
+
* `StorageLike` cannot enumerate. Per tab, dying with the tab, no garbage. The
|
|
47
|
+
* budget goes the other way for the opposite reason; see `budget.ts`.
|
|
48
|
+
*
|
|
49
|
+
* **AND IT IS OPT-IN.** `WidgetOptions.rememberChat` defaults off. A library
|
|
50
|
+
* must not start writing its users' business prose to disk because somebody
|
|
51
|
+
* upgraded, and "an app that opts into nothing behaves identically" is a rule
|
|
52
|
+
* this is not worth breaking. Once an app has opted in, the VIEWER's switch —
|
|
53
|
+
* `Settings.rememberChat`, beside the others — defaults on and turning it off
|
|
54
|
+
* forgets what is already stored. The app's `false` wins: an app handling
|
|
55
|
+
* records that must not be written down can say so, and no viewer can undo it.
|
|
56
|
+
*/
|
|
57
|
+
import { ASK, REDACTED } from "../core/index.js";
|
|
58
|
+
/**
|
|
59
|
+
* The schema version, written into every record and checked on the way back.
|
|
60
|
+
*
|
|
61
|
+
* A stored conversation from an older widget is the normal case and not the
|
|
62
|
+
* exceptional one — somebody has a tab open from before the deploy — and
|
|
63
|
+
* `settings.ts` folds field by field for exactly that reason. A transcript
|
|
64
|
+
* cannot be folded that way: a half-understood `Turn[]` handed to a model is a
|
|
65
|
+
* 400 from the provider, not a default pace. So the version is a gate, and a
|
|
66
|
+
* record that is not this version is dropped whole.
|
|
67
|
+
*/
|
|
68
|
+
export const CHAT_VERSION = 1;
|
|
69
|
+
/**
|
|
70
|
+
* How much stored conversation is enough.
|
|
71
|
+
*
|
|
72
|
+
* `sessionStorage` is about 5MB per origin and `setItem` THROWS on quota — and
|
|
73
|
+
* the quota is shared with the app this panel is embedded in, which is the part
|
|
74
|
+
* that makes a generous limit irresponsible rather than merely wasteful. A long
|
|
75
|
+
* run must not break the app it is a guest in.
|
|
76
|
+
*
|
|
77
|
+
* 128KB is roughly a hundred steps of a pruned conversation, because
|
|
78
|
+
* `pruneScreens` has already removed every screen but the newest: what is left
|
|
79
|
+
* is an outcome line per call and the person's own words. It is a fortieth of
|
|
80
|
+
* the origin's quota, so the panel cannot be the reason an app's own storage
|
|
81
|
+
* write fails.
|
|
82
|
+
*/
|
|
83
|
+
export const CHAT_LIMIT_CHARS = 128 * 1024;
|
|
84
|
+
export function chatKey(app) {
|
|
85
|
+
return `driverkit:widget:chat:${app}`;
|
|
86
|
+
}
|
|
87
|
+
/** `sessionStorage`, if reaching for it does not throw — which it does when
|
|
88
|
+
* site data is blocked, before any read has been attempted. The twin of
|
|
89
|
+
* `defaultStorage()` in `position.ts`, pointing at the per-tab one. */
|
|
90
|
+
export function defaultSession() {
|
|
91
|
+
try {
|
|
92
|
+
return globalThis.sessionStorage;
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Replace the value of every argument the app declared `sensitive`.
|
|
100
|
+
*
|
|
101
|
+
* **This is the leak `ArgSpec.sensitive` was built to stop, in the one new
|
|
102
|
+
* place it could reappear.** That field exists so a value never crosses the
|
|
103
|
+
* `onAudit` boundary — "the boundary a record is most likely to leave the box
|
|
104
|
+
* across" — and the core replaces it before the hook rather than asking the
|
|
105
|
+
* host to. Persisting the raw model turns would write the same value to disk,
|
|
106
|
+
* where it outlives the call, the run and the page, and it would do it under a
|
|
107
|
+
* feature nobody would think to check. An app that declared an argument too
|
|
108
|
+
* secret for its own logger did not thereby agree to have it in storage.
|
|
109
|
+
*
|
|
110
|
+
* Done HERE, at the one boundary, and not at the call sites that build turns —
|
|
111
|
+
* which is the repo's standing rule about scrubbing and the reason this takes a
|
|
112
|
+
* whole conversation rather than one argument. Every byte that reaches storage
|
|
113
|
+
* goes through this function; there is nowhere else to forget it.
|
|
114
|
+
*
|
|
115
|
+
* `REDACTED` is the core's own marker, reused rather than reinvented, so a
|
|
116
|
+
* restored turn says the same word an audit record says and neither can be
|
|
117
|
+
* mistaken for a string the agent actually sent.
|
|
118
|
+
*
|
|
119
|
+
* **The consequence, stated rather than hidden:** a restored conversation hands
|
|
120
|
+
* the model `[redacted]` where its own earlier argument was. That is correct —
|
|
121
|
+
* the alternative is the leak — and it is honest, because the turn then says
|
|
122
|
+
* out loud that the value is not being shown. A model that needs the value
|
|
123
|
+
* again asks for it again, which is what should happen to a secret after a
|
|
124
|
+
* reload.
|
|
125
|
+
*/
|
|
126
|
+
export function scrubTurns(turns, manifest) {
|
|
127
|
+
// Built once per save rather than looked up per argument. Empty for the
|
|
128
|
+
// overwhelming majority of apps, in which case the loop below is a shallow
|
|
129
|
+
// copy and the whole function is free.
|
|
130
|
+
const secret = new Map();
|
|
131
|
+
for (const verb of manifest.verbs) {
|
|
132
|
+
for (const [name, spec] of Object.entries(verb.args ?? {})) {
|
|
133
|
+
if (spec.sensitive !== true)
|
|
134
|
+
continue;
|
|
135
|
+
let fields = secret.get(verb.name);
|
|
136
|
+
if (!fields)
|
|
137
|
+
secret.set(verb.name, (fields = new Set()));
|
|
138
|
+
fields.add(name);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
if (secret.size === 0)
|
|
142
|
+
return turns;
|
|
143
|
+
return turns.map((turn) => {
|
|
144
|
+
if (turn.role !== "assistant" || !turn.calls)
|
|
145
|
+
return turn;
|
|
146
|
+
return {
|
|
147
|
+
...turn,
|
|
148
|
+
calls: turn.calls.map((call) => {
|
|
149
|
+
const fields = secret.get(call.name);
|
|
150
|
+
if (!fields)
|
|
151
|
+
return call;
|
|
152
|
+
const args = {};
|
|
153
|
+
for (const [key, value] of Object.entries(call.args)) {
|
|
154
|
+
args[key] = fields.has(key) ? REDACTED : value;
|
|
155
|
+
}
|
|
156
|
+
return { ...call, args };
|
|
157
|
+
}),
|
|
158
|
+
};
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Drop leading turns until the rest fits, cutting only at a safe seam.
|
|
163
|
+
*
|
|
164
|
+
* **The seam is the whole of this function and the reason it is not a `slice`.**
|
|
165
|
+
* Every tool-use API rejects a conversation in which a `tool_use` block has no
|
|
166
|
+
* matching result — `abandoned` in `loop.ts` exists for that one fact, and says
|
|
167
|
+
* what it costs: "one missing tool turn is a dead panel", forever, with nothing
|
|
168
|
+
* on screen to explain it. So trimming must never leave a tool turn whose
|
|
169
|
+
* assistant turn is gone, nor an assistant turn whose results are gone.
|
|
170
|
+
*
|
|
171
|
+
* A `user` turn is the only index where that is provable without reasoning
|
|
172
|
+
* about pairs: the loop answers every call of an assistant turn before it asks
|
|
173
|
+
* the model again, and a person speaks between runs. So the remainder is cut to
|
|
174
|
+
* begin at a user turn, and if no user boundary is small enough, NOTHING is
|
|
175
|
+
* stored and the caller says so. Storing a conversation that cannot be used is
|
|
176
|
+
* worse than storing none: the first breaks the panel permanently and the
|
|
177
|
+
* second loses a transcript.
|
|
178
|
+
*
|
|
179
|
+
* Returns the number dropped so the notice can admit it. A transcript quietly
|
|
180
|
+
* missing its beginning is one somebody will read as complete.
|
|
181
|
+
*/
|
|
182
|
+
export function trimTurns(turns, limitChars = CHAT_LIMIT_CHARS) {
|
|
183
|
+
if (JSON.stringify(turns).length <= limitChars)
|
|
184
|
+
return { messages: turns, trimmed: 0 };
|
|
185
|
+
for (let i = 1; i < turns.length; i++) {
|
|
186
|
+
if (turns[i].role !== "user")
|
|
187
|
+
continue;
|
|
188
|
+
const rest = turns.slice(i);
|
|
189
|
+
if (JSON.stringify(rest).length <= limitChars)
|
|
190
|
+
return { messages: rest, trimmed: i };
|
|
191
|
+
}
|
|
192
|
+
// No boundary fits: one enormous exchange, or one screen bigger than the
|
|
193
|
+
// whole limit. Nothing is kept, and `trimmed` says how much that was.
|
|
194
|
+
return { messages: [], trimmed: turns.length };
|
|
195
|
+
}
|
|
196
|
+
/**
|
|
197
|
+
* Answer every tool call left dangling, so the restored history is usable.
|
|
198
|
+
*
|
|
199
|
+
* **This is the correctness bug a reload creates and the single most
|
|
200
|
+
* load-bearing function in the file.** A page that dies mid-call leaves an
|
|
201
|
+
* assistant turn whose `tool_use` has no result. Handed back as `history` that
|
|
202
|
+
* is a 400 from the provider on the person's very next message, and on every
|
|
203
|
+
* message after it, with an apparently fine transcript on screen. The panel
|
|
204
|
+
* would come back looking restored and be permanently broken.
|
|
205
|
+
*
|
|
206
|
+
* So each dangling call gets an answer, and the answer is written for the model
|
|
207
|
+
* rather than for the protocol — the same judgement `abandoned` makes. What it
|
|
208
|
+
* must never say is anything that reads as a step to retry, and what it must
|
|
209
|
+
* never do is guess:
|
|
210
|
+
*
|
|
211
|
+
* `sent` — the outcome is UNKNOWN. This is the sentence the whole feature
|
|
212
|
+
* turns on, and it is deliberately the wording `render.py` uses for
|
|
213
|
+
* a relay `timeout`, because it is the same fact: the call was
|
|
214
|
+
* accepted, nobody heard back, and a commit may already have run.
|
|
215
|
+
* The natural reflex — treat a non-answer as a failure and retry
|
|
216
|
+
* it — is the one move that turns one bulk accept into two.
|
|
217
|
+
* `asked` — KNOWN not to have run, because the core asks before it runs.
|
|
218
|
+
* Said flatly, because an agent told "unknown" about a commit that
|
|
219
|
+
* provably did not happen will go and check for nothing, and may
|
|
220
|
+
* decide not to do the thing the person asked for.
|
|
221
|
+
*
|
|
222
|
+
* Only the call the record named gets the `asked` wording. Any other dangling
|
|
223
|
+
* call is unknown, which is the safe direction and also the true one.
|
|
224
|
+
*/
|
|
225
|
+
export function closeDangling(turns, inFlight) {
|
|
226
|
+
const answered = new Set();
|
|
227
|
+
for (const turn of turns) {
|
|
228
|
+
if (turn.role === "tool")
|
|
229
|
+
answered.add(turn.callId);
|
|
230
|
+
}
|
|
231
|
+
const out = [];
|
|
232
|
+
for (const turn of turns) {
|
|
233
|
+
out.push(turn);
|
|
234
|
+
if (turn.role !== "assistant" || !turn.calls)
|
|
235
|
+
continue;
|
|
236
|
+
for (const call of turn.calls) {
|
|
237
|
+
if (answered.has(call.id))
|
|
238
|
+
continue;
|
|
239
|
+
const known = inFlight?.phase === "asked" && inFlight.verb === call.name;
|
|
240
|
+
out.push({
|
|
241
|
+
role: "tool",
|
|
242
|
+
callId: call.id,
|
|
243
|
+
name: call.name,
|
|
244
|
+
text: known
|
|
245
|
+
? call.name === ASK
|
|
246
|
+
? // A QUESTION, not a confirmation, and the two must not share a
|
|
247
|
+
// sentence. "The person was being asked to confirm this" is false
|
|
248
|
+
// of a question in a way that matters: a model told its question
|
|
249
|
+
// was a confirmation request may conclude the answer would have
|
|
250
|
+
// been a yes, which is the one inference this channel exists to
|
|
251
|
+
// make impossible. Nothing changed either way -- a question runs
|
|
252
|
+
// no verb at all, which is a stronger claim than the one below.
|
|
253
|
+
"not run: you were being asked this question and the page was reloaded before " +
|
|
254
|
+
"anybody answered. No answer was recorded, nothing in the app changed, and no " +
|
|
255
|
+
"verb ran. This is not an error and it is not a yes. Ask again if you still " +
|
|
256
|
+
"need to know."
|
|
257
|
+
: "not run: the person was being asked to confirm this and the page was reloaded " +
|
|
258
|
+
"before they answered, so the verb did not run and nothing changed. This is not " +
|
|
259
|
+
"an error. Ask them again if it is still what they want."
|
|
260
|
+
: "the page was reloaded while this call was in flight, so no answer ever came back. " +
|
|
261
|
+
"The outcome is UNKNOWN: it may well have run. DO NOT retry it. Read the screen " +
|
|
262
|
+
"first and decide from what you see there, and say plainly that you cannot tell " +
|
|
263
|
+
"whether it took effect.",
|
|
264
|
+
});
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
return out;
|
|
268
|
+
}
|
|
269
|
+
/**
|
|
270
|
+
* What the panel says, in order, when a conversation comes back.
|
|
271
|
+
*
|
|
272
|
+
* Returned as lines rather than printed, so the words are testable without a
|
|
273
|
+
* DOM and so there is one place they are written. The first line is always
|
|
274
|
+
* about what may have happened to the data, because that is the thing a person
|
|
275
|
+
* has to act on and everything else can wait behind it.
|
|
276
|
+
*
|
|
277
|
+
* The verb is NAMED. "A call was in flight" sends somebody to look at the whole
|
|
278
|
+
* app; "`accept-selected` was in flight" sends them to one screen.
|
|
279
|
+
*/
|
|
280
|
+
export function restoredLines(record) {
|
|
281
|
+
const lines = [];
|
|
282
|
+
if (record.inFlight?.phase === "sent") {
|
|
283
|
+
lines.push(`The page reloaded while \`${record.inFlight.verb}\` was running. This panel cannot ` +
|
|
284
|
+
`tell whether it took effect — that answer was on the server, and the page waiting ` +
|
|
285
|
+
`for it is gone. Check the app before doing anything else.`);
|
|
286
|
+
}
|
|
287
|
+
else if (record.inFlight?.phase === "asked" && record.inFlight.verb === ASK) {
|
|
288
|
+
// A question, not a confirmation. "You were being asked to approve `ask`"
|
|
289
|
+
// is a sentence about something that did not happen, and the person reading
|
|
290
|
+
// it would go looking for the commit it named.
|
|
291
|
+
lines.push("The page reloaded while the agent was asking you a question. You never answered, so " +
|
|
292
|
+
"it was not told anything and nothing in the app changed.");
|
|
293
|
+
}
|
|
294
|
+
else if (record.inFlight?.phase === "asked") {
|
|
295
|
+
lines.push(`The page reloaded while you were being asked to approve \`${record.inFlight.verb}\`. ` +
|
|
296
|
+
`You never answered, so it did not run and nothing changed.`);
|
|
297
|
+
}
|
|
298
|
+
lines.push("This conversation is from before the reload. Nothing has been resumed: the run stopped " +
|
|
299
|
+
"when the page went away and will not pick itself back up. Ask again to carry on.");
|
|
300
|
+
if (record.trimmed) {
|
|
301
|
+
lines.push(`The first ${record.trimmed} message${record.trimmed === 1 ? "" : "s"} of this ` +
|
|
302
|
+
`conversation were too large to keep and are not shown.`);
|
|
303
|
+
}
|
|
304
|
+
return lines;
|
|
305
|
+
}
|
|
306
|
+
/**
|
|
307
|
+
* One readable line per stored turn, for redrawing the transcript.
|
|
308
|
+
*
|
|
309
|
+
* Deliberately not a reconstruction of what the panel looked like. A tool turn
|
|
310
|
+
* was a row in the step list with a state marker and a `title`; what comes back
|
|
311
|
+
* is a plain line of text, because the step list is a live thing — it glows, it
|
|
312
|
+
* marks a call as pending, it is about a run that is happening — and redrawing
|
|
313
|
+
* it for a run that ended at a reload would be a panel claiming to be mid-step.
|
|
314
|
+
* A restored transcript should read as a record, which is what it is.
|
|
315
|
+
*
|
|
316
|
+
* The screen blocks are dropped from what is DISPLAYED. They are still in the
|
|
317
|
+
* stored turns, where the model needs the newest one; a wall of table on reload
|
|
318
|
+
* is not what the person wants to see first.
|
|
319
|
+
*/
|
|
320
|
+
export function replayLines(record) {
|
|
321
|
+
const out = [];
|
|
322
|
+
for (const turn of record.messages) {
|
|
323
|
+
if (turn.role === "user") {
|
|
324
|
+
out.push({ className: "dk-you", text: firstPart(turn.text) });
|
|
325
|
+
}
|
|
326
|
+
else if (turn.role === "assistant") {
|
|
327
|
+
if (turn.text)
|
|
328
|
+
out.push({ className: "dk-said", text: turn.text });
|
|
329
|
+
for (const call of turn.calls ?? []) {
|
|
330
|
+
out.push({ className: "dk-step dk-step-done", text: call.name });
|
|
331
|
+
}
|
|
332
|
+
}
|
|
333
|
+
// Tool turns are not replayed as lines of their own. Their outcome already
|
|
334
|
+
// reads as the step above it in a live run, and a separate line per result
|
|
335
|
+
// would double the length of a restored transcript with text written for a
|
|
336
|
+
// model rather than for a person.
|
|
337
|
+
}
|
|
338
|
+
return out;
|
|
339
|
+
}
|
|
340
|
+
/** Everything a turn's text says before the screen block `loop.ts` appends.
|
|
341
|
+
* The marker is that file's `SCREEN_MARK`, matched on its text rather than
|
|
342
|
+
* imported, because the widget must not start depending on the loop's seam to
|
|
343
|
+
* render a line. */
|
|
344
|
+
function firstPart(text) {
|
|
345
|
+
const at = text.indexOf("\n\nOn screen now:\n");
|
|
346
|
+
return at === -1 ? text : text.slice(0, at);
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Read a stored conversation back, or null for every way that can fail.
|
|
350
|
+
*
|
|
351
|
+
* Validated field by field, and a failure is a `null` rather than a repair.
|
|
352
|
+
* `settings.ts` folds a partial record over the defaults because a missing pace
|
|
353
|
+
* is a readable record with a gap in it; a `Turn[]` with a gap in it is a
|
|
354
|
+
* provider error on the person's next message. The two kinds of persisted state
|
|
355
|
+
* want opposite treatment and this is the strict one.
|
|
356
|
+
*
|
|
357
|
+
* Every read is inside one try, like `loadJson`: a private window and blocked
|
|
358
|
+
* site data throw on the way IN, before any value has been looked at.
|
|
359
|
+
*/
|
|
360
|
+
export function loadChat(session, app) {
|
|
361
|
+
try {
|
|
362
|
+
const raw = session?.getItem(chatKey(app));
|
|
363
|
+
if (!raw)
|
|
364
|
+
return null;
|
|
365
|
+
const value = JSON.parse(raw);
|
|
366
|
+
if (!value || typeof value !== "object")
|
|
367
|
+
return null;
|
|
368
|
+
if (value.v !== CHAT_VERSION)
|
|
369
|
+
return null;
|
|
370
|
+
// The app is checked because one origin can serve two driverkit apps, and
|
|
371
|
+
// a conversation about somebody's contacts does not belong in the admin
|
|
372
|
+
// panel's transcript.
|
|
373
|
+
if (value.app !== app)
|
|
374
|
+
return null;
|
|
375
|
+
if (!Array.isArray(value.messages) || !value.messages.every(isTurn))
|
|
376
|
+
return null;
|
|
377
|
+
const inFlight = value.inFlight;
|
|
378
|
+
return {
|
|
379
|
+
v: CHAT_VERSION,
|
|
380
|
+
app,
|
|
381
|
+
at: typeof value.at === "number" ? value.at : 0,
|
|
382
|
+
messages: value.messages,
|
|
383
|
+
conversed: value.conversed === true,
|
|
384
|
+
...(inFlight &&
|
|
385
|
+
typeof inFlight.verb === "string" &&
|
|
386
|
+
(inFlight.phase === "asked" || inFlight.phase === "sent")
|
|
387
|
+
? { inFlight: { verb: inFlight.verb, phase: inFlight.phase } }
|
|
388
|
+
: {}),
|
|
389
|
+
...(typeof value.trimmed === "number" && value.trimmed > 0
|
|
390
|
+
? { trimmed: value.trimmed }
|
|
391
|
+
: {}),
|
|
392
|
+
};
|
|
393
|
+
}
|
|
394
|
+
catch {
|
|
395
|
+
return null;
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
/** Whether one stored value is a `Turn`. Shape only: it is about to be handed
|
|
399
|
+
* to a provider, and a turn with a missing `callId` is a 400 rather than a
|
|
400
|
+
* cosmetic gap. */
|
|
401
|
+
function isTurn(value) {
|
|
402
|
+
const turn = value;
|
|
403
|
+
if (!turn || typeof turn !== "object")
|
|
404
|
+
return false;
|
|
405
|
+
if (turn.role === "user")
|
|
406
|
+
return typeof turn.text === "string";
|
|
407
|
+
if (turn.role === "assistant") {
|
|
408
|
+
const t = turn;
|
|
409
|
+
if (t.text !== undefined && typeof t.text !== "string")
|
|
410
|
+
return false;
|
|
411
|
+
if (t.calls === undefined)
|
|
412
|
+
return true;
|
|
413
|
+
return Array.isArray(t.calls) && t.calls.every(isCall);
|
|
414
|
+
}
|
|
415
|
+
if (turn.role === "tool") {
|
|
416
|
+
const t = turn;
|
|
417
|
+
return typeof t.callId === "string" && typeof t.name === "string" && typeof t.text === "string";
|
|
418
|
+
}
|
|
419
|
+
return false;
|
|
420
|
+
}
|
|
421
|
+
function isCall(value) {
|
|
422
|
+
const call = value;
|
|
423
|
+
return (!!call &&
|
|
424
|
+
typeof call === "object" &&
|
|
425
|
+
typeof call.id === "string" &&
|
|
426
|
+
typeof call.name === "string" &&
|
|
427
|
+
!!call.args &&
|
|
428
|
+
typeof call.args === "object");
|
|
429
|
+
}
|
|
430
|
+
/**
|
|
431
|
+
* Write a conversation, and swallow every reason it can fail.
|
|
432
|
+
*
|
|
433
|
+
* Swallowed, unlike `budget.ts`, and the asymmetry is the point. A budget that
|
|
434
|
+
* cannot be written is an uncapped agent, so that one fails closed and stops
|
|
435
|
+
* the agent. A transcript that cannot be written is a conversation somebody
|
|
436
|
+
* will have to retype, which is not worth a thrown error — and a throw here
|
|
437
|
+
* would be thrown INSIDE a drive run, out of an `onResult` handler, where it
|
|
438
|
+
* would take down the run that is moving the person's screen. A storage write
|
|
439
|
+
* must never break a drive run. See `saveJson`, which makes the same promise
|
|
440
|
+
* for the panel's position and for the same reason.
|
|
441
|
+
*
|
|
442
|
+
* `trimmed: 0` is not written, so an ordinary record carries no field for it
|
|
443
|
+
* and `loadChat` reading its absence as "nothing was dropped" is the same
|
|
444
|
+
* sentence either way.
|
|
445
|
+
*/
|
|
446
|
+
export function saveChat(session, app, record) {
|
|
447
|
+
try {
|
|
448
|
+
session?.setItem(chatKey(app), JSON.stringify({
|
|
449
|
+
v: CHAT_VERSION,
|
|
450
|
+
app,
|
|
451
|
+
at: record.at,
|
|
452
|
+
messages: record.messages,
|
|
453
|
+
conversed: record.conversed,
|
|
454
|
+
...(record.inFlight === undefined ? {} : { inFlight: record.inFlight }),
|
|
455
|
+
...(record.trimmed ? { trimmed: record.trimmed } : {}),
|
|
456
|
+
}));
|
|
457
|
+
}
|
|
458
|
+
catch {
|
|
459
|
+
// A full quota, a private window, a viewer who blocked site data. The
|
|
460
|
+
// conversation is still correct for this sitting; it just will not come
|
|
461
|
+
// back after a reload, and that is not worth an exception thrown through a
|
|
462
|
+
// run that is driving somebody's screen.
|
|
463
|
+
}
|
|
464
|
+
}
|
|
465
|
+
/**
|
|
466
|
+
* Forget the stored conversation.
|
|
467
|
+
*
|
|
468
|
+
* Written empty rather than removed, because `StorageLike` is two methods and
|
|
469
|
+
* `removeItem` is not one of them — and `loadChat` reads an empty string as an
|
|
470
|
+
* empty slot, which is what a removal would leave anyway.
|
|
471
|
+
*
|
|
472
|
+
* Called by "Clear conversation", and that call is load-bearing rather than
|
|
473
|
+
* tidy. `era` in `widget.ts` exists so a dying run's writes cannot land in a
|
|
474
|
+
* fresh transcript after a clear; a stored record is the same hazard with a
|
|
475
|
+
* longer fuse — clear the panel, reload, and a cleared conversation comes back
|
|
476
|
+
* from disk. The destructive option has to be destructive all the way down.
|
|
477
|
+
*/
|
|
478
|
+
export function forgetChat(session, app) {
|
|
479
|
+
try {
|
|
480
|
+
session?.setItem(chatKey(app), "");
|
|
481
|
+
}
|
|
482
|
+
catch {
|
|
483
|
+
// Nothing was stored, so nothing needs forgetting.
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
//# sourceMappingURL=chat.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"chat.js","sourceRoot":"","sources":["../../src/widget/chat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuDG;AAGH,OAAO,EAAE,GAAG,EAAE,QAAQ,EAAE,MAAM,kBAAkB,CAAC;AAKjD;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,CAAC;AA6C9B;;;;;;;;;;;;;GAaG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,GAAG,IAAI,CA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CAAC,GAAG,CAAC,EAAE,EAAE,CAAC,CAAC;IACrC,CAAC;IAAC,MAAM,CAAC;QACP,mDAAmD;IACrD,CAAC;AACH,CAAC","sourcesContent":["/**\n * Surviving a page reload: restore everything, resume nothing.\n *\n * Today a reload destroys the drive loop, the transcript, and everything the\n * agent knows. Settings and the panel's position are remembered — see\n * `settings.ts` and `position.ts` — and the conversation, which is the only\n * thing in the panel anybody would miss, was not.\n *\n * **THE RULE, AND WHY IT IS NOT \"RESUME WHERE WE LEFT OFF\".** A page can die\n * mid-commit. Five steps in, `accept-selected` in flight on 3,412 rows, the tab\n * reloads. Storage can record that the call was STARTED. It cannot record\n * whether it LANDED — that answer is on the server, and the page that was\n * waiting for it is gone. A run that auto-resumed would either repeat a commit\n * that already happened or skip one that did not, and those two are precisely\n * what the plan token was built to prevent. So on return the transcript is\n * there, and the panel says plainly that a call was in flight and may or may\n * not have landed, naming the verb, before anything else happens.\n *\n * **WHAT IS PERSISTED: THE MODEL TURNS, AND THE RENDERED LINES ARE REBUILT FROM\n * THEM.** Those were the two candidates and only one of them is a conversation.\n * Persisting the rendered lines is cheaper and gives the person their history\n * back — and leaves the model with amnesia, so the panel reads \"I accepted\n * 1,000 contacts\" above an input box where \"undo that\" is unanswerable. That is\n * a worse lie than an empty panel, because it looks like it worked. Persisting\n * the turns gives both: the conversation continues coherently AND a readable\n * transcript can be drawn from it, out of one source of truth. Two stored\n * copies of one conversation is two things that come to disagree, which is the\n * same argument the core makes for building an `AuditEvent` off the `Result`\n * rather than from a second look at the app.\n *\n * Note what \"resume nothing\" does and does not mean. The run does not restart:\n * no step is retried, no verb is called, nothing happens until the person types\n * something. The CONVERSATION is continuous, which is the point of keeping it.\n *\n * **WHERE IT GOES: `sessionStorage`, NOT `localStorage`, AND THE SCOPE IS THE\n * PRIVACY ANSWER AS WELL AS THE CORRECTNESS ONE.** A transcript holds the\n * person's instructions and the model's prose about their records. That is a\n * different privacy class from a remembered pane position, on a machine that\n * may be shared, and `localStorage` would keep it until somebody cleared site\n * data. `sessionStorage` is per TAB, survives a reload, and is discarded when\n * the tab closes — so the conversation lives exactly as long as the sitting it\n * was had in. It also settles scoping for free, which `localStorage` could not:\n * two tabs of one app are two conversations and must not stomp each other, and\n * a per-tab key in `localStorage` would need a tab id and would leave a key\n * behind for every tab ever opened, which nothing can sweep up because\n * `StorageLike` cannot enumerate. Per tab, dying with the tab, no garbage. The\n * budget goes the other way for the opposite reason; see `budget.ts`.\n *\n * **AND IT IS OPT-IN.** `WidgetOptions.rememberChat` defaults off. A library\n * must not start writing its users' business prose to disk because somebody\n * upgraded, and \"an app that opts into nothing behaves identically\" is a rule\n * this is not worth breaking. Once an app has opted in, the VIEWER's switch —\n * `Settings.rememberChat`, beside the others — defaults on and turning it off\n * forgets what is already stored. The app's `false` wins: an app handling\n * records that must not be written down can say so, and no viewer can undo it.\n */\n\nimport type { Manifest, Scalar } from \"../core/index.ts\";\nimport { ASK, REDACTED } from \"../core/index.ts\";\nimport type { ToolCall, Turn } from \"../agent/types.ts\";\n\nimport type { StorageLike } from \"./dom.ts\";\n\n/**\n * The schema version, written into every record and checked on the way back.\n *\n * A stored conversation from an older widget is the normal case and not the\n * exceptional one — somebody has a tab open from before the deploy — and\n * `settings.ts` folds field by field for exactly that reason. A transcript\n * cannot be folded that way: a half-understood `Turn[]` handed to a model is a\n * 400 from the provider, not a default pace. So the version is a gate, and a\n * record that is not this version is dropped whole.\n */\nexport const CHAT_VERSION = 1;\n\n/**\n * What the panel was doing when the page went away.\n *\n * `asked` and `sent` are the two states the restored panel must never confuse,\n * and they are different KINDS of fact, not degrees of one:\n *\n * `asked` — a question was on screen and nobody had answered it. The core\n * asks before it runs, so this one is KNOWABLE: the verb did not\n * run and nothing moved. The panel can say so flatly.\n * `sent` — the call was past every gate and in flight. This one is NOT\n * knowable from here, ever, and no amount of care in this file\n * changes that. The answer was on the server.\n *\n * `verb` is the verb's name. Not its arguments: a name is a word out of the\n * app's own manifest and an argument is the person's data, and this record is\n * being written to disk for a sentence in a notice.\n */\nexport interface ChatInFlight {\n verb: string;\n phase: \"asked\" | \"sent\";\n}\n\n/** One stored conversation. */\nexport interface SavedChat {\n v: number;\n /** `MountOptions.app`, so a record found under a key this build no longer\n * writes cannot be shown in the wrong app's panel. */\n app: string;\n /** `Date.now()` at the write, for the notice and for anybody debugging. */\n at: number;\n /** The conversation, scrubbed and trimmed. See `scrubTurns`. */\n messages: Turn[];\n /** Whether anything had been asked. Drives the launcher's dot, which is a\n * different question from \"is there a transcript\". */\n conversed: boolean;\n /** What was in flight, when something was. See `ChatInFlight`. */\n inFlight?: ChatInFlight;\n /** How many leading turns `trimTurns` dropped for size. Present only when it\n * dropped some, because the notice has to say so: a transcript that is\n * quietly missing its beginning is one the person will read as complete. */\n trimmed?: number;\n}\n\n/**\n * How much stored conversation is enough.\n *\n * `sessionStorage` is about 5MB per origin and `setItem` THROWS on quota — and\n * the quota is shared with the app this panel is embedded in, which is the part\n * that makes a generous limit irresponsible rather than merely wasteful. A long\n * run must not break the app it is a guest in.\n *\n * 128KB is roughly a hundred steps of a pruned conversation, because\n * `pruneScreens` has already removed every screen but the newest: what is left\n * is an outcome line per call and the person's own words. It is a fortieth of\n * the origin's quota, so the panel cannot be the reason an app's own storage\n * write fails.\n */\nexport const CHAT_LIMIT_CHARS = 128 * 1024;\n\nexport function chatKey(app: string): string {\n return `driverkit:widget:chat:${app}`;\n}\n\n/** `sessionStorage`, if reaching for it does not throw — which it does when\n * site data is blocked, before any read has been attempted. The twin of\n * `defaultStorage()` in `position.ts`, pointing at the per-tab one. */\nexport function defaultSession(): StorageLike | undefined {\n try {\n return (globalThis as { sessionStorage?: StorageLike }).sessionStorage;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Replace the value of every argument the app declared `sensitive`.\n *\n * **This is the leak `ArgSpec.sensitive` was built to stop, in the one new\n * place it could reappear.** That field exists so a value never crosses the\n * `onAudit` boundary — \"the boundary a record is most likely to leave the box\n * across\" — and the core replaces it before the hook rather than asking the\n * host to. Persisting the raw model turns would write the same value to disk,\n * where it outlives the call, the run and the page, and it would do it under a\n * feature nobody would think to check. An app that declared an argument too\n * secret for its own logger did not thereby agree to have it in storage.\n *\n * Done HERE, at the one boundary, and not at the call sites that build turns —\n * which is the repo's standing rule about scrubbing and the reason this takes a\n * whole conversation rather than one argument. Every byte that reaches storage\n * goes through this function; there is nowhere else to forget it.\n *\n * `REDACTED` is the core's own marker, reused rather than reinvented, so a\n * restored turn says the same word an audit record says and neither can be\n * mistaken for a string the agent actually sent.\n *\n * **The consequence, stated rather than hidden:** a restored conversation hands\n * the model `[redacted]` where its own earlier argument was. That is correct —\n * the alternative is the leak — and it is honest, because the turn then says\n * out loud that the value is not being shown. A model that needs the value\n * again asks for it again, which is what should happen to a secret after a\n * reload.\n */\nexport function scrubTurns(turns: Turn[], manifest: Manifest): Turn[] {\n // Built once per save rather than looked up per argument. Empty for the\n // overwhelming majority of apps, in which case the loop below is a shallow\n // copy and the whole function is free.\n const secret = new Map<string, Set<string>>();\n for (const verb of manifest.verbs) {\n for (const [name, spec] of Object.entries(verb.args ?? {})) {\n if (spec.sensitive !== true) continue;\n let fields = secret.get(verb.name);\n if (!fields) secret.set(verb.name, (fields = new Set()));\n fields.add(name);\n }\n }\n if (secret.size === 0) return turns;\n\n return turns.map((turn) => {\n if (turn.role !== \"assistant\" || !turn.calls) return turn;\n return {\n ...turn,\n calls: turn.calls.map((call): ToolCall => {\n const fields = secret.get(call.name);\n if (!fields) return call;\n const args: Record<string, Scalar> = {};\n for (const [key, value] of Object.entries(call.args)) {\n args[key] = fields.has(key) ? REDACTED : value;\n }\n return { ...call, args };\n }),\n };\n });\n}\n\n/**\n * Drop leading turns until the rest fits, cutting only at a safe seam.\n *\n * **The seam is the whole of this function and the reason it is not a `slice`.**\n * Every tool-use API rejects a conversation in which a `tool_use` block has no\n * matching result — `abandoned` in `loop.ts` exists for that one fact, and says\n * what it costs: \"one missing tool turn is a dead panel\", forever, with nothing\n * on screen to explain it. So trimming must never leave a tool turn whose\n * assistant turn is gone, nor an assistant turn whose results are gone.\n *\n * A `user` turn is the only index where that is provable without reasoning\n * about pairs: the loop answers every call of an assistant turn before it asks\n * the model again, and a person speaks between runs. So the remainder is cut to\n * begin at a user turn, and if no user boundary is small enough, NOTHING is\n * stored and the caller says so. Storing a conversation that cannot be used is\n * worse than storing none: the first breaks the panel permanently and the\n * second loses a transcript.\n *\n * Returns the number dropped so the notice can admit it. A transcript quietly\n * missing its beginning is one somebody will read as complete.\n */\nexport function trimTurns(\n turns: Turn[],\n limitChars: number = CHAT_LIMIT_CHARS,\n): { messages: Turn[]; trimmed: number } {\n if (JSON.stringify(turns).length <= limitChars) return { messages: turns, trimmed: 0 };\n\n for (let i = 1; i < turns.length; i++) {\n if (turns[i]!.role !== \"user\") continue;\n const rest = turns.slice(i);\n if (JSON.stringify(rest).length <= limitChars) return { messages: rest, trimmed: i };\n }\n // No boundary fits: one enormous exchange, or one screen bigger than the\n // whole limit. Nothing is kept, and `trimmed` says how much that was.\n return { messages: [], trimmed: turns.length };\n}\n\n/**\n * Answer every tool call left dangling, so the restored history is usable.\n *\n * **This is the correctness bug a reload creates and the single most\n * load-bearing function in the file.** A page that dies mid-call leaves an\n * assistant turn whose `tool_use` has no result. Handed back as `history` that\n * is a 400 from the provider on the person's very next message, and on every\n * message after it, with an apparently fine transcript on screen. The panel\n * would come back looking restored and be permanently broken.\n *\n * So each dangling call gets an answer, and the answer is written for the model\n * rather than for the protocol — the same judgement `abandoned` makes. What it\n * must never say is anything that reads as a step to retry, and what it must\n * never do is guess:\n *\n * `sent` — the outcome is UNKNOWN. This is the sentence the whole feature\n * turns on, and it is deliberately the wording `render.py` uses for\n * a relay `timeout`, because it is the same fact: the call was\n * accepted, nobody heard back, and a commit may already have run.\n * The natural reflex — treat a non-answer as a failure and retry\n * it — is the one move that turns one bulk accept into two.\n * `asked` — KNOWN not to have run, because the core asks before it runs.\n * Said flatly, because an agent told \"unknown\" about a commit that\n * provably did not happen will go and check for nothing, and may\n * decide not to do the thing the person asked for.\n *\n * Only the call the record named gets the `asked` wording. Any other dangling\n * call is unknown, which is the safe direction and also the true one.\n */\nexport function closeDangling(turns: Turn[], inFlight?: ChatInFlight): Turn[] {\n const answered = new Set<string>();\n for (const turn of turns) {\n if (turn.role === \"tool\") answered.add(turn.callId);\n }\n\n const out: Turn[] = [];\n for (const turn of turns) {\n out.push(turn);\n if (turn.role !== \"assistant\" || !turn.calls) continue;\n for (const call of turn.calls) {\n if (answered.has(call.id)) continue;\n const known = inFlight?.phase === \"asked\" && inFlight.verb === call.name;\n out.push({\n role: \"tool\",\n callId: call.id,\n name: call.name,\n text: known\n ? call.name === ASK\n ? // A QUESTION, not a confirmation, and the two must not share a\n // sentence. \"The person was being asked to confirm this\" is false\n // of a question in a way that matters: a model told its question\n // was a confirmation request may conclude the answer would have\n // been a yes, which is the one inference this channel exists to\n // make impossible. Nothing changed either way -- a question runs\n // no verb at all, which is a stronger claim than the one below.\n \"not run: you were being asked this question and the page was reloaded before \" +\n \"anybody answered. No answer was recorded, nothing in the app changed, and no \" +\n \"verb ran. This is not an error and it is not a yes. Ask again if you still \" +\n \"need to know.\"\n : \"not run: the person was being asked to confirm this and the page was reloaded \" +\n \"before they answered, so the verb did not run and nothing changed. This is not \" +\n \"an error. Ask them again if it is still what they want.\"\n : \"the page was reloaded while this call was in flight, so no answer ever came back. \" +\n \"The outcome is UNKNOWN: it may well have run. DO NOT retry it. Read the screen \" +\n \"first and decide from what you see there, and say plainly that you cannot tell \" +\n \"whether it took effect.\",\n });\n }\n }\n return out;\n}\n\n/**\n * What the panel says, in order, when a conversation comes back.\n *\n * Returned as lines rather than printed, so the words are testable without a\n * DOM and so there is one place they are written. The first line is always\n * about what may have happened to the data, because that is the thing a person\n * has to act on and everything else can wait behind it.\n *\n * The verb is NAMED. \"A call was in flight\" sends somebody to look at the whole\n * app; \"`accept-selected` was in flight\" sends them to one screen.\n */\nexport function restoredLines(record: SavedChat): string[] {\n const lines: string[] = [];\n\n if (record.inFlight?.phase === \"sent\") {\n lines.push(\n `The page reloaded while \\`${record.inFlight.verb}\\` was running. This panel cannot ` +\n `tell whether it took effect — that answer was on the server, and the page waiting ` +\n `for it is gone. Check the app before doing anything else.`,\n );\n } else if (record.inFlight?.phase === \"asked\" && record.inFlight.verb === ASK) {\n // A question, not a confirmation. \"You were being asked to approve `ask`\"\n // is a sentence about something that did not happen, and the person reading\n // it would go looking for the commit it named.\n lines.push(\n \"The page reloaded while the agent was asking you a question. You never answered, so \" +\n \"it was not told anything and nothing in the app changed.\",\n );\n } else if (record.inFlight?.phase === \"asked\") {\n lines.push(\n `The page reloaded while you were being asked to approve \\`${record.inFlight.verb}\\`. ` +\n `You never answered, so it did not run and nothing changed.`,\n );\n }\n\n lines.push(\n \"This conversation is from before the reload. Nothing has been resumed: the run stopped \" +\n \"when the page went away and will not pick itself back up. Ask again to carry on.\",\n );\n\n if (record.trimmed) {\n lines.push(\n `The first ${record.trimmed} message${record.trimmed === 1 ? \"\" : \"s\"} of this ` +\n `conversation were too large to keep and are not shown.`,\n );\n }\n\n return lines;\n}\n\n/**\n * One readable line per stored turn, for redrawing the transcript.\n *\n * Deliberately not a reconstruction of what the panel looked like. A tool turn\n * was a row in the step list with a state marker and a `title`; what comes back\n * is a plain line of text, because the step list is a live thing — it glows, it\n * marks a call as pending, it is about a run that is happening — and redrawing\n * it for a run that ended at a reload would be a panel claiming to be mid-step.\n * A restored transcript should read as a record, which is what it is.\n *\n * The screen blocks are dropped from what is DISPLAYED. They are still in the\n * stored turns, where the model needs the newest one; a wall of table on reload\n * is not what the person wants to see first.\n */\nexport function replayLines(record: SavedChat): Array<{ className: string; text: string }> {\n const out: Array<{ className: string; text: string }> = [];\n for (const turn of record.messages) {\n if (turn.role === \"user\") {\n out.push({ className: \"dk-you\", text: firstPart(turn.text) });\n } else if (turn.role === \"assistant\") {\n if (turn.text) out.push({ className: \"dk-said\", text: turn.text });\n for (const call of turn.calls ?? []) {\n out.push({ className: \"dk-step dk-step-done\", text: call.name });\n }\n }\n // Tool turns are not replayed as lines of their own. Their outcome already\n // reads as the step above it in a live run, and a separate line per result\n // would double the length of a restored transcript with text written for a\n // model rather than for a person.\n }\n return out;\n}\n\n/** Everything a turn's text says before the screen block `loop.ts` appends.\n * The marker is that file's `SCREEN_MARK`, matched on its text rather than\n * imported, because the widget must not start depending on the loop's seam to\n * render a line. */\nfunction firstPart(text: string): string {\n const at = text.indexOf(\"\\n\\nOn screen now:\\n\");\n return at === -1 ? text : text.slice(0, at);\n}\n\n/**\n * Read a stored conversation back, or null for every way that can fail.\n *\n * Validated field by field, and a failure is a `null` rather than a repair.\n * `settings.ts` folds a partial record over the defaults because a missing pace\n * is a readable record with a gap in it; a `Turn[]` with a gap in it is a\n * provider error on the person's next message. The two kinds of persisted state\n * want opposite treatment and this is the strict one.\n *\n * Every read is inside one try, like `loadJson`: a private window and blocked\n * site data throw on the way IN, before any value has been looked at.\n */\nexport function loadChat(\n session: StorageLike | undefined,\n app: string,\n): SavedChat | null {\n try {\n const raw = session?.getItem(chatKey(app));\n if (!raw) return null;\n const value = JSON.parse(raw) as Partial<SavedChat> | null;\n if (!value || typeof value !== \"object\") return null;\n if (value.v !== CHAT_VERSION) return null;\n // The app is checked because one origin can serve two driverkit apps, and\n // a conversation about somebody's contacts does not belong in the admin\n // panel's transcript.\n if (value.app !== app) return null;\n if (!Array.isArray(value.messages) || !value.messages.every(isTurn)) return null;\n const inFlight = value.inFlight;\n return {\n v: CHAT_VERSION,\n app,\n at: typeof value.at === \"number\" ? value.at : 0,\n messages: value.messages,\n conversed: value.conversed === true,\n ...(inFlight &&\n typeof inFlight.verb === \"string\" &&\n (inFlight.phase === \"asked\" || inFlight.phase === \"sent\")\n ? { inFlight: { verb: inFlight.verb, phase: inFlight.phase } }\n : {}),\n ...(typeof value.trimmed === \"number\" && value.trimmed > 0\n ? { trimmed: value.trimmed }\n : {}),\n };\n } catch {\n return null;\n }\n}\n\n/** Whether one stored value is a `Turn`. Shape only: it is about to be handed\n * to a provider, and a turn with a missing `callId` is a 400 rather than a\n * cosmetic gap. */\nfunction isTurn(value: unknown): value is Turn {\n const turn = value as Partial<Turn> & { role?: unknown } | null;\n if (!turn || typeof turn !== \"object\") return false;\n if (turn.role === \"user\") return typeof (turn as { text?: unknown }).text === \"string\";\n if (turn.role === \"assistant\") {\n const t = turn as { text?: unknown; calls?: unknown };\n if (t.text !== undefined && typeof t.text !== \"string\") return false;\n if (t.calls === undefined) return true;\n return Array.isArray(t.calls) && t.calls.every(isCall);\n }\n if (turn.role === \"tool\") {\n const t = turn as { callId?: unknown; name?: unknown; text?: unknown };\n return typeof t.callId === \"string\" && typeof t.name === \"string\" && typeof t.text === \"string\";\n }\n return false;\n}\n\nfunction isCall(value: unknown): value is ToolCall {\n const call = value as { id?: unknown; name?: unknown; args?: unknown } | null;\n return (\n !!call &&\n typeof call === \"object\" &&\n typeof call.id === \"string\" &&\n typeof call.name === \"string\" &&\n !!call.args &&\n typeof call.args === \"object\"\n );\n}\n\n/**\n * Write a conversation, and swallow every reason it can fail.\n *\n * Swallowed, unlike `budget.ts`, and the asymmetry is the point. A budget that\n * cannot be written is an uncapped agent, so that one fails closed and stops\n * the agent. A transcript that cannot be written is a conversation somebody\n * will have to retype, which is not worth a thrown error — and a throw here\n * would be thrown INSIDE a drive run, out of an `onResult` handler, where it\n * would take down the run that is moving the person's screen. A storage write\n * must never break a drive run. See `saveJson`, which makes the same promise\n * for the panel's position and for the same reason.\n *\n * `trimmed: 0` is not written, so an ordinary record carries no field for it\n * and `loadChat` reading its absence as \"nothing was dropped\" is the same\n * sentence either way.\n */\nexport function saveChat(\n session: StorageLike | undefined,\n app: string,\n record: Omit<SavedChat, \"v\" | \"app\">,\n): void {\n try {\n session?.setItem(\n chatKey(app),\n JSON.stringify({\n v: CHAT_VERSION,\n app,\n at: record.at,\n messages: record.messages,\n conversed: record.conversed,\n ...(record.inFlight === undefined ? {} : { inFlight: record.inFlight }),\n ...(record.trimmed ? { trimmed: record.trimmed } : {}),\n } satisfies SavedChat),\n );\n } catch {\n // A full quota, a private window, a viewer who blocked site data. The\n // conversation is still correct for this sitting; it just will not come\n // back after a reload, and that is not worth an exception thrown through a\n // run that is driving somebody's screen.\n }\n}\n\n/**\n * Forget the stored conversation.\n *\n * Written empty rather than removed, because `StorageLike` is two methods and\n * `removeItem` is not one of them — and `loadChat` reads an empty string as an\n * empty slot, which is what a removal would leave anyway.\n *\n * Called by \"Clear conversation\", and that call is load-bearing rather than\n * tidy. `era` in `widget.ts` exists so a dying run's writes cannot land in a\n * fresh transcript after a clear; a stored record is the same hazard with a\n * longer fuse — clear the panel, reload, and a cleared conversation comes back\n * from disk. The destructive option has to be destructive all the way down.\n */\nexport function forgetChat(session: StorageLike | undefined, app: string): void {\n try {\n session?.setItem(chatKey(app), \"\");\n } catch {\n // Nothing was stored, so nothing needs forgetting.\n }\n}\n"]}
|