@agentshouse/kit 0.2.1-ccf188e02985d → 0.2.1-ccffb3f637815

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/README.md +37 -41
  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 +89 -0
  7. package/dist/bridge.js +29 -28
  8. package/dist/building.js +50 -0
  9. package/dist/calls.js +88 -0
  10. package/dist/chunks.js +49 -0
  11. package/dist/clis.js +62 -50
  12. package/dist/connect.js +108 -0
  13. package/dist/connection.js +120 -0
  14. package/dist/content.js +106 -0
  15. package/dist/conversations.js +594 -219
  16. package/dist/copies.js +772 -279
  17. package/dist/earlier.js +263 -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-main.js +24 -29
  22. package/dist/git.js +90 -15
  23. package/dist/grok.js +39 -0
  24. package/dist/home.js +80 -29
  25. package/dist/house-cli.js +155 -164
  26. package/dist/house-main.js +3 -3
  27. package/dist/instructions.js +29 -11
  28. package/dist/keys.js +238 -0
  29. package/dist/kit-cli.js +18 -8
  30. package/dist/kit-main.js +3 -3
  31. package/dist/login.js +36 -22
  32. package/dist/logout.js +2 -2
  33. package/dist/mcp.js +42 -3
  34. package/dist/old-references.js +27 -0
  35. package/dist/owner.js +46 -0
  36. package/dist/placement.js +15 -20
  37. package/dist/refusals.js +37 -21
  38. package/dist/relay.js +21 -0
  39. package/dist/resident.js +128 -82
  40. package/dist/scope.js +15 -4
  41. package/dist/scripts.js +303 -0
  42. package/dist/secret-input.js +1 -1
  43. package/dist/settings.js +188 -0
  44. package/dist/sign-in.js +67 -21
  45. package/dist/silence.js +28 -0
  46. package/dist/skills.js +42 -97
  47. package/dist/supervisor.js +163 -0
  48. package/dist/transcription.js +88 -45
  49. package/dist/translate.js +19 -18
  50. package/dist/update.js +118 -120
  51. package/dist/wire.js +30 -4
  52. package/dist/work.js +27 -2
  53. package/dist/workspace.js +103 -0
  54. package/package.json +26 -22
  55. package/dist/authority-main.js +0 -22
  56. package/dist/bootstrap.json +0 -24
  57. package/dist/chatgpt.js +0 -32
  58. package/dist/clis-main.js +0 -23
  59. package/dist/configure-main.js +0 -6
  60. package/dist/enrol-main.js +0 -10
  61. package/dist/inputs.js +0 -37
  62. package/dist/parts.js +0 -82
  63. package/dist/service-main.js +0 -9
  64. package/dist/service.js +0 -55
  65. package/dist/stream.js +0 -123
  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,27 @@
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;
22
23
  const KILLED = 'the conversation was killed';
24
+ const INTERRUPTED = 'the conversation was interrupted';
23
25
  const REFUSED = 'the CLI refused the prompt';
24
26
  const NO_CONNECTION = "the Agent's computer could not open this conversation; try again";
25
27
  const GONE = 'House no longer holds this conversation; start a new one';
@@ -31,9 +33,33 @@ const ENDED = {
31
33
  const NO_START = "the Agent's CLI did not start";
32
34
  const NO_SESSION = "the Agent's CLI did not open a session";
33
35
  const NO_RESUME = "the Agent's CLI could not resume this conversation";
36
+ const NOT_SIGNED_IN = "the Agent's CLI is not signed in; sign it in on the Agent's machine";
34
37
  const NO_SETTINGS = "the Agent's CLI refused the Agent's model, mode or effort";
38
+ const UNSTEERED = "the Agent's CLI did not take the message into its running turn";
39
+ const TAKEN_OUT = 'the message was taken out before it started';
40
+ const QUIET = {
41
+ title: null,
42
+ context: null,
43
+ limits: [],
44
+ cost: null,
45
+ tokens: null,
46
+ duration: null,
47
+ files: { count: 0, added: 0, removed: 0 },
48
+ branch: null,
49
+ worktree: null,
50
+ pull: null,
51
+ model: null,
52
+ effort: null,
53
+ mode: null,
54
+ suggestion: null,
55
+ running: [],
56
+ };
57
+ // A reader tells a working run from a stopped one by the minute, and House keeps no finer figure, so a run reports no oftener.
58
+ const ACTIVITY_REPORT_MS = 60_000;
35
59
  class NotStarted extends Error {
36
60
  }
61
+ class ResumeRefused extends NotStarted {
62
+ }
37
63
  async function step(reason, work) {
38
64
  try {
39
65
  return await work;
@@ -42,56 +68,97 @@ async function step(reason, work) {
42
68
  throw new NotStarted(typeof reason === 'string' ? reason : reason(error), { cause: error });
43
69
  }
44
70
  }
71
+ function unopened(reason) {
72
+ return (error) => (signedOut(error) ? NOT_SIGNED_IN : reason);
73
+ }
74
+ // A start-up step is shown only once it has lasted a second, so a quick start shows none of them.
75
+ const STARTING_SHOWN_AFTER_MS = 1_000;
76
+ function turnOf(conversation, turn) {
77
+ return { conversation: conversation.id, turn: turn.id };
78
+ }
45
79
  function unbridged(error) {
46
80
  return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
47
81
  }
48
- const EXIT_PLAN_MODE = {
82
+ const GROK_PLAN = {
83
+ parse(value) {
84
+ return value;
85
+ },
86
+ };
87
+ const GROK_QUESTION = {
49
88
  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
89
  return value;
54
90
  },
55
91
  };
56
- export const CONVERSATION_INPUTS = new Set(['open', 'message', 'interrupt', 'kill', 'option', 'answer']);
92
+ function addedTokens(sum, tokens) {
93
+ if (sum === null)
94
+ return tokens;
95
+ return {
96
+ input: sum.input + tokens.input,
97
+ output: sum.output + tokens.output,
98
+ cache_read: sum.cache_read + tokens.cache_read,
99
+ cache_write: sum.cache_write + tokens.cache_write,
100
+ };
101
+ }
102
+ function cliSaid(error) {
103
+ const details = error?.data?.details;
104
+ return typeof details === 'string' && details !== '' ? `${causeOf(error)}: ${details}` : causeOf(error);
105
+ }
57
106
  function causeOf(error) {
58
107
  return error instanceof Error ? error.message : String(error);
59
108
  }
60
109
  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) };
110
+ return { failure: signedOut(error) ? 'signed_out' : 'error', cause: causeOf(error) };
63
111
  }
64
112
  function exitedWith(running, cause) {
65
- return running.killed ? { failure: 'killed', cause: KILLED } : { failure: 'exited', cause };
113
+ if (running.killed)
114
+ return { failure: 'killed', cause: KILLED };
115
+ return { failure: running.adapter.silent() ? 'silent' : 'exited', cause };
66
116
  }
67
117
  function answerMessage(request, response) {
68
118
  return `The User answered a question you asked earlier.\nQuestion: ${JSON.stringify(request)}\nAnswer: ${JSON.stringify(response)}`;
69
119
  }
120
+ async function sentPart(url, bytes, headers) {
121
+ const answer = await fetch(relayed(url), { method: 'PUT', headers, body: bytes });
122
+ await answer.arrayBuffer();
123
+ if (!answer.ok)
124
+ throw storeRefusal('upload', answer.status);
125
+ }
70
126
  function logged(error) {
71
127
  process.stderr.write(`kit: ${causeOf(error)}\n`);
72
128
  }
73
129
  function refusal(conversation, error) {
74
130
  if (conversation.kills > 0)
75
131
  return KILLED;
76
- const cause = error instanceof NotStarted ? `${error.message}: ${causeOf(error.cause)}` : causeOf(error);
132
+ const cause = error instanceof Error && error.cause !== undefined ? `${error.message}: ${causeOf(error.cause)}` : causeOf(error);
77
133
  logged(new Error(`conversation ${conversation.id} did not start: ${cause}`));
78
134
  return causeOf(error);
79
135
  }
136
+ function audioOf(result) {
137
+ if (result.isError === true)
138
+ return null;
139
+ const file = fileInfo(result.content.map((content) => content.text).join('\n'));
140
+ return file?.media_type?.startsWith('audio/') === true ? file : null;
141
+ }
80
142
  function marker(bridge) {
81
143
  return `HOUSE_BRIDGE=${bridge.env.HOUSE_BRIDGE}`;
82
144
  }
145
+ function steers(adapter) {
146
+ return adapter.initialized._meta?.steering?.supported === true;
147
+ }
83
148
  class Turn {
84
149
  id = randomUUID();
85
- parts;
86
- admitted = false;
150
+ content;
87
151
  questions = 0;
88
152
  secrets = 0;
89
153
  prompted = false;
154
+ steered = false;
155
+ taken = null;
90
156
  ended = false;
157
+ quietUntil = Infinity;
91
158
  images = 0;
92
159
  uploads = [];
93
160
  constructor(emit) {
94
- this.parts = new Parts(emit);
161
+ this.content = new Content(emit);
95
162
  }
96
163
  }
97
164
  class Conversation {
@@ -100,21 +167,34 @@ class Conversation {
100
167
  session = null;
101
168
  turn = null;
102
169
  commands = null;
103
- context = null;
170
+ options = null;
171
+ exitUntold = false;
172
+ afk = false;
173
+ reader = null;
174
+ state = QUIET;
175
+ sentState = null;
176
+ tokens = null;
104
177
  leftovers = new Set();
105
178
  waiting = [];
179
+ done = false;
106
180
  sending = null;
107
- subagents = new Map();
108
- held = [];
181
+ subagents = new Set();
109
182
  opening = null;
183
+ bridge = null;
184
+ launch = null;
110
185
  prompted = null;
111
186
  kills = 0;
112
187
  killed = new AbortController();
113
188
  interrupts = 0;
114
189
  interrupted = new AbortController();
115
- open = 0;
190
+ turns = new Set();
116
191
  queue = Promise.resolve();
117
192
  reports = Promise.resolve();
193
+ starting = null;
194
+ preparing = null;
195
+ told = null;
196
+ untold = false;
197
+ shown = null;
118
198
  constructor(id) {
119
199
  this.id = id;
120
200
  }
@@ -133,28 +213,31 @@ export class Conversations {
133
213
  questions = new Map();
134
214
  reporting = 0;
135
215
  watched = false;
216
+ stopping = false;
136
217
  constructor(kit) {
137
218
  this.kit = kit;
138
219
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
139
220
  setInterval(() => this.look(), 2_000);
140
221
  }
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') {
222
+ call(call) {
223
+ void this.kit.calls.carry(call.input_id, () => {
224
+ const conversation = this.conversation(call.conversation_id);
225
+ if (call.kind === 'open' || call.kind === 'message')
226
+ conversation.afk = call.afk === true;
227
+ if (call.kind === 'kill') {
145
228
  conversation.kills++;
146
229
  conversation.killed.abort(new Error(KILLED));
147
230
  for (const waiting of conversation.waiting.splice(0))
148
231
  waiting.settle({ refused: KILLED });
149
232
  this.halt(conversation);
150
233
  }
151
- if (input.kind === 'interrupt') {
234
+ if (call.kind === 'interrupt') {
152
235
  conversation.interrupts++;
153
236
  conversation.interrupted.abort();
154
237
  }
155
- const handled = conversation.queue.then(() => this.carry(conversation, input));
238
+ const handled = conversation.queue.then(() => this.carry(conversation, call));
156
239
  conversation.queue = handled.catch(() => undefined);
157
- return handled.then(async ({ ack }) => ({ ack: await ack }));
240
+ return handled.then(async ({ result }) => ({ result: await result }));
158
241
  });
159
242
  }
160
243
  idle() {
@@ -163,7 +246,7 @@ export class Conversations {
163
246
  for (const conversation of this.conversations.values()) {
164
247
  const turn = conversation.turn;
165
248
  const asking = turn !== null && turn.questions > 0 && turn.secrets === 0;
166
- if (conversation.open > (asking ? 1 : 0))
249
+ if (conversation.turns.size > (asking ? 1 : 0))
167
250
  return false;
168
251
  }
169
252
  const conversations = [...this.conversations.values()];
@@ -172,7 +255,10 @@ export class Conversations {
172
255
  return !conversations.some((conversation) => conversation.running?.scope.working() || [...conversation.leftovers].some((scope) => scope.working()));
173
256
  }
174
257
  quiet() {
175
- return this.idle() && [...this.conversations.values()].every((conversation) => conversation.open === 0);
258
+ return this.idle() && !this.turnOpen();
259
+ }
260
+ turnOpen() {
261
+ return [...this.conversations.values()].some((conversation) => conversation.turns.size > 0);
176
262
  }
177
263
  look() {
178
264
  for (const conversation of this.conversations.values()) {
@@ -185,8 +271,25 @@ export class Conversations {
185
271
  }
186
272
  this.kit.changed();
187
273
  }
274
+ stopped() {
275
+ this.stopping = true;
276
+ for (const conversation of this.conversations.values()) {
277
+ if (conversation.running !== null)
278
+ this.process(conversation, false);
279
+ }
280
+ }
188
281
  opened() {
189
282
  this.watched = false;
283
+ for (const conversation of this.conversations.values()) {
284
+ if (conversation.running !== null) {
285
+ this.facts(conversation);
286
+ this.stateChanged(conversation, true);
287
+ }
288
+ else if (conversation.exitUntold)
289
+ this.process(conversation, false);
290
+ if (conversation.untold || conversation.told !== null)
291
+ this.retell(conversation);
292
+ }
190
293
  }
191
294
  watching(watched) {
192
295
  const resend = watched && !this.watched;
@@ -206,134 +309,329 @@ export class Conversations {
206
309
  }
207
310
  return conversation;
208
311
  }
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') {
312
+ async carry(conversation, call) {
313
+ if (call.kind === 'open')
314
+ return this.open(conversation, call);
315
+ if (call.kind === 'message')
316
+ return this.message(conversation, call);
317
+ if (call.kind === 'done') {
318
+ conversation.done = true;
319
+ this.next(conversation);
320
+ return { result: Promise.resolve({}) };
321
+ }
322
+ if (call.kind === 'take_out')
323
+ return { result: Promise.resolve(this.takeOut(conversation, call.message_id)) };
324
+ await this.launched(conversation);
325
+ if (call.kind === 'interrupt') {
215
326
  if (--conversation.interrupts === 0)
216
327
  conversation.interrupted = new AbortController();
217
- await this.interrupt(conversation, String(input.turn_id));
328
+ await this.interrupt(conversation, call.turn_id);
218
329
  }
219
- if (input.kind === 'kill') {
330
+ if (call.kind === 'kill') {
220
331
  await this.kill(conversation);
221
332
  await conversation.sending;
222
333
  if (--conversation.kills === 0)
223
334
  conversation.killed = new AbortController();
224
335
  }
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));
336
+ if (call.kind === 'option')
337
+ await this.option(conversation, call.option, call.value);
338
+ if (call.kind === 'answer') {
339
+ const question = this.questions.get(call.interaction_id);
229
340
  if (question === undefined) {
230
- const text = answerMessage(input.request, input.response);
231
- return this.message(conversation, { ...input, text, files: [], first: false });
341
+ const text = answerMessage(call.request, call.response);
342
+ return this.message(conversation, { ...call, text, first: false, message_id: null });
232
343
  }
233
- question.answer(input.response);
344
+ question.answer(call.response);
234
345
  }
235
- return { ack: Promise.resolve({}) };
346
+ return { result: Promise.resolve({}) };
236
347
  }
237
- async open(conversation, input) {
238
- if (conversation.running !== null)
239
- return {};
348
+ takeOut(conversation, messageId) {
349
+ const index = conversation.waiting.findIndex((waiting) => waiting.call.message_id === messageId);
350
+ if (index === -1)
351
+ return { started: true };
352
+ const [waiting] = conversation.waiting.splice(index, 1);
353
+ waiting.settle({ refused: TAKEN_OUT });
354
+ return {};
355
+ }
356
+ async open(conversation, call) {
357
+ await this.stop(conversation);
358
+ const launch = conversation.launch ?? this.launch(conversation, this.route(conversation, call.agent_id), null, true);
359
+ return {
360
+ result: launch.session.then((session) => ({ provider_session_id: session }), (error) => ({ refused: refusal(conversation, error) })),
361
+ };
362
+ }
363
+ async stop(conversation) {
364
+ const running = conversation.running;
365
+ running?.scope.kill();
366
+ await running?.adapter.exited;
367
+ }
368
+ launch(conversation, route, sessionId, empty) {
369
+ let opened;
370
+ let failed;
371
+ const bridge = new Promise((resolve, reject) => {
372
+ opened = resolve;
373
+ failed = reject;
374
+ });
375
+ bridge.catch(() => undefined);
376
+ const session = this.start(conversation, route, sessionId, empty, opened);
377
+ session.catch(failed);
378
+ const launch = { bridge, session };
379
+ conversation.launch = launch;
380
+ void session
381
+ .catch(() => undefined)
382
+ .then(() => {
383
+ if (conversation.launch !== launch)
384
+ return;
385
+ conversation.launch = null;
386
+ this.closeIdleBridge(conversation);
387
+ this.next(conversation);
388
+ });
389
+ this.next(conversation);
390
+ return launch;
391
+ }
392
+ async launched(conversation) {
393
+ while (conversation.launch !== null)
394
+ await conversation.launch.session.catch(() => undefined);
395
+ }
396
+ instructed(conversation, route) {
397
+ const bridge = conversation.running === null ? conversation.launch?.bridge : Promise.resolve(conversation.running.bridge);
398
+ if (bridge === undefined)
399
+ return null;
400
+ const read = bridge.then((opened) => instructions(opened, route.base_instructions));
401
+ read.catch(() => undefined);
402
+ return read;
403
+ }
404
+ async message(conversation, call) {
405
+ const content = [
406
+ ...(call.recent === undefined ? [] : [{ type: 'text', text: call.recent }]),
407
+ { type: 'text', text: call.text },
408
+ ];
409
+ let route;
410
+ let instructing = null;
240
411
  try {
241
- return { provider_session_id: await this.start(conversation, await this.route(conversation, input.agent_id), null, true) };
412
+ route = await this.route(conversation, call.agent_id);
413
+ if (call.first === true)
414
+ instructing = this.instructed(conversation, route);
415
+ if (call.message_id !== null)
416
+ content.push(...(await this.transcribed(conversation, call.message_id, call.text)));
417
+ if (conversation.kills > 0)
418
+ throw new Error(KILLED);
242
419
  }
243
420
  catch (error) {
244
- return { refused: refusal(conversation, error) };
421
+ this.closeIdleBridge(conversation);
422
+ this.prepares(conversation, null);
423
+ return { result: Promise.resolve({ refused: refusal(conversation, error) }) };
245
424
  }
425
+ conversation.preparing = null;
426
+ const { promise, resolve: settle } = Promise.withResolvers();
427
+ const waiting = { call, route, content, instructing, settle };
428
+ if (call.at_once === true && conversation.turns.size > 0)
429
+ await this.atOnce(conversation, waiting);
430
+ else
431
+ conversation.waiting.push(waiting);
432
+ this.next(conversation);
433
+ return { result: promise };
246
434
  }
247
- async message(conversation, input) {
248
- const content = [{ type: 'text', text: String(input.text) }];
249
- let route;
435
+ async atOnce(conversation, waiting) {
436
+ while (conversation.sending !== null)
437
+ await conversation.sending;
438
+ const running = conversation.running;
439
+ if (running !== null && conversation.turns.size > 0 && steers(running.adapter)) {
440
+ conversation.sending = this.steer(conversation, running, waiting);
441
+ await conversation.sending;
442
+ conversation.sending = null;
443
+ return;
444
+ }
445
+ this.ahead(conversation, waiting);
446
+ if (conversation.turns.size > 0)
447
+ await this.cancel(conversation);
448
+ }
449
+ ahead(conversation, waiting) {
450
+ const behind = conversation.waiting.findIndex((held) => held.call.at_once !== true);
451
+ conversation.waiting.splice(behind === -1 ? conversation.waiting.length : behind, 0, waiting);
452
+ }
453
+ async steer(conversation, running, waiting) {
454
+ let outcome;
250
455
  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);
456
+ ({ outcome } = await running.adapter.connection.agent.request('_session/steering', {
457
+ sessionId: running.sessionId,
458
+ prompt: waiting.content,
459
+ _meta: { steering: { idleBehavior: 'promptRequired' } },
460
+ }));
259
461
  }
260
462
  catch (error) {
261
- return { ack: Promise.resolve({ refused: refusal(conversation, error) }) };
463
+ outcome = error;
464
+ }
465
+ if (outcome === 'promptRequired') {
466
+ this.ahead(conversation, waiting);
467
+ }
468
+ else if (outcome === 'injected' || outcome === 'startedNewTurn') {
469
+ if (outcome === 'injected') {
470
+ for (const turn of conversation.turns)
471
+ turn.steered ||= turn.prompted;
472
+ }
473
+ this.kit.calls.keepResult(waiting.call.input_id, {});
474
+ waiting.settle({});
475
+ }
476
+ else {
477
+ const cause = outcome instanceof Error ? outcome : new Error(`the CLI answered ${JSON.stringify(outcome)}`);
478
+ waiting.settle({ refused: refusal(conversation, new NotStarted(UNSTEERED, { cause })) });
262
479
  }
263
- return {
264
- ack: new Promise((settle) => {
265
- conversation.waiting.push({ input, route, content, settle });
266
- this.next(conversation);
267
- }),
268
- };
269
480
  }
270
481
  next(conversation) {
271
- if (conversation.sending !== null || conversation.open > 0)
482
+ if (this.stopping || conversation.sending !== null || conversation.turns.size > 0)
272
483
  return;
273
484
  const waiting = conversation.waiting.shift();
274
- if (waiting === undefined)
485
+ if (waiting === undefined) {
486
+ const step = conversation.preparing ?? (conversation.launch === null ? null : 'session');
487
+ if (conversation.starting !== step)
488
+ this.starts(conversation, step);
489
+ if (conversation.done && conversation.launch === null)
490
+ void this.stop(conversation).catch(logged);
275
491
  return;
492
+ }
276
493
  conversation.sending = this.send(conversation, waiting).finally(() => {
277
494
  conversation.sending = null;
278
495
  this.next(conversation);
279
496
  });
280
497
  }
281
498
  async send(conversation, waiting) {
282
- const { input } = waiting;
283
- let ack = {};
499
+ const { call } = waiting;
500
+ let result = {};
284
501
  let started = false;
502
+ let instructing = waiting.instructing;
285
503
  const prompt = [];
286
504
  try {
287
505
  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;
506
+ this.starts(conversation, 'session');
507
+ await this.launched(conversation);
508
+ }
509
+ if (conversation.running === null) {
510
+ const stored = conversation.session ?? call.provider_session_id;
511
+ const empty = call.first === true && conversation.prompted !== stored;
512
+ const launch = this.launch(conversation, Promise.resolve(waiting.route), stored, empty);
513
+ if (call.first === true)
514
+ instructing = this.instructed(conversation, waiting.route);
515
+ started = (await launch.session) !== stored;
291
516
  }
292
517
  const session = conversation.running.sessionId;
293
- if (started || (input.first === true && session !== input.provider_session_id)) {
294
- ack = { provider_session_id: session };
518
+ if (started || (call.first === true && session !== call.provider_session_id)) {
519
+ result = { provider_session_id: session };
295
520
  }
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
- });
521
+ if (call.first === true) {
522
+ prompt.push({ type: 'text', text: await (instructing ?? this.instructed(conversation, waiting.route)) });
301
523
  }
302
524
  if (conversation.kills > 0)
303
525
  throw new Error(KILLED);
304
526
  }
305
527
  catch (error) {
528
+ this.starts(conversation, null);
306
529
  if (started) {
307
530
  conversation.session = null;
308
531
  await this.kill(conversation);
309
532
  }
310
- waiting.settle({ refused: refusal(conversation, error) });
533
+ const refused = refusal(conversation, error);
534
+ const resumeRefused = call.kind === 'message' && conversation.kills === 0 && error instanceof ResumeRefused;
535
+ waiting.settle(resumeRefused ? { refused, resume_refused: true } : { refused });
311
536
  return;
312
537
  }
313
- this.prompt(conversation, [...prompt, ...waiting.content]);
314
- waiting.settle(ack);
538
+ this.starts(conversation, null);
539
+ this.prompt(conversation, [...prompt, ...waiting.content], () => this.kit.calls.keepResult(call.input_id, result));
540
+ waiting.settle(result);
315
541
  }
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)}`));
542
+ starts(conversation, step) {
543
+ conversation.starting = step;
544
+ if (conversation.shown !== null)
545
+ clearTimeout(conversation.shown);
546
+ conversation.shown = null;
547
+ if (step === null || conversation.told !== null) {
548
+ this.tell(conversation, step);
549
+ return;
550
+ }
551
+ conversation.shown = setTimeout(() => {
552
+ conversation.shown = null;
553
+ if (conversation.starting === step)
554
+ this.tell(conversation, step);
555
+ }, STARTING_SHOWN_AFTER_MS);
556
+ }
557
+ prepares(conversation, step) {
558
+ conversation.preparing = step;
559
+ this.next(conversation);
560
+ }
561
+ tell(conversation, step) {
562
+ if (conversation.told === step && !conversation.untold)
563
+ return;
564
+ conversation.told = step;
565
+ this.retell(conversation);
566
+ }
567
+ retell(conversation) {
568
+ conversation.untold = !this.kit.send({ type: 'starting', conversation_id: conversation.id, step: conversation.told });
569
+ }
570
+ async transcribed(conversation, messageId, text) {
571
+ const paths = linkedPaths(text);
572
+ if (paths.length === 0)
573
+ return [];
574
+ const killed = conversation.killed.signal;
575
+ const interrupted = conversation.interrupted.signal;
576
+ const transcribing = AbortSignal.any([killed, interrupted]);
577
+ let signal = killed;
578
+ const blocks = [];
579
+ try {
580
+ const bridge = await step(unbridged, unlessAborted(this.bridged(conversation), killed));
581
+ const read = async (path) => audioOf(await step(unbridged, unlessAborted(bridge.tool('info', { path }), signal)));
582
+ for (const path of paths) {
583
+ let answered = await read(path);
584
+ if (answered === null)
585
+ continue;
586
+ signal = transcribing;
587
+ this.prepares(conversation, 'transcription');
588
+ const said = await transcribe(async () => {
589
+ const address = answered ?? (await read(path));
590
+ answered = null;
591
+ if (address === null)
592
+ throw new Error(`${path} is no longer an audio file`);
593
+ return address;
594
+ }, signal);
595
+ await step(unbridged, unlessAborted(this.kit.house.deliver('transcripts/keep', { conversation: conversation.id, message: messageId, path, text: said }, () => !signal.aborted), signal));
596
+ blocks.push({ type: 'text', text: `${path}\nTranscript: ${said}` });
331
597
  }
332
598
  }
333
- return lines;
599
+ catch (error) {
600
+ if (signal === transcribing && interrupted.aborted && conversation.kills === 0)
601
+ throw new NotStarted(INTERRUPTED, { cause: error });
602
+ throw error;
603
+ }
604
+ return blocks;
605
+ }
606
+ bridged(conversation) {
607
+ if (conversation.bridge === null) {
608
+ const bridging = openBridge(this.kit.house, this.kit.copies, conversation.id, conversation.killed.signal);
609
+ conversation.bridge = bridging;
610
+ bridging.catch(() => {
611
+ if (conversation.bridge === bridging)
612
+ conversation.bridge = null;
613
+ });
614
+ }
615
+ return conversation.bridge;
616
+ }
617
+ closeBridge(conversation, bridging, bridge) {
618
+ bridge.close();
619
+ if (conversation.bridge === bridging)
620
+ conversation.bridge = null;
621
+ }
622
+ closeIdleBridge(conversation) {
623
+ const bridging = conversation.bridge;
624
+ if (bridging === null || conversation.running !== null || conversation.launch !== null)
625
+ return;
626
+ conversation.bridge = null;
627
+ void bridging.then((bridge) => bridge.close(), () => undefined);
334
628
  }
335
629
  async interrupt(conversation, turnId) {
336
- if (conversation.running === null || conversation.turn?.id !== turnId)
630
+ if ([...conversation.turns].some((turn) => turn.id === turnId))
631
+ await this.cancel(conversation);
632
+ }
633
+ async cancel(conversation) {
634
+ if (conversation.running === null)
337
635
  return;
338
636
  await conversation.running.adapter.connection.agent.notify('session/cancel', {
339
637
  sessionId: conversation.running.sessionId,
@@ -359,6 +657,9 @@ export class Conversations {
359
657
  if (running === null)
360
658
  return;
361
659
  try {
660
+ if (conversation.options?.find(({ id }) => id === option)?.category === 'mode') {
661
+ throw new Error(`conversation ${conversation.id} keeps the mode its Agent's launch settings name`);
662
+ }
362
663
  running.reader.requested(option, value);
363
664
  const answered = await running.adapter.connection.agent.request('session/set_config_option', {
364
665
  sessionId: running.sessionId,
@@ -385,51 +686,54 @@ export class Conversations {
385
686
  }
386
687
  return route;
387
688
  }
388
- async start(conversation, route, sessionId, empty) {
689
+ async start(conversation, routed, sessionId, empty, bridged) {
690
+ const route = await routed;
389
691
  const reader = readerFor(route.kind);
390
692
  reader.session = sessionId;
693
+ conversation.reader = reader;
391
694
  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));
695
+ .onRequest('session/request_permission', ({ params, signal }) => conversation.afk ? permissionAllowed(params) : this.ask(conversation, 'session/request_permission', params, false, signal))
696
+ .onRequest('elicitation/create', ({ params, signal }) => conversation.afk ? formAnswered(route.kind, params) : this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
697
+ .onRequest('_x.ai/exit_plan_mode', GROK_PLAN, async ({ params, signal }) => conversation.afk ? PLAN_APPROVED : grokPlanAnswer(await this.askForm(conversation, grokPlanForm(params), signal)))
698
+ .onRequest('_x.ai/ask_user_question', GROK_QUESTION, async ({ params, signal }) => conversation.afk ? grokQuestionAnswered(params) : grokQuestionAnswer(await this.askForm(conversation, grokQuestionForm(params), signal)));
395
699
  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));
700
+ const bridging = this.bridged(conversation);
701
+ const bridge = await step(unbridged, bridging);
397
702
  if (conversation.kills > 0) {
398
- bridge.close();
703
+ this.closeBridge(conversation, bridging, bridge);
399
704
  throw new Error(KILLED);
400
705
  }
401
706
  conversation.opening = bridge;
402
- const work = workFor(route.kind, route.working_directory, () => this.kit.changed());
707
+ const work = workFor(route.kind, route.working_directory, () => this.kit.changed(), (message) => this.tapped(conversation, reader, message));
403
708
  const scope = new Scope(marker(bridge), randomUUID(), cli);
404
709
  let adapter = null;
405
710
  try {
406
- await unlessAborted(createHowWeWork(bridge), conversation.killed.signal);
711
+ bridged(bridge);
407
712
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
408
713
  const streamed = await step(NO_CONNECTION, work.open(cli));
714
+ if (this.stopping)
715
+ throw new Error(KILLED);
409
716
  adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
410
717
  work.read(message);
411
- this.read(conversation, reader, message);
718
+ return this.read(conversation, reader, work, message);
412
719
  }, { ...bridge.env, ...streamed }, undefined, scope));
413
- void adapter.exited.then(() => bridge.close());
720
+ void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
414
721
  const agent = adapter.connection.agent;
415
722
  const cwd = route.working_directory;
416
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
723
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
417
724
  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 })));
725
+ const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
419
726
  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 };
727
+ if (opened.sessionId !== conversation.session)
728
+ conversation.state = QUIET;
729
+ const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
425
730
  const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
426
731
  void work.settled().then(() => scope.record());
427
732
  conversation.running = running;
733
+ adapter.turn(conversation.turns.size > 0);
428
734
  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);
735
+ conversation.options = options;
736
+ this.facts(conversation);
433
737
  void adapter.lost.then((cause) => this.exited(conversation, running, cause));
434
738
  return running.sessionId;
435
739
  }
@@ -437,7 +741,7 @@ export class Conversations {
437
741
  adapter?.retire();
438
742
  work.close();
439
743
  conversation.leftovers.add(scope);
440
- bridge.close();
744
+ this.closeBridge(conversation, bridging, bridge);
441
745
  throw conversation.kills > 0 ? new Error(KILLED) : error;
442
746
  }
443
747
  finally {
@@ -450,7 +754,7 @@ export class Conversations {
450
754
  }
451
755
  catch (error) {
452
756
  if (!empty || conversation.kills > 0 || !CLIS[kind].unknownSession(error)) {
453
- throw new NotStarted(NO_RESUME, { cause: error });
757
+ throw signedOut(error) ? new NotStarted(NOT_SIGNED_IN, { cause: error }) : new ResumeRefused(NO_RESUME, { cause: error });
454
758
  }
455
759
  logged(new Error(`conversation ${conversation.id} opens a new session: ${NO_RESUME}: ${causeOf(error)}`));
456
760
  return null;
@@ -486,15 +790,40 @@ export class Conversations {
486
790
  this.kit.changed();
487
791
  }
488
792
  detach(conversation, running) {
793
+ if (conversation.bridge === running.bridging)
794
+ conversation.bridge = null;
489
795
  running.work.close();
490
796
  conversation.leftovers.add(running.scope);
491
797
  conversation.running = null;
492
798
  conversation.commands = null;
799
+ conversation.options = null;
800
+ conversation.subagents.clear();
801
+ this.stated(conversation, { running: [] });
493
802
  for (const [id, question] of this.questions) {
494
803
  if (question.conversation === conversation)
495
804
  this.questions.delete(id);
496
805
  }
497
- this.kit.send({ type: 'process', conversation_id: conversation.id, running: false });
806
+ this.process(conversation, false);
807
+ }
808
+ process(conversation, running) {
809
+ conversation.exitUntold = !this.kit.send({ type: 'process', conversation_id: conversation.id, running }) && !running;
810
+ }
811
+ facts(conversation) {
812
+ this.process(conversation, true);
813
+ if (conversation.commands !== null)
814
+ this.commands(conversation, conversation.commands);
815
+ if (conversation.options !== null)
816
+ this.options(conversation, conversation.options);
817
+ }
818
+ stated(conversation, change) {
819
+ conversation.state = { ...conversation.state, ...change };
820
+ this.stateChanged(conversation, false);
821
+ }
822
+ stateChanged(conversation, again) {
823
+ const state = JSON.stringify(conversation.state);
824
+ if (!again && state === conversation.sentState)
825
+ return;
826
+ conversation.sentState = this.kit.send({ type: 'state', conversation_id: conversation.id, state: conversation.state }) ? state : null;
498
827
  }
499
828
  commands(conversation, commands) {
500
829
  conversation.commands = commands;
@@ -505,11 +834,17 @@ export class Conversations {
505
834
  options(conversation, options) {
506
835
  if (conversation.running === null)
507
836
  return;
508
- this.kit.send({ type: 'options', conversation_id: conversation.id, options });
837
+ conversation.options = options;
838
+ this.kit.send({ type: 'options', conversation_id: conversation.id, options: options.filter((option) => option.category !== 'mode') });
839
+ const chosen = (category) => {
840
+ const value = options.find((option) => option.category === category)?.currentValue;
841
+ return value === undefined ? null : String(value);
842
+ };
843
+ this.stated(conversation, { model: chosen('model'), effort: chosen('thought_level'), mode: chosen('mode') });
509
844
  }
510
- deliver(conversation, turn, event, body) {
845
+ deliver(conversation, act, request, current) {
511
846
  this.reporting++;
512
- const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/conversations/${conversation.id}/turns/${turn.id}/${event}`, await body));
847
+ const delivered = conversation.reports.then(async () => this.kit.house.deliver(act, await request, current));
513
848
  conversation.reports = delivered
514
849
  .catch(() => undefined)
515
850
  .finally(() => {
@@ -519,28 +854,28 @@ export class Conversations {
519
854
  return delivered;
520
855
  }
521
856
  write(conversation, turn, operation) {
522
- if (!turn.admitted || turn.ended || !this.watched)
857
+ if (turn.ended || !this.watched)
523
858
  return;
524
- this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, ...operation });
859
+ this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, operation });
525
860
  }
526
861
  replay(conversation, turn) {
527
- for (const operation of turn.parts.operations())
862
+ for (const operation of turn.content.operations())
528
863
  this.write(conversation, turn, operation);
529
864
  }
530
865
  begin(conversation) {
531
866
  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);
867
+ conversation.turns.add(turn);
868
+ conversation.running?.adapter.turn(true);
869
+ void this.deliver(conversation, 'turns/start', turnOf(conversation, turn))
870
+ .then((answer) => {
871
+ if (answer.run === true)
872
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
537
873
  })
538
874
  .catch(logged);
539
875
  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);
876
+ this.stated(conversation, { suggestion: null });
877
+ for (const event of conversation.reader?.began() ?? [])
878
+ this.event(conversation, event);
544
879
  this.kit.changed();
545
880
  return turn;
546
881
  }
@@ -549,31 +884,36 @@ export class Conversations {
549
884
  return;
550
885
  if (failed !== null)
551
886
  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
- }
887
+ if (conversation.turn === turn)
888
+ conversation.reader?.closeTurn();
556
889
  if (notice !== null)
557
- turn.parts.start({ type: 'marker', marker: 'retry', text: notice });
890
+ turn.content.add({ type: 'notice', kind: 'error', text: notice });
558
891
  turn.ended = true;
559
- conversation.open--;
892
+ conversation.turns.delete(turn);
893
+ conversation.running?.adapter.turn(conversation.turns.size > 0);
560
894
  if (conversation.turn === turn)
561
895
  conversation.turn = null;
896
+ const tokens = conversation.tokens;
897
+ conversation.tokens = null;
898
+ if (tokens !== null)
899
+ this.stated(conversation, { tokens: addedTokens(conversation.state.tokens, tokens) });
562
900
  const body = Promise.allSettled(turn.uploads).then(() => ({
563
- parts: turn.parts.saved(),
564
- context: turn.parts.context,
901
+ ...turnOf(conversation, turn),
902
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
565
903
  ...(failed === null ? {} : { failed: failed.failure }),
566
904
  }));
567
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
905
+ void this.deliver(conversation, 'turns/end', body).catch(logged);
568
906
  this.next(conversation);
569
907
  this.kit.changed();
570
908
  }
571
- prompt(conversation, prompt) {
909
+ prompt(conversation, prompt, taken) {
572
910
  const running = conversation.running;
573
911
  const turn = this.begin(conversation);
574
912
  turn.prompted = true;
913
+ turn.taken = taken;
575
914
  conversation.prompted = running.sessionId;
576
915
  running.adapter.connection.agent.request('session/prompt', { sessionId: running.sessionId, prompt }).then((answer) => {
916
+ this.took(turn);
577
917
  const notice = answeredFailure(answer);
578
918
  if (notice !== null) {
579
919
  this.end(conversation, turn, { failure: notice.limit ? 'limit' : 'error', cause: notice.title }, notice.title);
@@ -586,30 +926,38 @@ export class Conversations {
586
926
  this.end(conversation, turn, exitedWith(running, await running.adapter.exited));
587
927
  }
588
928
  else {
589
- if (conversation.open === 1 && conversation.running === running) {
929
+ this.took(turn);
930
+ if (conversation.turns.size === 1 && conversation.turns.has(turn) && conversation.running === running) {
590
931
  running.adapter.retire();
591
932
  this.detach(conversation, running);
592
933
  }
593
- this.end(conversation, turn, answeredWith(error));
934
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
594
935
  }
595
936
  });
596
937
  }
597
938
  started(conversation) {
598
- return conversation.turn ?? this.begin(conversation);
939
+ const turn = conversation.turn ?? this.begin(conversation);
940
+ this.took(turn);
941
+ return turn;
599
942
  }
600
- ended(conversation) {
943
+ ended(conversation, stop) {
601
944
  const turn = conversation.turn;
602
945
  if (turn === null)
603
946
  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();
947
+ const held = stop !== null && !turn.steered && [...conversation.subagents].some((key) => turn.content.holds(key));
948
+ if (!turn.prompted || held) {
949
+ this.took(turn);
950
+ this.end(conversation, turn, stop === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
951
+ return;
612
952
  }
953
+ if (stop !== null)
954
+ return;
955
+ conversation.reader?.closeTurn();
956
+ conversation.turn = null;
957
+ this.kit.changed();
958
+ }
959
+ askForm(conversation, form, signal) {
960
+ return this.ask(conversation, 'elicitation/create', form, false, signal);
613
961
  }
614
962
  async ask(conversation, method, params, secret, signal) {
615
963
  const turn = this.started(conversation);
@@ -617,7 +965,8 @@ export class Conversations {
617
965
  const answered = new Promise((answer, fail) => {
618
966
  this.questions.set(interactionId, { conversation, answer: (response) => answer(response) });
619
967
  signal.addEventListener('abort', () => answer(null), { once: true });
620
- this.deliver(conversation, turn, 'interactions', {
968
+ this.deliver(conversation, 'conversations/interaction/ask', {
969
+ ...turnOf(conversation, turn),
621
970
  interaction_id: interactionId,
622
971
  request: { method, params },
623
972
  secret,
@@ -655,17 +1004,42 @@ export class Conversations {
655
1004
  if (content !== null)
656
1005
  this.questions.get(interactionId)?.answer({ action: 'accept', content });
657
1006
  }
658
- read(conversation, reader, message) {
659
- for (const event of reader.read(message))
1007
+ read(conversation, reader, work, message) {
1008
+ const events = reader.read(message);
1009
+ const apply = () => {
1010
+ for (const event of events)
1011
+ this.event(conversation, event);
1012
+ this.reportActivity(conversation);
1013
+ };
1014
+ const held = message.method === undefined || events.some((event) => event.kind === 'ended') ? work.caughtUp() : null;
1015
+ if (held === null) {
1016
+ apply();
1017
+ return null;
1018
+ }
1019
+ return held.then(apply);
1020
+ }
1021
+ tapped(conversation, reader, message) {
1022
+ for (const event of reader.tap(message))
660
1023
  this.event(conversation, event);
661
1024
  }
1025
+ reportActivity(conversation) {
1026
+ const turn = conversation.turn;
1027
+ if (turn === null || Date.now() < turn.quietUntil)
1028
+ return;
1029
+ turn.quietUntil = Infinity;
1030
+ void this.deliver(conversation, 'turns/activity/report', turnOf(conversation, turn), () => false)
1031
+ .catch(logged)
1032
+ .finally(() => {
1033
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
1034
+ });
1035
+ }
662
1036
  event(conversation, event) {
663
1037
  switch (event.kind) {
664
1038
  case 'started':
665
1039
  this.started(conversation);
666
1040
  return;
667
1041
  case 'ended':
668
- this.ended(conversation);
1042
+ this.ended(conversation, event.stop);
669
1043
  return;
670
1044
  case 'commands':
671
1045
  this.commands(conversation, event.commands);
@@ -673,84 +1047,85 @@ export class Conversations {
673
1047
  case 'options':
674
1048
  this.options(conversation, event.options);
675
1049
  return;
676
- case 'context':
677
- conversation.context = { used: event.used, window: event.window };
678
- conversation.turn?.parts.measure(conversation.context);
1050
+ case 'state':
1051
+ this.stated(conversation, event.state);
679
1052
  return;
680
- case 'subagent-done':
681
- this.subagentDone(conversation, event.id, event.result);
1053
+ case 'tokens':
1054
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
682
1055
  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 });
1056
+ case 'call':
1057
+ this.called(conversation, event);
689
1058
  return;
1059
+ case 'notice':
1060
+ case 'image':
1061
+ if (conversation.turn === null)
1062
+ return;
1063
+ break;
690
1064
  }
691
1065
  this.apply(conversation, this.started(conversation), event);
692
1066
  }
1067
+ took(turn) {
1068
+ const taken = turn.taken;
1069
+ turn.taken = null;
1070
+ taken?.();
1071
+ }
693
1072
  apply(conversation, turn, event) {
694
1073
  switch (event.kind) {
695
1074
  case 'text':
696
- case 'reasoning':
697
- turn.parts.write(event.kind, event.id, event.text);
698
- return;
699
- case 'command':
700
- turn.parts.command();
1075
+ turn.content.write(event.id, event.text);
701
1076
  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);
1077
+ case 'notice':
1078
+ turn.content.add({ type: 'notice', kind: event.notice, text: event.text });
715
1079
  return;
716
1080
  case 'image':
717
- turn.uploads.push(this.image(conversation, turn, turn.parts.reserve(), event.data, event.mediaType));
1081
+ turn.uploads.push(this.image(conversation, turn, event.data, event.mediaType));
718
1082
  this.kit.changed();
719
1083
  return;
720
1084
  }
721
1085
  }
722
- subagentDone(conversation, id, result) {
723
- const subagent = conversation.subagents.get(id);
724
- if (subagent === undefined)
1086
+ // A sub-agent's calls count only in the turn that holds the call that started it, and a call's later changes only in the turn that counted it.
1087
+ called(conversation, event) {
1088
+ if (event.running === true)
1089
+ conversation.subagents.add(event.key);
1090
+ if (event.running === false)
1091
+ conversation.subagents.delete(event.key);
1092
+ const turn = conversation.turn;
1093
+ if (!event.first) {
1094
+ if (turn?.content.holds(event.key))
1095
+ turn.content.call(event.key, event.parent, event.call);
725
1096
  return;
726
- conversation.subagents.delete(id);
727
- if (subagent.turn === conversation.turn) {
728
- subagent.turn.parts.done(subagent.index, result);
1097
+ }
1098
+ if (event.parent !== null) {
1099
+ turn?.content.call(event.key, event.parent, event.call);
729
1100
  return;
730
1101
  }
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);
1102
+ this.started(conversation).content.call(event.key, null, event.call);
736
1103
  }
737
- async image(conversation, turn, reserved, data, mediaType) {
1104
+ async image(conversation, turn, data, mediaType) {
738
1105
  const bytes = Buffer.from(data, 'base64');
739
1106
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
1107
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
740
1108
  try {
741
- const declared = (await this.deliver(conversation, turn, 'images', {
1109
+ const declared = (await this.deliver(conversation, 'turns/images/declare', {
1110
+ ...turnOf(conversation, turn),
742
1111
  name,
743
1112
  media_type: mediaType,
744
1113
  bytes: bytes.length,
745
- sha256: createHash('sha256').update(bytes).digest('hex'),
1114
+ sha256,
746
1115
  }));
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);
1116
+ const saved = await uploaded(declared.upload, {
1117
+ name,
1118
+ bytes: bytes.length,
1119
+ sha256,
1120
+ read: (start, end) => [bytes.subarray(start, end)],
1121
+ send: (url, start, end, headers) => sentPart(url, bytes.subarray(start, end), headers),
1122
+ finish: (upload, partSha256) => this.kit.house.deliver('uploads/finish', { upload, part_sha256: partSha256 }),
1123
+ });
1124
+ turn.content.arrived({ type: 'image', file: saved.path, name, media_type: mediaType });
751
1125
  }
752
1126
  catch (error) {
753
- turn.parts.arrive({ type: 'marker', marker: 'retry', text: `${name} was not saved: ${causeOf(error)}` }, reserved);
1127
+ const cause = error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error);
1128
+ turn.content.arrived({ type: 'notice', kind: 'error', text: `${name} was not saved: ${cause}` });
754
1129
  }
755
1130
  }
756
1131
  }