@agentshouse/kit 0.2.1-cf110d15f69c8 → 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 (147) hide show
  1. package/README.md +38 -44
  2. package/dist/acp.js +96 -22
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +221 -65
  5. package/dist/api.js +21 -3
  6. package/dist/app-git.js +10 -26
  7. package/dist/binaries.js +60 -0
  8. package/dist/bridge.js +101 -49
  9. package/dist/building.js +50 -0
  10. package/dist/calls.js +88 -0
  11. package/dist/chunks.js +54 -0
  12. package/dist/clis.js +80 -52
  13. package/dist/connect.js +121 -0
  14. package/dist/connection.js +120 -0
  15. package/dist/content.js +106 -0
  16. package/dist/conversations.js +711 -267
  17. package/dist/copies.js +1293 -595
  18. package/dist/earlier.js +273 -0
  19. package/dist/end.js +15 -3
  20. package/dist/events.js +553 -281
  21. package/dist/files.js +206 -32
  22. package/dist/git.js +2 -70
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +123 -15
  25. package/dist/house-cli.js +282 -0
  26. package/dist/house-main.js +7 -206
  27. package/dist/instructions.js +7 -13
  28. package/dist/keys.js +238 -0
  29. package/dist/kit-cli.js +78 -0
  30. package/dist/kit-main.js +8 -22
  31. package/dist/login.js +71 -39
  32. package/dist/logout.js +2 -4
  33. package/dist/manifest.js +75 -0
  34. package/dist/mcp.js +47 -7
  35. package/dist/owner.js +46 -0
  36. package/dist/placement.js +25 -0
  37. package/dist/refusals.js +50 -23
  38. package/dist/relay.js +22 -1
  39. package/dist/resident.js +153 -53
  40. package/dist/scope.js +15 -4
  41. package/dist/scripts.js +319 -0
  42. package/dist/secret-input.js +1 -1
  43. package/dist/settings.js +247 -0
  44. package/dist/sign-in.js +66 -38
  45. package/dist/silence.js +28 -0
  46. package/dist/skills.js +49 -35
  47. package/dist/supervisor.js +163 -0
  48. package/dist/transcription.js +90 -47
  49. package/dist/update.js +119 -102
  50. package/dist/wire.js +32 -0
  51. package/dist/work.js +30 -7
  52. package/dist/workspace.js +113 -0
  53. package/package.json +25 -21
  54. package/dist/authority-main.js +0 -22
  55. package/dist/bootstrap.json +0 -24
  56. package/dist/clis-main.js +0 -23
  57. package/dist/configure-main.js +0 -6
  58. package/dist/enrol-main.js +0 -10
  59. package/dist/git-main.js +0 -153
  60. package/dist/parts.js +0 -82
  61. package/dist/service-main.js +0 -9
  62. package/dist/service.js +0 -33
  63. package/dist/stream.js +0 -74
  64. package/dist/translate.js +0 -51
  65. package/how-we-work.md +0 -23
  66. package/skills/ask-matt/LICENSE +0 -21
  67. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  68. package/skills/ask-matt/SKILL.md +0 -91
  69. package/skills/ask-matt/agents/openai.yaml +0 -4
  70. package/skills/code-review/LICENSE +0 -21
  71. package/skills/code-review/SKILL.md +0 -89
  72. package/skills/code-review/agents/openai.yaml +0 -3
  73. package/skills/codebase-design/DEEPENING.md +0 -37
  74. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  75. package/skills/codebase-design/LICENSE +0 -21
  76. package/skills/codebase-design/SKILL.md +0 -116
  77. package/skills/codebase-design/agents/openai.yaml +0 -3
  78. package/skills/diagnosing-bugs/LICENSE +0 -21
  79. package/skills/diagnosing-bugs/SKILL.md +0 -140
  80. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  81. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  82. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  83. package/skills/domain-modeling/CONTEXT-FORMAT.md +0 -60
  84. package/skills/domain-modeling/LICENSE +0 -21
  85. package/skills/domain-modeling/SKILL.md +0 -76
  86. package/skills/domain-modeling/agents/openai.yaml +0 -3
  87. package/skills/grill-me/LICENSE +0 -21
  88. package/skills/grill-me/SKILL.md +0 -8
  89. package/skills/grill-me/agents/openai.yaml +0 -4
  90. package/skills/grill-with-docs/LICENSE +0 -21
  91. package/skills/grill-with-docs/SKILL.md +0 -8
  92. package/skills/grill-with-docs/agents/openai.yaml +0 -4
  93. package/skills/grilling/LICENSE +0 -21
  94. package/skills/grilling/SKILL.md +0 -30
  95. package/skills/grilling/agents/openai.yaml +0 -3
  96. package/skills/handoff/LICENSE +0 -21
  97. package/skills/handoff/SKILL.md +0 -17
  98. package/skills/handoff/agents/openai.yaml +0 -4
  99. package/skills/implement/LICENSE +0 -21
  100. package/skills/implement/SKILL.md +0 -16
  101. package/skills/implement/agents/openai.yaml +0 -4
  102. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  103. package/skills/improve-codebase-architecture/LICENSE +0 -21
  104. package/skills/improve-codebase-architecture/SKILL.md +0 -72
  105. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -4
  106. package/skills/prototype/LICENSE +0 -21
  107. package/skills/prototype/LOGIC.md +0 -67
  108. package/skills/prototype/SKILL.md +0 -28
  109. package/skills/prototype/UI.md +0 -112
  110. package/skills/prototype/agents/openai.yaml +0 -3
  111. package/skills/research/LICENSE +0 -21
  112. package/skills/research/SKILL.md +0 -14
  113. package/skills/research/agents/openai.yaml +0 -3
  114. package/skills/resolving-merge-conflicts/LICENSE +0 -21
  115. package/skills/resolving-merge-conflicts/SKILL.md +0 -16
  116. package/skills/resolving-merge-conflicts/agents/openai.yaml +0 -3
  117. package/skills/tdd/LICENSE +0 -21
  118. package/skills/tdd/SKILL.md +0 -40
  119. package/skills/tdd/agents/openai.yaml +0 -3
  120. package/skills/tdd/mocking.md +0 -59
  121. package/skills/tdd/tests.md +0 -77
  122. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  123. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  124. package/skills/teach/LICENSE +0 -21
  125. package/skills/teach/MISSION-FORMAT.md +0 -31
  126. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  127. package/skills/teach/SKILL.md +0 -141
  128. package/skills/teach/agents/openai.yaml +0 -4
  129. package/skills/to-questionnaire/LICENSE +0 -21
  130. package/skills/to-questionnaire/SKILL.md +0 -55
  131. package/skills/to-questionnaire/agents/openai.yaml +0 -4
  132. package/skills/to-spec/LICENSE +0 -21
  133. package/skills/to-spec/SKILL.md +0 -76
  134. package/skills/to-spec/agents/openai.yaml +0 -4
  135. package/skills/to-tickets/LICENSE +0 -21
  136. package/skills/to-tickets/SKILL.md +0 -106
  137. package/skills/to-tickets/agents/openai.yaml +0 -4
  138. package/skills/wait-what/LICENSE +0 -21
  139. package/skills/wait-what/SKILL.md +0 -8
  140. package/skills/wait-what/agents/openai.yaml +0 -4
  141. package/skills/wayfinder/LICENSE +0 -21
  142. package/skills/wayfinder/SKILL.md +0 -129
  143. package/skills/wayfinder/agents/openai.yaml +0 -4
  144. package/skills/writing-for-agents/LICENSE +0 -21
  145. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  146. package/skills/writing-for-agents/SKILL.md +0 -83
  147. package/skills/writing-for-agents/agents/openai.yaml +0 -3
@@ -3,44 +3,166 @@ 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';
8
+ import { finalRefusal, HouseRefusal } from './api.js';
7
9
  import { openBridge } from './bridge.js';
8
10
  import { CLIS } from './clis.js';
9
- import { readerFor } from './events.js';
10
- import { placeFiles, uploadBytes } from './files.js';
11
+ import { Content } from './content.js';
12
+ import { answeredFailure, readerFor } from './events.js';
13
+ import { fileInfo, linkedPaths, storeRefusal, uploaded } from './files.js';
14
+ import { grokPlanAnswer, grokPlanForm, grokQuestionAnswer, grokQuestionForm } from './grok.js';
11
15
  import { agentBase } from './home.js';
12
16
  import { instructions } from './instructions.js';
13
- import { Parts } from './parts.js';
17
+ import { refusalOf } from './refusals.js';
18
+ import { relayed } from './relay.js';
14
19
  import { killMarked, Scope } from './scope.js';
15
20
  import { holdSecretInput } from './secret-input.js';
16
- import { createHowWeWork } from './skills.js';
17
21
  import { transcribe } from './transcription.js';
18
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
+ }
19
27
  const KILLED = 'the conversation was killed';
28
+ const INTERRUPTED = 'the conversation was interrupted';
29
+ const REFUSED = 'the CLI refused the prompt';
30
+ const NO_CONNECTION = "the Agent's computer could not open this conversation; try again";
31
+ const GONE = 'House no longer holds this conversation; start a new one';
32
+ const RETIRED = "this conversation's Agent is retired, so it cannot start";
33
+ const ENDED = {
34
+ conversation_not_found: GONE,
35
+ conversation_historical: RETIRED,
36
+ };
37
+ const NO_START = "the Agent's CLI did not start";
38
+ const NO_SESSION = "the Agent's CLI did not open a session";
39
+ const NO_RESUME = "the Agent's CLI could not resume this conversation";
40
+ const NOT_SIGNED_IN = "the Agent's CLI is not signed in; sign it in on the Agent's machine";
41
+ const NO_SETTINGS = "the Agent's CLI refused the Agent's model, mode or effort";
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;
63
+ class NotStarted extends Error {
64
+ }
65
+ class ResumeRefused extends NotStarted {
66
+ }
67
+ async function step(reason, work) {
68
+ try {
69
+ return await work;
70
+ }
71
+ catch (error) {
72
+ throw new NotStarted(typeof reason === 'string' ? reason : reason(error), { cause: error });
73
+ }
74
+ }
75
+ function unopened(reason) {
76
+ return (error) => (signedOut(error) ? NOT_SIGNED_IN : reason);
77
+ }
78
+ // A start-up step is shown only once it has lasted a second, so a quick start shows none of them.
79
+ const STARTING_SHOWN_AFTER_MS = 1_000;
80
+ function turnOf(conversation, turn) {
81
+ return { conversation: conversation.id, turn: turn.id };
82
+ }
83
+ function unbridged(error) {
84
+ return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
85
+ }
86
+ const GROK_PLAN = {
87
+ parse(value) {
88
+ return value;
89
+ },
90
+ };
91
+ const GROK_QUESTION = {
92
+ parse(value) {
93
+ return value;
94
+ },
95
+ };
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
+ }
20
110
  function causeOf(error) {
21
111
  return error instanceof Error ? error.message : String(error);
22
112
  }
113
+ function answeredWith(error) {
114
+ return { failure: signedOut(error) ? 'signed_out' : 'error', cause: causeOf(error) };
115
+ }
116
+ function exitedWith(running, cause) {
117
+ if (running.killed)
118
+ return { failure: 'killed', cause: KILLED };
119
+ return { failure: running.adapter.silent() ? 'silent' : 'exited', cause };
120
+ }
23
121
  function answerMessage(request, response) {
24
122
  return `The User answered a question you asked earlier.\nQuestion: ${JSON.stringify(request)}\nAnswer: ${JSON.stringify(response)}`;
25
123
  }
124
+ async function sentPart(url, bytes, headers) {
125
+ const answer = await fetch(relayed(url), { method: 'PUT', headers, body: bytes });
126
+ await answer.arrayBuffer();
127
+ if (!answer.ok)
128
+ throw storeRefusal('upload', answer.status);
129
+ }
26
130
  function logged(error) {
27
131
  process.stderr.write(`kit: ${causeOf(error)}\n`);
28
132
  }
133
+ function refusal(conversation, error) {
134
+ if (conversation.kills > 0)
135
+ return KILLED;
136
+ const cause = error instanceof Error && error.cause !== undefined ? `${error.message}: ${causeOf(error.cause)}` : causeOf(error);
137
+ logged(new Error(`conversation ${conversation.id} did not start: ${cause}`));
138
+ return causeOf(error);
139
+ }
140
+ function audioOf(result) {
141
+ if (result.isError === true)
142
+ return null;
143
+ const file = fileInfo(result.content.map((content) => content.text).join('\n'));
144
+ return file?.media_type?.startsWith('audio/') === true ? file : null;
145
+ }
29
146
  function marker(bridge) {
30
147
  return `HOUSE_BRIDGE=${bridge.env.HOUSE_BRIDGE}`;
31
148
  }
149
+ function steers(adapter) {
150
+ return adapter.initialized._meta?.steering?.supported === true;
151
+ }
32
152
  class Turn {
33
153
  id = randomUUID();
34
- parts;
35
- admitted = false;
154
+ content;
36
155
  questions = 0;
37
156
  secrets = 0;
38
157
  prompted = false;
158
+ steered = false;
159
+ taken = null;
39
160
  ended = false;
161
+ quietUntil = Infinity;
40
162
  images = 0;
41
163
  uploads = [];
42
164
  constructor(emit) {
43
- this.parts = new Parts(emit);
165
+ this.content = new Content(emit);
44
166
  }
45
167
  }
46
168
  class Conversation {
@@ -49,20 +171,33 @@ class Conversation {
49
171
  session = null;
50
172
  turn = null;
51
173
  commands = null;
52
- context = null;
174
+ options = null;
175
+ exitUntold = false;
176
+ afk = false;
177
+ reader = null;
178
+ state = QUIET;
179
+ sentState = null;
180
+ tokens = null;
53
181
  leftovers = new Set();
54
182
  waiting = [];
55
183
  sending = null;
56
- subagents = new Map();
57
- held = [];
184
+ subagents = new Set();
58
185
  opening = null;
186
+ bridge = null;
187
+ launch = null;
188
+ prompted = null;
59
189
  kills = 0;
60
190
  killed = new AbortController();
61
191
  interrupts = 0;
62
192
  interrupted = new AbortController();
63
- open = 0;
193
+ turns = new Set();
64
194
  queue = Promise.resolve();
65
195
  reports = Promise.resolve();
196
+ starting = null;
197
+ preparing = null;
198
+ told = null;
199
+ untold = false;
200
+ shown = null;
66
201
  constructor(id) {
67
202
  this.id = id;
68
203
  }
@@ -78,53 +213,43 @@ function asksSecret(request) {
78
213
  export class Conversations {
79
214
  kit;
80
215
  conversations = new Map();
81
- acks = new Map();
82
216
  questions = new Map();
83
- carrying = 0;
84
217
  reporting = 0;
85
218
  watched = false;
219
+ stopping = false;
86
220
  constructor(kit) {
87
221
  this.kit = kit;
88
222
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
89
223
  setInterval(() => this.look(), 2_000);
90
224
  }
91
- input(input) {
92
- this.carrying++;
93
- const carried = this.acks.get(input.input_id) ??
94
- (() => {
95
- const conversation = this.conversation(input.conversation_id);
96
- if (input.kind === 'kill') {
97
- conversation.kills++;
98
- conversation.killed.abort(new Error(KILLED));
99
- for (const waiting of conversation.waiting.splice(0))
100
- waiting.settle({ refused: KILLED });
101
- this.halt(conversation);
102
- }
103
- if (input.kind === 'interrupt') {
104
- conversation.interrupts++;
105
- conversation.interrupted.abort();
106
- }
107
- const handled = conversation.queue.then(() => this.carry(conversation, input));
108
- conversation.queue = handled.catch(() => undefined);
109
- const work = handled.then(({ ack }) => ack);
110
- this.acks.set(input.input_id, work);
111
- return work;
112
- })();
113
- carried
114
- .then((body) => this.kit.house.deliver(`/kit/inputs/${input.input_id}/ack`, body))
115
- .catch(logged)
116
- .finally(() => {
117
- this.carrying--;
118
- this.kit.changed();
225
+ call(call) {
226
+ void this.kit.calls.carry(call.input_id, () => {
227
+ const conversation = this.conversation(call.conversation_id);
228
+ if (call.kind === 'open' || call.kind === 'message')
229
+ conversation.afk = call.afk === true;
230
+ if (call.kind === 'kill') {
231
+ conversation.kills++;
232
+ conversation.killed.abort(new Error(KILLED));
233
+ for (const waiting of conversation.waiting.splice(0))
234
+ waiting.settle({ refused: KILLED });
235
+ this.halt(conversation);
236
+ }
237
+ if (call.kind === 'interrupt') {
238
+ conversation.interrupts++;
239
+ conversation.interrupted.abort();
240
+ }
241
+ const handled = conversation.queue.then(() => this.carry(conversation, call));
242
+ conversation.queue = handled.catch(() => undefined);
243
+ return handled.then(async ({ result }) => ({ result: await result }));
119
244
  });
120
245
  }
121
246
  idle() {
122
- if (this.carrying > 0 || this.reporting > 0)
247
+ if (this.reporting > 0)
123
248
  return false;
124
249
  for (const conversation of this.conversations.values()) {
125
250
  const turn = conversation.turn;
126
251
  const asking = turn !== null && turn.questions > 0 && turn.secrets === 0;
127
- if (conversation.open > (asking ? 1 : 0))
252
+ if (conversation.turns.size > (asking ? 1 : 0))
128
253
  return false;
129
254
  }
130
255
  const conversations = [...this.conversations.values()];
@@ -133,7 +258,10 @@ export class Conversations {
133
258
  return !conversations.some((conversation) => conversation.running?.scope.working() || [...conversation.leftovers].some((scope) => scope.working()));
134
259
  }
135
260
  quiet() {
136
- return this.idle() && [...this.conversations.values()].every((conversation) => conversation.open === 0);
261
+ return this.idle() && !this.turnOpen();
262
+ }
263
+ turnOpen() {
264
+ return [...this.conversations.values()].some((conversation) => conversation.turns.size > 0);
137
265
  }
138
266
  look() {
139
267
  for (const conversation of this.conversations.values()) {
@@ -146,8 +274,25 @@ export class Conversations {
146
274
  }
147
275
  this.kit.changed();
148
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
+ }
149
284
  opened() {
150
285
  this.watched = false;
286
+ for (const conversation of this.conversations.values()) {
287
+ if (conversation.running !== null) {
288
+ this.facts(conversation);
289
+ this.stateChanged(conversation, true);
290
+ }
291
+ else if (conversation.exitUntold)
292
+ this.process(conversation, false);
293
+ if (conversation.untold || conversation.told !== null)
294
+ this.retell(conversation);
295
+ }
151
296
  }
152
297
  watching(watched) {
153
298
  const resend = watched && !this.watched;
@@ -167,130 +312,323 @@ export class Conversations {
167
312
  }
168
313
  return conversation;
169
314
  }
170
- async carry(conversation, input) {
171
- if (input.kind === 'open')
172
- return { ack: Promise.resolve(await this.open(conversation, input)) };
173
- if (input.kind === 'message')
174
- return this.message(conversation, input);
175
- if (input.kind === 'interrupt') {
315
+ async carry(conversation, call) {
316
+ if (call.kind === 'open')
317
+ return this.open(conversation, call);
318
+ if (call.kind === 'message')
319
+ return this.message(conversation, call);
320
+ if (call.kind === 'take_out')
321
+ return { result: Promise.resolve(this.takeOut(conversation, call.message_id)) };
322
+ await this.launched(conversation);
323
+ if (call.kind === 'interrupt') {
176
324
  if (--conversation.interrupts === 0)
177
325
  conversation.interrupted = new AbortController();
178
- await this.interrupt(conversation, String(input.turn_id));
326
+ await this.interrupt(conversation, call.turn_id);
179
327
  }
180
- if (input.kind === 'kill') {
328
+ if (call.kind === 'kill') {
181
329
  await this.kill(conversation);
182
330
  await conversation.sending;
183
331
  if (--conversation.kills === 0)
184
332
  conversation.killed = new AbortController();
185
333
  }
186
- if (input.kind === 'option')
187
- await this.option(conversation, String(input.option), input.value);
188
- if (input.kind === 'answer') {
189
- const question = this.questions.get(String(input.interaction_id));
334
+ if (call.kind === 'option')
335
+ await this.option(conversation, call);
336
+ if (call.kind === 'answer') {
337
+ const question = this.questions.get(call.interaction_id);
190
338
  if (question === undefined) {
191
- const text = answerMessage(input.request, input.response);
192
- return this.message(conversation, { ...input, text, files: [], first: false });
339
+ const text = answerMessage(call.request, call.response);
340
+ return this.message(conversation, { ...call, text, first: false, message_id: null });
193
341
  }
194
- question.answer(input.response);
342
+ question.answer(call.response);
195
343
  }
196
- return { ack: Promise.resolve({}) };
344
+ return { result: Promise.resolve({}) };
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
+ }
354
+ async open(conversation, call) {
355
+ await this.stop(conversation);
356
+ const launch = conversation.launch ??
357
+ this.launch(conversation, this.route(conversation, call.agent_id).then((route) => conversationRoute(route, call)), null, true);
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;
366
+ }
367
+ launch(conversation, route, sessionId, empty) {
368
+ let opened;
369
+ let failed;
370
+ const bridge = new Promise((resolve, reject) => {
371
+ opened = resolve;
372
+ failed = reject;
373
+ });
374
+ bridge.catch(() => undefined);
375
+ const session = this.start(conversation, route, sessionId, empty, opened);
376
+ session.catch(failed);
377
+ const launch = { bridge, session };
378
+ conversation.launch = launch;
379
+ void session
380
+ .catch(() => undefined)
381
+ .then(() => {
382
+ if (conversation.launch !== launch)
383
+ return;
384
+ conversation.launch = null;
385
+ this.closeIdleBridge(conversation);
386
+ this.next(conversation);
387
+ });
388
+ this.next(conversation);
389
+ return launch;
390
+ }
391
+ async launched(conversation) {
392
+ while (conversation.launch !== null)
393
+ await conversation.launch.session.catch(() => undefined);
394
+ }
395
+ instructed(conversation, route) {
396
+ const bridge = conversation.running === null ? conversation.launch?.bridge : Promise.resolve(conversation.running.bridge);
397
+ if (bridge === undefined)
398
+ return null;
399
+ const read = bridge.then((opened) => instructions(opened, route.base_instructions));
400
+ read.catch(() => undefined);
401
+ return read;
197
402
  }
198
- async open(conversation, input) {
199
- if (conversation.running !== null)
200
- return {};
403
+ async message(conversation, call) {
404
+ const content = [
405
+ ...(call.recent === undefined ? [] : [{ type: 'text', text: call.recent }]),
406
+ { type: 'text', text: call.text },
407
+ ];
408
+ let route;
409
+ let instructing = null;
201
410
  try {
202
- return { provider_session_id: await this.start(conversation, await this.route(conversation, input.agent_id), null) };
411
+ route = conversationRoute(await this.route(conversation, call.agent_id), call);
412
+ if (call.first === true)
413
+ instructing = this.instructed(conversation, route);
414
+ if (call.message_id !== null)
415
+ content.push(...(await this.transcribed(conversation, call.message_id, call.text)));
416
+ if (conversation.kills > 0)
417
+ throw new Error(KILLED);
203
418
  }
204
419
  catch (error) {
205
- return { refused: causeOf(error) };
420
+ this.closeIdleBridge(conversation);
421
+ this.prepares(conversation, null);
422
+ return { result: Promise.resolve({ refused: refusal(conversation, error) }) };
423
+ }
424
+ conversation.preparing = null;
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;
206
443
  }
444
+ this.ahead(conversation, waiting);
445
+ if (conversation.turns.size > 0)
446
+ await this.cancel(conversation);
207
447
  }
208
- async message(conversation, input) {
209
- const content = [{ type: 'text', text: String(input.text) }];
210
- let route;
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;
211
454
  try {
212
- route = await this.route(conversation, input.agent_id);
213
- const files = input.files;
214
- const paths = await placeFiles(this.kit.house, route.working_directory, files, conversation.killed.signal);
215
- const lines = await this.transcribed(conversation, files, paths);
216
- if (lines.length > 0)
217
- content.push({ type: 'text', text: lines.join('\n') });
218
- if (conversation.kills > 0)
219
- throw new Error(KILLED);
455
+ ({ outcome } = await running.adapter.connection.agent.request('_session/steering', {
456
+ sessionId: running.sessionId,
457
+ prompt: waiting.content,
458
+ _meta: { steering: { idleBehavior: 'promptRequired' } },
459
+ }));
220
460
  }
221
461
  catch (error) {
222
- return { ack: Promise.resolve({ refused: conversation.kills > 0 ? KILLED : causeOf(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(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 })) });
223
478
  }
224
- return {
225
- ack: new Promise((settle) => {
226
- conversation.waiting.push({ input, route, content, settle });
227
- this.next(conversation);
228
- }),
229
- };
230
479
  }
231
480
  next(conversation) {
232
- if (conversation.sending !== null || conversation.open > 0)
481
+ if (this.stopping || conversation.sending !== null || conversation.turns.size > 0)
233
482
  return;
234
483
  const waiting = conversation.waiting.shift();
235
- if (waiting === undefined)
484
+ if (waiting === undefined) {
485
+ const step = conversation.preparing ?? (conversation.launch === null ? null : 'session');
486
+ if (conversation.starting !== step)
487
+ this.starts(conversation, step);
236
488
  return;
489
+ }
237
490
  conversation.sending = this.send(conversation, waiting).finally(() => {
238
491
  conversation.sending = null;
239
492
  this.next(conversation);
240
493
  });
241
494
  }
242
495
  async send(conversation, waiting) {
243
- const { input } = waiting;
244
- let ack = {};
496
+ const { call } = waiting;
497
+ let result = {};
498
+ let started = false;
499
+ let instructing = waiting.instructing;
245
500
  const prompt = [];
246
501
  try {
247
502
  if (conversation.running === null) {
248
- const resumed = input.provider_session_id ?? conversation.session;
249
- const opened = await this.start(conversation, waiting.route, resumed);
250
- if (resumed === null)
251
- ack = { provider_session_id: opened };
503
+ this.starts(conversation, 'session');
504
+ await this.launched(conversation);
252
505
  }
253
- if (input.first === true) {
254
- prompt.push({
255
- type: 'text',
256
- text: await instructions(conversation.running.bridge, waiting.route.base_instructions, await this.kit.copies.mapping()),
257
- });
506
+ if (conversation.running === null) {
507
+ const stored = conversation.session ?? call.provider_session_id;
508
+ const empty = call.first === true && conversation.prompted !== stored;
509
+ const launch = this.launch(conversation, Promise.resolve(waiting.route), stored, empty);
510
+ if (call.first === true)
511
+ instructing = this.instructed(conversation, waiting.route);
512
+ started = (await launch.session) !== stored;
513
+ }
514
+ const session = conversation.running.sessionId;
515
+ if (started || (call.first === true && session !== call.provider_session_id)) {
516
+ result = { provider_session_id: session };
517
+ }
518
+ if (call.first === true) {
519
+ prompt.push({ type: 'text', text: await (instructing ?? this.instructed(conversation, waiting.route)) });
258
520
  }
259
521
  if (conversation.kills > 0)
260
522
  throw new Error(KILLED);
261
523
  }
262
524
  catch (error) {
263
- if ('provider_session_id' in ack) {
525
+ this.starts(conversation, null);
526
+ if (started) {
264
527
  conversation.session = null;
265
528
  await this.kill(conversation);
266
529
  }
267
- waiting.settle({ refused: conversation.kills > 0 ? KILLED : causeOf(error) });
530
+ const refused = refusal(conversation, error);
531
+ const resumeRefused = call.kind === 'message' && conversation.kills === 0 && error instanceof ResumeRefused;
532
+ waiting.settle(resumeRefused ? { refused, resume_refused: true } : { refused });
268
533
  return;
269
534
  }
270
- this.prompt(conversation, [...prompt, ...waiting.content]);
271
- waiting.settle(ack);
535
+ this.starts(conversation, null);
536
+ this.prompt(conversation, [...prompt, ...waiting.content], () => this.kit.calls.keepResult(call.input_id, result));
537
+ waiting.settle(result);
272
538
  }
273
- async transcribed(conversation, files, paths) {
274
- const lines = [];
275
- for (const [index, path] of paths.entries()) {
276
- lines.push(path);
277
- if (files[index].media_type?.startsWith('audio/') !== true)
278
- continue;
279
- try {
280
- const text = await transcribe(path, AbortSignal.any([conversation.killed.signal, conversation.interrupted.signal]));
281
- if (text !== null && text !== '')
282
- lines.push(`Transcript: ${text}`);
283
- }
284
- catch (error) {
285
- if (conversation.kills > 0)
286
- throw error;
287
- logged(new Error(`${files[index].name} was not transcribed: ${causeOf(error)}`));
539
+ starts(conversation, step) {
540
+ conversation.starting = step;
541
+ if (conversation.shown !== null)
542
+ clearTimeout(conversation.shown);
543
+ conversation.shown = null;
544
+ if (step === null || conversation.told !== null) {
545
+ this.tell(conversation, step);
546
+ return;
547
+ }
548
+ conversation.shown = setTimeout(() => {
549
+ conversation.shown = null;
550
+ if (conversation.starting === step)
551
+ this.tell(conversation, step);
552
+ }, STARTING_SHOWN_AFTER_MS);
553
+ }
554
+ prepares(conversation, step) {
555
+ conversation.preparing = step;
556
+ this.next(conversation);
557
+ }
558
+ tell(conversation, step) {
559
+ if (conversation.told === step && !conversation.untold)
560
+ return;
561
+ conversation.told = step;
562
+ this.retell(conversation);
563
+ }
564
+ retell(conversation) {
565
+ conversation.untold = !this.kit.send({ type: 'starting', conversation_id: conversation.id, step: conversation.told });
566
+ }
567
+ async transcribed(conversation, messageId, text) {
568
+ const paths = linkedPaths(text);
569
+ if (paths.length === 0)
570
+ return [];
571
+ const killed = conversation.killed.signal;
572
+ const interrupted = conversation.interrupted.signal;
573
+ const transcribing = AbortSignal.any([killed, interrupted]);
574
+ let signal = killed;
575
+ const blocks = [];
576
+ try {
577
+ const bridge = await step(unbridged, unlessAborted(this.bridged(conversation), killed));
578
+ const read = async (path) => audioOf(await step(unbridged, unlessAborted(bridge.tool('info', { path }), signal)));
579
+ for (const path of paths) {
580
+ let answered = await read(path);
581
+ if (answered === null)
582
+ continue;
583
+ signal = transcribing;
584
+ this.prepares(conversation, 'transcription');
585
+ const said = await transcribe(async () => {
586
+ const address = answered ?? (await read(path));
587
+ answered = null;
588
+ if (address === null)
589
+ throw new Error(`${path} is no longer an audio file`);
590
+ return address;
591
+ }, 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));
593
+ blocks.push({ type: 'text', text: `${path}\nTranscript: ${said}` });
288
594
  }
289
595
  }
290
- return lines;
596
+ catch (error) {
597
+ if (signal === transcribing && interrupted.aborted && conversation.kills === 0)
598
+ throw new NotStarted(INTERRUPTED, { cause: error });
599
+ throw error;
600
+ }
601
+ return blocks;
602
+ }
603
+ bridged(conversation) {
604
+ if (conversation.bridge === null) {
605
+ const bridging = openBridge(this.kit.house, this.kit.copies, conversation.id, conversation.killed.signal);
606
+ conversation.bridge = bridging;
607
+ bridging.catch(() => {
608
+ if (conversation.bridge === bridging)
609
+ conversation.bridge = null;
610
+ });
611
+ }
612
+ return conversation.bridge;
613
+ }
614
+ closeBridge(conversation, bridging, bridge) {
615
+ bridge.close();
616
+ if (conversation.bridge === bridging)
617
+ conversation.bridge = null;
618
+ }
619
+ closeIdleBridge(conversation) {
620
+ const bridging = conversation.bridge;
621
+ if (bridging === null || conversation.running !== null || conversation.launch !== null)
622
+ return;
623
+ conversation.bridge = null;
624
+ void bridging.then((bridge) => bridge.close(), () => undefined);
291
625
  }
292
626
  async interrupt(conversation, turnId) {
293
- if (conversation.running === null || conversation.turn?.id !== turnId)
627
+ if ([...conversation.turns].some((turn) => turn.id === turnId))
628
+ await this.cancel(conversation);
629
+ }
630
+ async cancel(conversation) {
631
+ if (conversation.running === null)
294
632
  return;
295
633
  await conversation.running.adapter.connection.agent.notify('session/cancel', {
296
634
  sessionId: conversation.running.sessionId,
@@ -311,22 +649,38 @@ export class Conversations {
311
649
  this.halt(conversation);
312
650
  await running?.adapter.exited;
313
651
  }
314
- async option(conversation, option, value) {
652
+ async option(conversation, chosen) {
653
+ while (conversation.running === null && conversation.sending !== null)
654
+ await conversation.sending;
315
655
  const running = conversation.running;
316
656
  if (running === null)
317
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);
318
677
  try {
319
- running.reader.requested(option, value);
320
- const answered = await running.adapter.connection.agent.request('session/set_config_option', {
321
- sessionId: running.sessionId,
322
- configId: option,
323
- ...(typeof value === 'boolean' ? { type: 'boolean', value } : { value: String(value) }),
324
- });
325
- 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;
326
680
  }
327
681
  catch (error) {
328
- running.reader.refused(option);
329
- logged(error);
682
+ running.reader.refused(configId);
683
+ throw error;
330
684
  }
331
685
  }
332
686
  async route(conversation, agentId) {
@@ -342,105 +696,136 @@ export class Conversations {
342
696
  }
343
697
  return route;
344
698
  }
345
- async start(conversation, route, sessionId) {
699
+ async start(conversation, routed, sessionId, empty, bridged) {
700
+ const route = await routed;
346
701
  const reader = readerFor(route.kind);
347
702
  reader.session = sessionId;
703
+ conversation.reader = reader;
348
704
  const app = client({ name: '@agentshouse/kit' })
349
- .onRequest('session/request_permission', ({ params, signal }) => this.ask(conversation, 'session/request_permission', params, false, signal))
350
- .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), 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)));
351
709
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
352
- const bridge = await openBridge(this.kit.house, this.kit.copies, conversation.id, conversation.killed.signal);
710
+ const bridging = this.bridged(conversation);
711
+ const bridge = await step(unbridged, bridging);
353
712
  if (conversation.kills > 0) {
354
- bridge.close();
713
+ this.closeBridge(conversation, bridging, bridge);
355
714
  throw new Error(KILLED);
356
715
  }
357
716
  conversation.opening = bridge;
358
- 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));
359
718
  const scope = new Scope(marker(bridge), randomUUID(), cli);
719
+ let adapter = null;
360
720
  try {
361
- await unlessAborted(createHowWeWork(bridge), conversation.killed.signal);
721
+ bridged(bridge);
362
722
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
363
- const adapter = await startAdapter(route.kind, cli, route.working_directory, app, (message) => {
723
+ const streamed = await step(NO_CONNECTION, work.open(cli));
724
+ if (this.stopping)
725
+ throw new Error(KILLED);
726
+ adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
364
727
  work.read(message);
365
- this.read(conversation, reader, message);
366
- }, { ...bridge.env, ...(await work.open(cli)) }, undefined, scope);
367
- void adapter.exited.then(() => bridge.close());
728
+ return this.read(conversation, reader, work, message);
729
+ }, { ...bridge.env, ...streamed }, undefined, scope));
730
+ void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
368
731
  const agent = adapter.connection.agent;
369
732
  const cwd = route.working_directory;
370
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
371
- const opened = sessionId === null
372
- ? await agent.request('session/new', { cwd, mcpServers: [], _meta })
373
- : { ...(await agent.request('session/resume', { sessionId, cwd, mcpServers: [], _meta })), sessionId };
733
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
734
+ const resumed = sessionId === null ? null : await this.resume(conversation, route.kind, adapter, { sessionId, cwd, mcpServers: [], _meta }, empty);
735
+ const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
374
736
  reader.session = opened.sessionId;
375
- if (sessionId === null && CLIS[route.kind].renames) {
376
- const prompt = [{ type: 'text', text: `/rename ${conversation.id}` }];
377
- await agent.request('session/prompt', { sessionId: opened.sessionId, prompt });
378
- }
379
- const running = { adapter, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
380
- const options = await this.launchSettings(running, route, opened.configOptions ?? []);
737
+ if (opened.sessionId !== conversation.session)
738
+ conversation.state = QUIET;
739
+ const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
740
+ const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
381
741
  void work.settled().then(() => scope.record());
382
742
  conversation.running = running;
743
+ adapter.turn(conversation.turns.size > 0);
383
744
  conversation.session = running.sessionId;
384
- this.kit.send({ type: 'process', conversation_id: conversation.id, running: true });
385
- if (conversation.commands !== null)
386
- this.commands(conversation, conversation.commands);
387
- this.options(conversation, options);
388
- void adapter.exited.then((cause) => this.exited(conversation, adapter, cause));
745
+ conversation.options = options;
746
+ this.facts(conversation);
747
+ void adapter.lost.then((cause) => this.exited(conversation, running, cause));
389
748
  return running.sessionId;
390
749
  }
391
750
  catch (error) {
392
- scope.kill();
751
+ adapter?.retire();
393
752
  work.close();
394
753
  conversation.leftovers.add(scope);
395
- bridge.close();
754
+ this.closeBridge(conversation, bridging, bridge);
396
755
  throw conversation.kills > 0 ? new Error(KILLED) : error;
397
756
  }
398
757
  finally {
399
758
  conversation.opening = null;
400
759
  }
401
760
  }
761
+ async resume(conversation, kind, adapter, request, empty) {
762
+ try {
763
+ return { ...(await adapter.connection.agent.request('session/resume', request)), sessionId: request.sessionId };
764
+ }
765
+ catch (error) {
766
+ if (!empty || conversation.kills > 0 || !CLIS[kind].unknownSession(error)) {
767
+ throw signedOut(error) ? new NotStarted(NOT_SIGNED_IN, { cause: error }) : new ResumeRefused(NO_RESUME, { cause: error });
768
+ }
769
+ logged(new Error(`conversation ${conversation.id} opens a new session: ${NO_RESUME}: ${causeOf(error)}`));
770
+ return null;
771
+ }
772
+ }
402
773
  async launchSettings(running, route, offered) {
403
774
  let options = offered;
404
775
  const settings = [
405
776
  ['mode', route.mode ?? CLIS[route.kind].fullAccess],
406
777
  ['model', route.model],
407
- ['thought_level', route.effort],
778
+ [EFFORT, route.effort],
408
779
  ];
409
780
  for (const [category, value] of settings) {
410
- if (value === null)
411
- continue;
412
- const option = options.find((candidate) => candidate.category === category);
413
- running.reader.requested(option?.id ?? category, value);
414
- const answered = await running.adapter.connection.agent.request('session/set_config_option', {
415
- sessionId: running.sessionId,
416
- configId: option?.id ?? category,
417
- value,
418
- });
419
- options = answered.configOptions;
781
+ if (value !== null)
782
+ options = (await this.setOption(running, options, category, value)) ?? options;
420
783
  }
421
784
  return options;
422
785
  }
423
- exited(conversation, adapter, cause) {
424
- const running = conversation.running;
425
- if (running?.adapter !== adapter)
426
- return;
786
+ exited(conversation, running, cause) {
427
787
  this.detach(conversation, running);
428
788
  if (conversation.turn !== null) {
429
- this.end(conversation, conversation.turn, { failed: running.killed ? KILLED : cause });
789
+ this.end(conversation, conversation.turn, exitedWith(running, cause));
430
790
  }
431
791
  this.next(conversation);
432
792
  this.kit.changed();
433
793
  }
434
794
  detach(conversation, running) {
795
+ if (conversation.bridge === running.bridging)
796
+ conversation.bridge = null;
435
797
  running.work.close();
436
798
  conversation.leftovers.add(running.scope);
437
799
  conversation.running = null;
438
800
  conversation.commands = null;
801
+ conversation.options = null;
802
+ conversation.subagents.clear();
803
+ this.stated(conversation, { running: [] });
439
804
  for (const [id, question] of this.questions) {
440
805
  if (question.conversation === conversation)
441
806
  this.questions.delete(id);
442
807
  }
443
- this.kit.send({ type: 'process', conversation_id: conversation.id, running: false });
808
+ this.process(conversation, false);
809
+ }
810
+ process(conversation, running) {
811
+ conversation.exitUntold = !this.kit.send({ type: 'process', conversation_id: conversation.id, running }) && !running;
812
+ }
813
+ facts(conversation) {
814
+ this.process(conversation, true);
815
+ if (conversation.commands !== null)
816
+ this.commands(conversation, conversation.commands);
817
+ if (conversation.options !== null)
818
+ this.options(conversation, conversation.options);
819
+ }
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;
444
829
  }
445
830
  commands(conversation, commands) {
446
831
  conversation.commands = commands;
@@ -451,11 +836,17 @@ export class Conversations {
451
836
  options(conversation, options) {
452
837
  if (conversation.running === null)
453
838
  return;
454
- this.kit.send({ type: 'options', conversation_id: conversation.id, options });
839
+ conversation.options = 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') });
455
846
  }
456
- deliver(conversation, turn, event, body) {
847
+ deliver(conversation, act, request, current) {
457
848
  this.reporting++;
458
- 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));
459
850
  conversation.reports = delivered
460
851
  .catch(() => undefined)
461
852
  .finally(() => {
@@ -465,84 +856,110 @@ export class Conversations {
465
856
  return delivered;
466
857
  }
467
858
  write(conversation, turn, operation) {
468
- if (!turn.admitted || turn.ended || !this.watched)
859
+ if (turn.ended || !this.watched)
469
860
  return;
470
- 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 });
471
862
  }
472
863
  replay(conversation, turn) {
473
- for (const operation of turn.parts.operations())
864
+ for (const operation of turn.content.operations())
474
865
  this.write(conversation, turn, operation);
475
866
  }
476
867
  begin(conversation) {
477
868
  const turn = new Turn((operation) => this.write(conversation, turn, operation));
478
- conversation.open++;
479
- void this.deliver(conversation, turn, 'started', {})
480
- .then(() => {
481
- turn.admitted = true;
482
- this.replay(conversation, turn);
869
+ conversation.turns.add(turn);
870
+ conversation.running?.adapter.turn(true);
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;
483
875
  })
484
876
  .catch(logged);
485
877
  conversation.turn = turn;
486
- if (conversation.context !== null)
487
- turn.parts.measure(conversation.context);
488
- for (const part of conversation.held.splice(0))
489
- turn.parts.start(part);
878
+ this.stated(conversation, { suggestion: null });
879
+ for (const event of conversation.reader?.began() ?? [])
880
+ this.event(conversation, event);
490
881
  this.kit.changed();
491
882
  return turn;
492
883
  }
493
- end(conversation, turn, failed) {
884
+ end(conversation, turn, failed, notice = null) {
494
885
  if (turn.ended)
495
886
  return;
496
- if (conversation.turn === turn) {
497
- for (const event of conversation.running?.reader.closeTurn() ?? [])
498
- this.apply(conversation, turn, event);
499
- }
887
+ if (failed !== null)
888
+ logged(new Error(`conversation ${conversation.id} turn ${turn.id} failed: ${failed.cause}`));
889
+ if (conversation.turn === turn)
890
+ conversation.reader?.closeTurn();
891
+ if (notice !== null)
892
+ turn.content.add({ type: 'notice', kind: 'error', text: notice });
500
893
  turn.ended = true;
501
- conversation.open--;
894
+ conversation.turns.delete(turn);
895
+ conversation.running?.adapter.turn(conversation.turns.size > 0);
502
896
  if (conversation.turn === turn)
503
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) });
504
902
  const body = Promise.allSettled(turn.uploads).then(() => ({
505
- parts: turn.parts.saved(),
506
- context: turn.parts.context,
507
- ...failed,
903
+ ...turnOf(conversation, turn),
904
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
905
+ ...(failed === null ? {} : { failed: failed.failure }),
508
906
  }));
509
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
907
+ void this.deliver(conversation, 'turns/end', body).catch(logged);
510
908
  this.next(conversation);
511
909
  this.kit.changed();
512
910
  }
513
- prompt(conversation, prompt) {
911
+ prompt(conversation, prompt, taken) {
514
912
  const running = conversation.running;
515
913
  const turn = this.begin(conversation);
516
914
  turn.prompted = true;
517
- running.adapter.connection.agent.request('session/prompt', { sessionId: running.sessionId, prompt }).then(() => this.end(conversation, turn, null), async (error) => {
915
+ turn.taken = taken;
916
+ conversation.prompted = running.sessionId;
917
+ running.adapter.connection.agent.request('session/prompt', { sessionId: running.sessionId, prompt }).then((answer) => {
918
+ this.took(turn);
919
+ const notice = answeredFailure(answer);
920
+ if (notice !== null) {
921
+ this.end(conversation, turn, { failure: notice.limit ? 'limit' : 'error', cause: notice.title }, notice.title);
922
+ }
923
+ else {
924
+ this.end(conversation, turn, answer.stopReason === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
925
+ }
926
+ }, async (error) => {
518
927
  if (running.adapter.connection.signal.aborted) {
519
- this.end(conversation, turn, { failed: running.killed ? KILLED : await running.adapter.exited });
928
+ this.end(conversation, turn, exitedWith(running, await running.adapter.exited));
520
929
  }
521
930
  else {
522
- if (conversation.open === 1 && conversation.running === running) {
523
- running.scope.kill();
931
+ this.took(turn);
932
+ if (conversation.turns.size === 1 && conversation.turns.has(turn) && conversation.running === running) {
933
+ running.adapter.retire();
524
934
  this.detach(conversation, running);
525
935
  }
526
- this.end(conversation, turn, { failed: causeOf(error) });
936
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
527
937
  }
528
938
  });
529
939
  }
530
940
  started(conversation) {
531
- return conversation.turn ?? this.begin(conversation);
941
+ const turn = conversation.turn ?? this.begin(conversation);
942
+ this.took(turn);
943
+ return turn;
532
944
  }
533
- ended(conversation) {
945
+ ended(conversation, stop) {
534
946
  const turn = conversation.turn;
535
947
  if (turn === null)
536
948
  return;
537
- if (!turn.prompted) {
538
- this.end(conversation, turn, null);
539
- }
540
- else {
541
- for (const event of conversation.running?.reader.closeTurn() ?? [])
542
- this.apply(conversation, turn, event);
543
- conversation.turn = null;
544
- this.kit.changed();
949
+ const held = stop !== null && !turn.steered && [...conversation.subagents].some((key) => turn.content.holds(key));
950
+ if (!turn.prompted || held) {
951
+ this.took(turn);
952
+ this.end(conversation, turn, stop === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
953
+ return;
545
954
  }
955
+ if (stop !== null)
956
+ return;
957
+ conversation.reader?.closeTurn();
958
+ conversation.turn = null;
959
+ this.kit.changed();
960
+ }
961
+ askForm(conversation, form, signal) {
962
+ return this.ask(conversation, 'elicitation/create', form, false, signal);
546
963
  }
547
964
  async ask(conversation, method, params, secret, signal) {
548
965
  const turn = this.started(conversation);
@@ -550,7 +967,8 @@ export class Conversations {
550
967
  const answered = new Promise((answer, fail) => {
551
968
  this.questions.set(interactionId, { conversation, answer: (response) => answer(response) });
552
969
  signal.addEventListener('abort', () => answer(null), { once: true });
553
- this.deliver(conversation, turn, 'interactions', {
970
+ this.deliver(conversation, 'agent_update.conversation_ask', {
971
+ ...turnOf(conversation, turn),
554
972
  interaction_id: interactionId,
555
973
  request: { method, params },
556
974
  secret,
@@ -588,17 +1006,42 @@ export class Conversations {
588
1006
  if (content !== null)
589
1007
  this.questions.get(interactionId)?.answer({ action: 'accept', content });
590
1008
  }
591
- read(conversation, reader, message) {
592
- 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))
593
1025
  this.event(conversation, event);
594
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
+ }
595
1038
  event(conversation, event) {
596
1039
  switch (event.kind) {
597
1040
  case 'started':
598
1041
  this.started(conversation);
599
1042
  return;
600
1043
  case 'ended':
601
- this.ended(conversation);
1044
+ this.ended(conversation, event.stop);
602
1045
  return;
603
1046
  case 'commands':
604
1047
  this.commands(conversation, event.commands);
@@ -606,84 +1049,85 @@ export class Conversations {
606
1049
  case 'options':
607
1050
  this.options(conversation, event.options);
608
1051
  return;
609
- case 'context':
610
- conversation.context = { used: event.used, window: event.window };
611
- conversation.turn?.parts.measure(conversation.context);
1052
+ case 'state':
1053
+ this.stated(conversation, event.state);
612
1054
  return;
613
- case 'subagent-done':
614
- this.subagentDone(conversation, event.id, event.result);
1055
+ case 'tokens':
1056
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
615
1057
  return;
616
- case 'marker':
617
- case 'image':
618
- if (conversation.turn !== null)
619
- break;
620
- if (event.kind === 'marker' && event.marker === 'job')
621
- conversation.held.push({ type: 'marker', marker: 'job', text: event.text });
1058
+ case 'call':
1059
+ this.called(conversation, event);
622
1060
  return;
1061
+ case 'notice':
1062
+ case 'image':
1063
+ if (conversation.turn === null)
1064
+ return;
1065
+ break;
623
1066
  }
624
1067
  this.apply(conversation, this.started(conversation), event);
625
1068
  }
1069
+ took(turn) {
1070
+ const taken = turn.taken;
1071
+ turn.taken = null;
1072
+ taken?.();
1073
+ }
626
1074
  apply(conversation, turn, event) {
627
1075
  switch (event.kind) {
628
1076
  case 'text':
629
- case 'reasoning':
630
- turn.parts.write(event.kind, event.id, event.text);
631
- return;
632
- case 'command':
633
- turn.parts.command();
1077
+ turn.content.write(event.id, event.text);
634
1078
  return;
635
- case 'subagent': {
636
- const index = turn.parts.start({ type: 'subagent', description: event.description, status: 'running', result: null });
637
- conversation.subagents.set(event.id, { description: event.description, turn, index });
638
- return;
639
- }
640
- case 'message':
641
- turn.parts.start({ type: 'message', command: event.command, target: event.target });
642
- return;
643
- case 'marker':
644
- turn.parts.start({ type: 'marker', marker: event.marker, text: event.text });
645
- return;
646
- case 'plan':
647
- turn.parts.plan(event.entries);
1079
+ case 'notice':
1080
+ turn.content.add({ type: 'notice', kind: event.notice, text: event.text });
648
1081
  return;
649
1082
  case 'image':
650
- 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));
651
1084
  this.kit.changed();
652
1085
  return;
653
1086
  }
654
1087
  }
655
- subagentDone(conversation, id, result) {
656
- const subagent = conversation.subagents.get(id);
657
- if (subagent === undefined)
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);
658
1098
  return;
659
- conversation.subagents.delete(id);
660
- if (subagent.turn === conversation.turn) {
661
- subagent.turn.parts.done(subagent.index, result);
1099
+ }
1100
+ if (event.parent !== null) {
1101
+ turn?.content.call(event.key, event.parent, event.call);
662
1102
  return;
663
1103
  }
664
- const part = { type: 'subagent', description: subagent.description, status: 'done', result };
665
- if (conversation.turn === null)
666
- conversation.held.push(part);
667
- else
668
- conversation.turn.parts.start(part);
1104
+ this.started(conversation).content.call(event.key, null, event.call);
669
1105
  }
670
- async image(conversation, turn, reserved, data, mediaType) {
1106
+ async image(conversation, turn, data, mediaType) {
671
1107
  const bytes = Buffer.from(data, 'base64');
672
1108
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
1109
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
673
1110
  try {
674
- const declared = (await this.deliver(conversation, turn, 'images', {
1111
+ const declared = (await this.deliver(conversation, 'turns/images/declare', {
1112
+ ...turnOf(conversation, turn),
675
1113
  name,
676
1114
  media_type: mediaType,
677
1115
  bytes: bytes.length,
678
- sha256: createHash('sha256').update(bytes).digest('hex'),
1116
+ sha256,
679
1117
  }));
680
- const saved = declared.upload === undefined ? declared : await uploadBytes(declared.upload, bytes);
681
- if (saved.save.status !== 'saved')
682
- throw new Error(saved.save.failure ?? saved.save.status);
683
- turn.parts.arrive({ type: 'image', file: saved.version, name, media_type: mediaType }, reserved);
1118
+ const saved = await uploaded(declared.upload, {
1119
+ name,
1120
+ bytes: bytes.length,
1121
+ sha256,
1122
+ read: (start, end) => [bytes.subarray(start, end)],
1123
+ send: (url, start, end, headers) => sentPart(url, bytes.subarray(start, end), headers),
1124
+ finish: (upload, partSha256) => this.kit.house.deliver('uploads/finish', { upload, part_sha256: partSha256 }),
1125
+ });
1126
+ turn.content.arrived({ type: 'image', file: saved.path, name, media_type: mediaType });
684
1127
  }
685
1128
  catch (error) {
686
- turn.parts.arrive({ type: 'marker', marker: 'retry', text: `${name} was not saved: ${causeOf(error)}` }, reserved);
1129
+ const cause = error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error);
1130
+ turn.content.arrived({ type: 'notice', kind: 'error', text: `${name} was not saved: ${cause}` });
687
1131
  }
688
1132
  }
689
1133
  }