@adroit-app/chat-core 0.0.0 → 0.1.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/reduce.js ADDED
@@ -0,0 +1,559 @@
1
+ import { AUTH_REQUIRED, } from "./state.js";
2
+ /**
3
+ * The Chat's state after `event`. A pure fold: the state holds nothing the
4
+ * agent did not report, so replaying a session rebuilds it.
5
+ */
6
+ export function reduce(state, event) {
7
+ switch (event.type) {
8
+ case "update":
9
+ return applyNotification(state, event.notification, event.at);
10
+ case "prompt-sent": {
11
+ const ahead = state.pending.some((p) => p.id !== event.id && p.error === null);
12
+ const submission = {
13
+ id: event.id,
14
+ prompt: event.prompt,
15
+ idempotencyKey: event.idempotencyKey,
16
+ error: null,
17
+ sending: !isWorking(state) && !ahead,
18
+ };
19
+ const known = state.pending.some((p) => p.id === event.id);
20
+ return {
21
+ ...state,
22
+ pending: known
23
+ ? state.pending.map((p) => (p.id === event.id ? submission : p))
24
+ : [...state.pending, submission],
25
+ };
26
+ }
27
+ case "prompt-inserted": {
28
+ const sent = state.pending.find((p) => p.id === event.id);
29
+ const pending = state.pending.filter((p) => p.id !== event.id);
30
+ const lastSubmission = sent
31
+ ? { prompt: sent.prompt, idempotencyKey: sent.idempotencyKey }
32
+ : state.lastSubmission;
33
+ state = { ...state, lastSubmission };
34
+ const reported = state.entries.some((e) => e.kind === "user" && e.id === event.messageId);
35
+ if (reported || !sent)
36
+ return { ...state, pending };
37
+ // The agent reports the message too; until it does, it reads as sent.
38
+ const user = { kind: "user", id: event.messageId, content: sent.prompt };
39
+ return { ...state, pending, entries: [...state.entries, user] };
40
+ }
41
+ case "prompt-failed": {
42
+ const failed = state.pending.find((p) => p.id === event.id);
43
+ if (event.code === AUTH_REQUIRED && failed) {
44
+ // Sent again from the sign-in, not from the list of prompts not taken in.
45
+ return {
46
+ ...state,
47
+ pending: state.pending.filter((p) => p !== failed),
48
+ signIn: {
49
+ reason: state.signIn?.reason ?? "signed_out",
50
+ retry: { prompt: failed.prompt, idempotencyKey: failed.idempotencyKey },
51
+ error: null,
52
+ },
53
+ };
54
+ }
55
+ return {
56
+ ...state,
57
+ pending: state.pending.map((p) => p.id === event.id ? { ...p, error: event.error, sending: false } : p),
58
+ };
59
+ }
60
+ case "sign-in-required":
61
+ return { ...state, signIn: { reason: event.reason, retry: null, error: null } };
62
+ case "sign-in-failed":
63
+ return state.signIn ? { ...state, signIn: { ...state.signIn, error: event.error } } : state;
64
+ case "signed-in":
65
+ return {
66
+ ...state,
67
+ signIn: null,
68
+ retry: state.signIn?.retry ?? null,
69
+ account: state.account ? { ...state.account, signedIn: true } : null,
70
+ };
71
+ case "retry-done":
72
+ return { ...state, retry: null };
73
+ case "auth-status": {
74
+ const accounts = event.accounts ?? [];
75
+ const active = accounts.find((a) => a.active) ?? accounts[0];
76
+ const signedIn = event.state === "authenticated" || event.state === "not_required";
77
+ return { ...state, account: { signedIn, label: signedIn ? (active?.label ?? null) : null } };
78
+ }
79
+ case "prompt-dismissed":
80
+ return { ...state, pending: state.pending.filter((p) => p.id !== event.id) };
81
+ case "cancel-requested":
82
+ return isWorking(state) ? { ...state, cancelling: true } : state;
83
+ case "permission-asked": {
84
+ const subject = event.request.subject;
85
+ const withSubject = subject?.type === "tool_call" && "toolCall" in subject
86
+ ? withToolPatched(state, event.request.sessionId, subject.toolCall)
87
+ : state;
88
+ return appendAsk(withSubject, {
89
+ kind: "ask",
90
+ id: event.id,
91
+ ask: { type: "permission", request: event.request },
92
+ answer: null,
93
+ });
94
+ }
95
+ case "elicitation-asked":
96
+ return appendAsk(state, {
97
+ kind: "ask",
98
+ id: event.id,
99
+ ask: { type: "elicitation", request: event.request },
100
+ answer: null,
101
+ });
102
+ case "permission-answered":
103
+ return answer(state, event.id, { type: "permission", outcome: event.outcome });
104
+ case "elicitation-answered":
105
+ return answer(state, event.id, { type: "elicitation", response: event.response });
106
+ }
107
+ }
108
+ /** Whether the agent reports foreground work, running or waiting on the user. */
109
+ export function isWorking(transcript) {
110
+ return transcript.activity === "running" || transcript.activity === "requires_action";
111
+ }
112
+ /** The latest stretch of foreground work, running or not. */
113
+ export function lastTurn(transcript) {
114
+ for (let i = transcript.entries.length - 1; i >= 0; i--) {
115
+ const entry = transcript.entries[i];
116
+ if (entry?.kind === "turn")
117
+ return entry;
118
+ }
119
+ return undefined;
120
+ }
121
+ function appendAsk(state, ask) {
122
+ return { ...state, entries: [...state.entries, ask] };
123
+ }
124
+ function answer(state, id, answer) {
125
+ return {
126
+ ...state,
127
+ entries: state.entries.map((e) => (e.kind === "ask" && e.id === id ? { ...e, answer } : e)),
128
+ };
129
+ }
130
+ function applyNotification(state, notification, at) {
131
+ const next = applyUpdate(state, notification, at);
132
+ if (notification.sessionId !== state.sessionId || !authRequired(notification.update))
133
+ return next;
134
+ return { ...next, signIn: { reason: "signed_out", retry: state.lastSubmission, error: null } };
135
+ }
136
+ /** A turn that ended because the agent needs the user to sign in. */
137
+ function authRequired(update) {
138
+ const u = update;
139
+ return (u.sessionUpdate === "state_update" &&
140
+ u.state === "idle" &&
141
+ u.stopReason === "error" &&
142
+ u.error?.code === AUTH_REQUIRED);
143
+ }
144
+ function applyUpdate(state, notification, at) {
145
+ const { sessionId, update } = notification;
146
+ const serial = state.serial + 1;
147
+ if (sessionId !== state.sessionId) {
148
+ const known = state.subagents[sessionId];
149
+ const subagent = known ?? newSubagent(sessionId);
150
+ const next = {
151
+ ...subagent,
152
+ ...applyToTranscript(subagent, update, `e${state.serial}`, at),
153
+ };
154
+ return withSubagent(known ? state : announce(state, sessionId), next, serial);
155
+ }
156
+ switch (update.sessionUpdate) {
157
+ case "plan_update": {
158
+ const { plan } = update;
159
+ return { ...state, plans: { ...state.plans, [plan.planId]: plan } };
160
+ }
161
+ case "plan_removed": {
162
+ const { planId } = update;
163
+ if (!(planId in state.plans))
164
+ return state;
165
+ const { [planId]: _, ...plans } = state.plans;
166
+ return { ...state, plans };
167
+ }
168
+ case "available_commands_update":
169
+ return {
170
+ ...state,
171
+ commands: update.availableCommands,
172
+ commandsReported: true,
173
+ };
174
+ case "config_option_update":
175
+ return {
176
+ ...state,
177
+ configOptions: update.configOptions,
178
+ };
179
+ case "session_info_update": {
180
+ const { title } = update;
181
+ return title === undefined ? state : { ...state, title };
182
+ }
183
+ case "usage_update": {
184
+ const u = update;
185
+ const cost = u.cost === undefined ? (state.context?.cost ?? null) : u.cost;
186
+ const context = { used: u.used, size: u.size, cost };
187
+ // acp-adapter counts the turn's thinking with its usage; the count is the turn's.
188
+ const thought = thinkingTokens(u._meta);
189
+ const turn = lastTurn(state);
190
+ if (thought === null || !turn)
191
+ return { ...state, context };
192
+ return {
193
+ ...state,
194
+ context,
195
+ entries: state.entries.map((e) => (e === turn ? { ...turn, thinkingTokens: thought } : e)),
196
+ };
197
+ }
198
+ case "subagent_update": {
199
+ const u = update;
200
+ const known = state.subagents[u.sessionId];
201
+ const subagent = {
202
+ ...(known ?? newSubagent(u.sessionId)),
203
+ ...(u.title !== undefined ? { title: u.title } : {}),
204
+ ...(u.description !== undefined ? { description: u.description } : {}),
205
+ ...(u.state ? { activity: u.state.state } : {}),
206
+ };
207
+ return withSubagent(known ? state : announce(state, u.sessionId), subagent, serial);
208
+ }
209
+ default: {
210
+ const transcript = applyToTranscript(state, update, `e${state.serial}`, at);
211
+ const settled = transcript.activity === "idle" && state.activity !== "idle";
212
+ const background = update.sessionUpdate === "state_update"
213
+ ? (update.background ?? null)
214
+ : state.background;
215
+ return {
216
+ ...state,
217
+ ...transcript,
218
+ background,
219
+ cancelling: settled ? false : state.cancelling,
220
+ serial,
221
+ };
222
+ }
223
+ }
224
+ }
225
+ /**
226
+ * `state` with the tool call `update` is about patched in the transcript of
227
+ * `sessionId`: the parent's, or a subagent's. Tool call ids are the session's
228
+ * own, so a subagent's call may share an id with one of the parent's.
229
+ */
230
+ function withToolPatched(state, sessionId, update) {
231
+ const patch = (entries) => upsertTool(entries, update.toolCallId, (known) => patchTool(known, update));
232
+ if (sessionId === state.sessionId)
233
+ return { ...state, entries: patch(state.entries) };
234
+ const known = state.subagents[sessionId];
235
+ const subagent = known ?? newSubagent(sessionId);
236
+ return withSubagent(known ? state : announce(state, sessionId), { ...subagent, entries: patch(subagent.entries) }, state.serial);
237
+ }
238
+ function newSubagent(sessionId) {
239
+ return {
240
+ sessionId,
241
+ title: null,
242
+ description: null,
243
+ activity: "idle",
244
+ entries: [],
245
+ terminals: {},
246
+ };
247
+ }
248
+ function announce(state, sessionId) {
249
+ return { ...state, entries: [...state.entries, { kind: "subagent", id: sessionId }] };
250
+ }
251
+ function withSubagent(state, subagent, serial) {
252
+ return { ...state, serial, subagents: { ...state.subagents, [subagent.sessionId]: subagent } };
253
+ }
254
+ /** What `update` changes of a transcript; `id` names an entry that has no id of its own. */
255
+ function applyToTranscript(transcript, update, id, at) {
256
+ const { entries, terminals } = transcript;
257
+ switch (update.sessionUpdate) {
258
+ case "state_update": {
259
+ const u = update;
260
+ return { ...transcript, activity: u.state, entries: applyState(transcript, u, id) };
261
+ }
262
+ case "user_message_chunk":
263
+ case "agent_message_chunk":
264
+ case "agent_thought_chunk": {
265
+ const u = update;
266
+ const kind = messageKind(update.sessionUpdate);
267
+ return {
268
+ ...transcript,
269
+ entries: withTokens(upsertMessage(entries, kind, u.messageId, (c) => [...c, u.content]), u.messageId, thinkingTokens(u._meta), entries),
270
+ };
271
+ }
272
+ case "user_message":
273
+ case "agent_message":
274
+ case "agent_thought": {
275
+ const u = update;
276
+ const kind = messageKind(update.sessionUpdate);
277
+ return {
278
+ ...transcript,
279
+ entries: upsertMessage(entries, kind, u.messageId, (c) => u.content === undefined ? c : (u.content ?? [])),
280
+ };
281
+ }
282
+ case "session_message": {
283
+ const u = update;
284
+ return {
285
+ ...transcript,
286
+ entries: upsertSessionMessage(entries, u.messageId, (m) => ({
287
+ ...m,
288
+ ...(u.senderSessionId !== undefined ? { senderSessionId: u.senderSessionId } : {}),
289
+ ...(u.recipientSessionId !== undefined
290
+ ? { recipientSessionId: u.recipientSessionId }
291
+ : {}),
292
+ ...(u.content !== undefined ? { content: u.content ?? [] } : {}),
293
+ })),
294
+ };
295
+ }
296
+ case "session_message_chunk": {
297
+ const u = update;
298
+ return {
299
+ ...transcript,
300
+ entries: upsertSessionMessage(entries, u.messageId, (m) => ({
301
+ ...m,
302
+ content: [...m.content, u.content],
303
+ })),
304
+ };
305
+ }
306
+ case "tool_call_update": {
307
+ const u = update;
308
+ return {
309
+ ...transcript,
310
+ entries: upsertTool(entries, u.toolCallId, (t, fresh) => timed(patchTool(t, u), t, fresh, u, at)),
311
+ };
312
+ }
313
+ case "tool_call_content_chunk": {
314
+ const u = update;
315
+ return {
316
+ ...transcript,
317
+ entries: upsertTool(entries, u.toolCallId, (t) => ({
318
+ ...t,
319
+ content: [...t.content, u.content],
320
+ })),
321
+ };
322
+ }
323
+ case "terminal_update": {
324
+ const u = update;
325
+ const known = terminals[u.terminalId] ?? {
326
+ id: u.terminalId,
327
+ command: null,
328
+ output: "",
329
+ exitStatus: null,
330
+ };
331
+ return {
332
+ ...transcript,
333
+ terminals: {
334
+ ...terminals,
335
+ [u.terminalId]: {
336
+ ...known,
337
+ ...(u.command !== undefined ? { command: u.command } : {}),
338
+ ...(u.output != null ? { output: u.output.data } : {}),
339
+ ...(u.exitStatus !== undefined ? { exitStatus: u.exitStatus } : {}),
340
+ },
341
+ },
342
+ };
343
+ }
344
+ case "terminal_output_chunk": {
345
+ const u = update;
346
+ const known = terminals[u.terminalId] ?? {
347
+ id: u.terminalId,
348
+ command: null,
349
+ output: "",
350
+ exitStatus: null,
351
+ };
352
+ return {
353
+ ...transcript,
354
+ terminals: { ...terminals, [u.terminalId]: { ...known, output: known.output + u.data } },
355
+ };
356
+ }
357
+ case "notice": {
358
+ const u = update;
359
+ return {
360
+ ...transcript,
361
+ entries: [
362
+ ...entries,
363
+ {
364
+ kind: "notice",
365
+ id,
366
+ severity: u.severity,
367
+ title: u.title,
368
+ description: u.description ?? null,
369
+ },
370
+ ],
371
+ };
372
+ }
373
+ case "compaction_update": {
374
+ const u = update;
375
+ return {
376
+ ...transcript,
377
+ entries: upsertCompaction(entries, u.compactionId, (c) => ({
378
+ ...c,
379
+ ...(u.status !== undefined ? { status: u.status } : {}),
380
+ ...(u.summary !== undefined ? { summary: u.summary ?? [] } : {}),
381
+ ...(u.error !== undefined ? { error: u.error } : {}),
382
+ })),
383
+ };
384
+ }
385
+ case "compaction_summary_chunk": {
386
+ const u = update;
387
+ return {
388
+ ...transcript,
389
+ entries: upsertCompaction(entries, u.compactionId, (c) => ({
390
+ ...c,
391
+ summary: [...c.summary, u.content],
392
+ })),
393
+ };
394
+ }
395
+ default:
396
+ return transcript;
397
+ }
398
+ }
399
+ /** The turns after `update`: one opens when work starts, and closes when the agent is idle. */
400
+ function applyState(transcript, update, id) {
401
+ const { entries } = transcript;
402
+ const active = update.state === "running" || update.state === "requires_action";
403
+ if (active) {
404
+ return lastTurn(transcript)?.outcome === "running"
405
+ ? entries
406
+ : [
407
+ ...entries,
408
+ {
409
+ kind: "turn",
410
+ id,
411
+ outcome: "running",
412
+ stopReason: null,
413
+ usage: null,
414
+ error: null,
415
+ thinkingTokens: null,
416
+ },
417
+ ];
418
+ }
419
+ if (update.state !== "idle")
420
+ return entries;
421
+ const open = lastTurn(transcript);
422
+ if (open?.outcome !== "running")
423
+ return entries;
424
+ const idle = update;
425
+ const stopReason = idle.stopReason ?? null;
426
+ const error = stopReason === "error"
427
+ ? idle.error?.code === AUTH_REQUIRED
428
+ ? "Sign-in required"
429
+ : (idle.error?.message ?? "error")
430
+ : null;
431
+ const closed = {
432
+ ...open,
433
+ outcome: stopReason === "cancelled" ? "cancelled" : stopReason === "error" ? "failed" : "ended",
434
+ stopReason,
435
+ usage: idle.usage ?? null,
436
+ error,
437
+ thinkingTokens: thinkingTokens(update._meta) ??
438
+ open.thinkingTokens,
439
+ };
440
+ return entries.map((e) => (e === open ? closed : e));
441
+ }
442
+ function messageKind(tag) {
443
+ return tag.startsWith("user") ? "user" : tag.startsWith("agent_thought") ? "thought" : "agent";
444
+ }
445
+ function upsertMessage(entries, kind, id, content) {
446
+ const index = entries.findIndex((e) => e.kind === kind && e.id === id);
447
+ if (index < 0)
448
+ return [...entries, { kind, id, content: content([]) }];
449
+ return entries.map((e, i) => i === index && e.kind === kind ? { ...e, content: content(e.content) } : e);
450
+ }
451
+ function upsertSessionMessage(entries, id, change) {
452
+ const index = entries.findIndex((e) => e.kind === "session-message" && e.id === id);
453
+ if (index < 0) {
454
+ return [
455
+ ...entries,
456
+ change({
457
+ kind: "session-message",
458
+ id,
459
+ senderSessionId: null,
460
+ recipientSessionId: null,
461
+ content: [],
462
+ }),
463
+ ];
464
+ }
465
+ return entries.map((e, i) => (i === index && e.kind === "session-message" ? change(e) : e));
466
+ }
467
+ function upsertCompaction(entries, id, change) {
468
+ const index = entries.findIndex((e) => e.kind === "compaction" && e.id === id);
469
+ if (index < 0) {
470
+ return [...entries, change({ kind: "compaction", id, status: null, summary: [], error: null })];
471
+ }
472
+ return entries.map((e, i) => (i === index && e.kind === "compaction" ? change(e) : e));
473
+ }
474
+ function upsertTool(entries, id, make) {
475
+ const index = entries.findIndex((e) => e.kind === "tool" && e.id === id);
476
+ if (index < 0)
477
+ return [...entries, make(blankTool(id), true)];
478
+ return entries.map((e, i) => (i === index && e.kind === "tool" ? make(e, false) : e));
479
+ }
480
+ const FINISHED = ["completed", "failed", "cancelled"];
481
+ /**
482
+ * `tool` with its times: the agent's `_meta.acpAdapter.startedAt`/`endedAt`
483
+ * when it sends them, otherwise when it came (`at`) first and finished.
484
+ */
485
+ function timed(tool, known, fresh, update, at) {
486
+ const meta = (update._meta?.acpAdapter ?? null);
487
+ if (typeof meta?.startedAt === "number") {
488
+ const endedAt = typeof meta.endedAt === "number" ? meta.endedAt : null;
489
+ return { ...tool, times: { startedAt: meta.startedAt, endedAt, agent: true } };
490
+ }
491
+ if (known.times?.agent || at === undefined)
492
+ return tool;
493
+ const finished = FINISHED.includes(tool.status);
494
+ if (fresh) {
495
+ return finished ? tool : { ...tool, times: { startedAt: at, endedAt: null, agent: false } };
496
+ }
497
+ if (known.times && known.times.endedAt === null && finished) {
498
+ return { ...tool, times: { ...known.times, endedAt: at } };
499
+ }
500
+ return tool;
501
+ }
502
+ function blankTool(id) {
503
+ return {
504
+ kind: "tool",
505
+ id,
506
+ title: "",
507
+ name: null,
508
+ toolKind: "other",
509
+ status: "pending",
510
+ content: [],
511
+ locations: [],
512
+ rawInput: undefined,
513
+ rawOutput: undefined,
514
+ };
515
+ }
516
+ function patchTool(tool, update) {
517
+ return {
518
+ ...tool,
519
+ ...(update.title != null ? { title: update.title } : {}),
520
+ ...(update.name != null ? { name: update.name } : {}),
521
+ ...(update.kind != null ? { toolKind: update.kind } : {}),
522
+ ...(update.status != null ? { status: update.status } : {}),
523
+ ...(update.content !== undefined ? { content: update.content ?? [] } : {}),
524
+ ...(update.locations !== undefined ? { locations: update.locations ?? [] } : {}),
525
+ ...(update.rawInput !== undefined ? { rawInput: update.rawInput } : {}),
526
+ ...(update.rawOutput !== undefined ? { rawOutput: update.rawOutput } : {}),
527
+ };
528
+ }
529
+ /** The thought tally acp-adapter puts in a chunk's `_meta`. */
530
+ function thinkingTokens(meta) {
531
+ const tokens = meta?.acpAdapter?.thinkingTokens;
532
+ return typeof tokens === "number" ? tokens : null;
533
+ }
534
+ /**
535
+ * `entries` with thought `id` a tally of `tokens`, counted on the turn running:
536
+ * a tally that grows replaces what it counted before.
537
+ */
538
+ function withTokens(entries, id, tokens, before) {
539
+ if (tokens === null)
540
+ return entries;
541
+ const known = before.find((e) => e.kind === "thought" && e.id === id);
542
+ const delta = tokens - (known?.thinkingTokens ?? 0);
543
+ let turn;
544
+ for (let i = entries.length - 1; i >= 0; i--) {
545
+ const e = entries[i];
546
+ if (e?.kind === "turn") {
547
+ turn = e;
548
+ break;
549
+ }
550
+ }
551
+ return entries.map((e) => {
552
+ if (e.kind === "thought" && e.id === id)
553
+ return { ...e, thinkingTokens: tokens, tally: true };
554
+ if (e === turn && turn.outcome === "running") {
555
+ return { ...turn, thinkingTokens: (turn.thinkingTokens ?? 0) + delta };
556
+ }
557
+ return e;
558
+ });
559
+ }