@agentshouse/kit 0.2.1-cf268dff1869b → 0.2.1-cf2c570b41f24

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.
Files changed (54) hide show
  1. package/README.md +18 -25
  2. package/dist/acp.js +12 -9
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +72 -26
  5. package/dist/api.js +18 -4
  6. package/dist/binaries.js +60 -0
  7. package/dist/bridge.js +99 -44
  8. package/dist/calls.js +18 -1
  9. package/dist/chunks.js +54 -0
  10. package/dist/clis.js +33 -15
  11. package/dist/connect.js +121 -0
  12. package/dist/connection.js +25 -10
  13. package/dist/content.js +106 -0
  14. package/dist/conversations.js +251 -158
  15. package/dist/copies.js +1260 -599
  16. package/dist/earlier.js +273 -0
  17. package/dist/end.js +6 -9
  18. package/dist/events.js +544 -297
  19. package/dist/files.js +77 -11
  20. package/dist/git.js +0 -70
  21. package/dist/grok.js +39 -0
  22. package/dist/home.js +86 -22
  23. package/dist/house-cli.js +145 -162
  24. package/dist/instructions.js +2 -4
  25. package/dist/keys.js +238 -0
  26. package/dist/kit-cli.js +14 -4
  27. package/dist/login.js +34 -20
  28. package/dist/logout.js +2 -2
  29. package/dist/manifest.js +75 -0
  30. package/dist/mcp.js +43 -7
  31. package/dist/owner.js +46 -0
  32. package/dist/placement.js +0 -6
  33. package/dist/refusals.js +50 -23
  34. package/dist/resident.js +117 -76
  35. package/dist/scripts.js +79 -15
  36. package/dist/secret-input.js +1 -1
  37. package/dist/settings.js +247 -0
  38. package/dist/sign-in.js +49 -4
  39. package/dist/supervisor.js +163 -0
  40. package/dist/transcription.js +5 -2
  41. package/dist/update.js +31 -22
  42. package/dist/wire.js +2 -10
  43. package/dist/work.js +27 -2
  44. package/dist/workspace.js +113 -0
  45. package/package.json +12 -8
  46. package/dist/authority-main.js +0 -22
  47. package/dist/chatgpt.js +0 -32
  48. package/dist/configure-main.js +0 -6
  49. package/dist/enrol-main.js +0 -10
  50. package/dist/git-main.js +0 -153
  51. package/dist/parts.js +0 -82
  52. package/dist/service-main.js +0 -9
  53. package/dist/service.js +0 -55
  54. package/dist/translate.js +0 -45
@@ -4,20 +4,26 @@ 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
- import { inspectedFile, linkedPaths, storeRefusal, uploaded } from './files.js';
13
+ import { fileInfo, 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';
18
20
  import { holdSecretInput } from './secret-input.js';
19
21
  import { transcribe } from './transcription.js';
20
22
  import { workFor } from './work.js';
23
+ const EFFORT = 'thought_level';
24
+ function conversationRoute(route, chosen) {
25
+ return { ...route, model: chosen.model ?? route.model, effort: chosen.effort ?? route.effort };
26
+ }
21
27
  const KILLED = 'the conversation was killed';
22
28
  const INTERRUPTED = 'the conversation was interrupted';
23
29
  const REFUSED = 'the CLI refused the prompt';
@@ -34,6 +40,26 @@ const NO_RESUME = "the Agent's CLI could not resume this conversation";
34
40
  const NOT_SIGNED_IN = "the Agent's CLI is not signed in; sign it in on the Agent's machine";
35
41
  const NO_SETTINGS = "the Agent's CLI refused the Agent's model, mode or effort";
36
42
  const UNSTEERED = "the Agent's CLI did not take the message into its running turn";
43
+ const TAKEN_OUT = 'the message was taken out before it started';
44
+ const QUIET = {
45
+ title: null,
46
+ context: null,
47
+ limits: [],
48
+ cost: null,
49
+ tokens: null,
50
+ duration: null,
51
+ files: { count: 0, added: 0, removed: 0 },
52
+ branch: null,
53
+ worktree: null,
54
+ pull: null,
55
+ model: null,
56
+ effort: null,
57
+ mode: null,
58
+ suggestion: null,
59
+ running: [],
60
+ };
61
+ // 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.
62
+ const ACTIVITY_REPORT_MS = 60_000;
37
63
  class NotStarted extends Error {
38
64
  }
39
65
  class ResumeRefused extends NotStarted {
@@ -51,18 +77,36 @@ function unopened(reason) {
51
77
  }
52
78
  // A start-up step is shown only once it has lasted a second, so a quick start shows none of them.
53
79
  const STARTING_SHOWN_AFTER_MS = 1_000;
80
+ function turnOf(conversation, turn) {
81
+ return { conversation: conversation.id, turn: turn.id };
82
+ }
54
83
  function unbridged(error) {
55
84
  return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
56
85
  }
57
- const EXIT_PLAN_MODE = {
86
+ const GROK_PLAN = {
87
+ parse(value) {
88
+ return value;
89
+ },
90
+ };
91
+ const GROK_QUESTION = {
58
92
  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
93
  return value;
63
94
  },
64
95
  };
65
- export const CONVERSATION_METHODS = new Set(['open', 'message', 'interrupt', 'kill', 'done', 'option', 'answer']);
96
+ function addedTokens(sum, tokens) {
97
+ if (sum === null)
98
+ return tokens;
99
+ return {
100
+ input: sum.input + tokens.input,
101
+ output: sum.output + tokens.output,
102
+ cache_read: sum.cache_read + tokens.cache_read,
103
+ cache_write: sum.cache_write + tokens.cache_write,
104
+ };
105
+ }
106
+ function cliSaid(error) {
107
+ const details = error?.data?.details;
108
+ return typeof details === 'string' && details !== '' ? `${causeOf(error)}: ${details}` : causeOf(error);
109
+ }
66
110
  function causeOf(error) {
67
111
  return error instanceof Error ? error.message : String(error);
68
112
  }
@@ -96,7 +140,7 @@ function refusal(conversation, error) {
96
140
  function audioOf(result) {
97
141
  if (result.isError === true)
98
142
  return null;
99
- const file = inspectedFile(result.content.map((content) => content.text).join('\n'));
143
+ const file = fileInfo(result.content.map((content) => content.text).join('\n'));
100
144
  return file?.media_type?.startsWith('audio/') === true ? file : null;
101
145
  }
102
146
  function marker(bridge) {
@@ -107,17 +151,18 @@ function steers(adapter) {
107
151
  }
108
152
  class Turn {
109
153
  id = randomUUID();
110
- parts;
154
+ content;
111
155
  questions = 0;
112
156
  secrets = 0;
113
157
  prompted = false;
114
158
  steered = false;
115
159
  taken = null;
116
160
  ended = false;
161
+ quietUntil = Infinity;
117
162
  images = 0;
118
163
  uploads = [];
119
164
  constructor(emit) {
120
- this.parts = new Parts(emit);
165
+ this.content = new Content(emit);
121
166
  }
122
167
  }
123
168
  class Conversation {
@@ -128,13 +173,15 @@ class Conversation {
128
173
  commands = null;
129
174
  options = null;
130
175
  exitUntold = false;
131
- context = null;
176
+ afk = false;
177
+ reader = null;
178
+ state = QUIET;
179
+ sentState = null;
180
+ tokens = null;
132
181
  leftovers = new Set();
133
182
  waiting = [];
134
- done = false;
135
183
  sending = null;
136
- subagents = new Map();
137
- held = [];
184
+ subagents = new Set();
138
185
  opening = null;
139
186
  bridge = null;
140
187
  launch = null;
@@ -169,6 +216,7 @@ export class Conversations {
169
216
  questions = new Map();
170
217
  reporting = 0;
171
218
  watched = false;
219
+ stopping = false;
172
220
  constructor(kit) {
173
221
  this.kit = kit;
174
222
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
@@ -177,6 +225,8 @@ export class Conversations {
177
225
  call(call) {
178
226
  void this.kit.calls.carry(call.input_id, () => {
179
227
  const conversation = this.conversation(call.conversation_id);
228
+ if (call.kind === 'open' || call.kind === 'message')
229
+ conversation.afk = call.afk === true;
180
230
  if (call.kind === 'kill') {
181
231
  conversation.kills++;
182
232
  conversation.killed.abort(new Error(KILLED));
@@ -208,7 +258,10 @@ export class Conversations {
208
258
  return !conversations.some((conversation) => conversation.running?.scope.working() || [...conversation.leftovers].some((scope) => scope.working()));
209
259
  }
210
260
  quiet() {
211
- return this.idle() && [...this.conversations.values()].every((conversation) => conversation.turns.size === 0);
261
+ return this.idle() && !this.turnOpen();
262
+ }
263
+ turnOpen() {
264
+ return [...this.conversations.values()].some((conversation) => conversation.turns.size > 0);
212
265
  }
213
266
  look() {
214
267
  for (const conversation of this.conversations.values()) {
@@ -221,12 +274,19 @@ export class Conversations {
221
274
  }
222
275
  this.kit.changed();
223
276
  }
277
+ stopped() {
278
+ this.stopping = true;
279
+ for (const conversation of this.conversations.values()) {
280
+ if (conversation.running !== null)
281
+ this.process(conversation, false);
282
+ }
283
+ }
224
284
  opened() {
225
285
  this.watched = false;
226
286
  for (const conversation of this.conversations.values()) {
227
287
  if (conversation.running !== null) {
228
288
  this.facts(conversation);
229
- this.subagentsChanged(conversation);
289
+ this.stateChanged(conversation, true);
230
290
  }
231
291
  else if (conversation.exitUntold)
232
292
  this.process(conversation, false);
@@ -257,16 +317,13 @@ export class Conversations {
257
317
  return this.open(conversation, call);
258
318
  if (call.kind === 'message')
259
319
  return this.message(conversation, call);
260
- if (call.kind === 'done') {
261
- conversation.done = true;
262
- this.next(conversation);
263
- return { result: Promise.resolve({}) };
264
- }
320
+ if (call.kind === 'take_out')
321
+ return { result: Promise.resolve(this.takeOut(conversation, call.message_id)) };
265
322
  await this.launched(conversation);
266
323
  if (call.kind === 'interrupt') {
267
324
  if (--conversation.interrupts === 0)
268
325
  conversation.interrupted = new AbortController();
269
- await this.interrupt(conversation, String(call.turn_id));
326
+ await this.interrupt(conversation, call.turn_id);
270
327
  }
271
328
  if (call.kind === 'kill') {
272
329
  await this.kill(conversation);
@@ -275,9 +332,9 @@ export class Conversations {
275
332
  conversation.killed = new AbortController();
276
333
  }
277
334
  if (call.kind === 'option')
278
- await this.option(conversation, String(call.option), call.value);
335
+ await this.option(conversation, call);
279
336
  if (call.kind === 'answer') {
280
- const question = this.questions.get(String(call.interaction_id));
337
+ const question = this.questions.get(call.interaction_id);
281
338
  if (question === undefined) {
282
339
  const text = answerMessage(call.request, call.response);
283
340
  return this.message(conversation, { ...call, text, first: false, message_id: null });
@@ -286,9 +343,18 @@ export class Conversations {
286
343
  }
287
344
  return { result: Promise.resolve({}) };
288
345
  }
346
+ takeOut(conversation, messageId) {
347
+ const index = conversation.waiting.findIndex((waiting) => waiting.call.message_id === messageId);
348
+ if (index === -1)
349
+ return { started: true };
350
+ const [waiting] = conversation.waiting.splice(index, 1);
351
+ waiting.settle({ refused: TAKEN_OUT });
352
+ return {};
353
+ }
289
354
  async open(conversation, call) {
290
355
  await this.stop(conversation);
291
- const launch = conversation.launch ?? this.launch(conversation, this.route(conversation, call.agent_id), null, true);
356
+ const launch = conversation.launch ??
357
+ this.launch(conversation, this.route(conversation, call.agent_id).then((route) => conversationRoute(route, call)), null, true);
292
358
  return {
293
359
  result: launch.session.then((session) => ({ provider_session_id: session }), (error) => ({ refused: refusal(conversation, error) })),
294
360
  };
@@ -330,23 +396,23 @@ 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
  }
337
403
  async message(conversation, call) {
338
404
  const content = [
339
- ...(typeof call.recent === 'string' ? [{ type: 'text', text: call.recent }] : []),
340
- { type: 'text', text: String(call.text) },
405
+ ...(call.recent === undefined ? [] : [{ type: 'text', text: call.recent }]),
406
+ { type: 'text', text: call.text },
341
407
  ];
342
408
  let route;
343
409
  let instructing = null;
344
410
  try {
345
- route = await this.route(conversation, call.agent_id);
411
+ route = conversationRoute(await this.route(conversation, call.agent_id), call);
346
412
  if (call.first === true)
347
413
  instructing = this.instructed(conversation, route);
348
414
  if (call.message_id !== null)
349
- content.push(...(await this.transcribed(conversation, String(call.message_id), String(call.text))));
415
+ content.push(...(await this.transcribed(conversation, call.message_id, call.text)));
350
416
  if (conversation.kills > 0)
351
417
  throw new Error(KILLED);
352
418
  }
@@ -403,7 +469,7 @@ export class Conversations {
403
469
  for (const turn of conversation.turns)
404
470
  turn.steered ||= turn.prompted;
405
471
  }
406
- this.kit.calls.keepResult(String(waiting.call.input_id), {});
472
+ this.kit.calls.keepResult(waiting.call.input_id, {});
407
473
  waiting.settle({});
408
474
  }
409
475
  else {
@@ -412,15 +478,13 @@ 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) {
419
485
  const step = conversation.preparing ?? (conversation.launch === null ? null : 'session');
420
486
  if (conversation.starting !== step)
421
487
  this.starts(conversation, step);
422
- if (conversation.done && conversation.launch === null)
423
- void this.stop(conversation).catch(logged);
424
488
  return;
425
489
  }
426
490
  conversation.sending = this.send(conversation, waiting).finally(() => {
@@ -469,7 +533,7 @@ export class Conversations {
469
533
  return;
470
534
  }
471
535
  this.starts(conversation, null);
472
- this.prompt(conversation, [...prompt, ...waiting.content], () => this.kit.calls.keepResult(String(call.input_id), result));
536
+ this.prompt(conversation, [...prompt, ...waiting.content], () => this.kit.calls.keepResult(call.input_id, result));
473
537
  waiting.settle(result);
474
538
  }
475
539
  starts(conversation, step) {
@@ -511,7 +575,7 @@ export class Conversations {
511
575
  const blocks = [];
512
576
  try {
513
577
  const bridge = await step(unbridged, unlessAborted(this.bridged(conversation), killed));
514
- const read = async (path) => audioOf(await step(unbridged, unlessAborted(bridge.tool('inspect', { path }), signal)));
578
+ const read = async (path) => audioOf(await step(unbridged, unlessAborted(bridge.tool('info', { path }), signal)));
515
579
  for (const path of paths) {
516
580
  let answered = await read(path);
517
581
  if (answered === null)
@@ -525,8 +589,7 @@ export class Conversations {
525
589
  throw new Error(`${path} is no longer an audio file`);
526
590
  return address;
527
591
  }, 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));
592
+ await step(unbridged, unlessAborted(this.kit.house.deliver('agent_update.transcript_keep', { conversation: conversation.id, message: messageId, path, text: said }, () => !signal.aborted), signal));
530
593
  blocks.push({ type: 'text', text: `${path}\nTranscript: ${said}` });
531
594
  }
532
595
  }
@@ -586,22 +649,38 @@ export class Conversations {
586
649
  this.halt(conversation);
587
650
  await running?.adapter.exited;
588
651
  }
589
- async option(conversation, option, value) {
652
+ async option(conversation, chosen) {
653
+ while (conversation.running === null && conversation.sending !== null)
654
+ await conversation.sending;
590
655
  const running = conversation.running;
591
656
  if (running === null)
592
657
  return;
658
+ for (const [category, value] of [['model', chosen.model], [EFFORT, chosen.effort]]) {
659
+ if (value === undefined)
660
+ continue;
661
+ try {
662
+ const options = await this.setOption(running, conversation.options ?? [], category, value);
663
+ if (options !== null)
664
+ this.options(conversation, options);
665
+ }
666
+ catch (error) {
667
+ logged(error);
668
+ }
669
+ }
670
+ }
671
+ async setOption(running, options, category, value) {
672
+ const option = options.find((candidate) => candidate.category === category);
673
+ if (option === undefined && category === EFFORT)
674
+ return null;
675
+ const configId = option?.id ?? category;
676
+ running.reader.requested(configId, value);
593
677
  try {
594
- running.reader.requested(option, value);
595
- const answered = await running.adapter.connection.agent.request('session/set_config_option', {
596
- sessionId: running.sessionId,
597
- configId: option,
598
- ...(typeof value === 'boolean' ? { type: 'boolean', value } : { value: String(value) }),
599
- });
600
- this.options(conversation, answered.configOptions);
678
+ const answered = await running.adapter.connection.agent.request('session/set_config_option', { sessionId: running.sessionId, configId, value });
679
+ return answered.configOptions;
601
680
  }
602
681
  catch (error) {
603
- running.reader.refused(option);
604
- logged(error);
682
+ running.reader.refused(configId);
683
+ throw error;
605
684
  }
606
685
  }
607
686
  async route(conversation, agentId) {
@@ -621,10 +700,12 @@ export class Conversations {
621
700
  const route = await routed;
622
701
  const reader = readerFor(route.kind);
623
702
  reader.session = sessionId;
703
+ conversation.reader = reader;
624
704
  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));
705
+ .onRequest('session/request_permission', ({ params, signal }) => conversation.afk ? permissionAllowed(params) : this.ask(conversation, 'session/request_permission', params, false, signal))
706
+ .onRequest('elicitation/create', ({ params, signal }) => conversation.afk ? formAnswered(route.kind, params) : this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
707
+ .onRequest('_x.ai/exit_plan_mode', GROK_PLAN, async ({ params, signal }) => conversation.afk ? PLAN_APPROVED : grokPlanAnswer(await this.askForm(conversation, grokPlanForm(params), signal)))
708
+ .onRequest('_x.ai/ask_user_question', GROK_QUESTION, async ({ params, signal }) => conversation.afk ? grokQuestionAnswered(params) : grokQuestionAnswer(await this.askForm(conversation, grokQuestionForm(params), signal)));
628
709
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
629
710
  const bridging = this.bridged(conversation);
630
711
  const bridge = await step(unbridged, bridging);
@@ -633,28 +714,28 @@ export class Conversations {
633
714
  throw new Error(KILLED);
634
715
  }
635
716
  conversation.opening = bridge;
636
- const work = workFor(route.kind, route.working_directory, () => this.kit.changed());
717
+ const work = workFor(route.kind, route.working_directory, () => this.kit.changed(), (message) => this.tapped(conversation, reader, message));
637
718
  const scope = new Scope(marker(bridge), randomUUID(), cli);
638
719
  let adapter = null;
639
720
  try {
640
721
  bridged(bridge);
641
722
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
642
723
  const streamed = await step(NO_CONNECTION, work.open(cli));
724
+ if (this.stopping)
725
+ throw new Error(KILLED);
643
726
  adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
644
727
  work.read(message);
645
- this.read(conversation, reader, message);
728
+ return this.read(conversation, reader, work, message);
646
729
  }, { ...bridge.env, ...streamed }, undefined, scope));
647
730
  void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
648
731
  const agent = adapter.connection.agent;
649
732
  const cwd = route.working_directory;
650
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
733
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
651
734
  const resumed = sessionId === null ? null : await this.resume(conversation, route.kind, adapter, { sessionId, cwd, mcpServers: [], _meta }, empty);
652
735
  const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
653
736
  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
- }
737
+ if (opened.sessionId !== conversation.session)
738
+ conversation.state = QUIET;
658
739
  const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
659
740
  const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
660
741
  void work.settled().then(() => scope.record());
@@ -694,19 +775,11 @@ export class Conversations {
694
775
  const settings = [
695
776
  ['mode', route.mode ?? CLIS[route.kind].fullAccess],
696
777
  ['model', route.model],
697
- ['thought_level', route.effort],
778
+ [EFFORT, route.effort],
698
779
  ];
699
780
  for (const [category, value] of settings) {
700
- if (value === null)
701
- continue;
702
- const option = options.find((candidate) => candidate.category === category);
703
- running.reader.requested(option?.id ?? category, value);
704
- const answered = await running.adapter.connection.agent.request('session/set_config_option', {
705
- sessionId: running.sessionId,
706
- configId: option?.id ?? category,
707
- value,
708
- });
709
- options = answered.configOptions;
781
+ if (value !== null)
782
+ options = (await this.setOption(running, options, category, value)) ?? options;
710
783
  }
711
784
  return options;
712
785
  }
@@ -726,10 +799,8 @@ export class Conversations {
726
799
  conversation.running = null;
727
800
  conversation.commands = null;
728
801
  conversation.options = null;
729
- if (conversation.subagents.size > 0) {
730
- conversation.subagents.clear();
731
- this.subagentsChanged(conversation);
732
- }
802
+ conversation.subagents.clear();
803
+ this.stated(conversation, { running: [] });
733
804
  for (const [id, question] of this.questions) {
734
805
  if (question.conversation === conversation)
735
806
  this.questions.delete(id);
@@ -746,9 +817,15 @@ export class Conversations {
746
817
  if (conversation.options !== null)
747
818
  this.options(conversation, conversation.options);
748
819
  }
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 });
820
+ stated(conversation, change) {
821
+ conversation.state = { ...conversation.state, ...change };
822
+ this.stateChanged(conversation, false);
823
+ }
824
+ stateChanged(conversation, again) {
825
+ const state = JSON.stringify(conversation.state);
826
+ if (!again && state === conversation.sentState)
827
+ return;
828
+ conversation.sentState = this.kit.send({ type: 'state', conversation_id: conversation.id, state: conversation.state }) ? state : null;
752
829
  }
753
830
  commands(conversation, commands) {
754
831
  conversation.commands = commands;
@@ -760,11 +837,16 @@ export class Conversations {
760
837
  if (conversation.running === null)
761
838
  return;
762
839
  conversation.options = options;
763
- this.kit.send({ type: 'options', conversation_id: conversation.id, options });
840
+ this.kit.send({ type: 'options', conversation_id: conversation.id, options: options.filter((option) => option.category !== 'mode') });
841
+ const chosen = (category) => {
842
+ const value = options.find((option) => option.category === category)?.currentValue;
843
+ return value === undefined ? null : String(value);
844
+ };
845
+ this.stated(conversation, { model: chosen('model'), effort: chosen(EFFORT), mode: chosen('mode') });
764
846
  }
765
- deliver(conversation, turn, event, body) {
847
+ deliver(conversation, act, request, current) {
766
848
  this.reporting++;
767
- const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/conversations/${conversation.id}/turns/${turn.id}/${event}`, await body));
849
+ const delivered = conversation.reports.then(async () => this.kit.house.deliver(act, await request, current));
768
850
  conversation.reports = delivered
769
851
  .catch(() => undefined)
770
852
  .finally(() => {
@@ -776,22 +858,26 @@ export class Conversations {
776
858
  write(conversation, turn, operation) {
777
859
  if (turn.ended || !this.watched)
778
860
  return;
779
- this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, ...operation });
861
+ this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, operation });
780
862
  }
781
863
  replay(conversation, turn) {
782
- for (const operation of turn.parts.operations())
864
+ for (const operation of turn.content.operations())
783
865
  this.write(conversation, turn, operation);
784
866
  }
785
867
  begin(conversation) {
786
868
  const turn = new Turn((operation) => this.write(conversation, turn, operation));
787
869
  conversation.turns.add(turn);
788
870
  conversation.running?.adapter.turn(true);
789
- void this.deliver(conversation, turn, 'started', {}).catch(logged);
871
+ void this.deliver(conversation, 'turns/start', turnOf(conversation, turn))
872
+ .then((answer) => {
873
+ if (answer.run === true)
874
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
875
+ })
876
+ .catch(logged);
790
877
  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);
878
+ this.stated(conversation, { suggestion: null });
879
+ for (const event of conversation.reader?.began() ?? [])
880
+ this.event(conversation, event);
795
881
  this.kit.changed();
796
882
  return turn;
797
883
  }
@@ -800,23 +886,25 @@ export class Conversations {
800
886
  return;
801
887
  if (failed !== null)
802
888
  logged(new Error(`conversation ${conversation.id} turn ${turn.id} failed: ${failed.cause}`));
803
- if (conversation.turn === turn) {
804
- for (const event of conversation.running?.reader.closeTurn() ?? [])
805
- this.apply(conversation, turn, event);
806
- }
889
+ if (conversation.turn === turn)
890
+ conversation.reader?.closeTurn();
807
891
  if (notice !== null)
808
- turn.parts.start({ type: 'marker', marker: 'retry', text: notice });
892
+ turn.content.add({ type: 'notice', kind: 'error', text: notice });
809
893
  turn.ended = true;
810
894
  conversation.turns.delete(turn);
811
895
  conversation.running?.adapter.turn(conversation.turns.size > 0);
812
896
  if (conversation.turn === turn)
813
897
  conversation.turn = null;
898
+ const tokens = conversation.tokens;
899
+ conversation.tokens = null;
900
+ if (tokens !== null)
901
+ this.stated(conversation, { tokens: addedTokens(conversation.state.tokens, tokens) });
814
902
  const body = Promise.allSettled(turn.uploads).then(() => ({
815
- parts: turn.parts.saved(),
816
- context: turn.parts.context,
903
+ ...turnOf(conversation, turn),
904
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
817
905
  ...(failed === null ? {} : { failed: failed.failure }),
818
906
  }));
819
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
907
+ void this.deliver(conversation, 'turns/end', body).catch(logged);
820
908
  this.next(conversation);
821
909
  this.kit.changed();
822
910
  }
@@ -845,7 +933,7 @@ export class Conversations {
845
933
  running.adapter.retire();
846
934
  this.detach(conversation, running);
847
935
  }
848
- this.end(conversation, turn, answeredWith(error));
936
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
849
937
  }
850
938
  });
851
939
  }
@@ -858,7 +946,7 @@ export class Conversations {
858
946
  const turn = conversation.turn;
859
947
  if (turn === null)
860
948
  return;
861
- const held = stop !== null && !turn.steered && [...conversation.subagents.values()].some((subagent) => subagent.turn === turn);
949
+ const held = stop !== null && !turn.steered && [...conversation.subagents].some((key) => turn.content.holds(key));
862
950
  if (!turn.prompted || held) {
863
951
  this.took(turn);
864
952
  this.end(conversation, turn, stop === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
@@ -866,18 +954,21 @@ export class Conversations {
866
954
  }
867
955
  if (stop !== null)
868
956
  return;
869
- for (const event of conversation.running?.reader.closeTurn() ?? [])
870
- this.apply(conversation, turn, event);
957
+ conversation.reader?.closeTurn();
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, 'agent_update.conversation_ask', {
971
+ ...turnOf(conversation, turn),
881
972
  interaction_id: interactionId,
882
973
  request: { method, params },
883
974
  secret,
@@ -915,10 +1006,35 @@ export class Conversations {
915
1006
  if (content !== null)
916
1007
  this.questions.get(interactionId)?.answer({ action: 'accept', content });
917
1008
  }
918
- read(conversation, reader, message) {
919
- for (const event of reader.read(message))
1009
+ read(conversation, reader, work, message) {
1010
+ const events = reader.read(message);
1011
+ const apply = () => {
1012
+ for (const event of events)
1013
+ this.event(conversation, event);
1014
+ this.reportActivity(conversation);
1015
+ };
1016
+ const held = message.method === undefined || events.some((event) => event.kind === 'ended') ? work.caughtUp() : null;
1017
+ if (held === null) {
1018
+ apply();
1019
+ return null;
1020
+ }
1021
+ return held.then(apply);
1022
+ }
1023
+ tapped(conversation, reader, message) {
1024
+ for (const event of reader.tap(message))
920
1025
  this.event(conversation, event);
921
1026
  }
1027
+ reportActivity(conversation) {
1028
+ const turn = conversation.turn;
1029
+ if (turn === null || Date.now() < turn.quietUntil)
1030
+ return;
1031
+ turn.quietUntil = Infinity;
1032
+ void this.deliver(conversation, 'turns/activity/report', turnOf(conversation, turn), () => false)
1033
+ .catch(logged)
1034
+ .finally(() => {
1035
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
1036
+ });
1037
+ }
922
1038
  event(conversation, event) {
923
1039
  switch (event.kind) {
924
1040
  case 'started':
@@ -933,23 +1049,20 @@ export class Conversations {
933
1049
  case 'options':
934
1050
  this.options(conversation, event.options);
935
1051
  return;
936
- case 'context':
937
- conversation.context = { used: event.used, window: event.window };
938
- conversation.turn?.parts.measure(conversation.context);
1052
+ case 'state':
1053
+ this.stated(conversation, event.state);
939
1054
  return;
940
- case 'subagent-done':
941
- this.subagentDone(conversation, event.id, event.result);
1055
+ case 'tokens':
1056
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
942
1057
  return;
943
- case 'subagent-activity':
944
- this.subagentActivity(conversation, event.id, event.activity);
1058
+ case 'call':
1059
+ this.called(conversation, event);
945
1060
  return;
946
- case 'marker':
1061
+ case 'notice':
947
1062
  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;
1063
+ if (conversation.turn === null)
1064
+ return;
1065
+ break;
953
1066
  }
954
1067
  this.apply(conversation, this.started(conversation), event);
955
1068
  }
@@ -961,62 +1074,42 @@ export class Conversations {
961
1074
  apply(conversation, turn, event) {
962
1075
  switch (event.kind) {
963
1076
  case 'text':
964
- case 'reasoning':
965
- turn.parts.write(event.kind, event.id, event.text);
966
- return;
967
- case 'command':
968
- turn.parts.command();
1077
+ turn.content.write(event.id, event.text);
969
1078
  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);
974
- return;
975
- }
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 });
981
- return;
982
- case 'plan':
983
- turn.parts.plan(event.entries);
1079
+ case 'notice':
1080
+ turn.content.add({ type: 'notice', kind: event.notice, text: event.text });
984
1081
  return;
985
1082
  case 'image':
986
- turn.uploads.push(this.image(conversation, turn, turn.parts.reserve(), event.data, event.mediaType));
1083
+ turn.uploads.push(this.image(conversation, turn, event.data, event.mediaType));
987
1084
  this.kit.changed();
988
1085
  return;
989
1086
  }
990
1087
  }
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);
1088
+ // A sub-agent's calls count only in the turn that holds the call that started it, and a call's later changes only in the turn that counted it.
1089
+ called(conversation, event) {
1090
+ if (event.running === true)
1091
+ conversation.subagents.add(event.key);
1092
+ if (event.running === false)
1093
+ conversation.subagents.delete(event.key);
1094
+ const turn = conversation.turn;
1095
+ if (!event.first) {
1096
+ if (turn?.content.holds(event.key))
1097
+ turn.content.call(event.key, event.parent, event.call);
999
1098
  return;
1000
1099
  }
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)
1100
+ if (event.parent !== null) {
1101
+ turn?.content.call(event.key, event.parent, event.call);
1010
1102
  return;
1011
- subagent.activity = activity;
1012
- this.subagentsChanged(conversation);
1103
+ }
1104
+ this.started(conversation).content.call(event.key, null, event.call);
1013
1105
  }
1014
- async image(conversation, turn, reserved, data, mediaType) {
1106
+ async image(conversation, turn, data, mediaType) {
1015
1107
  const bytes = Buffer.from(data, 'base64');
1016
1108
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
1017
1109
  const sha256 = createHash('sha256').update(bytes).digest('hex');
1018
1110
  try {
1019
- const declared = (await this.deliver(conversation, turn, 'images', {
1111
+ const declared = (await this.deliver(conversation, 'turns/images/declare', {
1112
+ ...turnOf(conversation, turn),
1020
1113
  name,
1021
1114
  media_type: mediaType,
1022
1115
  bytes: bytes.length,
@@ -1028,13 +1121,13 @@ export class Conversations {
1028
1121
  sha256,
1029
1122
  read: (start, end) => [bytes.subarray(start, end)],
1030
1123
  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 }),
1124
+ finish: (upload, partSha256) => this.kit.house.deliver('uploads/finish', { upload, part_sha256: partSha256 }),
1032
1125
  });
1033
- turn.parts.arrive({ type: 'image', file: saved.path, name, media_type: mediaType }, reserved);
1126
+ turn.content.arrived({ type: 'image', file: saved.path, name, media_type: mediaType });
1034
1127
  }
1035
1128
  catch (error) {
1036
1129
  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);
1130
+ turn.content.arrived({ type: 'notice', kind: 'error', text: `${name} was not saved: ${cause}` });
1038
1131
  }
1039
1132
  }
1040
1133
  }