@agentshouse/kit 0.2.1-ce47f621f90e1 → 0.2.1-ce9401bb7d372

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.
@@ -4,14 +4,16 @@ import { mkdir } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { unlessAborted } from './abort.js';
6
6
  import { signedOut, startAdapter } from './acp.js';
7
+ import { formAnswered, grokQuestionAnswered, permissionAllowed, PLAN_APPROVED } from './afk.js';
7
8
  import { finalRefusal, HouseRefusal } from './api.js';
8
9
  import { openBridge } from './bridge.js';
9
10
  import { CLIS } from './clis.js';
11
+ import { Content } from './content.js';
10
12
  import { answeredFailure, readerFor } from './events.js';
11
13
  import { inspectedFile, linkedPaths, storeRefusal, uploaded } from './files.js';
14
+ import { grokPlanAnswer, grokPlanForm, grokQuestionAnswer, grokQuestionForm } from './grok.js';
12
15
  import { agentBase } from './home.js';
13
16
  import { instructions } from './instructions.js';
14
- import { Parts } from './parts.js';
15
17
  import { refusalOf } from './refusals.js';
16
18
  import { relayed } from './relay.js';
17
19
  import { killMarked, Scope } from './scope.js';
@@ -34,6 +36,26 @@ const NO_RESUME = "the Agent's CLI could not resume this conversation";
34
36
  const NOT_SIGNED_IN = "the Agent's CLI is not signed in; sign it in on the Agent's machine";
35
37
  const NO_SETTINGS = "the Agent's CLI refused the Agent's model, mode or effort";
36
38
  const UNSTEERED = "the Agent's CLI did not take the message into its running turn";
39
+ const TAKEN_OUT = 'the message was taken out before it started';
40
+ const QUIET = {
41
+ title: null,
42
+ context: null,
43
+ limits: [],
44
+ cost: null,
45
+ tokens: null,
46
+ duration: null,
47
+ files: [],
48
+ branch: null,
49
+ worktree: null,
50
+ pull: null,
51
+ model: null,
52
+ effort: null,
53
+ mode: null,
54
+ suggestion: null,
55
+ running: [],
56
+ };
57
+ // A reader tells a working run from a stopped one by the minute, and House keeps no finer figure, so a run reports no oftener.
58
+ const ACTIVITY_REPORT_MS = 60_000;
37
59
  class NotStarted extends Error {
38
60
  }
39
61
  class ResumeRefused extends NotStarted {
@@ -51,18 +73,39 @@ function unopened(reason) {
51
73
  }
52
74
  // A start-up step is shown only once it has lasted a second, so a quick start shows none of them.
53
75
  const STARTING_SHOWN_AFTER_MS = 1_000;
76
+ function turnOf(conversation, turn) {
77
+ return { conversation: conversation.id, turn: turn.id };
78
+ }
54
79
  function unbridged(error) {
55
80
  return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
56
81
  }
57
- const EXIT_PLAN_MODE = {
82
+ const GROK_PLAN = {
83
+ parse(value) {
84
+ return value;
85
+ },
86
+ };
87
+ const GROK_QUESTION = {
58
88
  parse(value) {
59
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
60
- throw new Error('_x.ai/exit_plan_mode needs an object');
61
- }
62
89
  return value;
63
90
  },
64
91
  };
65
- export const CONVERSATION_METHODS = new Set(['open', 'message', 'interrupt', 'kill', 'done', 'option', 'answer']);
92
+ function addedTokens(sum, tokens) {
93
+ if (sum === null)
94
+ return tokens;
95
+ return {
96
+ input: sum.input + tokens.input,
97
+ output: sum.output + tokens.output,
98
+ cache_read: sum.cache_read + tokens.cache_read,
99
+ cache_write: sum.cache_write + tokens.cache_write,
100
+ };
101
+ }
102
+ function workRuns(part) {
103
+ return part.type === 'subagent' || part.type === 'background' ? part.status === 'running' : null;
104
+ }
105
+ function cliSaid(error) {
106
+ const details = error?.data?.details;
107
+ return typeof details === 'string' && details !== '' ? `${causeOf(error)}: ${details}` : causeOf(error);
108
+ }
66
109
  function causeOf(error) {
67
110
  return error instanceof Error ? error.message : String(error);
68
111
  }
@@ -107,17 +150,18 @@ function steers(adapter) {
107
150
  }
108
151
  class Turn {
109
152
  id = randomUUID();
110
- parts;
153
+ content;
111
154
  questions = 0;
112
155
  secrets = 0;
113
156
  prompted = false;
114
157
  steered = false;
115
158
  taken = null;
116
159
  ended = false;
160
+ quietUntil = Infinity;
117
161
  images = 0;
118
162
  uploads = [];
119
163
  constructor(emit) {
120
- this.parts = new Parts(emit);
164
+ this.content = new Content(emit);
121
165
  }
122
166
  }
123
167
  class Conversation {
@@ -128,12 +172,16 @@ class Conversation {
128
172
  commands = null;
129
173
  options = null;
130
174
  exitUntold = false;
131
- context = null;
175
+ afk = false;
176
+ reader = null;
177
+ state = QUIET;
178
+ sentState = null;
179
+ tokens = null;
132
180
  leftovers = new Set();
133
181
  waiting = [];
134
182
  done = false;
135
183
  sending = null;
136
- subagents = new Map();
184
+ work = new Map();
137
185
  held = [];
138
186
  opening = null;
139
187
  bridge = null;
@@ -169,6 +217,7 @@ export class Conversations {
169
217
  questions = new Map();
170
218
  reporting = 0;
171
219
  watched = false;
220
+ stopping = false;
172
221
  constructor(kit) {
173
222
  this.kit = kit;
174
223
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
@@ -177,6 +226,8 @@ export class Conversations {
177
226
  call(call) {
178
227
  void this.kit.calls.carry(call.input_id, () => {
179
228
  const conversation = this.conversation(call.conversation_id);
229
+ if (call.kind === 'open' || call.kind === 'message')
230
+ conversation.afk = call.afk === true;
180
231
  if (call.kind === 'kill') {
181
232
  conversation.kills++;
182
233
  conversation.killed.abort(new Error(KILLED));
@@ -221,12 +272,19 @@ export class Conversations {
221
272
  }
222
273
  this.kit.changed();
223
274
  }
275
+ stopped() {
276
+ this.stopping = true;
277
+ for (const conversation of this.conversations.values()) {
278
+ if (conversation.running !== null)
279
+ this.process(conversation, false);
280
+ }
281
+ }
224
282
  opened() {
225
283
  this.watched = false;
226
284
  for (const conversation of this.conversations.values()) {
227
285
  if (conversation.running !== null) {
228
286
  this.facts(conversation);
229
- this.subagentsChanged(conversation);
287
+ this.stateChanged(conversation, true);
230
288
  }
231
289
  else if (conversation.exitUntold)
232
290
  this.process(conversation, false);
@@ -262,11 +320,13 @@ export class Conversations {
262
320
  this.next(conversation);
263
321
  return { result: Promise.resolve({}) };
264
322
  }
323
+ if (call.kind === 'take_out')
324
+ return { result: Promise.resolve(this.takeOut(conversation, call.message_id)) };
265
325
  await this.launched(conversation);
266
326
  if (call.kind === 'interrupt') {
267
327
  if (--conversation.interrupts === 0)
268
328
  conversation.interrupted = new AbortController();
269
- await this.interrupt(conversation, String(call.turn_id));
329
+ await this.interrupt(conversation, call.turn_id);
270
330
  }
271
331
  if (call.kind === 'kill') {
272
332
  await this.kill(conversation);
@@ -275,9 +335,9 @@ export class Conversations {
275
335
  conversation.killed = new AbortController();
276
336
  }
277
337
  if (call.kind === 'option')
278
- await this.option(conversation, String(call.option), call.value);
338
+ await this.option(conversation, call.option, call.value);
279
339
  if (call.kind === 'answer') {
280
- const question = this.questions.get(String(call.interaction_id));
340
+ const question = this.questions.get(call.interaction_id);
281
341
  if (question === undefined) {
282
342
  const text = answerMessage(call.request, call.response);
283
343
  return this.message(conversation, { ...call, text, first: false, message_id: null });
@@ -286,6 +346,14 @@ export class Conversations {
286
346
  }
287
347
  return { result: Promise.resolve({}) };
288
348
  }
349
+ takeOut(conversation, messageId) {
350
+ const index = conversation.waiting.findIndex((waiting) => waiting.call.message_id === messageId);
351
+ if (index === -1)
352
+ return { started: true };
353
+ const [waiting] = conversation.waiting.splice(index, 1);
354
+ waiting.settle({ refused: TAKEN_OUT });
355
+ return {};
356
+ }
289
357
  async open(conversation, call) {
290
358
  await this.stop(conversation);
291
359
  const launch = conversation.launch ?? this.launch(conversation, this.route(conversation, call.agent_id), null, true);
@@ -330,14 +398,14 @@ export class Conversations {
330
398
  const bridge = conversation.running === null ? conversation.launch?.bridge : Promise.resolve(conversation.running.bridge);
331
399
  if (bridge === undefined)
332
400
  return null;
333
- const read = Promise.all([bridge, this.kit.copies.mapping()]).then(([opened, copies]) => instructions(opened, route.base_instructions, copies));
401
+ const read = bridge.then((opened) => instructions(opened, route.base_instructions));
334
402
  read.catch(() => undefined);
335
403
  return read;
336
404
  }
337
405
  async message(conversation, call) {
338
406
  const content = [
339
- ...(typeof call.recent === 'string' ? [{ type: 'text', text: call.recent }] : []),
340
- { type: 'text', text: String(call.text) },
407
+ ...(call.recent === undefined ? [] : [{ type: 'text', text: call.recent }]),
408
+ { type: 'text', text: call.text },
341
409
  ];
342
410
  let route;
343
411
  let instructing = null;
@@ -346,7 +414,7 @@ export class Conversations {
346
414
  if (call.first === true)
347
415
  instructing = this.instructed(conversation, route);
348
416
  if (call.message_id !== null)
349
- content.push(...(await this.transcribed(conversation, String(call.message_id), String(call.text))));
417
+ content.push(...(await this.transcribed(conversation, call.message_id, call.text)));
350
418
  if (conversation.kills > 0)
351
419
  throw new Error(KILLED);
352
420
  }
@@ -403,7 +471,7 @@ export class Conversations {
403
471
  for (const turn of conversation.turns)
404
472
  turn.steered ||= turn.prompted;
405
473
  }
406
- this.kit.calls.keepResult(String(waiting.call.input_id), {});
474
+ this.kit.calls.keepResult(waiting.call.input_id, {});
407
475
  waiting.settle({});
408
476
  }
409
477
  else {
@@ -412,7 +480,7 @@ export class Conversations {
412
480
  }
413
481
  }
414
482
  next(conversation) {
415
- if (conversation.sending !== null || conversation.turns.size > 0)
483
+ if (this.stopping || conversation.sending !== null || conversation.turns.size > 0)
416
484
  return;
417
485
  const waiting = conversation.waiting.shift();
418
486
  if (waiting === undefined) {
@@ -469,7 +537,7 @@ export class Conversations {
469
537
  return;
470
538
  }
471
539
  this.starts(conversation, null);
472
- this.prompt(conversation, [...prompt, ...waiting.content], () => this.kit.calls.keepResult(String(call.input_id), result));
540
+ this.prompt(conversation, [...prompt, ...waiting.content], () => this.kit.calls.keepResult(call.input_id, result));
473
541
  waiting.settle(result);
474
542
  }
475
543
  starts(conversation, step) {
@@ -525,8 +593,7 @@ export class Conversations {
525
593
  throw new Error(`${path} is no longer an audio file`);
526
594
  return address;
527
595
  }, signal);
528
- const transcript = `/kit/conversations/${conversation.id}/messages/${messageId}/transcripts`;
529
- await step(unbridged, unlessAborted(this.kit.house.deliver(transcript, { path, text: said }, () => !signal.aborted), signal));
596
+ await step(unbridged, unlessAborted(this.kit.house.deliver('transcripts/keep', { conversation: conversation.id, message: messageId, path, text: said }, () => !signal.aborted), signal));
530
597
  blocks.push({ type: 'text', text: `${path}\nTranscript: ${said}` });
531
598
  }
532
599
  }
@@ -591,6 +658,9 @@ export class Conversations {
591
658
  if (running === null)
592
659
  return;
593
660
  try {
661
+ if (conversation.options?.find(({ id }) => id === option)?.category === 'mode') {
662
+ throw new Error(`conversation ${conversation.id} keeps the mode its Agent's launch settings name`);
663
+ }
594
664
  running.reader.requested(option, value);
595
665
  const answered = await running.adapter.connection.agent.request('session/set_config_option', {
596
666
  sessionId: running.sessionId,
@@ -621,10 +691,12 @@ export class Conversations {
621
691
  const route = await routed;
622
692
  const reader = readerFor(route.kind);
623
693
  reader.session = sessionId;
694
+ conversation.reader = reader;
624
695
  const app = client({ name: '@agentshouse/kit' })
625
- .onRequest('session/request_permission', ({ params, signal }) => this.ask(conversation, 'session/request_permission', params, false, signal))
626
- .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
627
- .onRequest('_x.ai/exit_plan_mode', EXIT_PLAN_MODE, ({ params, signal }) => this.ask(conversation, '_x.ai/exit_plan_mode', params, false, signal));
696
+ .onRequest('session/request_permission', ({ params, signal }) => conversation.afk ? permissionAllowed(params) : this.ask(conversation, 'session/request_permission', params, false, signal))
697
+ .onRequest('elicitation/create', ({ params, signal }) => conversation.afk ? formAnswered(route.kind, params) : this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
698
+ .onRequest('_x.ai/exit_plan_mode', GROK_PLAN, async ({ params, signal }) => conversation.afk ? PLAN_APPROVED : grokPlanAnswer(await this.askForm(conversation, grokPlanForm(params), signal)))
699
+ .onRequest('_x.ai/ask_user_question', GROK_QUESTION, async ({ params, signal }) => conversation.afk ? grokQuestionAnswered(params) : grokQuestionAnswer(await this.askForm(conversation, grokQuestionForm(params), signal)));
628
700
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
629
701
  const bridging = this.bridged(conversation);
630
702
  const bridge = await step(unbridged, bridging);
@@ -633,13 +705,15 @@ export class Conversations {
633
705
  throw new Error(KILLED);
634
706
  }
635
707
  conversation.opening = bridge;
636
- const work = workFor(route.kind, route.working_directory, () => this.kit.changed());
708
+ const work = workFor(route.kind, route.working_directory, () => this.kit.changed(), (message) => this.tapped(conversation, reader, message));
637
709
  const scope = new Scope(marker(bridge), randomUUID(), cli);
638
710
  let adapter = null;
639
711
  try {
640
712
  bridged(bridge);
641
713
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
642
714
  const streamed = await step(NO_CONNECTION, work.open(cli));
715
+ if (this.stopping)
716
+ throw new Error(KILLED);
643
717
  adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
644
718
  work.read(message);
645
719
  this.read(conversation, reader, message);
@@ -647,14 +721,12 @@ export class Conversations {
647
721
  void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
648
722
  const agent = adapter.connection.agent;
649
723
  const cwd = route.working_directory;
650
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
724
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
651
725
  const resumed = sessionId === null ? null : await this.resume(conversation, route.kind, adapter, { sessionId, cwd, mcpServers: [], _meta }, empty);
652
726
  const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
653
727
  reader.session = opened.sessionId;
654
- if (opened.sessionId !== sessionId && CLIS[route.kind].renames) {
655
- const prompt = [{ type: 'text', text: `/rename ${conversation.id}` }];
656
- await step(unopened(NO_SESSION), agent.request('session/prompt', { sessionId: opened.sessionId, prompt }));
657
- }
728
+ if (opened.sessionId !== conversation.session)
729
+ conversation.state = QUIET;
658
730
  const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
659
731
  const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
660
732
  void work.settled().then(() => scope.record());
@@ -726,10 +798,8 @@ export class Conversations {
726
798
  conversation.running = null;
727
799
  conversation.commands = null;
728
800
  conversation.options = null;
729
- if (conversation.subagents.size > 0) {
730
- conversation.subagents.clear();
731
- this.subagentsChanged(conversation);
732
- }
801
+ conversation.work.clear();
802
+ this.stated(conversation, { running: [] });
733
803
  for (const [id, question] of this.questions) {
734
804
  if (question.conversation === conversation)
735
805
  this.questions.delete(id);
@@ -746,9 +816,15 @@ export class Conversations {
746
816
  if (conversation.options !== null)
747
817
  this.options(conversation, conversation.options);
748
818
  }
749
- subagentsChanged(conversation) {
750
- const subagents = [...conversation.subagents.values()].map(({ description, activity }) => ({ description, activity }));
751
- this.kit.send({ type: 'subagents', conversation_id: conversation.id, subagents });
819
+ stated(conversation, change) {
820
+ conversation.state = { ...conversation.state, ...change };
821
+ this.stateChanged(conversation, false);
822
+ }
823
+ stateChanged(conversation, again) {
824
+ const state = JSON.stringify(conversation.state);
825
+ if (!again && state === conversation.sentState)
826
+ return;
827
+ conversation.sentState = this.kit.send({ type: 'state', conversation_id: conversation.id, state: conversation.state }) ? state : null;
752
828
  }
753
829
  commands(conversation, commands) {
754
830
  conversation.commands = commands;
@@ -760,11 +836,16 @@ export class Conversations {
760
836
  if (conversation.running === null)
761
837
  return;
762
838
  conversation.options = options;
763
- this.kit.send({ type: 'options', conversation_id: conversation.id, options });
839
+ this.kit.send({ type: 'options', conversation_id: conversation.id, options: options.filter((option) => option.category !== 'mode') });
840
+ const chosen = (category) => {
841
+ const value = options.find((option) => option.category === category)?.currentValue;
842
+ return value === undefined ? null : String(value);
843
+ };
844
+ this.stated(conversation, { model: chosen('model'), effort: chosen('thought_level'), mode: chosen('mode') });
764
845
  }
765
- deliver(conversation, turn, event, body) {
846
+ deliver(conversation, act, request, current) {
766
847
  this.reporting++;
767
- const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/conversations/${conversation.id}/turns/${turn.id}/${event}`, await body));
848
+ const delivered = conversation.reports.then(async () => this.kit.house.deliver(act, await request, current));
768
849
  conversation.reports = delivered
769
850
  .catch(() => undefined)
770
851
  .finally(() => {
@@ -776,22 +857,28 @@ export class Conversations {
776
857
  write(conversation, turn, operation) {
777
858
  if (turn.ended || !this.watched)
778
859
  return;
779
- this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, ...operation });
860
+ this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, operation });
780
861
  }
781
862
  replay(conversation, turn) {
782
- for (const operation of turn.parts.operations())
863
+ for (const operation of turn.content.operations())
783
864
  this.write(conversation, turn, operation);
784
865
  }
785
866
  begin(conversation) {
786
867
  const turn = new Turn((operation) => this.write(conversation, turn, operation));
787
868
  conversation.turns.add(turn);
788
869
  conversation.running?.adapter.turn(true);
789
- void this.deliver(conversation, turn, 'started', {}).catch(logged);
870
+ void this.deliver(conversation, 'turns/start', turnOf(conversation, turn))
871
+ .then((answer) => {
872
+ if (answer.run === true)
873
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
874
+ })
875
+ .catch(logged);
790
876
  conversation.turn = turn;
791
- if (conversation.context !== null)
792
- turn.parts.measure(conversation.context);
793
- for (const part of conversation.held.splice(0))
794
- turn.parts.start(part);
877
+ this.stated(conversation, { suggestion: null });
878
+ for (const event of conversation.reader?.began() ?? [])
879
+ this.event(conversation, event);
880
+ for (const held of conversation.held.splice(0))
881
+ this.place(turn, held);
795
882
  this.kit.changed();
796
883
  return turn;
797
884
  }
@@ -801,22 +888,26 @@ export class Conversations {
801
888
  if (failed !== null)
802
889
  logged(new Error(`conversation ${conversation.id} turn ${turn.id} failed: ${failed.cause}`));
803
890
  if (conversation.turn === turn) {
804
- for (const event of conversation.running?.reader.closeTurn() ?? [])
805
- this.apply(conversation, turn, event);
891
+ for (const event of conversation.reader?.closeTurn() ?? [])
892
+ this.event(conversation, event);
806
893
  }
807
894
  if (notice !== null)
808
- turn.parts.start({ type: 'marker', marker: 'retry', text: notice });
895
+ turn.content.add(null, { type: 'notice', kind: 'error', text: notice });
809
896
  turn.ended = true;
810
897
  conversation.turns.delete(turn);
811
898
  conversation.running?.adapter.turn(conversation.turns.size > 0);
812
899
  if (conversation.turn === turn)
813
900
  conversation.turn = null;
901
+ const tokens = conversation.tokens;
902
+ conversation.tokens = null;
903
+ if (tokens !== null)
904
+ this.stated(conversation, { tokens: addedTokens(conversation.state.tokens, tokens) });
814
905
  const body = Promise.allSettled(turn.uploads).then(() => ({
815
- parts: turn.parts.saved(),
816
- context: turn.parts.context,
906
+ ...turnOf(conversation, turn),
907
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
817
908
  ...(failed === null ? {} : { failed: failed.failure }),
818
909
  }));
819
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
910
+ void this.deliver(conversation, 'turns/end', body).catch(logged);
820
911
  this.next(conversation);
821
912
  this.kit.changed();
822
913
  }
@@ -845,7 +936,7 @@ export class Conversations {
845
936
  running.adapter.retire();
846
937
  this.detach(conversation, running);
847
938
  }
848
- this.end(conversation, turn, answeredWith(error));
939
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
849
940
  }
850
941
  });
851
942
  }
@@ -858,7 +949,9 @@ export class Conversations {
858
949
  const turn = conversation.turn;
859
950
  if (turn === null)
860
951
  return;
861
- const held = stop !== null && !turn.steered && [...conversation.subagents.values()].some((subagent) => subagent.turn === turn);
952
+ const held = stop !== null &&
953
+ !turn.steered &&
954
+ [...conversation.work.values()].some((work) => work.part.type === 'subagent' && turn.content.index(work.key) !== undefined);
862
955
  if (!turn.prompted || held) {
863
956
  this.took(turn);
864
957
  this.end(conversation, turn, stop === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
@@ -866,18 +959,22 @@ export class Conversations {
866
959
  }
867
960
  if (stop !== null)
868
961
  return;
869
- for (const event of conversation.running?.reader.closeTurn() ?? [])
870
- this.apply(conversation, turn, event);
962
+ for (const event of conversation.reader?.closeTurn() ?? [])
963
+ this.event(conversation, event);
871
964
  conversation.turn = null;
872
965
  this.kit.changed();
873
966
  }
967
+ askForm(conversation, form, signal) {
968
+ return this.ask(conversation, 'elicitation/create', form, false, signal);
969
+ }
874
970
  async ask(conversation, method, params, secret, signal) {
875
971
  const turn = this.started(conversation);
876
972
  const interactionId = randomUUID();
877
973
  const answered = new Promise((answer, fail) => {
878
974
  this.questions.set(interactionId, { conversation, answer: (response) => answer(response) });
879
975
  signal.addEventListener('abort', () => answer(null), { once: true });
880
- this.deliver(conversation, turn, 'interactions', {
976
+ this.deliver(conversation, 'conversations/interaction/ask', {
977
+ ...turnOf(conversation, turn),
881
978
  interaction_id: interactionId,
882
979
  request: { method, params },
883
980
  secret,
@@ -918,6 +1015,22 @@ export class Conversations {
918
1015
  read(conversation, reader, message) {
919
1016
  for (const event of reader.read(message))
920
1017
  this.event(conversation, event);
1018
+ this.reportActivity(conversation);
1019
+ }
1020
+ tapped(conversation, reader, message) {
1021
+ for (const event of reader.tap(message))
1022
+ this.event(conversation, event);
1023
+ }
1024
+ reportActivity(conversation) {
1025
+ const turn = conversation.turn;
1026
+ if (turn === null || Date.now() < turn.quietUntil)
1027
+ return;
1028
+ turn.quietUntil = Infinity;
1029
+ void this.deliver(conversation, 'turns/activity/report', turnOf(conversation, turn), () => false)
1030
+ .catch(logged)
1031
+ .finally(() => {
1032
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
1033
+ });
921
1034
  }
922
1035
  event(conversation, event) {
923
1036
  switch (event.kind) {
@@ -933,23 +1046,25 @@ export class Conversations {
933
1046
  case 'options':
934
1047
  this.options(conversation, event.options);
935
1048
  return;
936
- case 'context':
937
- conversation.context = { used: event.used, window: event.window };
938
- conversation.turn?.parts.measure(conversation.context);
1049
+ case 'state':
1050
+ this.stated(conversation, event.state);
939
1051
  return;
940
- case 'subagent-done':
941
- this.subagentDone(conversation, event.id, event.result);
1052
+ case 'tokens':
1053
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
942
1054
  return;
943
- case 'subagent-activity':
944
- this.subagentActivity(conversation, event.id, event.activity);
1055
+ case 'part':
1056
+ this.keyed(conversation, event);
945
1057
  return;
946
- case 'marker':
1058
+ case 'notice':
947
1059
  case 'image':
948
- if (conversation.turn !== null)
949
- break;
950
- if (event.kind === 'marker' && event.marker === 'job')
951
- conversation.held.push({ type: 'marker', marker: 'job', text: event.text });
952
- return;
1060
+ if (conversation.turn === null)
1061
+ return;
1062
+ break;
1063
+ case 'text':
1064
+ case 'reasoning':
1065
+ if (event.parent !== null && conversation.turn === null)
1066
+ return;
1067
+ break;
953
1068
  }
954
1069
  this.apply(conversation, this.started(conversation), event);
955
1070
  }
@@ -961,62 +1076,68 @@ export class Conversations {
961
1076
  apply(conversation, turn, event) {
962
1077
  switch (event.kind) {
963
1078
  case 'text':
964
- case 'reasoning':
965
- turn.parts.write(event.kind, event.id, event.text);
966
- return;
967
- case 'command':
968
- turn.parts.command();
969
- return;
970
- case 'subagent': {
971
- const index = turn.parts.start({ type: 'subagent', description: event.description, status: 'running', result: null });
972
- conversation.subagents.set(event.id, { description: event.description, turn, index, activity: null });
973
- this.subagentsChanged(conversation);
1079
+ case 'reasoning': {
1080
+ const parent = this.parentIn(turn, event.parent);
1081
+ if (parent !== undefined)
1082
+ turn.content.write(event.kind, event.id, parent, event.text);
974
1083
  return;
975
1084
  }
976
- case 'message':
977
- turn.parts.start({ type: 'message', command: event.command, target: event.target });
978
- return;
979
- case 'marker':
980
- turn.parts.start({ type: 'marker', marker: event.marker, text: event.text });
1085
+ case 'notice':
1086
+ turn.content.add(null, { type: 'notice', kind: event.notice, text: event.text });
981
1087
  return;
982
1088
  case 'plan':
983
- turn.parts.plan(event.entries);
1089
+ turn.content.plan(event.entries);
984
1090
  return;
985
- case 'image':
986
- turn.uploads.push(this.image(conversation, turn, turn.parts.reserve(), event.data, event.mediaType));
1091
+ case 'image': {
1092
+ const parent = this.parentIn(turn, event.parent);
1093
+ if (parent === undefined)
1094
+ return;
1095
+ turn.uploads.push(this.image(conversation, turn, parent, event.data, event.mediaType));
987
1096
  this.kit.changed();
988
1097
  return;
1098
+ }
989
1099
  }
990
1100
  }
991
- subagentDone(conversation, id, result) {
992
- const subagent = conversation.subagents.get(id);
993
- if (subagent === undefined)
994
- return;
995
- conversation.subagents.delete(id);
996
- this.subagentsChanged(conversation);
997
- if (subagent.turn === conversation.turn) {
998
- subagent.turn.parts.done(subagent.index, result);
1101
+ keyed(conversation, keyed) {
1102
+ const running = workRuns(keyed.part);
1103
+ const earlier = running !== null && conversation.work.has(keyed.key) && conversation.turn?.content.index(keyed.key) === undefined;
1104
+ if (running === true)
1105
+ conversation.work.set(keyed.key, keyed);
1106
+ if (running === false)
1107
+ conversation.work.delete(keyed.key);
1108
+ const turn = conversation.turn;
1109
+ if (earlier) {
1110
+ if (running)
1111
+ return;
1112
+ if (turn === null)
1113
+ conversation.held.push(keyed);
1114
+ else
1115
+ this.place(turn, keyed);
999
1116
  return;
1000
1117
  }
1001
- const part = { type: 'subagent', description: subagent.description, status: 'done', result };
1002
- if (conversation.turn === null)
1003
- conversation.held.push(part);
1004
- else
1005
- conversation.turn.parts.start(part);
1006
- }
1007
- subagentActivity(conversation, id, activity) {
1008
- const subagent = conversation.subagents.get(id);
1009
- if (subagent === undefined || subagent.activity === activity)
1118
+ if (keyed.parent !== null && turn === null)
1010
1119
  return;
1011
- subagent.activity = activity;
1012
- this.subagentsChanged(conversation);
1120
+ this.place(this.started(conversation), keyed);
1121
+ }
1122
+ place(turn, keyed) {
1123
+ const parent = this.parentIn(turn, keyed.parent);
1124
+ if (parent !== undefined)
1125
+ turn.content.put(keyed.key, parent, keyed.part);
1126
+ }
1127
+ // A sub-agent's card lives only in the turn keyed() placed it in, so its steps, text, images and sub-agents join a turn only under a card that turn holds.
1128
+ parentIn(turn, key) {
1129
+ if (key === null)
1130
+ return null;
1131
+ const index = turn.content.index(key);
1132
+ return index !== undefined && turn.content.parts[index].type === 'subagent' ? index : undefined;
1013
1133
  }
1014
- async image(conversation, turn, reserved, data, mediaType) {
1134
+ async image(conversation, turn, parent, data, mediaType) {
1015
1135
  const bytes = Buffer.from(data, 'base64');
1016
1136
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
1017
1137
  const sha256 = createHash('sha256').update(bytes).digest('hex');
1018
1138
  try {
1019
- const declared = (await this.deliver(conversation, turn, 'images', {
1139
+ const declared = (await this.deliver(conversation, 'turns/images/declare', {
1140
+ ...turnOf(conversation, turn),
1020
1141
  name,
1021
1142
  media_type: mediaType,
1022
1143
  bytes: bytes.length,
@@ -1028,13 +1149,13 @@ export class Conversations {
1028
1149
  sha256,
1029
1150
  read: (start, end) => [bytes.subarray(start, end)],
1030
1151
  send: (url, start, end, headers) => sentPart(url, bytes.subarray(start, end), headers),
1031
- finish: (upload, partSha256) => this.kit.house.deliver('/kit/uploads/finish', { upload, part_sha256: partSha256 }),
1152
+ finish: (upload, partSha256) => this.kit.house.deliver('uploads/finish', { upload, part_sha256: partSha256 }),
1032
1153
  });
1033
- turn.parts.arrive({ type: 'image', file: saved.path, name, media_type: mediaType }, reserved);
1154
+ turn.content.arrived(parent, { type: 'image', file: saved.path, name, media_type: mediaType });
1034
1155
  }
1035
1156
  catch (error) {
1036
1157
  const cause = error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error);
1037
- turn.parts.arrive({ type: 'marker', marker: 'retry', text: `${name} was not saved: ${cause}` }, reserved);
1158
+ turn.content.arrived(null, { type: 'notice', kind: 'error', text: `${name} was not saved: ${cause}` });
1038
1159
  }
1039
1160
  }
1040
1161
  }