@agentshouse/kit 0.2.1-ce47f621f90e1 → 0.2.1-ce8e5419af3f9

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 {
@@ -54,15 +76,34 @@ const STARTING_SHOWN_AFTER_MS = 1_000;
54
76
  function unbridged(error) {
55
77
  return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
56
78
  }
57
- const EXIT_PLAN_MODE = {
79
+ const GROK_PLAN = {
80
+ parse(value) {
81
+ return value;
82
+ },
83
+ };
84
+ const GROK_QUESTION = {
58
85
  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
86
  return value;
63
87
  },
64
88
  };
65
- export const CONVERSATION_METHODS = new Set(['open', 'message', 'interrupt', 'kill', 'done', 'option', 'answer']);
89
+ export const CONVERSATION_METHODS = new Set(['open', 'message', 'take_out', 'interrupt', 'kill', 'done', 'option', 'answer']);
90
+ function addedTokens(sum, tokens) {
91
+ if (sum === null)
92
+ return tokens;
93
+ return {
94
+ input: sum.input + tokens.input,
95
+ output: sum.output + tokens.output,
96
+ cache_read: sum.cache_read + tokens.cache_read,
97
+ cache_write: sum.cache_write + tokens.cache_write,
98
+ };
99
+ }
100
+ function workRuns(part) {
101
+ return part.type === 'subagent' || part.type === 'background' ? part.status === 'running' : null;
102
+ }
103
+ function cliSaid(error) {
104
+ const details = error?.data?.details;
105
+ return typeof details === 'string' && details !== '' ? `${causeOf(error)}: ${details}` : causeOf(error);
106
+ }
66
107
  function causeOf(error) {
67
108
  return error instanceof Error ? error.message : String(error);
68
109
  }
@@ -107,17 +148,18 @@ function steers(adapter) {
107
148
  }
108
149
  class Turn {
109
150
  id = randomUUID();
110
- parts;
151
+ content;
111
152
  questions = 0;
112
153
  secrets = 0;
113
154
  prompted = false;
114
155
  steered = false;
115
156
  taken = null;
116
157
  ended = false;
158
+ quietUntil = Infinity;
117
159
  images = 0;
118
160
  uploads = [];
119
161
  constructor(emit) {
120
- this.parts = new Parts(emit);
162
+ this.content = new Content(emit);
121
163
  }
122
164
  }
123
165
  class Conversation {
@@ -128,12 +170,16 @@ class Conversation {
128
170
  commands = null;
129
171
  options = null;
130
172
  exitUntold = false;
131
- context = null;
173
+ afk = false;
174
+ reader = null;
175
+ state = QUIET;
176
+ sentState = null;
177
+ tokens = null;
132
178
  leftovers = new Set();
133
179
  waiting = [];
134
180
  done = false;
135
181
  sending = null;
136
- subagents = new Map();
182
+ work = new Map();
137
183
  held = [];
138
184
  opening = null;
139
185
  bridge = null;
@@ -169,6 +215,7 @@ export class Conversations {
169
215
  questions = new Map();
170
216
  reporting = 0;
171
217
  watched = false;
218
+ stopping = false;
172
219
  constructor(kit) {
173
220
  this.kit = kit;
174
221
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
@@ -177,6 +224,8 @@ export class Conversations {
177
224
  call(call) {
178
225
  void this.kit.calls.carry(call.input_id, () => {
179
226
  const conversation = this.conversation(call.conversation_id);
227
+ if (call.kind === 'open' || call.kind === 'message')
228
+ conversation.afk = call.afk === true;
180
229
  if (call.kind === 'kill') {
181
230
  conversation.kills++;
182
231
  conversation.killed.abort(new Error(KILLED));
@@ -221,12 +270,19 @@ export class Conversations {
221
270
  }
222
271
  this.kit.changed();
223
272
  }
273
+ stopped() {
274
+ this.stopping = true;
275
+ for (const conversation of this.conversations.values()) {
276
+ if (conversation.running !== null)
277
+ this.process(conversation, false);
278
+ }
279
+ }
224
280
  opened() {
225
281
  this.watched = false;
226
282
  for (const conversation of this.conversations.values()) {
227
283
  if (conversation.running !== null) {
228
284
  this.facts(conversation);
229
- this.subagentsChanged(conversation);
285
+ this.stateChanged(conversation, true);
230
286
  }
231
287
  else if (conversation.exitUntold)
232
288
  this.process(conversation, false);
@@ -262,6 +318,8 @@ export class Conversations {
262
318
  this.next(conversation);
263
319
  return { result: Promise.resolve({}) };
264
320
  }
321
+ if (call.kind === 'take_out')
322
+ return { result: Promise.resolve(this.takeOut(conversation, String(call.message_id))) };
265
323
  await this.launched(conversation);
266
324
  if (call.kind === 'interrupt') {
267
325
  if (--conversation.interrupts === 0)
@@ -286,6 +344,14 @@ export class Conversations {
286
344
  }
287
345
  return { result: Promise.resolve({}) };
288
346
  }
347
+ takeOut(conversation, messageId) {
348
+ const index = conversation.waiting.findIndex((waiting) => waiting.call.message_id === messageId);
349
+ if (index === -1)
350
+ return { started: true };
351
+ const [waiting] = conversation.waiting.splice(index, 1);
352
+ waiting.settle({ refused: TAKEN_OUT });
353
+ return {};
354
+ }
289
355
  async open(conversation, call) {
290
356
  await this.stop(conversation);
291
357
  const launch = conversation.launch ?? this.launch(conversation, this.route(conversation, call.agent_id), null, true);
@@ -330,7 +396,7 @@ export class Conversations {
330
396
  const bridge = conversation.running === null ? conversation.launch?.bridge : Promise.resolve(conversation.running.bridge);
331
397
  if (bridge === undefined)
332
398
  return null;
333
- const read = Promise.all([bridge, this.kit.copies.mapping()]).then(([opened, copies]) => instructions(opened, route.base_instructions, copies));
399
+ const read = bridge.then((opened) => instructions(opened, route.base_instructions));
334
400
  read.catch(() => undefined);
335
401
  return read;
336
402
  }
@@ -412,7 +478,7 @@ export class Conversations {
412
478
  }
413
479
  }
414
480
  next(conversation) {
415
- if (conversation.sending !== null || conversation.turns.size > 0)
481
+ if (this.stopping || conversation.sending !== null || conversation.turns.size > 0)
416
482
  return;
417
483
  const waiting = conversation.waiting.shift();
418
484
  if (waiting === undefined) {
@@ -525,8 +591,7 @@ export class Conversations {
525
591
  throw new Error(`${path} is no longer an audio file`);
526
592
  return address;
527
593
  }, 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));
594
+ await step(unbridged, unlessAborted(this.kit.house.deliver('/kit/transcripts/keep', { conversation: conversation.id, message: messageId, path, text: said }, () => !signal.aborted), signal));
530
595
  blocks.push({ type: 'text', text: `${path}\nTranscript: ${said}` });
531
596
  }
532
597
  }
@@ -621,10 +686,12 @@ export class Conversations {
621
686
  const route = await routed;
622
687
  const reader = readerFor(route.kind);
623
688
  reader.session = sessionId;
689
+ conversation.reader = reader;
624
690
  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));
691
+ .onRequest('session/request_permission', ({ params, signal }) => conversation.afk ? permissionAllowed(params) : this.ask(conversation, 'session/request_permission', params, false, signal))
692
+ .onRequest('elicitation/create', ({ params, signal }) => conversation.afk ? formAnswered(route.kind, params) : this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
693
+ .onRequest('_x.ai/exit_plan_mode', GROK_PLAN, async ({ params, signal }) => conversation.afk ? PLAN_APPROVED : grokPlanAnswer(await this.askForm(conversation, grokPlanForm(params), signal)))
694
+ .onRequest('_x.ai/ask_user_question', GROK_QUESTION, async ({ params, signal }) => conversation.afk ? grokQuestionAnswered(params) : grokQuestionAnswer(await this.askForm(conversation, grokQuestionForm(params), signal)));
628
695
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
629
696
  const bridging = this.bridged(conversation);
630
697
  const bridge = await step(unbridged, bridging);
@@ -633,13 +700,15 @@ export class Conversations {
633
700
  throw new Error(KILLED);
634
701
  }
635
702
  conversation.opening = bridge;
636
- const work = workFor(route.kind, route.working_directory, () => this.kit.changed());
703
+ const work = workFor(route.kind, route.working_directory, () => this.kit.changed(), (message) => this.tapped(conversation, reader, message));
637
704
  const scope = new Scope(marker(bridge), randomUUID(), cli);
638
705
  let adapter = null;
639
706
  try {
640
707
  bridged(bridge);
641
708
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
642
709
  const streamed = await step(NO_CONNECTION, work.open(cli));
710
+ if (this.stopping)
711
+ throw new Error(KILLED);
643
712
  adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
644
713
  work.read(message);
645
714
  this.read(conversation, reader, message);
@@ -647,14 +716,12 @@ export class Conversations {
647
716
  void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
648
717
  const agent = adapter.connection.agent;
649
718
  const cwd = route.working_directory;
650
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
719
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
651
720
  const resumed = sessionId === null ? null : await this.resume(conversation, route.kind, adapter, { sessionId, cwd, mcpServers: [], _meta }, empty);
652
721
  const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
653
722
  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
- }
723
+ if (opened.sessionId !== conversation.session)
724
+ conversation.state = QUIET;
658
725
  const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
659
726
  const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
660
727
  void work.settled().then(() => scope.record());
@@ -726,10 +793,8 @@ export class Conversations {
726
793
  conversation.running = null;
727
794
  conversation.commands = null;
728
795
  conversation.options = null;
729
- if (conversation.subagents.size > 0) {
730
- conversation.subagents.clear();
731
- this.subagentsChanged(conversation);
732
- }
796
+ conversation.work.clear();
797
+ this.stated(conversation, { running: [] });
733
798
  for (const [id, question] of this.questions) {
734
799
  if (question.conversation === conversation)
735
800
  this.questions.delete(id);
@@ -746,9 +811,15 @@ export class Conversations {
746
811
  if (conversation.options !== null)
747
812
  this.options(conversation, conversation.options);
748
813
  }
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 });
814
+ stated(conversation, change) {
815
+ conversation.state = { ...conversation.state, ...change };
816
+ this.stateChanged(conversation, false);
817
+ }
818
+ stateChanged(conversation, again) {
819
+ const state = JSON.stringify(conversation.state);
820
+ if (!again && state === conversation.sentState)
821
+ return;
822
+ conversation.sentState = this.kit.send({ type: 'state', conversation_id: conversation.id, state: conversation.state }) ? state : null;
752
823
  }
753
824
  commands(conversation, commands) {
754
825
  conversation.commands = commands;
@@ -761,10 +832,15 @@ export class Conversations {
761
832
  return;
762
833
  conversation.options = options;
763
834
  this.kit.send({ type: 'options', conversation_id: conversation.id, options });
835
+ const chosen = (category) => {
836
+ const value = options.find((option) => option.category === category)?.currentValue;
837
+ return value === undefined ? null : String(value);
838
+ };
839
+ this.stated(conversation, { model: chosen('model'), effort: chosen('thought_level'), mode: chosen('mode') });
764
840
  }
765
- deliver(conversation, turn, event, body) {
841
+ deliver(conversation, turn, act, body, current) {
766
842
  this.reporting++;
767
- const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/conversations/${conversation.id}/turns/${turn.id}/${event}`, await body));
843
+ const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/${act}`, { conversation: conversation.id, turn: turn.id, ...(await body) }, current));
768
844
  conversation.reports = delivered
769
845
  .catch(() => undefined)
770
846
  .finally(() => {
@@ -776,22 +852,28 @@ export class Conversations {
776
852
  write(conversation, turn, operation) {
777
853
  if (turn.ended || !this.watched)
778
854
  return;
779
- this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, ...operation });
855
+ this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, operation });
780
856
  }
781
857
  replay(conversation, turn) {
782
- for (const operation of turn.parts.operations())
858
+ for (const operation of turn.content.operations())
783
859
  this.write(conversation, turn, operation);
784
860
  }
785
861
  begin(conversation) {
786
862
  const turn = new Turn((operation) => this.write(conversation, turn, operation));
787
863
  conversation.turns.add(turn);
788
864
  conversation.running?.adapter.turn(true);
789
- void this.deliver(conversation, turn, 'started', {}).catch(logged);
865
+ void this.deliver(conversation, turn, 'turns/start', {})
866
+ .then((answer) => {
867
+ if (answer.run === true)
868
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
869
+ })
870
+ .catch(logged);
790
871
  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);
872
+ this.stated(conversation, { suggestion: null });
873
+ for (const event of conversation.reader?.began() ?? [])
874
+ this.event(conversation, event);
875
+ for (const held of conversation.held.splice(0))
876
+ this.place(conversation, turn, held);
795
877
  this.kit.changed();
796
878
  return turn;
797
879
  }
@@ -801,22 +883,25 @@ export class Conversations {
801
883
  if (failed !== null)
802
884
  logged(new Error(`conversation ${conversation.id} turn ${turn.id} failed: ${failed.cause}`));
803
885
  if (conversation.turn === turn) {
804
- for (const event of conversation.running?.reader.closeTurn() ?? [])
805
- this.apply(conversation, turn, event);
886
+ for (const event of conversation.reader?.closeTurn() ?? [])
887
+ this.event(conversation, event);
806
888
  }
807
889
  if (notice !== null)
808
- turn.parts.start({ type: 'marker', marker: 'retry', text: notice });
890
+ turn.content.add(null, { type: 'notice', kind: 'error', text: notice });
809
891
  turn.ended = true;
810
892
  conversation.turns.delete(turn);
811
893
  conversation.running?.adapter.turn(conversation.turns.size > 0);
812
894
  if (conversation.turn === turn)
813
895
  conversation.turn = null;
896
+ const tokens = conversation.tokens;
897
+ conversation.tokens = null;
898
+ if (tokens !== null)
899
+ this.stated(conversation, { tokens: addedTokens(conversation.state.tokens, tokens) });
814
900
  const body = Promise.allSettled(turn.uploads).then(() => ({
815
- parts: turn.parts.saved(),
816
- context: turn.parts.context,
901
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
817
902
  ...(failed === null ? {} : { failed: failed.failure }),
818
903
  }));
819
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
904
+ void this.deliver(conversation, turn, 'turns/end', body).catch(logged);
820
905
  this.next(conversation);
821
906
  this.kit.changed();
822
907
  }
@@ -845,7 +930,7 @@ export class Conversations {
845
930
  running.adapter.retire();
846
931
  this.detach(conversation, running);
847
932
  }
848
- this.end(conversation, turn, answeredWith(error));
933
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
849
934
  }
850
935
  });
851
936
  }
@@ -858,7 +943,9 @@ export class Conversations {
858
943
  const turn = conversation.turn;
859
944
  if (turn === null)
860
945
  return;
861
- const held = stop !== null && !turn.steered && [...conversation.subagents.values()].some((subagent) => subagent.turn === turn);
946
+ const held = stop !== null &&
947
+ !turn.steered &&
948
+ [...conversation.work.values()].some((work) => work.part.type === 'subagent' && turn.content.index(work.key) !== undefined);
862
949
  if (!turn.prompted || held) {
863
950
  this.took(turn);
864
951
  this.end(conversation, turn, stop === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
@@ -866,18 +953,21 @@ export class Conversations {
866
953
  }
867
954
  if (stop !== null)
868
955
  return;
869
- for (const event of conversation.running?.reader.closeTurn() ?? [])
870
- this.apply(conversation, turn, event);
956
+ for (const event of conversation.reader?.closeTurn() ?? [])
957
+ this.event(conversation, event);
871
958
  conversation.turn = null;
872
959
  this.kit.changed();
873
960
  }
961
+ askForm(conversation, form, signal) {
962
+ return this.ask(conversation, 'elicitation/create', form, false, signal);
963
+ }
874
964
  async ask(conversation, method, params, secret, signal) {
875
965
  const turn = this.started(conversation);
876
966
  const interactionId = randomUUID();
877
967
  const answered = new Promise((answer, fail) => {
878
968
  this.questions.set(interactionId, { conversation, answer: (response) => answer(response) });
879
969
  signal.addEventListener('abort', () => answer(null), { once: true });
880
- this.deliver(conversation, turn, 'interactions', {
970
+ this.deliver(conversation, turn, 'conversations/interaction/ask', {
881
971
  interaction_id: interactionId,
882
972
  request: { method, params },
883
973
  secret,
@@ -918,6 +1008,22 @@ export class Conversations {
918
1008
  read(conversation, reader, message) {
919
1009
  for (const event of reader.read(message))
920
1010
  this.event(conversation, event);
1011
+ this.reportActivity(conversation);
1012
+ }
1013
+ tapped(conversation, reader, message) {
1014
+ for (const event of reader.tap(message))
1015
+ this.event(conversation, event);
1016
+ }
1017
+ reportActivity(conversation) {
1018
+ const turn = conversation.turn;
1019
+ if (turn === null || Date.now() < turn.quietUntil)
1020
+ return;
1021
+ turn.quietUntil = Infinity;
1022
+ void this.deliver(conversation, turn, 'turns/activity/report', {}, () => false)
1023
+ .catch(logged)
1024
+ .finally(() => {
1025
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
1026
+ });
921
1027
  }
922
1028
  event(conversation, event) {
923
1029
  switch (event.kind) {
@@ -933,23 +1039,25 @@ export class Conversations {
933
1039
  case 'options':
934
1040
  this.options(conversation, event.options);
935
1041
  return;
936
- case 'context':
937
- conversation.context = { used: event.used, window: event.window };
938
- conversation.turn?.parts.measure(conversation.context);
1042
+ case 'state':
1043
+ this.stated(conversation, event.state);
939
1044
  return;
940
- case 'subagent-done':
941
- this.subagentDone(conversation, event.id, event.result);
1045
+ case 'tokens':
1046
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
942
1047
  return;
943
- case 'subagent-activity':
944
- this.subagentActivity(conversation, event.id, event.activity);
1048
+ case 'part':
1049
+ this.keyed(conversation, event);
945
1050
  return;
946
- case 'marker':
1051
+ case 'notice':
947
1052
  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;
1053
+ if (conversation.turn === null)
1054
+ return;
1055
+ break;
1056
+ case 'text':
1057
+ case 'reasoning':
1058
+ if (event.parent !== null && conversation.turn === null)
1059
+ return;
1060
+ break;
953
1061
  }
954
1062
  this.apply(conversation, this.started(conversation), event);
955
1063
  }
@@ -961,62 +1069,69 @@ export class Conversations {
961
1069
  apply(conversation, turn, event) {
962
1070
  switch (event.kind) {
963
1071
  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);
1072
+ case 'reasoning': {
1073
+ const parent = this.parentIn(conversation, turn, event.parent);
1074
+ if (parent !== undefined)
1075
+ turn.content.write(event.kind, event.id, parent, event.text);
974
1076
  return;
975
1077
  }
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 });
1078
+ case 'notice':
1079
+ turn.content.add(null, { type: 'notice', kind: event.notice, text: event.text });
981
1080
  return;
982
1081
  case 'plan':
983
- turn.parts.plan(event.entries);
1082
+ turn.content.plan(event.entries);
984
1083
  return;
985
1084
  case 'image':
986
- turn.uploads.push(this.image(conversation, turn, turn.parts.reserve(), event.data, event.mediaType));
1085
+ turn.uploads.push(this.image(conversation, turn, event.parent, event.data, event.mediaType));
987
1086
  this.kit.changed();
988
1087
  return;
989
1088
  }
990
1089
  }
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);
1090
+ keyed(conversation, keyed) {
1091
+ const running = workRuns(keyed.part);
1092
+ const earlier = running !== null && conversation.work.has(keyed.key) && conversation.turn?.content.index(keyed.key) === undefined;
1093
+ if (running === true)
1094
+ conversation.work.set(keyed.key, keyed);
1095
+ if (running === false)
1096
+ conversation.work.delete(keyed.key);
1097
+ const turn = conversation.turn;
1098
+ if (earlier) {
1099
+ if (running)
1100
+ return;
1101
+ if (turn === null)
1102
+ conversation.held.push(keyed);
1103
+ else
1104
+ this.place(conversation, turn, keyed);
999
1105
  return;
1000
1106
  }
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);
1107
+ if (keyed.parent !== null && turn === null)
1108
+ return;
1109
+ this.place(conversation, this.started(conversation), keyed);
1006
1110
  }
1007
- subagentActivity(conversation, id, activity) {
1008
- const subagent = conversation.subagents.get(id);
1009
- if (subagent === undefined || subagent.activity === activity)
1111
+ place(conversation, turn, keyed) {
1112
+ const parent = this.parentIn(conversation, turn, keyed.parent);
1113
+ if (parent === undefined && workRuns(keyed.part) === null)
1010
1114
  return;
1011
- subagent.activity = activity;
1012
- this.subagentsChanged(conversation);
1115
+ turn.content.put(keyed.key, parent ?? null, keyed.part);
1013
1116
  }
1014
- async image(conversation, turn, reserved, data, mediaType) {
1117
+ parentIn(conversation, turn, key) {
1118
+ if (key === null)
1119
+ return null;
1120
+ const index = turn.content.index(key);
1121
+ if (index !== undefined)
1122
+ return turn.content.parts[index].type === 'subagent' ? index : undefined;
1123
+ const running = conversation.work.get(key);
1124
+ if (running?.part.type !== 'subagent')
1125
+ return undefined;
1126
+ const parent = this.parentIn(conversation, turn, running.parent);
1127
+ return parent === undefined ? undefined : turn.content.put(key, parent, running.part);
1128
+ }
1129
+ async image(conversation, turn, parent, data, mediaType) {
1015
1130
  const bytes = Buffer.from(data, 'base64');
1016
1131
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
1017
1132
  const sha256 = createHash('sha256').update(bytes).digest('hex');
1018
1133
  try {
1019
- const declared = (await this.deliver(conversation, turn, 'images', {
1134
+ const declared = (await this.deliver(conversation, turn, 'turns/images/declare', {
1020
1135
  name,
1021
1136
  media_type: mediaType,
1022
1137
  bytes: bytes.length,
@@ -1030,11 +1145,11 @@ export class Conversations {
1030
1145
  send: (url, start, end, headers) => sentPart(url, bytes.subarray(start, end), headers),
1031
1146
  finish: (upload, partSha256) => this.kit.house.deliver('/kit/uploads/finish', { upload, part_sha256: partSha256 }),
1032
1147
  });
1033
- turn.parts.arrive({ type: 'image', file: saved.path, name, media_type: mediaType }, reserved);
1148
+ turn.content.arrived(this.parentIn(conversation, turn, parent) ?? null, { type: 'image', file: saved.path, name, media_type: mediaType });
1034
1149
  }
1035
1150
  catch (error) {
1036
1151
  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);
1152
+ turn.content.arrived(null, { type: 'notice', kind: 'error', text: `${name} was not saved: ${cause}` });
1038
1153
  }
1039
1154
  }
1040
1155
  }