@agentshouse/kit 0.2.1-cf6a92e13f031 → 0.2.1-cfbadfb5b5e28

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 (48) hide show
  1. package/README.md +14 -15
  2. package/dist/acp.js +58 -7
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +58 -32
  5. package/dist/authority-main.js +3 -3
  6. package/dist/bridge.js +4 -4
  7. package/dist/building.js +50 -0
  8. package/dist/calls.js +12 -4
  9. package/dist/chunks.js +49 -0
  10. package/dist/clis.js +41 -42
  11. package/dist/connection.js +27 -33
  12. package/dist/content.js +63 -0
  13. package/dist/conversations.js +348 -126
  14. package/dist/copies.js +294 -148
  15. package/dist/end.js +8 -2
  16. package/dist/events.js +742 -210
  17. package/dist/files.js +35 -19
  18. package/dist/git.js +46 -12
  19. package/dist/grok.js +39 -0
  20. package/dist/home.js +0 -7
  21. package/dist/house-cli.js +26 -13
  22. package/dist/house-main.js +3 -3
  23. package/dist/instructions.js +5 -7
  24. package/dist/kit-cli.js +3 -6
  25. package/dist/kit-main.js +3 -3
  26. package/dist/login.js +5 -3
  27. package/dist/logout.js +1 -1
  28. package/dist/mcp.js +2 -0
  29. package/dist/placement.js +10 -18
  30. package/dist/relay.js +21 -0
  31. package/dist/resident.js +47 -32
  32. package/dist/scope.js +12 -4
  33. package/dist/scripts.js +255 -0
  34. package/dist/secret-input.js +1 -1
  35. package/dist/sign-in.js +3 -2
  36. package/dist/silence.js +28 -0
  37. package/dist/skills.js +38 -12
  38. package/dist/transcription.js +37 -25
  39. package/dist/translate.js +18 -9
  40. package/dist/update.js +109 -120
  41. package/dist/wire.js +23 -5
  42. package/dist/work.js +9 -2
  43. package/package.json +18 -17
  44. package/dist/bootstrap.json +0 -24
  45. package/dist/chatgpt.js +0 -32
  46. package/dist/clis-main.js +0 -23
  47. package/dist/parts.js +0 -82
  48. package/dist/web-wizard.js +0 -100
@@ -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
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';
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';
@@ -34,6 +35,27 @@ const NO_SESSION = "the Agent's CLI did not open a session";
34
35
  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";
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 {
@@ -46,9 +68,6 @@ async function step(reason, work) {
46
68
  throw new NotStarted(typeof reason === 'string' ? reason : reason(error), { cause: error });
47
69
  }
48
70
  }
49
- function signedOut(error) {
50
- return typeof error === 'object' && error !== null && error.code === SIGNED_OUT;
51
- }
52
71
  function unopened(reason) {
53
72
  return (error) => (signedOut(error) ? NOT_SIGNED_IN : reason);
54
73
  }
@@ -57,15 +76,34 @@ const STARTING_SHOWN_AFTER_MS = 1_000;
57
76
  function unbridged(error) {
58
77
  return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
59
78
  }
60
- const EXIT_PLAN_MODE = {
79
+ const GROK_PLAN = {
80
+ parse(value) {
81
+ return value;
82
+ },
83
+ };
84
+ const GROK_QUESTION = {
61
85
  parse(value) {
62
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
63
- throw new Error('_x.ai/exit_plan_mode needs an object');
64
- }
65
86
  return value;
66
87
  },
67
88
  };
68
- export const CONVERSATION_METHODS = new Set(['open', 'message', 'interrupt', 'kill', '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
+ }
69
107
  function causeOf(error) {
70
108
  return error instanceof Error ? error.message : String(error);
71
109
  }
@@ -73,13 +111,15 @@ function answeredWith(error) {
73
111
  return { failure: signedOut(error) ? 'signed_out' : 'error', cause: causeOf(error) };
74
112
  }
75
113
  function exitedWith(running, cause) {
76
- return running.killed ? { failure: 'killed', cause: KILLED } : { failure: 'exited', cause };
114
+ if (running.killed)
115
+ return { failure: 'killed', cause: KILLED };
116
+ return { failure: running.adapter.silent() ? 'silent' : 'exited', cause };
77
117
  }
78
118
  function answerMessage(request, response) {
79
119
  return `The User answered a question you asked earlier.\nQuestion: ${JSON.stringify(request)}\nAnswer: ${JSON.stringify(response)}`;
80
120
  }
81
- async function sentPart(url, bytes) {
82
- const answer = await fetch(relayed(url), { method: 'PUT', body: bytes });
121
+ async function sentPart(url, bytes, headers) {
122
+ const answer = await fetch(relayed(url), { method: 'PUT', headers, body: bytes });
83
123
  await answer.arrayBuffer();
84
124
  if (!answer.ok)
85
125
  throw storeRefusal('upload', answer.status);
@@ -103,18 +143,23 @@ function audioOf(result) {
103
143
  function marker(bridge) {
104
144
  return `HOUSE_BRIDGE=${bridge.env.HOUSE_BRIDGE}`;
105
145
  }
146
+ function steers(adapter) {
147
+ return adapter.initialized._meta?.steering?.supported === true;
148
+ }
106
149
  class Turn {
107
150
  id = randomUUID();
108
- parts;
151
+ content;
109
152
  questions = 0;
110
153
  secrets = 0;
111
154
  prompted = false;
155
+ steered = false;
112
156
  taken = null;
113
157
  ended = false;
158
+ quietUntil = Infinity;
114
159
  images = 0;
115
160
  uploads = [];
116
161
  constructor(emit) {
117
- this.parts = new Parts(emit);
162
+ this.content = new Content(emit);
118
163
  }
119
164
  }
120
165
  class Conversation {
@@ -125,11 +170,16 @@ class Conversation {
125
170
  commands = null;
126
171
  options = null;
127
172
  exitUntold = false;
128
- context = null;
173
+ afk = false;
174
+ reader = null;
175
+ state = QUIET;
176
+ sentState = null;
177
+ tokens = null;
129
178
  leftovers = new Set();
130
179
  waiting = [];
180
+ done = false;
131
181
  sending = null;
132
- subagents = new Map();
182
+ work = new Map();
133
183
  held = [];
134
184
  opening = null;
135
185
  bridge = null;
@@ -139,7 +189,7 @@ class Conversation {
139
189
  killed = new AbortController();
140
190
  interrupts = 0;
141
191
  interrupted = new AbortController();
142
- open = 0;
192
+ turns = new Set();
143
193
  queue = Promise.resolve();
144
194
  reports = Promise.resolve();
145
195
  starting = null;
@@ -165,6 +215,7 @@ export class Conversations {
165
215
  questions = new Map();
166
216
  reporting = 0;
167
217
  watched = false;
218
+ stopping = false;
168
219
  constructor(kit) {
169
220
  this.kit = kit;
170
221
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
@@ -173,6 +224,8 @@ export class Conversations {
173
224
  call(call) {
174
225
  void this.kit.calls.carry(call.input_id, () => {
175
226
  const conversation = this.conversation(call.conversation_id);
227
+ if (call.kind === 'open' || call.kind === 'message')
228
+ conversation.afk = call.afk === true;
176
229
  if (call.kind === 'kill') {
177
230
  conversation.kills++;
178
231
  conversation.killed.abort(new Error(KILLED));
@@ -195,7 +248,7 @@ export class Conversations {
195
248
  for (const conversation of this.conversations.values()) {
196
249
  const turn = conversation.turn;
197
250
  const asking = turn !== null && turn.questions > 0 && turn.secrets === 0;
198
- if (conversation.open > (asking ? 1 : 0))
251
+ if (conversation.turns.size > (asking ? 1 : 0))
199
252
  return false;
200
253
  }
201
254
  const conversations = [...this.conversations.values()];
@@ -204,7 +257,7 @@ export class Conversations {
204
257
  return !conversations.some((conversation) => conversation.running?.scope.working() || [...conversation.leftovers].some((scope) => scope.working()));
205
258
  }
206
259
  quiet() {
207
- return this.idle() && [...this.conversations.values()].every((conversation) => conversation.open === 0);
260
+ return this.idle() && [...this.conversations.values()].every((conversation) => conversation.turns.size === 0);
208
261
  }
209
262
  look() {
210
263
  for (const conversation of this.conversations.values()) {
@@ -217,11 +270,20 @@ export class Conversations {
217
270
  }
218
271
  this.kit.changed();
219
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
+ }
220
280
  opened() {
221
281
  this.watched = false;
222
282
  for (const conversation of this.conversations.values()) {
223
- if (conversation.running !== null)
283
+ if (conversation.running !== null) {
224
284
  this.facts(conversation);
285
+ this.stateChanged(conversation, true);
286
+ }
225
287
  else if (conversation.exitUntold)
226
288
  this.process(conversation, false);
227
289
  if (conversation.untold || conversation.told !== null)
@@ -248,9 +310,16 @@ export class Conversations {
248
310
  }
249
311
  async carry(conversation, call) {
250
312
  if (call.kind === 'open')
251
- return { result: this.open(conversation, call) };
313
+ return this.open(conversation, call);
252
314
  if (call.kind === 'message')
253
315
  return this.message(conversation, call);
316
+ if (call.kind === 'done') {
317
+ conversation.done = true;
318
+ this.next(conversation);
319
+ return { result: Promise.resolve({}) };
320
+ }
321
+ if (call.kind === 'take_out')
322
+ return { result: Promise.resolve(this.takeOut(conversation, String(call.message_id))) };
254
323
  await this.launched(conversation);
255
324
  if (call.kind === 'interrupt') {
256
325
  if (--conversation.interrupts === 0)
@@ -275,11 +344,25 @@ export class Conversations {
275
344
  }
276
345
  return { result: Promise.resolve({}) };
277
346
  }
278
- open(conversation, call) {
279
- if (conversation.running !== null)
280
- return Promise.resolve({});
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
+ }
355
+ async open(conversation, call) {
356
+ await this.stop(conversation);
281
357
  const launch = conversation.launch ?? this.launch(conversation, this.route(conversation, call.agent_id), null, true);
282
- return launch.session.then((session) => ({ provider_session_id: session }), (error) => ({ refused: refusal(conversation, error) }));
358
+ return {
359
+ result: launch.session.then((session) => ({ provider_session_id: session }), (error) => ({ refused: refusal(conversation, error) })),
360
+ };
361
+ }
362
+ async stop(conversation) {
363
+ const running = conversation.running;
364
+ running?.scope.kill();
365
+ await running?.adapter.exited;
283
366
  }
284
367
  launch(conversation, route, sessionId, empty) {
285
368
  let opened;
@@ -313,12 +396,15 @@ export class Conversations {
313
396
  const bridge = conversation.running === null ? conversation.launch?.bridge : Promise.resolve(conversation.running.bridge);
314
397
  if (bridge === undefined)
315
398
  return null;
316
- 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));
317
400
  read.catch(() => undefined);
318
401
  return read;
319
402
  }
320
403
  async message(conversation, call) {
321
- const content = [{ type: 'text', text: String(call.text) }];
404
+ const content = [
405
+ ...(typeof call.recent === 'string' ? [{ type: 'text', text: call.recent }] : []),
406
+ { type: 'text', text: String(call.text) },
407
+ ];
322
408
  let route;
323
409
  let instructing = null;
324
410
  try {
@@ -336,21 +422,71 @@ export class Conversations {
336
422
  return { result: Promise.resolve({ refused: refusal(conversation, error) }) };
337
423
  }
338
424
  conversation.preparing = null;
339
- return {
340
- result: new Promise((settle) => {
341
- conversation.waiting.push({ call, route, content, instructing, settle });
342
- this.next(conversation);
343
- }),
344
- };
425
+ const { promise, resolve: settle } = Promise.withResolvers();
426
+ const waiting = { call, route, content, instructing, settle };
427
+ if (call.at_once === true && conversation.turns.size > 0)
428
+ await this.atOnce(conversation, waiting);
429
+ else
430
+ conversation.waiting.push(waiting);
431
+ this.next(conversation);
432
+ return { result: promise };
433
+ }
434
+ async atOnce(conversation, waiting) {
435
+ while (conversation.sending !== null)
436
+ await conversation.sending;
437
+ const running = conversation.running;
438
+ if (running !== null && conversation.turns.size > 0 && steers(running.adapter)) {
439
+ conversation.sending = this.steer(conversation, running, waiting);
440
+ await conversation.sending;
441
+ conversation.sending = null;
442
+ return;
443
+ }
444
+ this.ahead(conversation, waiting);
445
+ if (conversation.turns.size > 0)
446
+ await this.cancel(conversation);
447
+ }
448
+ ahead(conversation, waiting) {
449
+ const behind = conversation.waiting.findIndex((held) => held.call.at_once !== true);
450
+ conversation.waiting.splice(behind === -1 ? conversation.waiting.length : behind, 0, waiting);
451
+ }
452
+ async steer(conversation, running, waiting) {
453
+ let outcome;
454
+ try {
455
+ ({ outcome } = await running.adapter.connection.agent.request('_session/steering', {
456
+ sessionId: running.sessionId,
457
+ prompt: waiting.content,
458
+ _meta: { steering: { idleBehavior: 'promptRequired' } },
459
+ }));
460
+ }
461
+ catch (error) {
462
+ outcome = error;
463
+ }
464
+ if (outcome === 'promptRequired') {
465
+ this.ahead(conversation, waiting);
466
+ }
467
+ else if (outcome === 'injected' || outcome === 'startedNewTurn') {
468
+ if (outcome === 'injected') {
469
+ for (const turn of conversation.turns)
470
+ turn.steered ||= turn.prompted;
471
+ }
472
+ this.kit.calls.keepResult(String(waiting.call.input_id), {});
473
+ waiting.settle({});
474
+ }
475
+ else {
476
+ const cause = outcome instanceof Error ? outcome : new Error(`the CLI answered ${JSON.stringify(outcome)}`);
477
+ waiting.settle({ refused: refusal(conversation, new NotStarted(UNSTEERED, { cause })) });
478
+ }
345
479
  }
346
480
  next(conversation) {
347
- if (conversation.sending !== null || conversation.open > 0)
481
+ if (this.stopping || conversation.sending !== null || conversation.turns.size > 0)
348
482
  return;
349
483
  const waiting = conversation.waiting.shift();
350
484
  if (waiting === undefined) {
351
485
  const step = conversation.preparing ?? (conversation.launch === null ? null : 'session');
352
486
  if (conversation.starting !== step)
353
487
  this.starts(conversation, step);
488
+ if (conversation.done && conversation.launch === null)
489
+ void this.stop(conversation).catch(logged);
354
490
  return;
355
491
  }
356
492
  conversation.sending = this.send(conversation, waiting).finally(() => {
@@ -455,8 +591,7 @@ export class Conversations {
455
591
  throw new Error(`${path} is no longer an audio file`);
456
592
  return address;
457
593
  }, signal);
458
- const transcript = `/kit/conversations/${conversation.id}/messages/${messageId}/transcripts`;
459
- 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));
460
595
  blocks.push({ type: 'text', text: `${path}\nTranscript: ${said}` });
461
596
  }
462
597
  }
@@ -491,7 +626,11 @@ export class Conversations {
491
626
  void bridging.then((bridge) => bridge.close(), () => undefined);
492
627
  }
493
628
  async interrupt(conversation, turnId) {
494
- if (conversation.running === null || conversation.turn?.id !== turnId)
629
+ if ([...conversation.turns].some((turn) => turn.id === turnId))
630
+ await this.cancel(conversation);
631
+ }
632
+ async cancel(conversation) {
633
+ if (conversation.running === null)
495
634
  return;
496
635
  await conversation.running.adapter.connection.agent.notify('session/cancel', {
497
636
  sessionId: conversation.running.sessionId,
@@ -517,6 +656,9 @@ export class Conversations {
517
656
  if (running === null)
518
657
  return;
519
658
  try {
659
+ if (conversation.options?.find(({ id }) => id === option)?.category === 'mode') {
660
+ throw new Error(`conversation ${conversation.id} keeps the mode its Agent's launch settings name`);
661
+ }
520
662
  running.reader.requested(option, value);
521
663
  const answered = await running.adapter.connection.agent.request('session/set_config_option', {
522
664
  sessionId: running.sessionId,
@@ -547,10 +689,12 @@ export class Conversations {
547
689
  const route = await routed;
548
690
  const reader = readerFor(route.kind);
549
691
  reader.session = sessionId;
692
+ conversation.reader = reader;
550
693
  const app = client({ name: '@agentshouse/kit' })
551
- .onRequest('session/request_permission', ({ params, signal }) => this.ask(conversation, 'session/request_permission', params, false, signal))
552
- .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
553
- .onRequest('_x.ai/exit_plan_mode', EXIT_PLAN_MODE, ({ params, signal }) => this.ask(conversation, '_x.ai/exit_plan_mode', params, false, signal));
694
+ .onRequest('session/request_permission', ({ params, signal }) => conversation.afk ? permissionAllowed(params) : this.ask(conversation, 'session/request_permission', params, false, signal))
695
+ .onRequest('elicitation/create', ({ params, signal }) => conversation.afk ? formAnswered(route.kind, params) : this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
696
+ .onRequest('_x.ai/exit_plan_mode', GROK_PLAN, async ({ params, signal }) => conversation.afk ? PLAN_APPROVED : grokPlanAnswer(await this.askForm(conversation, grokPlanForm(params), signal)))
697
+ .onRequest('_x.ai/ask_user_question', GROK_QUESTION, async ({ params, signal }) => conversation.afk ? grokQuestionAnswered(params) : grokQuestionAnswer(await this.askForm(conversation, grokQuestionForm(params), signal)));
554
698
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
555
699
  const bridging = this.bridged(conversation);
556
700
  const bridge = await step(unbridged, bridging);
@@ -559,13 +703,15 @@ export class Conversations {
559
703
  throw new Error(KILLED);
560
704
  }
561
705
  conversation.opening = bridge;
562
- const work = workFor(route.kind, route.working_directory, () => this.kit.changed());
706
+ const work = workFor(route.kind, route.working_directory, () => this.kit.changed(), (message) => this.tapped(conversation, reader, message));
563
707
  const scope = new Scope(marker(bridge), randomUUID(), cli);
564
708
  let adapter = null;
565
709
  try {
566
710
  bridged(bridge);
567
711
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
568
712
  const streamed = await step(NO_CONNECTION, work.open(cli));
713
+ if (this.stopping)
714
+ throw new Error(KILLED);
569
715
  adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
570
716
  work.read(message);
571
717
  this.read(conversation, reader, message);
@@ -573,18 +719,17 @@ export class Conversations {
573
719
  void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
574
720
  const agent = adapter.connection.agent;
575
721
  const cwd = route.working_directory;
576
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
722
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
577
723
  const resumed = sessionId === null ? null : await this.resume(conversation, route.kind, adapter, { sessionId, cwd, mcpServers: [], _meta }, empty);
578
724
  const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
579
725
  reader.session = opened.sessionId;
580
- if (opened.sessionId !== sessionId && CLIS[route.kind].renames) {
581
- const prompt = [{ type: 'text', text: `/rename ${conversation.id}` }];
582
- await step(unopened(NO_SESSION), agent.request('session/prompt', { sessionId: opened.sessionId, prompt }));
583
- }
726
+ if (opened.sessionId !== conversation.session)
727
+ conversation.state = QUIET;
584
728
  const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
585
729
  const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
586
730
  void work.settled().then(() => scope.record());
587
731
  conversation.running = running;
732
+ adapter.turn(conversation.turns.size > 0);
588
733
  conversation.session = running.sessionId;
589
734
  conversation.options = options;
590
735
  this.facts(conversation);
@@ -651,6 +796,8 @@ export class Conversations {
651
796
  conversation.running = null;
652
797
  conversation.commands = null;
653
798
  conversation.options = null;
799
+ conversation.work.clear();
800
+ this.stated(conversation, { running: [] });
654
801
  for (const [id, question] of this.questions) {
655
802
  if (question.conversation === conversation)
656
803
  this.questions.delete(id);
@@ -667,6 +814,16 @@ export class Conversations {
667
814
  if (conversation.options !== null)
668
815
  this.options(conversation, conversation.options);
669
816
  }
817
+ stated(conversation, change) {
818
+ conversation.state = { ...conversation.state, ...change };
819
+ this.stateChanged(conversation, false);
820
+ }
821
+ stateChanged(conversation, again) {
822
+ const state = JSON.stringify(conversation.state);
823
+ if (!again && state === conversation.sentState)
824
+ return;
825
+ conversation.sentState = this.kit.send({ type: 'state', conversation_id: conversation.id, state: conversation.state }) ? state : null;
826
+ }
670
827
  commands(conversation, commands) {
671
828
  conversation.commands = commands;
672
829
  if (conversation.running === null)
@@ -677,11 +834,16 @@ export class Conversations {
677
834
  if (conversation.running === null)
678
835
  return;
679
836
  conversation.options = options;
680
- this.kit.send({ type: 'options', conversation_id: conversation.id, options });
837
+ this.kit.send({ type: 'options', conversation_id: conversation.id, options: options.filter((option) => option.category !== 'mode') });
838
+ const chosen = (category) => {
839
+ const value = options.find((option) => option.category === category)?.currentValue;
840
+ return value === undefined ? null : String(value);
841
+ };
842
+ this.stated(conversation, { model: chosen('model'), effort: chosen('thought_level'), mode: chosen('mode') });
681
843
  }
682
- deliver(conversation, turn, event, body) {
844
+ deliver(conversation, turn, act, body, current) {
683
845
  this.reporting++;
684
- const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/conversations/${conversation.id}/turns/${turn.id}/${event}`, await body));
846
+ const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/${act}`, { conversation: conversation.id, turn: turn.id, ...(await body) }, current));
685
847
  conversation.reports = delivered
686
848
  .catch(() => undefined)
687
849
  .finally(() => {
@@ -693,21 +855,28 @@ export class Conversations {
693
855
  write(conversation, turn, operation) {
694
856
  if (turn.ended || !this.watched)
695
857
  return;
696
- this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, ...operation });
858
+ this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, operation });
697
859
  }
698
860
  replay(conversation, turn) {
699
- for (const operation of turn.parts.operations())
861
+ for (const operation of turn.content.operations())
700
862
  this.write(conversation, turn, operation);
701
863
  }
702
864
  begin(conversation) {
703
865
  const turn = new Turn((operation) => this.write(conversation, turn, operation));
704
- conversation.open++;
705
- void this.deliver(conversation, turn, 'started', {}).catch(logged);
866
+ conversation.turns.add(turn);
867
+ conversation.running?.adapter.turn(true);
868
+ void this.deliver(conversation, turn, 'turns/start', {})
869
+ .then((answer) => {
870
+ if (answer.run === true)
871
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
872
+ })
873
+ .catch(logged);
706
874
  conversation.turn = turn;
707
- if (conversation.context !== null)
708
- turn.parts.measure(conversation.context);
709
- for (const part of conversation.held.splice(0))
710
- turn.parts.start(part);
875
+ this.stated(conversation, { suggestion: null });
876
+ for (const event of conversation.reader?.began() ?? [])
877
+ this.event(conversation, event);
878
+ for (const held of conversation.held.splice(0))
879
+ this.place(conversation, turn, held);
711
880
  this.kit.changed();
712
881
  return turn;
713
882
  }
@@ -717,21 +886,25 @@ export class Conversations {
717
886
  if (failed !== null)
718
887
  logged(new Error(`conversation ${conversation.id} turn ${turn.id} failed: ${failed.cause}`));
719
888
  if (conversation.turn === turn) {
720
- for (const event of conversation.running?.reader.closeTurn() ?? [])
721
- this.apply(conversation, turn, event);
889
+ for (const event of conversation.reader?.closeTurn() ?? [])
890
+ this.event(conversation, event);
722
891
  }
723
892
  if (notice !== null)
724
- turn.parts.start({ type: 'marker', marker: 'retry', text: notice });
893
+ turn.content.add(null, { type: 'notice', kind: 'error', text: notice });
725
894
  turn.ended = true;
726
- conversation.open--;
895
+ conversation.turns.delete(turn);
896
+ conversation.running?.adapter.turn(conversation.turns.size > 0);
727
897
  if (conversation.turn === turn)
728
898
  conversation.turn = null;
899
+ const tokens = conversation.tokens;
900
+ conversation.tokens = null;
901
+ if (tokens !== null)
902
+ this.stated(conversation, { tokens: addedTokens(conversation.state.tokens, tokens) });
729
903
  const body = Promise.allSettled(turn.uploads).then(() => ({
730
- parts: turn.parts.saved(),
731
- context: turn.parts.context,
904
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
732
905
  ...(failed === null ? {} : { failed: failed.failure }),
733
906
  }));
734
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
907
+ void this.deliver(conversation, turn, 'turns/end', body).catch(logged);
735
908
  this.next(conversation);
736
909
  this.kit.changed();
737
910
  }
@@ -756,11 +929,11 @@ export class Conversations {
756
929
  }
757
930
  else {
758
931
  this.took(turn);
759
- if (conversation.open === 1 && conversation.running === running) {
932
+ if (conversation.turns.size === 1 && conversation.turns.has(turn) && conversation.running === running) {
760
933
  running.adapter.retire();
761
934
  this.detach(conversation, running);
762
935
  }
763
- this.end(conversation, turn, answeredWith(error));
936
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
764
937
  }
765
938
  });
766
939
  }
@@ -769,19 +942,27 @@ export class Conversations {
769
942
  this.took(turn);
770
943
  return turn;
771
944
  }
772
- ended(conversation) {
945
+ ended(conversation, stop) {
773
946
  const turn = conversation.turn;
774
947
  if (turn === null)
775
948
  return;
776
- if (!turn.prompted) {
777
- this.end(conversation, turn, null);
778
- }
779
- else {
780
- for (const event of conversation.running?.reader.closeTurn() ?? [])
781
- this.apply(conversation, turn, event);
782
- conversation.turn = null;
783
- this.kit.changed();
949
+ const held = stop !== null &&
950
+ !turn.steered &&
951
+ [...conversation.work.values()].some((work) => work.part.type === 'subagent' && turn.content.index(work.key) !== undefined);
952
+ if (!turn.prompted || held) {
953
+ this.took(turn);
954
+ this.end(conversation, turn, stop === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
955
+ return;
784
956
  }
957
+ if (stop !== null)
958
+ return;
959
+ for (const event of conversation.reader?.closeTurn() ?? [])
960
+ this.event(conversation, event);
961
+ conversation.turn = null;
962
+ this.kit.changed();
963
+ }
964
+ askForm(conversation, form, signal) {
965
+ return this.ask(conversation, 'elicitation/create', form, false, signal);
785
966
  }
786
967
  async ask(conversation, method, params, secret, signal) {
787
968
  const turn = this.started(conversation);
@@ -789,7 +970,7 @@ export class Conversations {
789
970
  const answered = new Promise((answer, fail) => {
790
971
  this.questions.set(interactionId, { conversation, answer: (response) => answer(response) });
791
972
  signal.addEventListener('abort', () => answer(null), { once: true });
792
- this.deliver(conversation, turn, 'interactions', {
973
+ this.deliver(conversation, turn, 'conversations/interaction/ask', {
793
974
  interaction_id: interactionId,
794
975
  request: { method, params },
795
976
  secret,
@@ -830,6 +1011,22 @@ export class Conversations {
830
1011
  read(conversation, reader, message) {
831
1012
  for (const event of reader.read(message))
832
1013
  this.event(conversation, event);
1014
+ this.reportActivity(conversation);
1015
+ }
1016
+ tapped(conversation, reader, message) {
1017
+ for (const event of reader.tap(message))
1018
+ this.event(conversation, event);
1019
+ }
1020
+ reportActivity(conversation) {
1021
+ const turn = conversation.turn;
1022
+ if (turn === null || Date.now() < turn.quietUntil)
1023
+ return;
1024
+ turn.quietUntil = Infinity;
1025
+ void this.deliver(conversation, turn, 'turns/activity/report', {}, () => false)
1026
+ .catch(logged)
1027
+ .finally(() => {
1028
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
1029
+ });
833
1030
  }
834
1031
  event(conversation, event) {
835
1032
  switch (event.kind) {
@@ -837,7 +1034,7 @@ export class Conversations {
837
1034
  this.started(conversation);
838
1035
  return;
839
1036
  case 'ended':
840
- this.ended(conversation);
1037
+ this.ended(conversation, event.stop);
841
1038
  return;
842
1039
  case 'commands':
843
1040
  this.commands(conversation, event.commands);
@@ -845,20 +1042,25 @@ export class Conversations {
845
1042
  case 'options':
846
1043
  this.options(conversation, event.options);
847
1044
  return;
848
- case 'context':
849
- conversation.context = { used: event.used, window: event.window };
850
- conversation.turn?.parts.measure(conversation.context);
1045
+ case 'state':
1046
+ this.stated(conversation, event.state);
851
1047
  return;
852
- case 'subagent-done':
853
- this.subagentDone(conversation, event.id, event.result);
1048
+ case 'tokens':
1049
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
854
1050
  return;
855
- case 'marker':
856
- case 'image':
857
- if (conversation.turn !== null)
858
- break;
859
- if (event.kind === 'marker' && event.marker === 'job')
860
- conversation.held.push({ type: 'marker', marker: 'job', text: event.text });
1051
+ case 'part':
1052
+ this.keyed(conversation, event);
861
1053
  return;
1054
+ case 'notice':
1055
+ case 'image':
1056
+ if (conversation.turn === null)
1057
+ return;
1058
+ break;
1059
+ case 'text':
1060
+ case 'reasoning':
1061
+ if (event.parent !== null && conversation.turn === null)
1062
+ return;
1063
+ break;
862
1064
  }
863
1065
  this.apply(conversation, this.started(conversation), event);
864
1066
  }
@@ -870,67 +1072,87 @@ export class Conversations {
870
1072
  apply(conversation, turn, event) {
871
1073
  switch (event.kind) {
872
1074
  case 'text':
873
- case 'reasoning':
874
- turn.parts.write(event.kind, event.id, event.text);
875
- return;
876
- case 'command':
877
- turn.parts.command();
878
- return;
879
- case 'subagent': {
880
- const index = turn.parts.start({ type: 'subagent', description: event.description, status: 'running', result: null });
881
- conversation.subagents.set(event.id, { description: event.description, turn, index });
1075
+ case 'reasoning': {
1076
+ const parent = this.parentIn(conversation, turn, event.parent);
1077
+ if (parent !== undefined)
1078
+ turn.content.write(event.kind, event.id, parent, event.text);
882
1079
  return;
883
1080
  }
884
- case 'message':
885
- turn.parts.start({ type: 'message', command: event.command, target: event.target });
886
- return;
887
- case 'marker':
888
- turn.parts.start({ type: 'marker', marker: event.marker, text: event.text });
1081
+ case 'notice':
1082
+ turn.content.add(null, { type: 'notice', kind: event.notice, text: event.text });
889
1083
  return;
890
1084
  case 'plan':
891
- turn.parts.plan(event.entries);
1085
+ turn.content.plan(event.entries);
892
1086
  return;
893
1087
  case 'image':
894
- turn.uploads.push(this.image(conversation, turn, turn.parts.reserve(), event.data, event.mediaType));
1088
+ turn.uploads.push(this.image(conversation, turn, event.parent, event.data, event.mediaType));
895
1089
  this.kit.changed();
896
1090
  return;
897
1091
  }
898
1092
  }
899
- subagentDone(conversation, id, result) {
900
- const subagent = conversation.subagents.get(id);
901
- if (subagent === undefined)
902
- return;
903
- conversation.subagents.delete(id);
904
- if (subagent.turn === conversation.turn) {
905
- subagent.turn.parts.done(subagent.index, result);
1093
+ keyed(conversation, keyed) {
1094
+ const running = workRuns(keyed.part);
1095
+ const earlier = running !== null && conversation.work.has(keyed.key) && conversation.turn?.content.index(keyed.key) === undefined;
1096
+ if (running === true)
1097
+ conversation.work.set(keyed.key, keyed);
1098
+ if (running === false)
1099
+ conversation.work.delete(keyed.key);
1100
+ const turn = conversation.turn;
1101
+ if (earlier) {
1102
+ if (running)
1103
+ return;
1104
+ if (turn === null)
1105
+ conversation.held.push(keyed);
1106
+ else
1107
+ this.place(conversation, turn, keyed);
906
1108
  return;
907
1109
  }
908
- const part = { type: 'subagent', description: subagent.description, status: 'done', result };
909
- if (conversation.turn === null)
910
- conversation.held.push(part);
911
- else
912
- conversation.turn.parts.start(part);
1110
+ if (keyed.parent !== null && turn === null)
1111
+ return;
1112
+ this.place(conversation, this.started(conversation), keyed);
1113
+ }
1114
+ place(conversation, turn, keyed) {
1115
+ const parent = this.parentIn(conversation, turn, keyed.parent);
1116
+ if (parent === undefined && workRuns(keyed.part) === null)
1117
+ return;
1118
+ turn.content.put(keyed.key, parent ?? null, keyed.part);
913
1119
  }
914
- async image(conversation, turn, reserved, data, mediaType) {
1120
+ parentIn(conversation, turn, key) {
1121
+ if (key === null)
1122
+ return null;
1123
+ const index = turn.content.index(key);
1124
+ if (index !== undefined)
1125
+ return turn.content.parts[index].type === 'subagent' ? index : undefined;
1126
+ const running = conversation.work.get(key);
1127
+ if (running?.part.type !== 'subagent')
1128
+ return undefined;
1129
+ const parent = this.parentIn(conversation, turn, running.parent);
1130
+ return parent === undefined ? undefined : turn.content.put(key, parent, running.part);
1131
+ }
1132
+ async image(conversation, turn, parent, data, mediaType) {
915
1133
  const bytes = Buffer.from(data, 'base64');
916
1134
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
1135
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
917
1136
  try {
918
- const declared = (await this.deliver(conversation, turn, 'images', {
1137
+ const declared = (await this.deliver(conversation, turn, 'turns/images/declare', {
919
1138
  name,
920
1139
  media_type: mediaType,
921
1140
  bytes: bytes.length,
922
- sha256: createHash('sha256').update(bytes).digest('hex'),
1141
+ sha256,
923
1142
  }));
924
1143
  const saved = await uploaded(declared.upload, {
1144
+ name,
925
1145
  bytes: bytes.length,
926
- send: (url, start, end) => sentPart(url, bytes.subarray(start, end)),
927
- finish: (upload) => this.kit.house.deliver('/kit/uploads/finish', { upload }),
1146
+ sha256,
1147
+ read: (start, end) => [bytes.subarray(start, end)],
1148
+ send: (url, start, end, headers) => sentPart(url, bytes.subarray(start, end), headers),
1149
+ finish: (upload, partSha256) => this.kit.house.deliver('/kit/uploads/finish', { upload, part_sha256: partSha256 }),
928
1150
  });
929
- turn.parts.arrive({ type: 'image', file: saved.path, name, media_type: mediaType }, reserved);
1151
+ turn.content.arrived(this.parentIn(conversation, turn, parent) ?? null, { type: 'image', file: saved.path, name, media_type: mediaType });
930
1152
  }
931
1153
  catch (error) {
932
1154
  const cause = error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error);
933
- turn.parts.arrive({ type: 'marker', marker: 'retry', text: `${name} was not saved: ${cause}` }, reserved);
1155
+ turn.content.arrived(null, { type: 'notice', kind: 'error', text: `${name} was not saved: ${cause}` });
934
1156
  }
935
1157
  }
936
1158
  }