@agentshouse/kit 0.2.1-cfb7b543f2af6 → 0.2.1-cfbadfb5b5e28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/README.md +33 -34
  2. package/dist/acp.js +91 -20
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +91 -44
  5. package/dist/api.js +5 -5
  6. package/dist/app-git.js +10 -26
  7. package/dist/authority-main.js +3 -3
  8. package/dist/bridge.js +7 -10
  9. package/dist/building.js +50 -0
  10. package/dist/calls.js +71 -0
  11. package/dist/chunks.js +49 -0
  12. package/dist/clis.js +56 -45
  13. package/dist/connection.js +120 -0
  14. package/dist/content.js +63 -0
  15. package/dist/conversations.js +703 -244
  16. package/dist/copies.js +344 -171
  17. package/dist/end.js +15 -4
  18. package/dist/events.js +746 -210
  19. package/dist/files.js +139 -37
  20. package/dist/git.js +49 -16
  21. package/dist/grok.js +39 -0
  22. package/dist/home.js +27 -20
  23. package/dist/house-cli.js +98 -90
  24. package/dist/house-main.js +3 -3
  25. package/dist/instructions.js +29 -10
  26. package/dist/kit-cli.js +5 -8
  27. package/dist/kit-main.js +3 -3
  28. package/dist/login.js +20 -11
  29. package/dist/logout.js +1 -3
  30. package/dist/mcp.js +6 -2
  31. package/dist/placement.js +19 -36
  32. package/dist/relay.js +21 -0
  33. package/dist/resident.js +118 -52
  34. package/dist/scope.js +15 -4
  35. package/dist/scripts.js +255 -0
  36. package/dist/secret-input.js +1 -1
  37. package/dist/service.js +23 -1
  38. package/dist/sign-in.js +22 -39
  39. package/dist/silence.js +28 -0
  40. package/dist/skills.js +42 -97
  41. package/dist/transcription.js +88 -45
  42. package/dist/translate.js +19 -16
  43. package/dist/update.js +113 -127
  44. package/dist/wire.js +37 -3
  45. package/dist/work.js +12 -7
  46. package/package.json +22 -21
  47. package/dist/bootstrap.json +0 -24
  48. package/dist/chatgpt.js +0 -32
  49. package/dist/clis-main.js +0 -23
  50. package/dist/parts.js +0 -82
  51. package/dist/stream.js +0 -123
  52. package/how-we-work.md +0 -33
  53. package/skills/ask-matt/LICENSE +0 -21
  54. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  55. package/skills/ask-matt/SKILL.md +0 -97
  56. package/skills/ask-matt/agents/openai.yaml +0 -5
  57. package/skills/code-review/LICENSE +0 -21
  58. package/skills/code-review/SKILL.md +0 -89
  59. package/skills/code-review/agents/openai.yaml +0 -3
  60. package/skills/codebase-design/DEEPENING.md +0 -37
  61. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  62. package/skills/codebase-design/LICENSE +0 -21
  63. package/skills/codebase-design/SKILL.md +0 -114
  64. package/skills/codebase-design/agents/openai.yaml +0 -3
  65. package/skills/diagnosing-bugs/LICENSE +0 -21
  66. package/skills/diagnosing-bugs/SKILL.md +0 -138
  67. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  68. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  69. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  70. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  71. package/skills/domain-modeling/LICENSE +0 -21
  72. package/skills/domain-modeling/SKILL.md +0 -74
  73. package/skills/domain-modeling/agents/openai.yaml +0 -3
  74. package/skills/grill-me/LICENSE +0 -21
  75. package/skills/grill-me/SKILL.md +0 -7
  76. package/skills/grill-me/agents/openai.yaml +0 -5
  77. package/skills/grill-with-docs/LICENSE +0 -21
  78. package/skills/grill-with-docs/SKILL.md +0 -7
  79. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  80. package/skills/grilling/LICENSE +0 -21
  81. package/skills/grilling/SKILL.md +0 -30
  82. package/skills/grilling/agents/openai.yaml +0 -3
  83. package/skills/handoff/LICENSE +0 -21
  84. package/skills/handoff/SKILL.md +0 -16
  85. package/skills/handoff/agents/openai.yaml +0 -5
  86. package/skills/implement/LICENSE +0 -21
  87. package/skills/implement/SKILL.md +0 -17
  88. package/skills/implement/agents/openai.yaml +0 -5
  89. package/skills/implement-spec/LICENSE +0 -21
  90. package/skills/implement-spec/SKILL.md +0 -40
  91. package/skills/implement-spec/agents/openai.yaml +0 -5
  92. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  93. package/skills/improve-codebase-architecture/LICENSE +0 -21
  94. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  95. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  96. package/skills/pr/CREDITS.md +0 -3
  97. package/skills/pr/LICENSE +0 -21
  98. package/skills/pr/SKILL.md +0 -170
  99. package/skills/pr/agents/openai.yaml +0 -3
  100. package/skills/prototype/LICENSE +0 -21
  101. package/skills/prototype/LOGIC.md +0 -67
  102. package/skills/prototype/SKILL.md +0 -26
  103. package/skills/prototype/UI.md +0 -112
  104. package/skills/prototype/agents/openai.yaml +0 -3
  105. package/skills/research/LICENSE +0 -21
  106. package/skills/research/SKILL.md +0 -12
  107. package/skills/research/agents/openai.yaml +0 -3
  108. package/skills/retro/LICENSE +0 -21
  109. package/skills/retro/SKILL.md +0 -44
  110. package/skills/retro/agents/openai.yaml +0 -5
  111. package/skills/tdd/LICENSE +0 -21
  112. package/skills/tdd/SKILL.md +0 -38
  113. package/skills/tdd/agents/openai.yaml +0 -3
  114. package/skills/tdd/mocking.md +0 -59
  115. package/skills/tdd/tests.md +0 -77
  116. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  117. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  118. package/skills/teach/LICENSE +0 -21
  119. package/skills/teach/MISSION-FORMAT.md +0 -31
  120. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  121. package/skills/teach/SKILL.md +0 -140
  122. package/skills/teach/agents/openai.yaml +0 -5
  123. package/skills/to-questionnaire/LICENSE +0 -21
  124. package/skills/to-questionnaire/SKILL.md +0 -54
  125. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  126. package/skills/to-spec/LICENSE +0 -21
  127. package/skills/to-spec/SKILL.md +0 -75
  128. package/skills/to-spec/agents/openai.yaml +0 -5
  129. package/skills/to-tickets/LICENSE +0 -21
  130. package/skills/to-tickets/SKILL.md +0 -105
  131. package/skills/to-tickets/agents/openai.yaml +0 -5
  132. package/skills/triage/AGENT-BRIEF.md +0 -207
  133. package/skills/triage/LICENSE +0 -21
  134. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  135. package/skills/triage/SKILL.md +0 -112
  136. package/skills/triage/agents/openai.yaml +0 -5
  137. package/skills/wait-what/LICENSE +0 -21
  138. package/skills/wait-what/SKILL.md +0 -7
  139. package/skills/wait-what/agents/openai.yaml +0 -5
  140. package/skills/wayfinder/LICENSE +0 -21
  141. package/skills/wayfinder/SKILL.md +0 -128
  142. package/skills/wayfinder/agents/openai.yaml +0 -5
  143. package/skills/wizard/LICENSE +0 -21
  144. package/skills/wizard/SKILL.md +0 -44
  145. package/skills/wizard/agents/openai.yaml +0 -3
  146. package/skills/wizard/template.sh +0 -223
  147. package/skills/writing-for-agents/LICENSE +0 -21
  148. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  149. package/skills/writing-for-agents/SKILL.md +0 -81
  150. package/skills/writing-for-agents/agents/openai.yaml +0 -3
@@ -3,53 +3,163 @@ import { createHash, randomUUID } from 'node:crypto';
3
3
  import { mkdir } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { unlessAborted } from './abort.js';
6
- import { startAdapter } from './acp.js';
6
+ import { signedOut, startAdapter } from './acp.js';
7
+ import { formAnswered, grokQuestionAnswered, permissionAllowed, PLAN_APPROVED } from './afk.js';
8
+ import { finalRefusal, HouseRefusal } from './api.js';
7
9
  import { openBridge } from './bridge.js';
8
10
  import { CLIS } from './clis.js';
9
- import { readerFor } from './events.js';
10
- import { placeFiles, uploadBytes } from './files.js';
11
+ import { Content } from './content.js';
12
+ import { answeredFailure, readerFor } from './events.js';
13
+ import { inspectedFile, linkedPaths, storeRefusal, uploaded } from './files.js';
14
+ import { grokPlanAnswer, grokPlanForm, grokQuestionAnswer, grokQuestionForm } from './grok.js';
11
15
  import { agentBase } from './home.js';
12
16
  import { instructions } from './instructions.js';
13
- import { Parts } from './parts.js';
17
+ import { refusalOf } from './refusals.js';
18
+ import { relayed } from './relay.js';
14
19
  import { killMarked, Scope } from './scope.js';
15
20
  import { holdSecretInput } from './secret-input.js';
16
- import { createHowWeWork } from './skills.js';
17
21
  import { transcribe } from './transcription.js';
18
22
  import { workFor } from './work.js';
19
23
  const KILLED = 'the conversation was killed';
20
- const EXIT_PLAN_MODE = {
24
+ const INTERRUPTED = 'the conversation was interrupted';
25
+ const REFUSED = 'the CLI refused the prompt';
26
+ const NO_CONNECTION = "the Agent's computer could not open this conversation; try again";
27
+ const GONE = 'House no longer holds this conversation; start a new one';
28
+ const RETIRED = "this conversation's Agent is retired, so it cannot start";
29
+ const ENDED = {
30
+ conversation_not_found: GONE,
31
+ conversation_historical: RETIRED,
32
+ };
33
+ const NO_START = "the Agent's CLI did not start";
34
+ const NO_SESSION = "the Agent's CLI did not open a session";
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";
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;
59
+ class NotStarted extends Error {
60
+ }
61
+ class ResumeRefused extends NotStarted {
62
+ }
63
+ async function step(reason, work) {
64
+ try {
65
+ return await work;
66
+ }
67
+ catch (error) {
68
+ throw new NotStarted(typeof reason === 'string' ? reason : reason(error), { cause: error });
69
+ }
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 unbridged(error) {
77
+ return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
78
+ }
79
+ const GROK_PLAN = {
80
+ parse(value) {
81
+ return value;
82
+ },
83
+ };
84
+ const GROK_QUESTION = {
21
85
  parse(value) {
22
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
23
- throw new Error('_x.ai/exit_plan_mode needs an object');
24
- }
25
86
  return value;
26
87
  },
27
88
  };
28
- export const CONVERSATION_INPUTS = new Set(['open', 'message', 'interrupt', 'kill', 'option', 'answer']);
89
+ export const CONVERSATION_METHODS = new Set(['open', 'message', 'take_out', 'interrupt', 'kill', 'done', 'option', 'answer']);
90
+ function addedTokens(sum, tokens) {
91
+ if (sum === null)
92
+ return tokens;
93
+ return {
94
+ input: sum.input + tokens.input,
95
+ output: sum.output + tokens.output,
96
+ cache_read: sum.cache_read + tokens.cache_read,
97
+ cache_write: sum.cache_write + tokens.cache_write,
98
+ };
99
+ }
100
+ function workRuns(part) {
101
+ return part.type === 'subagent' || part.type === 'background' ? part.status === 'running' : null;
102
+ }
103
+ function cliSaid(error) {
104
+ const details = error?.data?.details;
105
+ return typeof details === 'string' && details !== '' ? `${causeOf(error)}: ${details}` : causeOf(error);
106
+ }
29
107
  function causeOf(error) {
30
108
  return error instanceof Error ? error.message : String(error);
31
109
  }
110
+ function answeredWith(error) {
111
+ return { failure: signedOut(error) ? 'signed_out' : 'error', cause: causeOf(error) };
112
+ }
113
+ function exitedWith(running, cause) {
114
+ if (running.killed)
115
+ return { failure: 'killed', cause: KILLED };
116
+ return { failure: running.adapter.silent() ? 'silent' : 'exited', cause };
117
+ }
32
118
  function answerMessage(request, response) {
33
119
  return `The User answered a question you asked earlier.\nQuestion: ${JSON.stringify(request)}\nAnswer: ${JSON.stringify(response)}`;
34
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
+ }
35
127
  function logged(error) {
36
128
  process.stderr.write(`kit: ${causeOf(error)}\n`);
37
129
  }
130
+ function refusal(conversation, error) {
131
+ if (conversation.kills > 0)
132
+ return KILLED;
133
+ const cause = error instanceof Error && error.cause !== undefined ? `${error.message}: ${causeOf(error.cause)}` : causeOf(error);
134
+ logged(new Error(`conversation ${conversation.id} did not start: ${cause}`));
135
+ return causeOf(error);
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
+ }
38
143
  function marker(bridge) {
39
144
  return `HOUSE_BRIDGE=${bridge.env.HOUSE_BRIDGE}`;
40
145
  }
146
+ function steers(adapter) {
147
+ return adapter.initialized._meta?.steering?.supported === true;
148
+ }
41
149
  class Turn {
42
150
  id = randomUUID();
43
- parts;
44
- admitted = false;
151
+ content;
45
152
  questions = 0;
46
153
  secrets = 0;
47
154
  prompted = false;
155
+ steered = false;
156
+ taken = null;
48
157
  ended = false;
158
+ quietUntil = Infinity;
49
159
  images = 0;
50
160
  uploads = [];
51
161
  constructor(emit) {
52
- this.parts = new Parts(emit);
162
+ this.content = new Content(emit);
53
163
  }
54
164
  }
55
165
  class Conversation {
@@ -58,20 +168,35 @@ class Conversation {
58
168
  session = null;
59
169
  turn = null;
60
170
  commands = null;
61
- context = null;
171
+ options = null;
172
+ exitUntold = false;
173
+ afk = false;
174
+ reader = null;
175
+ state = QUIET;
176
+ sentState = null;
177
+ tokens = null;
62
178
  leftovers = new Set();
63
179
  waiting = [];
180
+ done = false;
64
181
  sending = null;
65
- subagents = new Map();
182
+ work = new Map();
66
183
  held = [];
67
184
  opening = null;
185
+ bridge = null;
186
+ launch = null;
187
+ prompted = null;
68
188
  kills = 0;
69
189
  killed = new AbortController();
70
190
  interrupts = 0;
71
191
  interrupted = new AbortController();
72
- open = 0;
192
+ turns = new Set();
73
193
  queue = Promise.resolve();
74
194
  reports = Promise.resolve();
195
+ starting = null;
196
+ preparing = null;
197
+ told = null;
198
+ untold = false;
199
+ shown = null;
75
200
  constructor(id) {
76
201
  this.id = id;
77
202
  }
@@ -87,53 +212,43 @@ function asksSecret(request) {
87
212
  export class Conversations {
88
213
  kit;
89
214
  conversations = new Map();
90
- acks = new Map();
91
215
  questions = new Map();
92
- carrying = 0;
93
216
  reporting = 0;
94
217
  watched = false;
218
+ stopping = false;
95
219
  constructor(kit) {
96
220
  this.kit = kit;
97
221
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
98
222
  setInterval(() => this.look(), 2_000);
99
223
  }
100
- input(input) {
101
- this.carrying++;
102
- const carried = this.acks.get(input.input_id) ??
103
- (() => {
104
- const conversation = this.conversation(input.conversation_id);
105
- if (input.kind === 'kill') {
106
- conversation.kills++;
107
- conversation.killed.abort(new Error(KILLED));
108
- for (const waiting of conversation.waiting.splice(0))
109
- waiting.settle({ refused: KILLED });
110
- this.halt(conversation);
111
- }
112
- if (input.kind === 'interrupt') {
113
- conversation.interrupts++;
114
- conversation.interrupted.abort();
115
- }
116
- const handled = conversation.queue.then(() => this.carry(conversation, input));
117
- conversation.queue = handled.catch(() => undefined);
118
- const work = handled.then(({ ack }) => ack);
119
- this.acks.set(input.input_id, work);
120
- return work;
121
- })();
122
- carried
123
- .then((body) => this.kit.house.deliver(`/kit/inputs/${input.input_id}/ack`, body))
124
- .catch(logged)
125
- .finally(() => {
126
- this.carrying--;
127
- this.kit.changed();
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') {
230
+ conversation.kills++;
231
+ conversation.killed.abort(new Error(KILLED));
232
+ for (const waiting of conversation.waiting.splice(0))
233
+ waiting.settle({ refused: KILLED });
234
+ this.halt(conversation);
235
+ }
236
+ if (call.kind === 'interrupt') {
237
+ conversation.interrupts++;
238
+ conversation.interrupted.abort();
239
+ }
240
+ const handled = conversation.queue.then(() => this.carry(conversation, call));
241
+ conversation.queue = handled.catch(() => undefined);
242
+ return handled.then(async ({ result }) => ({ result: await result }));
128
243
  });
129
244
  }
130
245
  idle() {
131
- if (this.carrying > 0 || this.reporting > 0)
246
+ if (this.reporting > 0)
132
247
  return false;
133
248
  for (const conversation of this.conversations.values()) {
134
249
  const turn = conversation.turn;
135
250
  const asking = turn !== null && turn.questions > 0 && turn.secrets === 0;
136
- if (conversation.open > (asking ? 1 : 0))
251
+ if (conversation.turns.size > (asking ? 1 : 0))
137
252
  return false;
138
253
  }
139
254
  const conversations = [...this.conversations.values()];
@@ -142,7 +257,7 @@ export class Conversations {
142
257
  return !conversations.some((conversation) => conversation.running?.scope.working() || [...conversation.leftovers].some((scope) => scope.working()));
143
258
  }
144
259
  quiet() {
145
- return this.idle() && [...this.conversations.values()].every((conversation) => conversation.open === 0);
260
+ return this.idle() && [...this.conversations.values()].every((conversation) => conversation.turns.size === 0);
146
261
  }
147
262
  look() {
148
263
  for (const conversation of this.conversations.values()) {
@@ -155,8 +270,25 @@ export class Conversations {
155
270
  }
156
271
  this.kit.changed();
157
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
+ }
158
280
  opened() {
159
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
+ }
160
292
  }
161
293
  watching(watched) {
162
294
  const resend = watched && !this.watched;
@@ -176,130 +308,329 @@ export class Conversations {
176
308
  }
177
309
  return conversation;
178
310
  }
179
- async carry(conversation, input) {
180
- if (input.kind === 'open')
181
- return { ack: Promise.resolve(await this.open(conversation, input)) };
182
- if (input.kind === 'message')
183
- return this.message(conversation, input);
184
- 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') {
185
325
  if (--conversation.interrupts === 0)
186
326
  conversation.interrupted = new AbortController();
187
- await this.interrupt(conversation, String(input.turn_id));
327
+ await this.interrupt(conversation, String(call.turn_id));
188
328
  }
189
- if (input.kind === 'kill') {
329
+ if (call.kind === 'kill') {
190
330
  await this.kill(conversation);
191
331
  await conversation.sending;
192
332
  if (--conversation.kills === 0)
193
333
  conversation.killed = new AbortController();
194
334
  }
195
- if (input.kind === 'option')
196
- await this.option(conversation, String(input.option), input.value);
197
- if (input.kind === 'answer') {
198
- 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));
199
339
  if (question === undefined) {
200
- const text = answerMessage(input.request, input.response);
201
- 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 });
202
342
  }
203
- question.answer(input.response);
343
+ question.answer(call.response);
204
344
  }
205
- 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
+ };
206
361
  }
207
- async open(conversation, input) {
208
- if (conversation.running !== null)
209
- return {};
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;
402
+ }
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;
210
410
  try {
211
- return { provider_session_id: await this.start(conversation, await this.route(conversation, input.agent_id), null) };
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);
212
418
  }
213
419
  catch (error) {
214
- return { refused: causeOf(error) };
420
+ this.closeIdleBridge(conversation);
421
+ this.prepares(conversation, null);
422
+ return { result: Promise.resolve({ refused: refusal(conversation, error) }) };
215
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 };
216
433
  }
217
- async message(conversation, input) {
218
- const content = [{ type: 'text', text: String(input.text) }];
219
- 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;
220
454
  try {
221
- route = await this.route(conversation, input.agent_id);
222
- const files = input.files;
223
- const paths = await placeFiles(this.kit.house, route.working_directory, files, conversation.killed.signal);
224
- const lines = await this.transcribed(conversation, files, paths);
225
- if (lines.length > 0)
226
- content.push({ type: 'text', text: lines.join('\n') });
227
- if (conversation.kills > 0)
228
- 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
+ }));
229
460
  }
230
461
  catch (error) {
231
- return { ack: Promise.resolve({ refused: conversation.kills > 0 ? KILLED : causeOf(error) }) };
462
+ outcome = error;
463
+ }
464
+ if (outcome === 'promptRequired') {
465
+ this.ahead(conversation, waiting);
466
+ }
467
+ else if (outcome === 'injected' || outcome === 'startedNewTurn') {
468
+ if (outcome === 'injected') {
469
+ for (const turn of conversation.turns)
470
+ turn.steered ||= turn.prompted;
471
+ }
472
+ this.kit.calls.keepResult(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 })) });
232
478
  }
233
- return {
234
- ack: new Promise((settle) => {
235
- conversation.waiting.push({ input, route, content, settle });
236
- this.next(conversation);
237
- }),
238
- };
239
479
  }
240
480
  next(conversation) {
241
- if (conversation.sending !== null || conversation.open > 0)
481
+ if (this.stopping || conversation.sending !== null || conversation.turns.size > 0)
242
482
  return;
243
483
  const waiting = conversation.waiting.shift();
244
- 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);
245
490
  return;
491
+ }
246
492
  conversation.sending = this.send(conversation, waiting).finally(() => {
247
493
  conversation.sending = null;
248
494
  this.next(conversation);
249
495
  });
250
496
  }
251
497
  async send(conversation, waiting) {
252
- const { input } = waiting;
253
- let ack = {};
498
+ const { call } = waiting;
499
+ let result = {};
500
+ let started = false;
501
+ let instructing = waiting.instructing;
254
502
  const prompt = [];
255
503
  try {
256
504
  if (conversation.running === null) {
257
- const resumed = input.provider_session_id ?? conversation.session;
258
- const opened = await this.start(conversation, waiting.route, resumed);
259
- if (resumed === null)
260
- ack = { provider_session_id: opened };
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;
261
515
  }
262
- if (input.first === true) {
263
- prompt.push({
264
- type: 'text',
265
- text: await instructions(conversation.running.bridge, waiting.route.base_instructions, await this.kit.copies.mapping()),
266
- });
516
+ const session = conversation.running.sessionId;
517
+ if (started || (call.first === true && session !== call.provider_session_id)) {
518
+ result = { provider_session_id: session };
519
+ }
520
+ if (call.first === true) {
521
+ prompt.push({ type: 'text', text: await (instructing ?? this.instructed(conversation, waiting.route)) });
267
522
  }
268
523
  if (conversation.kills > 0)
269
524
  throw new Error(KILLED);
270
525
  }
271
526
  catch (error) {
272
- if ('provider_session_id' in ack) {
527
+ this.starts(conversation, null);
528
+ if (started) {
273
529
  conversation.session = null;
274
530
  await this.kill(conversation);
275
531
  }
276
- waiting.settle({ refused: conversation.kills > 0 ? KILLED : causeOf(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 });
277
535
  return;
278
536
  }
279
- this.prompt(conversation, [...prompt, ...waiting.content]);
280
- 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);
281
540
  }
282
- async transcribed(conversation, files, paths) {
283
- const lines = [];
284
- for (const [index, path] of paths.entries()) {
285
- lines.push(path);
286
- if (files[index].media_type?.startsWith('audio/') !== true)
287
- continue;
288
- try {
289
- const text = await transcribe(path, AbortSignal.any([conversation.killed.signal, conversation.interrupted.signal]));
290
- if (text !== null && text !== '')
291
- lines.push(`Transcript: ${text}`);
292
- }
293
- catch (error) {
294
- if (conversation.kills > 0)
295
- throw error;
296
- 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}` });
297
596
  }
298
597
  }
299
- 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);
300
627
  }
301
628
  async interrupt(conversation, turnId) {
302
- 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)
303
634
  return;
304
635
  await conversation.running.adapter.connection.agent.notify('session/cancel', {
305
636
  sessionId: conversation.running.sessionId,
@@ -325,6 +656,9 @@ export class Conversations {
325
656
  if (running === null)
326
657
  return;
327
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
+ }
328
662
  running.reader.requested(option, value);
329
663
  const answered = await running.adapter.connection.agent.request('session/set_config_option', {
330
664
  sessionId: running.sessionId,
@@ -351,64 +685,80 @@ export class Conversations {
351
685
  }
352
686
  return route;
353
687
  }
354
- async start(conversation, route, sessionId) {
688
+ async start(conversation, routed, sessionId, empty, bridged) {
689
+ const route = await routed;
355
690
  const reader = readerFor(route.kind);
356
691
  reader.session = sessionId;
692
+ conversation.reader = reader;
357
693
  const app = client({ name: '@agentshouse/kit' })
358
- .onRequest('session/request_permission', ({ params, signal }) => this.ask(conversation, 'session/request_permission', params, false, signal))
359
- .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
360
- .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)));
361
698
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
362
- const bridge = await 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);
363
701
  if (conversation.kills > 0) {
364
- bridge.close();
702
+ this.closeBridge(conversation, bridging, bridge);
365
703
  throw new Error(KILLED);
366
704
  }
367
705
  conversation.opening = bridge;
368
- 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));
369
707
  const scope = new Scope(marker(bridge), randomUUID(), cli);
708
+ let adapter = null;
370
709
  try {
371
- await unlessAborted(createHowWeWork(bridge), conversation.killed.signal);
710
+ bridged(bridge);
372
711
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
373
- const adapter = await startAdapter(route.kind, cli, route.working_directory, app, (message) => {
712
+ const streamed = await step(NO_CONNECTION, work.open(cli));
713
+ if (this.stopping)
714
+ throw new Error(KILLED);
715
+ adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
374
716
  work.read(message);
375
717
  this.read(conversation, reader, message);
376
- }, { ...bridge.env, ...(await work.open(cli)) }, undefined, scope);
377
- void adapter.exited.then(() => bridge.close());
718
+ }, { ...bridge.env, ...streamed }, undefined, scope));
719
+ void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
378
720
  const agent = adapter.connection.agent;
379
721
  const cwd = route.working_directory;
380
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
381
- const opened = sessionId === null
382
- ? await agent.request('session/new', { cwd, mcpServers: [], _meta })
383
- : { ...(await agent.request('session/resume', { sessionId, cwd, mcpServers: [], _meta })), sessionId };
722
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
723
+ const resumed = sessionId === null ? null : await this.resume(conversation, route.kind, adapter, { sessionId, cwd, mcpServers: [], _meta }, empty);
724
+ const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
384
725
  reader.session = opened.sessionId;
385
- if (sessionId === null && CLIS[route.kind].renames) {
386
- const prompt = [{ type: 'text', text: `/rename ${conversation.id}` }];
387
- await agent.request('session/prompt', { sessionId: opened.sessionId, prompt });
388
- }
389
- const running = { adapter, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
390
- const options = await this.launchSettings(running, route, opened.configOptions ?? []);
726
+ if (opened.sessionId !== conversation.session)
727
+ conversation.state = QUIET;
728
+ const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
729
+ const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
391
730
  void work.settled().then(() => scope.record());
392
731
  conversation.running = running;
732
+ adapter.turn(conversation.turns.size > 0);
393
733
  conversation.session = running.sessionId;
394
- this.kit.send({ type: 'process', conversation_id: conversation.id, running: true });
395
- if (conversation.commands !== null)
396
- this.commands(conversation, conversation.commands);
397
- this.options(conversation, options);
398
- void adapter.exited.then((cause) => this.exited(conversation, adapter, cause));
734
+ conversation.options = options;
735
+ this.facts(conversation);
736
+ void adapter.lost.then((cause) => this.exited(conversation, running, cause));
399
737
  return running.sessionId;
400
738
  }
401
739
  catch (error) {
402
- scope.kill();
740
+ adapter?.retire();
403
741
  work.close();
404
742
  conversation.leftovers.add(scope);
405
- bridge.close();
743
+ this.closeBridge(conversation, bridging, bridge);
406
744
  throw conversation.kills > 0 ? new Error(KILLED) : error;
407
745
  }
408
746
  finally {
409
747
  conversation.opening = null;
410
748
  }
411
749
  }
750
+ async resume(conversation, kind, adapter, request, empty) {
751
+ try {
752
+ return { ...(await adapter.connection.agent.request('session/resume', request)), sessionId: request.sessionId };
753
+ }
754
+ catch (error) {
755
+ if (!empty || conversation.kills > 0 || !CLIS[kind].unknownSession(error)) {
756
+ throw signedOut(error) ? new NotStarted(NOT_SIGNED_IN, { cause: error }) : new ResumeRefused(NO_RESUME, { cause: error });
757
+ }
758
+ logged(new Error(`conversation ${conversation.id} opens a new session: ${NO_RESUME}: ${causeOf(error)}`));
759
+ return null;
760
+ }
761
+ }
412
762
  async launchSettings(running, route, offered) {
413
763
  let options = offered;
414
764
  const settings = [
@@ -430,27 +780,49 @@ export class Conversations {
430
780
  }
431
781
  return options;
432
782
  }
433
- exited(conversation, adapter, cause) {
434
- const running = conversation.running;
435
- if (running?.adapter !== adapter)
436
- return;
783
+ exited(conversation, running, cause) {
437
784
  this.detach(conversation, running);
438
785
  if (conversation.turn !== null) {
439
- this.end(conversation, conversation.turn, { failed: running.killed ? KILLED : cause });
786
+ this.end(conversation, conversation.turn, exitedWith(running, cause));
440
787
  }
441
788
  this.next(conversation);
442
789
  this.kit.changed();
443
790
  }
444
791
  detach(conversation, running) {
792
+ if (conversation.bridge === running.bridging)
793
+ conversation.bridge = null;
445
794
  running.work.close();
446
795
  conversation.leftovers.add(running.scope);
447
796
  conversation.running = null;
448
797
  conversation.commands = null;
798
+ conversation.options = null;
799
+ conversation.work.clear();
800
+ this.stated(conversation, { running: [] });
449
801
  for (const [id, question] of this.questions) {
450
802
  if (question.conversation === conversation)
451
803
  this.questions.delete(id);
452
804
  }
453
- 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;
454
826
  }
455
827
  commands(conversation, commands) {
456
828
  conversation.commands = commands;
@@ -461,11 +833,17 @@ export class Conversations {
461
833
  options(conversation, options) {
462
834
  if (conversation.running === null)
463
835
  return;
464
- 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') });
465
843
  }
466
- deliver(conversation, turn, event, body) {
844
+ deliver(conversation, turn, act, body, current) {
467
845
  this.reporting++;
468
- 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));
469
847
  conversation.reports = delivered
470
848
  .catch(() => undefined)
471
849
  .finally(() => {
@@ -475,84 +853,116 @@ export class Conversations {
475
853
  return delivered;
476
854
  }
477
855
  write(conversation, turn, operation) {
478
- if (!turn.admitted || turn.ended || !this.watched)
856
+ if (turn.ended || !this.watched)
479
857
  return;
480
- 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 });
481
859
  }
482
860
  replay(conversation, turn) {
483
- for (const operation of turn.parts.operations())
861
+ for (const operation of turn.content.operations())
484
862
  this.write(conversation, turn, operation);
485
863
  }
486
864
  begin(conversation) {
487
865
  const turn = new Turn((operation) => this.write(conversation, turn, operation));
488
- conversation.open++;
489
- void this.deliver(conversation, turn, 'started', {})
490
- .then(() => {
491
- turn.admitted = true;
492
- this.replay(conversation, turn);
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;
493
872
  })
494
873
  .catch(logged);
495
874
  conversation.turn = turn;
496
- if (conversation.context !== null)
497
- turn.parts.measure(conversation.context);
498
- for (const part of conversation.held.splice(0))
499
- 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);
500
880
  this.kit.changed();
501
881
  return turn;
502
882
  }
503
- end(conversation, turn, failed) {
883
+ end(conversation, turn, failed, notice = null) {
504
884
  if (turn.ended)
505
885
  return;
886
+ if (failed !== null)
887
+ logged(new Error(`conversation ${conversation.id} turn ${turn.id} failed: ${failed.cause}`));
506
888
  if (conversation.turn === turn) {
507
- for (const event of conversation.running?.reader.closeTurn() ?? [])
508
- this.apply(conversation, turn, event);
889
+ for (const event of conversation.reader?.closeTurn() ?? [])
890
+ this.event(conversation, event);
509
891
  }
892
+ if (notice !== null)
893
+ turn.content.add(null, { type: 'notice', kind: 'error', text: notice });
510
894
  turn.ended = true;
511
- conversation.open--;
895
+ conversation.turns.delete(turn);
896
+ conversation.running?.adapter.turn(conversation.turns.size > 0);
512
897
  if (conversation.turn === turn)
513
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) });
514
903
  const body = Promise.allSettled(turn.uploads).then(() => ({
515
- parts: turn.parts.saved(),
516
- context: turn.parts.context,
517
- ...failed,
904
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
905
+ ...(failed === null ? {} : { failed: failed.failure }),
518
906
  }));
519
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
907
+ void this.deliver(conversation, turn, 'turns/end', body).catch(logged);
520
908
  this.next(conversation);
521
909
  this.kit.changed();
522
910
  }
523
- prompt(conversation, prompt) {
911
+ prompt(conversation, prompt, taken) {
524
912
  const running = conversation.running;
525
913
  const turn = this.begin(conversation);
526
914
  turn.prompted = true;
527
- running.adapter.connection.agent.request('session/prompt', { sessionId: running.sessionId, prompt }).then(() => this.end(conversation, turn, null), async (error) => {
915
+ turn.taken = taken;
916
+ conversation.prompted = running.sessionId;
917
+ running.adapter.connection.agent.request('session/prompt', { sessionId: running.sessionId, prompt }).then((answer) => {
918
+ this.took(turn);
919
+ const notice = answeredFailure(answer);
920
+ if (notice !== null) {
921
+ this.end(conversation, turn, { failure: notice.limit ? 'limit' : 'error', cause: notice.title }, notice.title);
922
+ }
923
+ else {
924
+ this.end(conversation, turn, answer.stopReason === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
925
+ }
926
+ }, async (error) => {
528
927
  if (running.adapter.connection.signal.aborted) {
529
- this.end(conversation, turn, { failed: running.killed ? KILLED : await running.adapter.exited });
928
+ this.end(conversation, turn, exitedWith(running, await running.adapter.exited));
530
929
  }
531
930
  else {
532
- if (conversation.open === 1 && conversation.running === running) {
533
- running.scope.kill();
931
+ this.took(turn);
932
+ if (conversation.turns.size === 1 && conversation.turns.has(turn) && conversation.running === running) {
933
+ running.adapter.retire();
534
934
  this.detach(conversation, running);
535
935
  }
536
- this.end(conversation, turn, { failed: causeOf(error) });
936
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
537
937
  }
538
938
  });
539
939
  }
540
940
  started(conversation) {
541
- return conversation.turn ?? this.begin(conversation);
941
+ const turn = conversation.turn ?? this.begin(conversation);
942
+ this.took(turn);
943
+ return turn;
542
944
  }
543
- ended(conversation) {
945
+ ended(conversation, stop) {
544
946
  const turn = conversation.turn;
545
947
  if (turn === null)
546
948
  return;
547
- if (!turn.prompted) {
548
- this.end(conversation, turn, null);
549
- }
550
- else {
551
- for (const event of conversation.running?.reader.closeTurn() ?? [])
552
- this.apply(conversation, turn, event);
553
- conversation.turn = null;
554
- 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;
555
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);
556
966
  }
557
967
  async ask(conversation, method, params, secret, signal) {
558
968
  const turn = this.started(conversation);
@@ -560,7 +970,7 @@ export class Conversations {
560
970
  const answered = new Promise((answer, fail) => {
561
971
  this.questions.set(interactionId, { conversation, answer: (response) => answer(response) });
562
972
  signal.addEventListener('abort', () => answer(null), { once: true });
563
- this.deliver(conversation, turn, 'interactions', {
973
+ this.deliver(conversation, turn, 'conversations/interaction/ask', {
564
974
  interaction_id: interactionId,
565
975
  request: { method, params },
566
976
  secret,
@@ -601,6 +1011,22 @@ export class Conversations {
601
1011
  read(conversation, reader, message) {
602
1012
  for (const event of reader.read(message))
603
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
+ });
604
1030
  }
605
1031
  event(conversation, event) {
606
1032
  switch (event.kind) {
@@ -608,7 +1034,7 @@ export class Conversations {
608
1034
  this.started(conversation);
609
1035
  return;
610
1036
  case 'ended':
611
- this.ended(conversation);
1037
+ this.ended(conversation, event.stop);
612
1038
  return;
613
1039
  case 'commands':
614
1040
  this.commands(conversation, event.commands);
@@ -616,84 +1042,117 @@ export class Conversations {
616
1042
  case 'options':
617
1043
  this.options(conversation, event.options);
618
1044
  return;
619
- case 'context':
620
- conversation.context = { used: event.used, window: event.window };
621
- conversation.turn?.parts.measure(conversation.context);
1045
+ case 'state':
1046
+ this.stated(conversation, event.state);
622
1047
  return;
623
- case 'subagent-done':
624
- this.subagentDone(conversation, event.id, event.result);
1048
+ case 'tokens':
1049
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
625
1050
  return;
626
- case 'marker':
627
- case 'image':
628
- if (conversation.turn !== null)
629
- break;
630
- if (event.kind === 'marker' && event.marker === 'job')
631
- conversation.held.push({ type: 'marker', marker: 'job', text: event.text });
1051
+ case 'part':
1052
+ this.keyed(conversation, event);
632
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;
633
1064
  }
634
1065
  this.apply(conversation, this.started(conversation), event);
635
1066
  }
1067
+ took(turn) {
1068
+ const taken = turn.taken;
1069
+ turn.taken = null;
1070
+ taken?.();
1071
+ }
636
1072
  apply(conversation, turn, event) {
637
1073
  switch (event.kind) {
638
1074
  case 'text':
639
- case 'reasoning':
640
- turn.parts.write(event.kind, event.id, event.text);
641
- return;
642
- case 'command':
643
- turn.parts.command();
644
- return;
645
- case 'subagent': {
646
- const index = turn.parts.start({ type: 'subagent', description: event.description, status: 'running', result: null });
647
- 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);
648
1079
  return;
649
1080
  }
650
- case 'message':
651
- turn.parts.start({ type: 'message', command: event.command, target: event.target });
652
- return;
653
- case 'marker':
654
- 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 });
655
1083
  return;
656
1084
  case 'plan':
657
- turn.parts.plan(event.entries);
1085
+ turn.content.plan(event.entries);
658
1086
  return;
659
1087
  case 'image':
660
- 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));
661
1089
  this.kit.changed();
662
1090
  return;
663
1091
  }
664
1092
  }
665
- subagentDone(conversation, id, result) {
666
- const subagent = conversation.subagents.get(id);
667
- if (subagent === undefined)
668
- return;
669
- conversation.subagents.delete(id);
670
- if (subagent.turn === conversation.turn) {
671
- 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);
672
1108
  return;
673
1109
  }
674
- const part = { type: 'subagent', description: subagent.description, status: 'done', result };
675
- if (conversation.turn === null)
676
- conversation.held.push(part);
677
- else
678
- 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);
679
1131
  }
680
- async image(conversation, turn, reserved, data, mediaType) {
1132
+ async image(conversation, turn, parent, data, mediaType) {
681
1133
  const bytes = Buffer.from(data, 'base64');
682
1134
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
1135
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
683
1136
  try {
684
- const declared = (await this.deliver(conversation, turn, 'images', {
1137
+ const declared = (await this.deliver(conversation, turn, 'turns/images/declare', {
685
1138
  name,
686
1139
  media_type: mediaType,
687
1140
  bytes: bytes.length,
688
- sha256: createHash('sha256').update(bytes).digest('hex'),
1141
+ sha256,
689
1142
  }));
690
- const saved = declared.upload === undefined ? declared : await uploadBytes(declared.upload, bytes);
691
- if (saved.save.status !== 'saved')
692
- throw new Error(saved.save.failure ?? saved.save.status);
693
- 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 });
694
1152
  }
695
1153
  catch (error) {
696
- 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}` });
697
1156
  }
698
1157
  }
699
1158
  }