@agentshouse/kit 0.2.1-ccb257fa8a318 → 0.2.1-ccffb3f637815

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 (57) hide show
  1. package/README.md +27 -31
  2. package/dist/acp.js +17 -10
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +121 -52
  5. package/dist/api.js +11 -6
  6. package/dist/binaries.js +89 -0
  7. package/dist/bridge.js +28 -27
  8. package/dist/building.js +7 -3
  9. package/dist/calls.js +18 -1
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +52 -63
  12. package/dist/connect.js +108 -0
  13. package/dist/connection.js +24 -20
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +255 -134
  16. package/dist/copies.js +748 -248
  17. package/dist/earlier.js +263 -0
  18. package/dist/end.js +9 -6
  19. package/dist/events.js +549 -281
  20. package/dist/files.js +77 -11
  21. package/dist/git-main.js +24 -29
  22. package/dist/git.js +87 -12
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +80 -29
  25. package/dist/house-cli.js +106 -123
  26. package/dist/instructions.js +2 -4
  27. package/dist/keys.js +238 -0
  28. package/dist/kit-cli.js +14 -4
  29. package/dist/login.js +34 -20
  30. package/dist/logout.js +2 -2
  31. package/dist/mcp.js +38 -3
  32. package/dist/old-references.js +27 -0
  33. package/dist/owner.js +46 -0
  34. package/dist/placement.js +9 -23
  35. package/dist/refusals.js +37 -21
  36. package/dist/resident.js +107 -72
  37. package/dist/scope.js +12 -4
  38. package/dist/scripts.js +59 -11
  39. package/dist/secret-input.js +1 -1
  40. package/dist/settings.js +188 -0
  41. package/dist/sign-in.js +49 -4
  42. package/dist/supervisor.js +163 -0
  43. package/dist/transcription.js +5 -2
  44. package/dist/translate.js +18 -11
  45. package/dist/update.js +115 -160
  46. package/dist/wire.js +19 -9
  47. package/dist/work.js +27 -2
  48. package/dist/workspace.js +103 -0
  49. package/package.json +13 -8
  50. package/dist/authority-main.js +0 -22
  51. package/dist/chatgpt.js +0 -32
  52. package/dist/clis-main.js +0 -23
  53. package/dist/configure-main.js +0 -6
  54. package/dist/enrol-main.js +0 -10
  55. package/dist/parts.js +0 -82
  56. package/dist/service-main.js +0 -9
  57. package/dist/service.js +0 -55
@@ -1,24 +1,25 @@
1
- import { client, RequestError, } from '@agentclientprotocol/sdk';
1
+ import { client, } from '@agentclientprotocol/sdk';
2
2
  import { createHash, randomUUID } from 'node:crypto';
3
3
  import { mkdir } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { unlessAborted } from './abort.js';
6
- import { startAdapter } from './acp.js';
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';
21
- const SIGNED_OUT = RequestError.authRequired().code;
22
23
  const KILLED = 'the conversation was killed';
23
24
  const INTERRUPTED = 'the conversation was interrupted';
24
25
  const REFUSED = 'the CLI refused the prompt';
@@ -35,6 +36,26 @@ const NO_RESUME = "the Agent's CLI could not resume this conversation";
35
36
  const NOT_SIGNED_IN = "the Agent's CLI is not signed in; sign it in on the Agent's machine";
36
37
  const NO_SETTINGS = "the Agent's CLI refused the Agent's model, mode or effort";
37
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: { count: 0, added: 0, removed: 0 },
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;
38
59
  class NotStarted extends Error {
39
60
  }
40
61
  class ResumeRefused extends NotStarted {
@@ -47,26 +68,41 @@ async function step(reason, work) {
47
68
  throw new NotStarted(typeof reason === 'string' ? reason : reason(error), { cause: error });
48
69
  }
49
70
  }
50
- function signedOut(error) {
51
- return typeof error === 'object' && error !== null && error.code === SIGNED_OUT;
52
- }
53
71
  function unopened(reason) {
54
72
  return (error) => (signedOut(error) ? NOT_SIGNED_IN : reason);
55
73
  }
56
74
  // A start-up step is shown only once it has lasted a second, so a quick start shows none of them.
57
75
  const STARTING_SHOWN_AFTER_MS = 1_000;
76
+ function turnOf(conversation, turn) {
77
+ return { conversation: conversation.id, turn: turn.id };
78
+ }
58
79
  function unbridged(error) {
59
80
  return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
60
81
  }
61
- const EXIT_PLAN_MODE = {
82
+ const GROK_PLAN = {
83
+ parse(value) {
84
+ return value;
85
+ },
86
+ };
87
+ const GROK_QUESTION = {
62
88
  parse(value) {
63
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
64
- throw new Error('_x.ai/exit_plan_mode needs an object');
65
- }
66
89
  return value;
67
90
  },
68
91
  };
69
- 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 cliSaid(error) {
103
+ const details = error?.data?.details;
104
+ return typeof details === 'string' && details !== '' ? `${causeOf(error)}: ${details}` : causeOf(error);
105
+ }
70
106
  function causeOf(error) {
71
107
  return error instanceof Error ? error.message : String(error);
72
108
  }
@@ -100,7 +136,7 @@ function refusal(conversation, error) {
100
136
  function audioOf(result) {
101
137
  if (result.isError === true)
102
138
  return null;
103
- const file = inspectedFile(result.content.map((content) => content.text).join('\n'));
139
+ const file = fileInfo(result.content.map((content) => content.text).join('\n'));
104
140
  return file?.media_type?.startsWith('audio/') === true ? file : null;
105
141
  }
106
142
  function marker(bridge) {
@@ -111,16 +147,18 @@ function steers(adapter) {
111
147
  }
112
148
  class Turn {
113
149
  id = randomUUID();
114
- parts;
150
+ content;
115
151
  questions = 0;
116
152
  secrets = 0;
117
153
  prompted = false;
154
+ steered = false;
118
155
  taken = null;
119
156
  ended = false;
157
+ quietUntil = Infinity;
120
158
  images = 0;
121
159
  uploads = [];
122
160
  constructor(emit) {
123
- this.parts = new Parts(emit);
161
+ this.content = new Content(emit);
124
162
  }
125
163
  }
126
164
  class Conversation {
@@ -131,13 +169,16 @@ class Conversation {
131
169
  commands = null;
132
170
  options = null;
133
171
  exitUntold = false;
134
- context = null;
172
+ afk = false;
173
+ reader = null;
174
+ state = QUIET;
175
+ sentState = null;
176
+ tokens = null;
135
177
  leftovers = new Set();
136
178
  waiting = [];
137
179
  done = false;
138
180
  sending = null;
139
- subagents = new Map();
140
- held = [];
181
+ subagents = new Set();
141
182
  opening = null;
142
183
  bridge = null;
143
184
  launch = null;
@@ -146,7 +187,7 @@ class Conversation {
146
187
  killed = new AbortController();
147
188
  interrupts = 0;
148
189
  interrupted = new AbortController();
149
- open = 0;
190
+ turns = new Set();
150
191
  queue = Promise.resolve();
151
192
  reports = Promise.resolve();
152
193
  starting = null;
@@ -172,6 +213,7 @@ export class Conversations {
172
213
  questions = new Map();
173
214
  reporting = 0;
174
215
  watched = false;
216
+ stopping = false;
175
217
  constructor(kit) {
176
218
  this.kit = kit;
177
219
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
@@ -180,6 +222,8 @@ export class Conversations {
180
222
  call(call) {
181
223
  void this.kit.calls.carry(call.input_id, () => {
182
224
  const conversation = this.conversation(call.conversation_id);
225
+ if (call.kind === 'open' || call.kind === 'message')
226
+ conversation.afk = call.afk === true;
183
227
  if (call.kind === 'kill') {
184
228
  conversation.kills++;
185
229
  conversation.killed.abort(new Error(KILLED));
@@ -202,7 +246,7 @@ export class Conversations {
202
246
  for (const conversation of this.conversations.values()) {
203
247
  const turn = conversation.turn;
204
248
  const asking = turn !== null && turn.questions > 0 && turn.secrets === 0;
205
- if (conversation.open > (asking ? 1 : 0))
249
+ if (conversation.turns.size > (asking ? 1 : 0))
206
250
  return false;
207
251
  }
208
252
  const conversations = [...this.conversations.values()];
@@ -211,7 +255,10 @@ export class Conversations {
211
255
  return !conversations.some((conversation) => conversation.running?.scope.working() || [...conversation.leftovers].some((scope) => scope.working()));
212
256
  }
213
257
  quiet() {
214
- return this.idle() && [...this.conversations.values()].every((conversation) => conversation.open === 0);
258
+ return this.idle() && !this.turnOpen();
259
+ }
260
+ turnOpen() {
261
+ return [...this.conversations.values()].some((conversation) => conversation.turns.size > 0);
215
262
  }
216
263
  look() {
217
264
  for (const conversation of this.conversations.values()) {
@@ -224,11 +271,20 @@ export class Conversations {
224
271
  }
225
272
  this.kit.changed();
226
273
  }
274
+ stopped() {
275
+ this.stopping = true;
276
+ for (const conversation of this.conversations.values()) {
277
+ if (conversation.running !== null)
278
+ this.process(conversation, false);
279
+ }
280
+ }
227
281
  opened() {
228
282
  this.watched = false;
229
283
  for (const conversation of this.conversations.values()) {
230
- if (conversation.running !== null)
284
+ if (conversation.running !== null) {
231
285
  this.facts(conversation);
286
+ this.stateChanged(conversation, true);
287
+ }
232
288
  else if (conversation.exitUntold)
233
289
  this.process(conversation, false);
234
290
  if (conversation.untold || conversation.told !== null)
@@ -263,11 +319,13 @@ export class Conversations {
263
319
  this.next(conversation);
264
320
  return { result: Promise.resolve({}) };
265
321
  }
322
+ if (call.kind === 'take_out')
323
+ return { result: Promise.resolve(this.takeOut(conversation, call.message_id)) };
266
324
  await this.launched(conversation);
267
325
  if (call.kind === 'interrupt') {
268
326
  if (--conversation.interrupts === 0)
269
327
  conversation.interrupted = new AbortController();
270
- await this.interrupt(conversation, String(call.turn_id));
328
+ await this.interrupt(conversation, call.turn_id);
271
329
  }
272
330
  if (call.kind === 'kill') {
273
331
  await this.kill(conversation);
@@ -276,9 +334,9 @@ export class Conversations {
276
334
  conversation.killed = new AbortController();
277
335
  }
278
336
  if (call.kind === 'option')
279
- await this.option(conversation, String(call.option), call.value);
337
+ await this.option(conversation, call.option, call.value);
280
338
  if (call.kind === 'answer') {
281
- const question = this.questions.get(String(call.interaction_id));
339
+ const question = this.questions.get(call.interaction_id);
282
340
  if (question === undefined) {
283
341
  const text = answerMessage(call.request, call.response);
284
342
  return this.message(conversation, { ...call, text, first: false, message_id: null });
@@ -287,6 +345,14 @@ export class Conversations {
287
345
  }
288
346
  return { result: Promise.resolve({}) };
289
347
  }
348
+ takeOut(conversation, messageId) {
349
+ const index = conversation.waiting.findIndex((waiting) => waiting.call.message_id === messageId);
350
+ if (index === -1)
351
+ return { started: true };
352
+ const [waiting] = conversation.waiting.splice(index, 1);
353
+ waiting.settle({ refused: TAKEN_OUT });
354
+ return {};
355
+ }
290
356
  async open(conversation, call) {
291
357
  await this.stop(conversation);
292
358
  const launch = conversation.launch ?? this.launch(conversation, this.route(conversation, call.agent_id), null, true);
@@ -331,14 +397,14 @@ export class Conversations {
331
397
  const bridge = conversation.running === null ? conversation.launch?.bridge : Promise.resolve(conversation.running.bridge);
332
398
  if (bridge === undefined)
333
399
  return null;
334
- const read = Promise.all([bridge, this.kit.copies.mapping()]).then(([opened, copies]) => instructions(opened, route.base_instructions, copies));
400
+ const read = bridge.then((opened) => instructions(opened, route.base_instructions));
335
401
  read.catch(() => undefined);
336
402
  return read;
337
403
  }
338
404
  async message(conversation, call) {
339
405
  const content = [
340
- ...(typeof call.recent === 'string' ? [{ type: 'text', text: call.recent }] : []),
341
- { type: 'text', text: String(call.text) },
406
+ ...(call.recent === undefined ? [] : [{ type: 'text', text: call.recent }]),
407
+ { type: 'text', text: call.text },
342
408
  ];
343
409
  let route;
344
410
  let instructing = null;
@@ -347,7 +413,7 @@ export class Conversations {
347
413
  if (call.first === true)
348
414
  instructing = this.instructed(conversation, route);
349
415
  if (call.message_id !== null)
350
- content.push(...(await this.transcribed(conversation, String(call.message_id), String(call.text))));
416
+ content.push(...(await this.transcribed(conversation, call.message_id, call.text)));
351
417
  if (conversation.kills > 0)
352
418
  throw new Error(KILLED);
353
419
  }
@@ -359,7 +425,7 @@ export class Conversations {
359
425
  conversation.preparing = null;
360
426
  const { promise, resolve: settle } = Promise.withResolvers();
361
427
  const waiting = { call, route, content, instructing, settle };
362
- if (call.at_once === true && conversation.open > 0)
428
+ if (call.at_once === true && conversation.turns.size > 0)
363
429
  await this.atOnce(conversation, waiting);
364
430
  else
365
431
  conversation.waiting.push(waiting);
@@ -370,15 +436,15 @@ export class Conversations {
370
436
  while (conversation.sending !== null)
371
437
  await conversation.sending;
372
438
  const running = conversation.running;
373
- if (running !== null && conversation.open > 0 && steers(running.adapter)) {
439
+ if (running !== null && conversation.turns.size > 0 && steers(running.adapter)) {
374
440
  conversation.sending = this.steer(conversation, running, waiting);
375
441
  await conversation.sending;
376
442
  conversation.sending = null;
377
443
  return;
378
444
  }
379
445
  this.ahead(conversation, waiting);
380
- if (conversation.turn !== null)
381
- await this.interrupt(conversation, conversation.turn.id);
446
+ if (conversation.turns.size > 0)
447
+ await this.cancel(conversation);
382
448
  }
383
449
  ahead(conversation, waiting) {
384
450
  const behind = conversation.waiting.findIndex((held) => held.call.at_once !== true);
@@ -400,7 +466,11 @@ export class Conversations {
400
466
  this.ahead(conversation, waiting);
401
467
  }
402
468
  else if (outcome === 'injected' || outcome === 'startedNewTurn') {
403
- this.kit.calls.keepResult(String(waiting.call.input_id), {});
469
+ if (outcome === 'injected') {
470
+ for (const turn of conversation.turns)
471
+ turn.steered ||= turn.prompted;
472
+ }
473
+ this.kit.calls.keepResult(waiting.call.input_id, {});
404
474
  waiting.settle({});
405
475
  }
406
476
  else {
@@ -409,7 +479,7 @@ export class Conversations {
409
479
  }
410
480
  }
411
481
  next(conversation) {
412
- if (conversation.sending !== null || conversation.open > 0)
482
+ if (this.stopping || conversation.sending !== null || conversation.turns.size > 0)
413
483
  return;
414
484
  const waiting = conversation.waiting.shift();
415
485
  if (waiting === undefined) {
@@ -466,7 +536,7 @@ export class Conversations {
466
536
  return;
467
537
  }
468
538
  this.starts(conversation, null);
469
- this.prompt(conversation, [...prompt, ...waiting.content], () => this.kit.calls.keepResult(String(call.input_id), result));
539
+ this.prompt(conversation, [...prompt, ...waiting.content], () => this.kit.calls.keepResult(call.input_id, result));
470
540
  waiting.settle(result);
471
541
  }
472
542
  starts(conversation, step) {
@@ -508,7 +578,7 @@ export class Conversations {
508
578
  const blocks = [];
509
579
  try {
510
580
  const bridge = await step(unbridged, unlessAborted(this.bridged(conversation), killed));
511
- const read = async (path) => audioOf(await step(unbridged, unlessAborted(bridge.tool('inspect', { path }), signal)));
581
+ const read = async (path) => audioOf(await step(unbridged, unlessAborted(bridge.tool('info', { path }), signal)));
512
582
  for (const path of paths) {
513
583
  let answered = await read(path);
514
584
  if (answered === null)
@@ -522,8 +592,7 @@ export class Conversations {
522
592
  throw new Error(`${path} is no longer an audio file`);
523
593
  return address;
524
594
  }, signal);
525
- const transcript = `/kit/conversations/${conversation.id}/messages/${messageId}/transcripts`;
526
- await step(unbridged, unlessAborted(this.kit.house.deliver(transcript, { path, text: said }, () => !signal.aborted), signal));
595
+ await step(unbridged, unlessAborted(this.kit.house.deliver('transcripts/keep', { conversation: conversation.id, message: messageId, path, text: said }, () => !signal.aborted), signal));
527
596
  blocks.push({ type: 'text', text: `${path}\nTranscript: ${said}` });
528
597
  }
529
598
  }
@@ -558,7 +627,11 @@ export class Conversations {
558
627
  void bridging.then((bridge) => bridge.close(), () => undefined);
559
628
  }
560
629
  async interrupt(conversation, turnId) {
561
- if (conversation.running === null || conversation.turn?.id !== turnId)
630
+ if ([...conversation.turns].some((turn) => turn.id === turnId))
631
+ await this.cancel(conversation);
632
+ }
633
+ async cancel(conversation) {
634
+ if (conversation.running === null)
562
635
  return;
563
636
  await conversation.running.adapter.connection.agent.notify('session/cancel', {
564
637
  sessionId: conversation.running.sessionId,
@@ -584,6 +657,9 @@ export class Conversations {
584
657
  if (running === null)
585
658
  return;
586
659
  try {
660
+ if (conversation.options?.find(({ id }) => id === option)?.category === 'mode') {
661
+ throw new Error(`conversation ${conversation.id} keeps the mode its Agent's launch settings name`);
662
+ }
587
663
  running.reader.requested(option, value);
588
664
  const answered = await running.adapter.connection.agent.request('session/set_config_option', {
589
665
  sessionId: running.sessionId,
@@ -614,10 +690,12 @@ export class Conversations {
614
690
  const route = await routed;
615
691
  const reader = readerFor(route.kind);
616
692
  reader.session = sessionId;
693
+ conversation.reader = reader;
617
694
  const app = client({ name: '@agentshouse/kit' })
618
- .onRequest('session/request_permission', ({ params, signal }) => this.ask(conversation, 'session/request_permission', params, false, signal))
619
- .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
620
- .onRequest('_x.ai/exit_plan_mode', EXIT_PLAN_MODE, ({ params, signal }) => this.ask(conversation, '_x.ai/exit_plan_mode', params, false, signal));
695
+ .onRequest('session/request_permission', ({ params, signal }) => conversation.afk ? permissionAllowed(params) : this.ask(conversation, 'session/request_permission', params, false, signal))
696
+ .onRequest('elicitation/create', ({ params, signal }) => conversation.afk ? formAnswered(route.kind, params) : this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
697
+ .onRequest('_x.ai/exit_plan_mode', GROK_PLAN, async ({ params, signal }) => conversation.afk ? PLAN_APPROVED : grokPlanAnswer(await this.askForm(conversation, grokPlanForm(params), signal)))
698
+ .onRequest('_x.ai/ask_user_question', GROK_QUESTION, async ({ params, signal }) => conversation.afk ? grokQuestionAnswered(params) : grokQuestionAnswer(await this.askForm(conversation, grokQuestionForm(params), signal)));
621
699
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
622
700
  const bridging = this.bridged(conversation);
623
701
  const bridge = await step(unbridged, bridging);
@@ -626,33 +704,33 @@ export class Conversations {
626
704
  throw new Error(KILLED);
627
705
  }
628
706
  conversation.opening = bridge;
629
- const work = workFor(route.kind, route.working_directory, () => this.kit.changed());
707
+ const work = workFor(route.kind, route.working_directory, () => this.kit.changed(), (message) => this.tapped(conversation, reader, message));
630
708
  const scope = new Scope(marker(bridge), randomUUID(), cli);
631
709
  let adapter = null;
632
710
  try {
633
711
  bridged(bridge);
634
712
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
635
713
  const streamed = await step(NO_CONNECTION, work.open(cli));
714
+ if (this.stopping)
715
+ throw new Error(KILLED);
636
716
  adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
637
717
  work.read(message);
638
- this.read(conversation, reader, message);
718
+ return this.read(conversation, reader, work, message);
639
719
  }, { ...bridge.env, ...streamed }, undefined, scope));
640
720
  void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
641
721
  const agent = adapter.connection.agent;
642
722
  const cwd = route.working_directory;
643
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
723
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
644
724
  const resumed = sessionId === null ? null : await this.resume(conversation, route.kind, adapter, { sessionId, cwd, mcpServers: [], _meta }, empty);
645
725
  const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
646
726
  reader.session = opened.sessionId;
647
- if (opened.sessionId !== sessionId && CLIS[route.kind].renames) {
648
- const prompt = [{ type: 'text', text: `/rename ${conversation.id}` }];
649
- await step(unopened(NO_SESSION), agent.request('session/prompt', { sessionId: opened.sessionId, prompt }));
650
- }
727
+ if (opened.sessionId !== conversation.session)
728
+ conversation.state = QUIET;
651
729
  const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
652
730
  const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
653
731
  void work.settled().then(() => scope.record());
654
732
  conversation.running = running;
655
- adapter.turn(conversation.open > 0);
733
+ adapter.turn(conversation.turns.size > 0);
656
734
  conversation.session = running.sessionId;
657
735
  conversation.options = options;
658
736
  this.facts(conversation);
@@ -719,6 +797,8 @@ export class Conversations {
719
797
  conversation.running = null;
720
798
  conversation.commands = null;
721
799
  conversation.options = null;
800
+ conversation.subagents.clear();
801
+ this.stated(conversation, { running: [] });
722
802
  for (const [id, question] of this.questions) {
723
803
  if (question.conversation === conversation)
724
804
  this.questions.delete(id);
@@ -735,6 +815,16 @@ export class Conversations {
735
815
  if (conversation.options !== null)
736
816
  this.options(conversation, conversation.options);
737
817
  }
818
+ stated(conversation, change) {
819
+ conversation.state = { ...conversation.state, ...change };
820
+ this.stateChanged(conversation, false);
821
+ }
822
+ stateChanged(conversation, again) {
823
+ const state = JSON.stringify(conversation.state);
824
+ if (!again && state === conversation.sentState)
825
+ return;
826
+ conversation.sentState = this.kit.send({ type: 'state', conversation_id: conversation.id, state: conversation.state }) ? state : null;
827
+ }
738
828
  commands(conversation, commands) {
739
829
  conversation.commands = commands;
740
830
  if (conversation.running === null)
@@ -745,11 +835,16 @@ export class Conversations {
745
835
  if (conversation.running === null)
746
836
  return;
747
837
  conversation.options = options;
748
- this.kit.send({ type: 'options', conversation_id: conversation.id, options });
838
+ this.kit.send({ type: 'options', conversation_id: conversation.id, options: options.filter((option) => option.category !== 'mode') });
839
+ const chosen = (category) => {
840
+ const value = options.find((option) => option.category === category)?.currentValue;
841
+ return value === undefined ? null : String(value);
842
+ };
843
+ this.stated(conversation, { model: chosen('model'), effort: chosen('thought_level'), mode: chosen('mode') });
749
844
  }
750
- deliver(conversation, turn, event, body) {
845
+ deliver(conversation, act, request, current) {
751
846
  this.reporting++;
752
- const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/conversations/${conversation.id}/turns/${turn.id}/${event}`, await body));
847
+ const delivered = conversation.reports.then(async () => this.kit.house.deliver(act, await request, current));
753
848
  conversation.reports = delivered
754
849
  .catch(() => undefined)
755
850
  .finally(() => {
@@ -761,22 +856,26 @@ export class Conversations {
761
856
  write(conversation, turn, operation) {
762
857
  if (turn.ended || !this.watched)
763
858
  return;
764
- this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, ...operation });
859
+ this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, operation });
765
860
  }
766
861
  replay(conversation, turn) {
767
- for (const operation of turn.parts.operations())
862
+ for (const operation of turn.content.operations())
768
863
  this.write(conversation, turn, operation);
769
864
  }
770
865
  begin(conversation) {
771
866
  const turn = new Turn((operation) => this.write(conversation, turn, operation));
772
- conversation.open++;
867
+ conversation.turns.add(turn);
773
868
  conversation.running?.adapter.turn(true);
774
- void this.deliver(conversation, turn, 'started', {}).catch(logged);
869
+ void this.deliver(conversation, 'turns/start', turnOf(conversation, turn))
870
+ .then((answer) => {
871
+ if (answer.run === true)
872
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
873
+ })
874
+ .catch(logged);
775
875
  conversation.turn = turn;
776
- if (conversation.context !== null)
777
- turn.parts.measure(conversation.context);
778
- for (const part of conversation.held.splice(0))
779
- turn.parts.start(part);
876
+ this.stated(conversation, { suggestion: null });
877
+ for (const event of conversation.reader?.began() ?? [])
878
+ this.event(conversation, event);
780
879
  this.kit.changed();
781
880
  return turn;
782
881
  }
@@ -785,23 +884,25 @@ export class Conversations {
785
884
  return;
786
885
  if (failed !== null)
787
886
  logged(new Error(`conversation ${conversation.id} turn ${turn.id} failed: ${failed.cause}`));
788
- if (conversation.turn === turn) {
789
- for (const event of conversation.running?.reader.closeTurn() ?? [])
790
- this.apply(conversation, turn, event);
791
- }
887
+ if (conversation.turn === turn)
888
+ conversation.reader?.closeTurn();
792
889
  if (notice !== null)
793
- turn.parts.start({ type: 'marker', marker: 'retry', text: notice });
890
+ turn.content.add({ type: 'notice', kind: 'error', text: notice });
794
891
  turn.ended = true;
795
- conversation.open--;
796
- conversation.running?.adapter.turn(conversation.open > 0);
892
+ conversation.turns.delete(turn);
893
+ conversation.running?.adapter.turn(conversation.turns.size > 0);
797
894
  if (conversation.turn === turn)
798
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) });
799
900
  const body = Promise.allSettled(turn.uploads).then(() => ({
800
- parts: turn.parts.saved(),
801
- context: turn.parts.context,
901
+ ...turnOf(conversation, turn),
902
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
802
903
  ...(failed === null ? {} : { failed: failed.failure }),
803
904
  }));
804
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
905
+ void this.deliver(conversation, 'turns/end', body).catch(logged);
805
906
  this.next(conversation);
806
907
  this.kit.changed();
807
908
  }
@@ -826,11 +927,11 @@ export class Conversations {
826
927
  }
827
928
  else {
828
929
  this.took(turn);
829
- if (conversation.open === 1 && conversation.running === running) {
930
+ if (conversation.turns.size === 1 && conversation.turns.has(turn) && conversation.running === running) {
830
931
  running.adapter.retire();
831
932
  this.detach(conversation, running);
832
933
  }
833
- this.end(conversation, turn, answeredWith(error));
934
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
834
935
  }
835
936
  });
836
937
  }
@@ -839,19 +940,24 @@ export class Conversations {
839
940
  this.took(turn);
840
941
  return turn;
841
942
  }
842
- ended(conversation) {
943
+ ended(conversation, stop) {
843
944
  const turn = conversation.turn;
844
945
  if (turn === null)
845
946
  return;
846
- if (!turn.prompted) {
847
- this.end(conversation, turn, null);
848
- }
849
- else {
850
- for (const event of conversation.running?.reader.closeTurn() ?? [])
851
- this.apply(conversation, turn, event);
852
- conversation.turn = null;
853
- this.kit.changed();
947
+ const held = stop !== null && !turn.steered && [...conversation.subagents].some((key) => turn.content.holds(key));
948
+ if (!turn.prompted || held) {
949
+ this.took(turn);
950
+ this.end(conversation, turn, stop === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
951
+ return;
854
952
  }
953
+ if (stop !== null)
954
+ return;
955
+ conversation.reader?.closeTurn();
956
+ conversation.turn = null;
957
+ this.kit.changed();
958
+ }
959
+ askForm(conversation, form, signal) {
960
+ return this.ask(conversation, 'elicitation/create', form, false, signal);
855
961
  }
856
962
  async ask(conversation, method, params, secret, signal) {
857
963
  const turn = this.started(conversation);
@@ -859,7 +965,8 @@ export class Conversations {
859
965
  const answered = new Promise((answer, fail) => {
860
966
  this.questions.set(interactionId, { conversation, answer: (response) => answer(response) });
861
967
  signal.addEventListener('abort', () => answer(null), { once: true });
862
- this.deliver(conversation, turn, 'interactions', {
968
+ this.deliver(conversation, 'conversations/interaction/ask', {
969
+ ...turnOf(conversation, turn),
863
970
  interaction_id: interactionId,
864
971
  request: { method, params },
865
972
  secret,
@@ -897,17 +1004,42 @@ export class Conversations {
897
1004
  if (content !== null)
898
1005
  this.questions.get(interactionId)?.answer({ action: 'accept', content });
899
1006
  }
900
- read(conversation, reader, message) {
901
- for (const event of reader.read(message))
1007
+ read(conversation, reader, work, message) {
1008
+ const events = reader.read(message);
1009
+ const apply = () => {
1010
+ for (const event of events)
1011
+ this.event(conversation, event);
1012
+ this.reportActivity(conversation);
1013
+ };
1014
+ const held = message.method === undefined || events.some((event) => event.kind === 'ended') ? work.caughtUp() : null;
1015
+ if (held === null) {
1016
+ apply();
1017
+ return null;
1018
+ }
1019
+ return held.then(apply);
1020
+ }
1021
+ tapped(conversation, reader, message) {
1022
+ for (const event of reader.tap(message))
902
1023
  this.event(conversation, event);
903
1024
  }
1025
+ reportActivity(conversation) {
1026
+ const turn = conversation.turn;
1027
+ if (turn === null || Date.now() < turn.quietUntil)
1028
+ return;
1029
+ turn.quietUntil = Infinity;
1030
+ void this.deliver(conversation, 'turns/activity/report', turnOf(conversation, turn), () => false)
1031
+ .catch(logged)
1032
+ .finally(() => {
1033
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
1034
+ });
1035
+ }
904
1036
  event(conversation, event) {
905
1037
  switch (event.kind) {
906
1038
  case 'started':
907
1039
  this.started(conversation);
908
1040
  return;
909
1041
  case 'ended':
910
- this.ended(conversation);
1042
+ this.ended(conversation, event.stop);
911
1043
  return;
912
1044
  case 'commands':
913
1045
  this.commands(conversation, event.commands);
@@ -915,20 +1047,20 @@ export class Conversations {
915
1047
  case 'options':
916
1048
  this.options(conversation, event.options);
917
1049
  return;
918
- case 'context':
919
- conversation.context = { used: event.used, window: event.window };
920
- conversation.turn?.parts.measure(conversation.context);
1050
+ case 'state':
1051
+ this.stated(conversation, event.state);
921
1052
  return;
922
- case 'subagent-done':
923
- this.subagentDone(conversation, event.id, event.result);
1053
+ case 'tokens':
1054
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
924
1055
  return;
925
- case 'marker':
926
- case 'image':
927
- if (conversation.turn !== null)
928
- break;
929
- if (event.kind === 'marker' && event.marker === 'job')
930
- conversation.held.push({ type: 'marker', marker: 'job', text: event.text });
1056
+ case 'call':
1057
+ this.called(conversation, event);
931
1058
  return;
1059
+ case 'notice':
1060
+ case 'image':
1061
+ if (conversation.turn === null)
1062
+ return;
1063
+ break;
932
1064
  }
933
1065
  this.apply(conversation, this.started(conversation), event);
934
1066
  }
@@ -940,53 +1072,42 @@ export class Conversations {
940
1072
  apply(conversation, turn, event) {
941
1073
  switch (event.kind) {
942
1074
  case 'text':
943
- case 'reasoning':
944
- turn.parts.write(event.kind, event.id, event.text);
945
- return;
946
- case 'command':
947
- turn.parts.command();
1075
+ turn.content.write(event.id, event.text);
948
1076
  return;
949
- case 'subagent': {
950
- const index = turn.parts.start({ type: 'subagent', description: event.description, status: 'running', result: null });
951
- conversation.subagents.set(event.id, { description: event.description, turn, index });
952
- return;
953
- }
954
- case 'message':
955
- turn.parts.start({ type: 'message', command: event.command, target: event.target });
956
- return;
957
- case 'marker':
958
- turn.parts.start({ type: 'marker', marker: event.marker, text: event.text });
959
- return;
960
- case 'plan':
961
- turn.parts.plan(event.entries);
1077
+ case 'notice':
1078
+ turn.content.add({ type: 'notice', kind: event.notice, text: event.text });
962
1079
  return;
963
1080
  case 'image':
964
- turn.uploads.push(this.image(conversation, turn, turn.parts.reserve(), event.data, event.mediaType));
1081
+ turn.uploads.push(this.image(conversation, turn, event.data, event.mediaType));
965
1082
  this.kit.changed();
966
1083
  return;
967
1084
  }
968
1085
  }
969
- subagentDone(conversation, id, result) {
970
- const subagent = conversation.subagents.get(id);
971
- if (subagent === undefined)
1086
+ // 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.
1087
+ called(conversation, event) {
1088
+ if (event.running === true)
1089
+ conversation.subagents.add(event.key);
1090
+ if (event.running === false)
1091
+ conversation.subagents.delete(event.key);
1092
+ const turn = conversation.turn;
1093
+ if (!event.first) {
1094
+ if (turn?.content.holds(event.key))
1095
+ turn.content.call(event.key, event.parent, event.call);
972
1096
  return;
973
- conversation.subagents.delete(id);
974
- if (subagent.turn === conversation.turn) {
975
- subagent.turn.parts.done(subagent.index, result);
1097
+ }
1098
+ if (event.parent !== null) {
1099
+ turn?.content.call(event.key, event.parent, event.call);
976
1100
  return;
977
1101
  }
978
- const part = { type: 'subagent', description: subagent.description, status: 'done', result };
979
- if (conversation.turn === null)
980
- conversation.held.push(part);
981
- else
982
- conversation.turn.parts.start(part);
1102
+ this.started(conversation).content.call(event.key, null, event.call);
983
1103
  }
984
- async image(conversation, turn, reserved, data, mediaType) {
1104
+ async image(conversation, turn, data, mediaType) {
985
1105
  const bytes = Buffer.from(data, 'base64');
986
1106
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
987
1107
  const sha256 = createHash('sha256').update(bytes).digest('hex');
988
1108
  try {
989
- const declared = (await this.deliver(conversation, turn, 'images', {
1109
+ const declared = (await this.deliver(conversation, 'turns/images/declare', {
1110
+ ...turnOf(conversation, turn),
990
1111
  name,
991
1112
  media_type: mediaType,
992
1113
  bytes: bytes.length,
@@ -998,13 +1119,13 @@ export class Conversations {
998
1119
  sha256,
999
1120
  read: (start, end) => [bytes.subarray(start, end)],
1000
1121
  send: (url, start, end, headers) => sentPart(url, bytes.subarray(start, end), headers),
1001
- finish: (upload, partSha256) => this.kit.house.deliver('/kit/uploads/finish', { upload, part_sha256: partSha256 }),
1122
+ finish: (upload, partSha256) => this.kit.house.deliver('uploads/finish', { upload, part_sha256: partSha256 }),
1002
1123
  });
1003
- turn.parts.arrive({ type: 'image', file: saved.path, name, media_type: mediaType }, reserved);
1124
+ turn.content.arrived({ type: 'image', file: saved.path, name, media_type: mediaType });
1004
1125
  }
1005
1126
  catch (error) {
1006
1127
  const cause = error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error);
1007
- turn.parts.arrive({ type: 'marker', marker: 'retry', text: `${name} was not saved: ${cause}` }, reserved);
1128
+ turn.content.arrived({ type: 'notice', kind: 'error', text: `${name} was not saved: ${cause}` });
1008
1129
  }
1009
1130
  }
1010
1131
  }