@agentshouse/kit 0.2.1-ce3d2bb67177c → 0.2.1-ce8e5419af3f9

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 (146) hide show
  1. package/README.md +17 -18
  2. package/dist/acp.js +58 -7
  3. package/dist/afk.js +17 -0
  4. package/dist/agents.js +58 -32
  5. package/dist/authority-main.js +3 -3
  6. package/dist/bridge.js +5 -5
  7. package/dist/building.js +50 -0
  8. package/dist/calls.js +12 -4
  9. package/dist/chunks.js +49 -0
  10. package/dist/clis.js +46 -44
  11. package/dist/connection.js +28 -33
  12. package/dist/content.js +63 -0
  13. package/dist/conversations.js +344 -127
  14. package/dist/copies.js +294 -148
  15. package/dist/end.js +8 -2
  16. package/dist/events.js +742 -210
  17. package/dist/files.js +35 -19
  18. package/dist/git.js +46 -12
  19. package/dist/grok.js +39 -0
  20. package/dist/home.js +0 -7
  21. package/dist/house-cli.js +29 -57
  22. package/dist/house-main.js +3 -3
  23. package/dist/instructions.js +29 -11
  24. package/dist/kit-cli.js +3 -6
  25. package/dist/kit-main.js +3 -3
  26. package/dist/login.js +5 -3
  27. package/dist/logout.js +1 -1
  28. package/dist/mcp.js +2 -0
  29. package/dist/placement.js +10 -18
  30. package/dist/relay.js +21 -0
  31. package/dist/resident.js +47 -26
  32. package/dist/scope.js +12 -4
  33. package/dist/scripts.js +255 -0
  34. package/dist/secret-input.js +1 -1
  35. package/dist/sign-in.js +3 -2
  36. package/dist/silence.js +28 -0
  37. package/dist/skills.js +41 -96
  38. package/dist/transcription.js +37 -24
  39. package/dist/translate.js +18 -9
  40. package/dist/update.js +109 -120
  41. package/dist/wire.js +23 -5
  42. package/dist/work.js +9 -2
  43. package/package.json +21 -20
  44. package/dist/bootstrap.json +0 -24
  45. package/dist/chatgpt.js +0 -32
  46. package/dist/clis-main.js +0 -23
  47. package/dist/parts.js +0 -82
  48. package/how-we-work.md +0 -33
  49. package/skills/ask-matt/LICENSE +0 -21
  50. package/skills/ask-matt/PHASE-BOUNDARIES.md +0 -55
  51. package/skills/ask-matt/SKILL.md +0 -97
  52. package/skills/ask-matt/agents/openai.yaml +0 -5
  53. package/skills/code-review/LICENSE +0 -21
  54. package/skills/code-review/SKILL.md +0 -89
  55. package/skills/code-review/agents/openai.yaml +0 -3
  56. package/skills/codebase-design/DEEPENING.md +0 -37
  57. package/skills/codebase-design/DESIGN-IT-TWICE.md +0 -44
  58. package/skills/codebase-design/LICENSE +0 -21
  59. package/skills/codebase-design/SKILL.md +0 -114
  60. package/skills/codebase-design/agents/openai.yaml +0 -3
  61. package/skills/diagnosing-bugs/LICENSE +0 -21
  62. package/skills/diagnosing-bugs/SKILL.md +0 -138
  63. package/skills/diagnosing-bugs/agents/openai.yaml +0 -3
  64. package/skills/diagnosing-bugs/scripts/hitl-loop.template.sh +0 -44
  65. package/skills/domain-modeling/ADR-FORMAT.md +0 -47
  66. package/skills/domain-modeling/GLOSSARY-FORMAT.md +0 -60
  67. package/skills/domain-modeling/LICENSE +0 -21
  68. package/skills/domain-modeling/SKILL.md +0 -74
  69. package/skills/domain-modeling/agents/openai.yaml +0 -3
  70. package/skills/grill-me/LICENSE +0 -21
  71. package/skills/grill-me/SKILL.md +0 -7
  72. package/skills/grill-me/agents/openai.yaml +0 -5
  73. package/skills/grill-with-docs/LICENSE +0 -21
  74. package/skills/grill-with-docs/SKILL.md +0 -7
  75. package/skills/grill-with-docs/agents/openai.yaml +0 -5
  76. package/skills/grilling/LICENSE +0 -21
  77. package/skills/grilling/SKILL.md +0 -30
  78. package/skills/grilling/agents/openai.yaml +0 -3
  79. package/skills/handoff/LICENSE +0 -21
  80. package/skills/handoff/SKILL.md +0 -16
  81. package/skills/handoff/agents/openai.yaml +0 -5
  82. package/skills/implement/LICENSE +0 -21
  83. package/skills/implement/SKILL.md +0 -17
  84. package/skills/implement/agents/openai.yaml +0 -5
  85. package/skills/implement-spec/LICENSE +0 -21
  86. package/skills/implement-spec/SKILL.md +0 -40
  87. package/skills/implement-spec/agents/openai.yaml +0 -5
  88. package/skills/improve-codebase-architecture/HTML-REPORT.md +0 -123
  89. package/skills/improve-codebase-architecture/LICENSE +0 -21
  90. package/skills/improve-codebase-architecture/SKILL.md +0 -71
  91. package/skills/improve-codebase-architecture/agents/openai.yaml +0 -5
  92. package/skills/pr/CREDITS.md +0 -3
  93. package/skills/pr/LICENSE +0 -21
  94. package/skills/pr/SKILL.md +0 -170
  95. package/skills/pr/agents/openai.yaml +0 -3
  96. package/skills/prototype/LICENSE +0 -21
  97. package/skills/prototype/LOGIC.md +0 -67
  98. package/skills/prototype/SKILL.md +0 -26
  99. package/skills/prototype/UI.md +0 -112
  100. package/skills/prototype/agents/openai.yaml +0 -3
  101. package/skills/research/LICENSE +0 -21
  102. package/skills/research/SKILL.md +0 -12
  103. package/skills/research/agents/openai.yaml +0 -3
  104. package/skills/retro/LICENSE +0 -21
  105. package/skills/retro/SKILL.md +0 -44
  106. package/skills/retro/agents/openai.yaml +0 -5
  107. package/skills/tdd/LICENSE +0 -21
  108. package/skills/tdd/SKILL.md +0 -38
  109. package/skills/tdd/agents/openai.yaml +0 -3
  110. package/skills/tdd/mocking.md +0 -59
  111. package/skills/tdd/tests.md +0 -77
  112. package/skills/teach/GLOSSARY-FORMAT.md +0 -35
  113. package/skills/teach/LEARNING-RECORD-FORMAT.md +0 -46
  114. package/skills/teach/LICENSE +0 -21
  115. package/skills/teach/MISSION-FORMAT.md +0 -31
  116. package/skills/teach/RESOURCES-FORMAT.md +0 -32
  117. package/skills/teach/SKILL.md +0 -140
  118. package/skills/teach/agents/openai.yaml +0 -5
  119. package/skills/to-questionnaire/LICENSE +0 -21
  120. package/skills/to-questionnaire/SKILL.md +0 -54
  121. package/skills/to-questionnaire/agents/openai.yaml +0 -5
  122. package/skills/to-spec/LICENSE +0 -21
  123. package/skills/to-spec/SKILL.md +0 -75
  124. package/skills/to-spec/agents/openai.yaml +0 -5
  125. package/skills/to-tickets/LICENSE +0 -21
  126. package/skills/to-tickets/SKILL.md +0 -105
  127. package/skills/to-tickets/agents/openai.yaml +0 -5
  128. package/skills/triage/AGENT-BRIEF.md +0 -207
  129. package/skills/triage/LICENSE +0 -21
  130. package/skills/triage/OUT-OF-SCOPE.md +0 -105
  131. package/skills/triage/SKILL.md +0 -112
  132. package/skills/triage/agents/openai.yaml +0 -5
  133. package/skills/wait-what/LICENSE +0 -21
  134. package/skills/wait-what/SKILL.md +0 -7
  135. package/skills/wait-what/agents/openai.yaml +0 -5
  136. package/skills/wayfinder/LICENSE +0 -21
  137. package/skills/wayfinder/SKILL.md +0 -128
  138. package/skills/wayfinder/agents/openai.yaml +0 -5
  139. package/skills/wizard/LICENSE +0 -21
  140. package/skills/wizard/SKILL.md +0 -44
  141. package/skills/wizard/agents/openai.yaml +0 -3
  142. package/skills/wizard/template.sh +0 -223
  143. package/skills/writing-for-agents/LICENSE +0 -21
  144. package/skills/writing-for-agents/SKILL-MECHANICS.md +0 -22
  145. package/skills/writing-for-agents/SKILL.md +0 -81
  146. package/skills/writing-for-agents/agents/openai.yaml +0 -3
@@ -1,25 +1,25 @@
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';
6
+ import { signedOut, startAdapter } from './acp.js';
7
+ import { formAnswered, grokQuestionAnswered, permissionAllowed, PLAN_APPROVED } from './afk.js';
7
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
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';
16
18
  import { relayed } from './relay.js';
17
19
  import { killMarked, Scope } from './scope.js';
18
20
  import { holdSecretInput } from './secret-input.js';
19
- import { createHowWeWork } from './skills.js';
20
21
  import { transcribe } from './transcription.js';
21
22
  import { workFor } from './work.js';
22
- const SIGNED_OUT = RequestError.authRequired().code;
23
23
  const KILLED = 'the conversation was killed';
24
24
  const INTERRUPTED = 'the conversation was interrupted';
25
25
  const REFUSED = 'the CLI refused the prompt';
@@ -35,6 +35,27 @@ const NO_SESSION = "the Agent's CLI did not open a session";
35
35
  const NO_RESUME = "the Agent's CLI could not resume this conversation";
36
36
  const NOT_SIGNED_IN = "the Agent's CLI is not signed in; sign it in on the Agent's machine";
37
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;
38
59
  class NotStarted extends Error {
39
60
  }
40
61
  class ResumeRefused extends NotStarted {
@@ -47,9 +68,6 @@ async function step(reason, work) {
47
68
  throw new NotStarted(typeof reason === 'string' ? reason : reason(error), { cause: error });
48
69
  }
49
70
  }
50
- function signedOut(error) {
51
- return typeof error === 'object' && error !== null && error.code === SIGNED_OUT;
52
- }
53
71
  function unopened(reason) {
54
72
  return (error) => (signedOut(error) ? NOT_SIGNED_IN : reason);
55
73
  }
@@ -58,15 +76,34 @@ const STARTING_SHOWN_AFTER_MS = 1_000;
58
76
  function unbridged(error) {
59
77
  return (finalRefusal(error) ? ENDED[refusalOf(error.text)?.code ?? ''] : undefined) ?? NO_CONNECTION;
60
78
  }
61
- const EXIT_PLAN_MODE = {
79
+ const GROK_PLAN = {
80
+ parse(value) {
81
+ return value;
82
+ },
83
+ };
84
+ const GROK_QUESTION = {
62
85
  parse(value) {
63
- if (typeof value !== 'object' || value === null || Array.isArray(value)) {
64
- throw new Error('_x.ai/exit_plan_mode needs an object');
65
- }
66
86
  return value;
67
87
  },
68
88
  };
69
- export const CONVERSATION_METHODS = 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
+ }
70
107
  function causeOf(error) {
71
108
  return error instanceof Error ? error.message : String(error);
72
109
  }
@@ -74,13 +111,15 @@ function answeredWith(error) {
74
111
  return { failure: signedOut(error) ? 'signed_out' : 'error', cause: causeOf(error) };
75
112
  }
76
113
  function exitedWith(running, cause) {
77
- 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 };
78
117
  }
79
118
  function answerMessage(request, response) {
80
119
  return `The User answered a question you asked earlier.\nQuestion: ${JSON.stringify(request)}\nAnswer: ${JSON.stringify(response)}`;
81
120
  }
82
- async function sentPart(url, bytes) {
83
- const answer = await fetch(relayed(url), { method: 'PUT', body: bytes });
121
+ async function sentPart(url, bytes, headers) {
122
+ const answer = await fetch(relayed(url), { method: 'PUT', headers, body: bytes });
84
123
  await answer.arrayBuffer();
85
124
  if (!answer.ok)
86
125
  throw storeRefusal('upload', answer.status);
@@ -104,18 +143,23 @@ function audioOf(result) {
104
143
  function marker(bridge) {
105
144
  return `HOUSE_BRIDGE=${bridge.env.HOUSE_BRIDGE}`;
106
145
  }
146
+ function steers(adapter) {
147
+ return adapter.initialized._meta?.steering?.supported === true;
148
+ }
107
149
  class Turn {
108
150
  id = randomUUID();
109
- parts;
151
+ content;
110
152
  questions = 0;
111
153
  secrets = 0;
112
154
  prompted = false;
155
+ steered = false;
113
156
  taken = null;
114
157
  ended = false;
158
+ quietUntil = Infinity;
115
159
  images = 0;
116
160
  uploads = [];
117
161
  constructor(emit) {
118
- this.parts = new Parts(emit);
162
+ this.content = new Content(emit);
119
163
  }
120
164
  }
121
165
  class Conversation {
@@ -126,11 +170,16 @@ class Conversation {
126
170
  commands = null;
127
171
  options = null;
128
172
  exitUntold = false;
129
- context = null;
173
+ afk = false;
174
+ reader = null;
175
+ state = QUIET;
176
+ sentState = null;
177
+ tokens = null;
130
178
  leftovers = new Set();
131
179
  waiting = [];
180
+ done = false;
132
181
  sending = null;
133
- subagents = new Map();
182
+ work = new Map();
134
183
  held = [];
135
184
  opening = null;
136
185
  bridge = null;
@@ -140,7 +189,7 @@ class Conversation {
140
189
  killed = new AbortController();
141
190
  interrupts = 0;
142
191
  interrupted = new AbortController();
143
- open = 0;
192
+ turns = new Set();
144
193
  queue = Promise.resolve();
145
194
  reports = Promise.resolve();
146
195
  starting = null;
@@ -166,6 +215,7 @@ export class Conversations {
166
215
  questions = new Map();
167
216
  reporting = 0;
168
217
  watched = false;
218
+ stopping = false;
169
219
  constructor(kit) {
170
220
  this.kit = kit;
171
221
  // A process or a durable schedule ends without a report, so the Kit looks at both again every two seconds.
@@ -174,6 +224,8 @@ export class Conversations {
174
224
  call(call) {
175
225
  void this.kit.calls.carry(call.input_id, () => {
176
226
  const conversation = this.conversation(call.conversation_id);
227
+ if (call.kind === 'open' || call.kind === 'message')
228
+ conversation.afk = call.afk === true;
177
229
  if (call.kind === 'kill') {
178
230
  conversation.kills++;
179
231
  conversation.killed.abort(new Error(KILLED));
@@ -196,7 +248,7 @@ export class Conversations {
196
248
  for (const conversation of this.conversations.values()) {
197
249
  const turn = conversation.turn;
198
250
  const asking = turn !== null && turn.questions > 0 && turn.secrets === 0;
199
- if (conversation.open > (asking ? 1 : 0))
251
+ if (conversation.turns.size > (asking ? 1 : 0))
200
252
  return false;
201
253
  }
202
254
  const conversations = [...this.conversations.values()];
@@ -205,7 +257,7 @@ export class Conversations {
205
257
  return !conversations.some((conversation) => conversation.running?.scope.working() || [...conversation.leftovers].some((scope) => scope.working()));
206
258
  }
207
259
  quiet() {
208
- return this.idle() && [...this.conversations.values()].every((conversation) => conversation.open === 0);
260
+ return this.idle() && [...this.conversations.values()].every((conversation) => conversation.turns.size === 0);
209
261
  }
210
262
  look() {
211
263
  for (const conversation of this.conversations.values()) {
@@ -218,11 +270,20 @@ export class Conversations {
218
270
  }
219
271
  this.kit.changed();
220
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
+ }
221
280
  opened() {
222
281
  this.watched = false;
223
282
  for (const conversation of this.conversations.values()) {
224
- if (conversation.running !== null)
283
+ if (conversation.running !== null) {
225
284
  this.facts(conversation);
285
+ this.stateChanged(conversation, true);
286
+ }
226
287
  else if (conversation.exitUntold)
227
288
  this.process(conversation, false);
228
289
  if (conversation.untold || conversation.told !== null)
@@ -249,9 +310,16 @@ export class Conversations {
249
310
  }
250
311
  async carry(conversation, call) {
251
312
  if (call.kind === 'open')
252
- return { result: this.open(conversation, call) };
313
+ return this.open(conversation, call);
253
314
  if (call.kind === 'message')
254
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))) };
255
323
  await this.launched(conversation);
256
324
  if (call.kind === 'interrupt') {
257
325
  if (--conversation.interrupts === 0)
@@ -276,11 +344,25 @@ export class Conversations {
276
344
  }
277
345
  return { result: Promise.resolve({}) };
278
346
  }
279
- open(conversation, call) {
280
- if (conversation.running !== null)
281
- return Promise.resolve({});
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);
282
357
  const launch = conversation.launch ?? this.launch(conversation, this.route(conversation, call.agent_id), null, true);
283
- return launch.session.then((session) => ({ provider_session_id: session }), (error) => ({ refused: refusal(conversation, error) }));
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;
284
366
  }
285
367
  launch(conversation, route, sessionId, empty) {
286
368
  let opened;
@@ -314,12 +396,15 @@ export class Conversations {
314
396
  const bridge = conversation.running === null ? conversation.launch?.bridge : Promise.resolve(conversation.running.bridge);
315
397
  if (bridge === undefined)
316
398
  return null;
317
- const read = Promise.all([bridge, this.kit.copies.mapping()]).then(([opened, copies]) => instructions(opened, route.base_instructions, copies));
399
+ const read = bridge.then((opened) => instructions(opened, route.base_instructions));
318
400
  read.catch(() => undefined);
319
401
  return read;
320
402
  }
321
403
  async message(conversation, call) {
322
- const content = [{ type: 'text', text: String(call.text) }];
404
+ const content = [
405
+ ...(typeof call.recent === 'string' ? [{ type: 'text', text: call.recent }] : []),
406
+ { type: 'text', text: String(call.text) },
407
+ ];
323
408
  let route;
324
409
  let instructing = null;
325
410
  try {
@@ -337,21 +422,71 @@ export class Conversations {
337
422
  return { result: Promise.resolve({ refused: refusal(conversation, error) }) };
338
423
  }
339
424
  conversation.preparing = null;
340
- return {
341
- result: new Promise((settle) => {
342
- conversation.waiting.push({ call, route, content, instructing, settle });
343
- this.next(conversation);
344
- }),
345
- };
425
+ const { promise, resolve: settle } = Promise.withResolvers();
426
+ const waiting = { call, route, content, instructing, settle };
427
+ if (call.at_once === true && conversation.turns.size > 0)
428
+ await this.atOnce(conversation, waiting);
429
+ else
430
+ conversation.waiting.push(waiting);
431
+ this.next(conversation);
432
+ return { result: promise };
433
+ }
434
+ async atOnce(conversation, waiting) {
435
+ while (conversation.sending !== null)
436
+ await conversation.sending;
437
+ const running = conversation.running;
438
+ if (running !== null && conversation.turns.size > 0 && steers(running.adapter)) {
439
+ conversation.sending = this.steer(conversation, running, waiting);
440
+ await conversation.sending;
441
+ conversation.sending = null;
442
+ return;
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;
454
+ try {
455
+ ({ outcome } = await running.adapter.connection.agent.request('_session/steering', {
456
+ sessionId: running.sessionId,
457
+ prompt: waiting.content,
458
+ _meta: { steering: { idleBehavior: 'promptRequired' } },
459
+ }));
460
+ }
461
+ catch (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 })) });
478
+ }
346
479
  }
347
480
  next(conversation) {
348
- if (conversation.sending !== null || conversation.open > 0)
481
+ if (this.stopping || conversation.sending !== null || conversation.turns.size > 0)
349
482
  return;
350
483
  const waiting = conversation.waiting.shift();
351
484
  if (waiting === undefined) {
352
485
  const step = conversation.preparing ?? (conversation.launch === null ? null : 'session');
353
486
  if (conversation.starting !== step)
354
487
  this.starts(conversation, step);
488
+ if (conversation.done && conversation.launch === null)
489
+ void this.stop(conversation).catch(logged);
355
490
  return;
356
491
  }
357
492
  conversation.sending = this.send(conversation, waiting).finally(() => {
@@ -456,8 +591,7 @@ export class Conversations {
456
591
  throw new Error(`${path} is no longer an audio file`);
457
592
  return address;
458
593
  }, signal);
459
- const transcript = `/kit/conversations/${conversation.id}/messages/${messageId}/transcripts`;
460
- await step(unbridged, unlessAborted(this.kit.house.deliver(transcript, { path, text: said }, () => !signal.aborted), signal));
594
+ await step(unbridged, unlessAborted(this.kit.house.deliver('/kit/transcripts/keep', { conversation: conversation.id, message: messageId, path, text: said }, () => !signal.aborted), signal));
461
595
  blocks.push({ type: 'text', text: `${path}\nTranscript: ${said}` });
462
596
  }
463
597
  }
@@ -492,7 +626,11 @@ export class Conversations {
492
626
  void bridging.then((bridge) => bridge.close(), () => undefined);
493
627
  }
494
628
  async interrupt(conversation, turnId) {
495
- 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)
496
634
  return;
497
635
  await conversation.running.adapter.connection.agent.notify('session/cancel', {
498
636
  sessionId: conversation.running.sessionId,
@@ -548,10 +686,12 @@ export class Conversations {
548
686
  const route = await routed;
549
687
  const reader = readerFor(route.kind);
550
688
  reader.session = sessionId;
689
+ conversation.reader = reader;
551
690
  const app = client({ name: '@agentshouse/kit' })
552
- .onRequest('session/request_permission', ({ params, signal }) => this.ask(conversation, 'session/request_permission', params, false, signal))
553
- .onRequest('elicitation/create', ({ params, signal }) => this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
554
- .onRequest('_x.ai/exit_plan_mode', EXIT_PLAN_MODE, ({ params, signal }) => this.ask(conversation, '_x.ai/exit_plan_mode', params, false, signal));
691
+ .onRequest('session/request_permission', ({ params, signal }) => conversation.afk ? permissionAllowed(params) : this.ask(conversation, 'session/request_permission', params, false, signal))
692
+ .onRequest('elicitation/create', ({ params, signal }) => conversation.afk ? formAnswered(route.kind, params) : this.ask(conversation, 'elicitation/create', params, asksSecret(params), signal))
693
+ .onRequest('_x.ai/exit_plan_mode', GROK_PLAN, async ({ params, signal }) => conversation.afk ? PLAN_APPROVED : grokPlanAnswer(await this.askForm(conversation, grokPlanForm(params), signal)))
694
+ .onRequest('_x.ai/ask_user_question', GROK_QUESTION, async ({ params, signal }) => conversation.afk ? grokQuestionAnswered(params) : grokQuestionAnswer(await this.askForm(conversation, grokQuestionForm(params), signal)));
555
695
  const cli = await unlessAborted(this.kit.agents.cli(route.kind), conversation.killed.signal);
556
696
  const bridging = this.bridged(conversation);
557
697
  const bridge = await step(unbridged, bridging);
@@ -560,14 +700,15 @@ export class Conversations {
560
700
  throw new Error(KILLED);
561
701
  }
562
702
  conversation.opening = bridge;
563
- const work = workFor(route.kind, route.working_directory, () => this.kit.changed());
703
+ const work = workFor(route.kind, route.working_directory, () => this.kit.changed(), (message) => this.tapped(conversation, reader, message));
564
704
  const scope = new Scope(marker(bridge), randomUUID(), cli);
565
705
  let adapter = null;
566
706
  try {
567
- await unlessAborted(createHowWeWork(bridge), conversation.killed.signal);
568
707
  bridged(bridge);
569
708
  await CLIS[route.kind].allowHouse(bridge.env.PATH);
570
709
  const streamed = await step(NO_CONNECTION, work.open(cli));
710
+ if (this.stopping)
711
+ throw new Error(KILLED);
571
712
  adapter = await step(NO_START, startAdapter(route.kind, cli, route.working_directory, app, (message) => {
572
713
  work.read(message);
573
714
  this.read(conversation, reader, message);
@@ -575,18 +716,17 @@ export class Conversations {
575
716
  void adapter.exited.then(() => this.closeBridge(conversation, bridging, bridge));
576
717
  const agent = adapter.connection.agent;
577
718
  const cwd = route.working_directory;
578
- const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE, conversation.id);
719
+ const _meta = CLIS[route.kind].sessionMeta(bridge.env.HOUSE_BRIDGE);
579
720
  const resumed = sessionId === null ? null : await this.resume(conversation, route.kind, adapter, { sessionId, cwd, mcpServers: [], _meta }, empty);
580
721
  const opened = resumed ?? (await step(unopened(NO_SESSION), agent.request('session/new', { cwd, mcpServers: [], _meta })));
581
722
  reader.session = opened.sessionId;
582
- if (opened.sessionId !== sessionId && CLIS[route.kind].renames) {
583
- const prompt = [{ type: 'text', text: `/rename ${conversation.id}` }];
584
- await step(unopened(NO_SESSION), agent.request('session/prompt', { sessionId: opened.sessionId, prompt }));
585
- }
723
+ if (opened.sessionId !== conversation.session)
724
+ conversation.state = QUIET;
586
725
  const running = { adapter, bridging, bridge, sessionId: opened.sessionId, killed: false, reader, work, scope };
587
726
  const options = await step(NO_SETTINGS, this.launchSettings(running, route, opened.configOptions ?? []));
588
727
  void work.settled().then(() => scope.record());
589
728
  conversation.running = running;
729
+ adapter.turn(conversation.turns.size > 0);
590
730
  conversation.session = running.sessionId;
591
731
  conversation.options = options;
592
732
  this.facts(conversation);
@@ -653,6 +793,8 @@ export class Conversations {
653
793
  conversation.running = null;
654
794
  conversation.commands = null;
655
795
  conversation.options = null;
796
+ conversation.work.clear();
797
+ this.stated(conversation, { running: [] });
656
798
  for (const [id, question] of this.questions) {
657
799
  if (question.conversation === conversation)
658
800
  this.questions.delete(id);
@@ -669,6 +811,16 @@ export class Conversations {
669
811
  if (conversation.options !== null)
670
812
  this.options(conversation, conversation.options);
671
813
  }
814
+ stated(conversation, change) {
815
+ conversation.state = { ...conversation.state, ...change };
816
+ this.stateChanged(conversation, false);
817
+ }
818
+ stateChanged(conversation, again) {
819
+ const state = JSON.stringify(conversation.state);
820
+ if (!again && state === conversation.sentState)
821
+ return;
822
+ conversation.sentState = this.kit.send({ type: 'state', conversation_id: conversation.id, state: conversation.state }) ? state : null;
823
+ }
672
824
  commands(conversation, commands) {
673
825
  conversation.commands = commands;
674
826
  if (conversation.running === null)
@@ -680,10 +832,15 @@ export class Conversations {
680
832
  return;
681
833
  conversation.options = options;
682
834
  this.kit.send({ type: 'options', conversation_id: conversation.id, options });
835
+ const chosen = (category) => {
836
+ const value = options.find((option) => option.category === category)?.currentValue;
837
+ return value === undefined ? null : String(value);
838
+ };
839
+ this.stated(conversation, { model: chosen('model'), effort: chosen('thought_level'), mode: chosen('mode') });
683
840
  }
684
- deliver(conversation, turn, event, body) {
841
+ deliver(conversation, turn, act, body, current) {
685
842
  this.reporting++;
686
- const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/conversations/${conversation.id}/turns/${turn.id}/${event}`, await body));
843
+ const delivered = conversation.reports.then(async () => this.kit.house.deliver(`/kit/${act}`, { conversation: conversation.id, turn: turn.id, ...(await body) }, current));
687
844
  conversation.reports = delivered
688
845
  .catch(() => undefined)
689
846
  .finally(() => {
@@ -695,21 +852,28 @@ export class Conversations {
695
852
  write(conversation, turn, operation) {
696
853
  if (turn.ended || !this.watched)
697
854
  return;
698
- this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, ...operation });
855
+ this.kit.send({ type: 'turn', conversation_id: conversation.id, turn_id: turn.id, operation });
699
856
  }
700
857
  replay(conversation, turn) {
701
- for (const operation of turn.parts.operations())
858
+ for (const operation of turn.content.operations())
702
859
  this.write(conversation, turn, operation);
703
860
  }
704
861
  begin(conversation) {
705
862
  const turn = new Turn((operation) => this.write(conversation, turn, operation));
706
- conversation.open++;
707
- void this.deliver(conversation, turn, 'started', {}).catch(logged);
863
+ conversation.turns.add(turn);
864
+ conversation.running?.adapter.turn(true);
865
+ void this.deliver(conversation, turn, 'turns/start', {})
866
+ .then((answer) => {
867
+ if (answer.run === true)
868
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
869
+ })
870
+ .catch(logged);
708
871
  conversation.turn = turn;
709
- if (conversation.context !== null)
710
- turn.parts.measure(conversation.context);
711
- for (const part of conversation.held.splice(0))
712
- turn.parts.start(part);
872
+ this.stated(conversation, { suggestion: null });
873
+ for (const event of conversation.reader?.began() ?? [])
874
+ this.event(conversation, event);
875
+ for (const held of conversation.held.splice(0))
876
+ this.place(conversation, turn, held);
713
877
  this.kit.changed();
714
878
  return turn;
715
879
  }
@@ -719,21 +883,25 @@ export class Conversations {
719
883
  if (failed !== null)
720
884
  logged(new Error(`conversation ${conversation.id} turn ${turn.id} failed: ${failed.cause}`));
721
885
  if (conversation.turn === turn) {
722
- for (const event of conversation.running?.reader.closeTurn() ?? [])
723
- this.apply(conversation, turn, event);
886
+ for (const event of conversation.reader?.closeTurn() ?? [])
887
+ this.event(conversation, event);
724
888
  }
725
889
  if (notice !== null)
726
- turn.parts.start({ type: 'marker', marker: 'retry', text: notice });
890
+ turn.content.add(null, { type: 'notice', kind: 'error', text: notice });
727
891
  turn.ended = true;
728
- conversation.open--;
892
+ conversation.turns.delete(turn);
893
+ conversation.running?.adapter.turn(conversation.turns.size > 0);
729
894
  if (conversation.turn === turn)
730
895
  conversation.turn = null;
896
+ const tokens = conversation.tokens;
897
+ conversation.tokens = null;
898
+ if (tokens !== null)
899
+ this.stated(conversation, { tokens: addedTokens(conversation.state.tokens, tokens) });
731
900
  const body = Promise.allSettled(turn.uploads).then(() => ({
732
- parts: turn.parts.saved(),
733
- context: turn.parts.context,
901
+ content: { parts: turn.content.parts, tokens, state: conversation.state },
734
902
  ...(failed === null ? {} : { failed: failed.failure }),
735
903
  }));
736
- void this.deliver(conversation, turn, 'ended', body).catch(logged);
904
+ void this.deliver(conversation, turn, 'turns/end', body).catch(logged);
737
905
  this.next(conversation);
738
906
  this.kit.changed();
739
907
  }
@@ -758,11 +926,11 @@ export class Conversations {
758
926
  }
759
927
  else {
760
928
  this.took(turn);
761
- if (conversation.open === 1 && conversation.running === running) {
929
+ if (conversation.turns.size === 1 && conversation.turns.has(turn) && conversation.running === running) {
762
930
  running.adapter.retire();
763
931
  this.detach(conversation, running);
764
932
  }
765
- this.end(conversation, turn, answeredWith(error));
933
+ this.end(conversation, turn, answeredWith(error), cliSaid(error));
766
934
  }
767
935
  });
768
936
  }
@@ -771,19 +939,27 @@ export class Conversations {
771
939
  this.took(turn);
772
940
  return turn;
773
941
  }
774
- ended(conversation) {
942
+ ended(conversation, stop) {
775
943
  const turn = conversation.turn;
776
944
  if (turn === null)
777
945
  return;
778
- if (!turn.prompted) {
779
- this.end(conversation, turn, null);
780
- }
781
- else {
782
- for (const event of conversation.running?.reader.closeTurn() ?? [])
783
- this.apply(conversation, turn, event);
784
- conversation.turn = null;
785
- this.kit.changed();
946
+ const held = stop !== null &&
947
+ !turn.steered &&
948
+ [...conversation.work.values()].some((work) => work.part.type === 'subagent' && turn.content.index(work.key) !== undefined);
949
+ if (!turn.prompted || held) {
950
+ this.took(turn);
951
+ this.end(conversation, turn, stop === 'refusal' ? { failure: 'refused', cause: REFUSED } : null);
952
+ return;
786
953
  }
954
+ if (stop !== null)
955
+ return;
956
+ for (const event of conversation.reader?.closeTurn() ?? [])
957
+ this.event(conversation, event);
958
+ conversation.turn = null;
959
+ this.kit.changed();
960
+ }
961
+ askForm(conversation, form, signal) {
962
+ return this.ask(conversation, 'elicitation/create', form, false, signal);
787
963
  }
788
964
  async ask(conversation, method, params, secret, signal) {
789
965
  const turn = this.started(conversation);
@@ -791,7 +967,7 @@ export class Conversations {
791
967
  const answered = new Promise((answer, fail) => {
792
968
  this.questions.set(interactionId, { conversation, answer: (response) => answer(response) });
793
969
  signal.addEventListener('abort', () => answer(null), { once: true });
794
- this.deliver(conversation, turn, 'interactions', {
970
+ this.deliver(conversation, turn, 'conversations/interaction/ask', {
795
971
  interaction_id: interactionId,
796
972
  request: { method, params },
797
973
  secret,
@@ -832,6 +1008,22 @@ export class Conversations {
832
1008
  read(conversation, reader, message) {
833
1009
  for (const event of reader.read(message))
834
1010
  this.event(conversation, event);
1011
+ this.reportActivity(conversation);
1012
+ }
1013
+ tapped(conversation, reader, message) {
1014
+ for (const event of reader.tap(message))
1015
+ this.event(conversation, event);
1016
+ }
1017
+ reportActivity(conversation) {
1018
+ const turn = conversation.turn;
1019
+ if (turn === null || Date.now() < turn.quietUntil)
1020
+ return;
1021
+ turn.quietUntil = Infinity;
1022
+ void this.deliver(conversation, turn, 'turns/activity/report', {}, () => false)
1023
+ .catch(logged)
1024
+ .finally(() => {
1025
+ turn.quietUntil = Date.now() + ACTIVITY_REPORT_MS;
1026
+ });
835
1027
  }
836
1028
  event(conversation, event) {
837
1029
  switch (event.kind) {
@@ -839,7 +1031,7 @@ export class Conversations {
839
1031
  this.started(conversation);
840
1032
  return;
841
1033
  case 'ended':
842
- this.ended(conversation);
1034
+ this.ended(conversation, event.stop);
843
1035
  return;
844
1036
  case 'commands':
845
1037
  this.commands(conversation, event.commands);
@@ -847,20 +1039,25 @@ export class Conversations {
847
1039
  case 'options':
848
1040
  this.options(conversation, event.options);
849
1041
  return;
850
- case 'context':
851
- conversation.context = { used: event.used, window: event.window };
852
- conversation.turn?.parts.measure(conversation.context);
1042
+ case 'state':
1043
+ this.stated(conversation, event.state);
853
1044
  return;
854
- case 'subagent-done':
855
- this.subagentDone(conversation, event.id, event.result);
1045
+ case 'tokens':
1046
+ conversation.tokens = addedTokens(conversation.tokens, event.tokens);
856
1047
  return;
857
- case 'marker':
858
- case 'image':
859
- if (conversation.turn !== null)
860
- break;
861
- if (event.kind === 'marker' && event.marker === 'job')
862
- conversation.held.push({ type: 'marker', marker: 'job', text: event.text });
1048
+ case 'part':
1049
+ this.keyed(conversation, event);
863
1050
  return;
1051
+ case 'notice':
1052
+ case 'image':
1053
+ if (conversation.turn === null)
1054
+ return;
1055
+ break;
1056
+ case 'text':
1057
+ case 'reasoning':
1058
+ if (event.parent !== null && conversation.turn === null)
1059
+ return;
1060
+ break;
864
1061
  }
865
1062
  this.apply(conversation, this.started(conversation), event);
866
1063
  }
@@ -872,67 +1069,87 @@ export class Conversations {
872
1069
  apply(conversation, turn, event) {
873
1070
  switch (event.kind) {
874
1071
  case 'text':
875
- case 'reasoning':
876
- turn.parts.write(event.kind, event.id, event.text);
877
- return;
878
- case 'command':
879
- turn.parts.command();
880
- return;
881
- case 'subagent': {
882
- const index = turn.parts.start({ type: 'subagent', description: event.description, status: 'running', result: null });
883
- conversation.subagents.set(event.id, { description: event.description, turn, index });
1072
+ case 'reasoning': {
1073
+ const parent = this.parentIn(conversation, turn, event.parent);
1074
+ if (parent !== undefined)
1075
+ turn.content.write(event.kind, event.id, parent, event.text);
884
1076
  return;
885
1077
  }
886
- case 'message':
887
- turn.parts.start({ type: 'message', command: event.command, target: event.target });
888
- return;
889
- case 'marker':
890
- turn.parts.start({ type: 'marker', marker: event.marker, text: event.text });
1078
+ case 'notice':
1079
+ turn.content.add(null, { type: 'notice', kind: event.notice, text: event.text });
891
1080
  return;
892
1081
  case 'plan':
893
- turn.parts.plan(event.entries);
1082
+ turn.content.plan(event.entries);
894
1083
  return;
895
1084
  case 'image':
896
- turn.uploads.push(this.image(conversation, turn, turn.parts.reserve(), event.data, event.mediaType));
1085
+ turn.uploads.push(this.image(conversation, turn, event.parent, event.data, event.mediaType));
897
1086
  this.kit.changed();
898
1087
  return;
899
1088
  }
900
1089
  }
901
- subagentDone(conversation, id, result) {
902
- const subagent = conversation.subagents.get(id);
903
- if (subagent === undefined)
904
- return;
905
- conversation.subagents.delete(id);
906
- if (subagent.turn === conversation.turn) {
907
- subagent.turn.parts.done(subagent.index, result);
1090
+ keyed(conversation, keyed) {
1091
+ const running = workRuns(keyed.part);
1092
+ const earlier = running !== null && conversation.work.has(keyed.key) && conversation.turn?.content.index(keyed.key) === undefined;
1093
+ if (running === true)
1094
+ conversation.work.set(keyed.key, keyed);
1095
+ if (running === false)
1096
+ conversation.work.delete(keyed.key);
1097
+ const turn = conversation.turn;
1098
+ if (earlier) {
1099
+ if (running)
1100
+ return;
1101
+ if (turn === null)
1102
+ conversation.held.push(keyed);
1103
+ else
1104
+ this.place(conversation, turn, keyed);
908
1105
  return;
909
1106
  }
910
- const part = { type: 'subagent', description: subagent.description, status: 'done', result };
911
- if (conversation.turn === null)
912
- conversation.held.push(part);
913
- else
914
- conversation.turn.parts.start(part);
1107
+ if (keyed.parent !== null && turn === null)
1108
+ return;
1109
+ this.place(conversation, this.started(conversation), keyed);
1110
+ }
1111
+ place(conversation, turn, keyed) {
1112
+ const parent = this.parentIn(conversation, turn, keyed.parent);
1113
+ if (parent === undefined && workRuns(keyed.part) === null)
1114
+ return;
1115
+ turn.content.put(keyed.key, parent ?? null, keyed.part);
915
1116
  }
916
- async image(conversation, turn, reserved, data, mediaType) {
1117
+ parentIn(conversation, turn, key) {
1118
+ if (key === null)
1119
+ return null;
1120
+ const index = turn.content.index(key);
1121
+ if (index !== undefined)
1122
+ return turn.content.parts[index].type === 'subagent' ? index : undefined;
1123
+ const running = conversation.work.get(key);
1124
+ if (running?.part.type !== 'subagent')
1125
+ return undefined;
1126
+ const parent = this.parentIn(conversation, turn, running.parent);
1127
+ return parent === undefined ? undefined : turn.content.put(key, parent, running.part);
1128
+ }
1129
+ async image(conversation, turn, parent, data, mediaType) {
917
1130
  const bytes = Buffer.from(data, 'base64');
918
1131
  const name = `image-${++turn.images}.${mediaType.split('/')[1]}`;
1132
+ const sha256 = createHash('sha256').update(bytes).digest('hex');
919
1133
  try {
920
- const declared = (await this.deliver(conversation, turn, 'images', {
1134
+ const declared = (await this.deliver(conversation, turn, 'turns/images/declare', {
921
1135
  name,
922
1136
  media_type: mediaType,
923
1137
  bytes: bytes.length,
924
- sha256: createHash('sha256').update(bytes).digest('hex'),
1138
+ sha256,
925
1139
  }));
926
1140
  const saved = await uploaded(declared.upload, {
1141
+ name,
927
1142
  bytes: bytes.length,
928
- send: (url, start, end) => sentPart(url, bytes.subarray(start, end)),
929
- finish: (upload) => this.kit.house.deliver('/kit/uploads/finish', { upload }),
1143
+ sha256,
1144
+ read: (start, end) => [bytes.subarray(start, end)],
1145
+ send: (url, start, end, headers) => sentPart(url, bytes.subarray(start, end), headers),
1146
+ finish: (upload, partSha256) => this.kit.house.deliver('/kit/uploads/finish', { upload, part_sha256: partSha256 }),
930
1147
  });
931
- turn.parts.arrive({ type: 'image', file: saved.path, name, media_type: mediaType }, reserved);
1148
+ turn.content.arrived(this.parentIn(conversation, turn, parent) ?? null, { type: 'image', file: saved.path, name, media_type: mediaType });
932
1149
  }
933
1150
  catch (error) {
934
1151
  const cause = error instanceof HouseRefusal ? (refusalOf(error.text)?.text ?? causeOf(error)) : causeOf(error);
935
- turn.parts.arrive({ type: 'marker', marker: 'retry', text: `${name} was not saved: ${cause}` }, reserved);
1152
+ turn.content.arrived(null, { type: 'notice', kind: 'error', text: `${name} was not saved: ${cause}` });
936
1153
  }
937
1154
  }
938
1155
  }