@agentshouse/kit 0.2.1-cde47fd72fe59 → 0.2.1-ce0af1aee9a57

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