@agentshouse/kit 0.2.1-ccf188e02985d → 0.2.1-cd423aab3dbcc

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