mixdog 1.4.3 → 1.4.4

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 (80) hide show
  1. package/package.json +1 -1
  2. package/src/defaults/shipped-history.json +4 -0
  3. package/src/defaults/skills/computer-use/SKILL.md +14 -3
  4. package/src/defaults/skills/memory-management/SKILL.md +10 -5
  5. package/src/defaults/skills/setup/references/actions.md +1 -1
  6. package/src/rules/agent-mode/MIXY.md +5 -3
  7. package/src/runtime/agent/orchestrator/providers/admission-scheduler.mjs +2 -1
  8. package/src/runtime/agent/orchestrator/providers/anthropic-api-request.mjs +11 -1
  9. package/src/runtime/agent/orchestrator/providers/anthropic-sse-turn/turn-events/content-block-start.mjs +4 -0
  10. package/src/runtime/agent/orchestrator/providers/anthropic-sse-turn/turn-outcome.mjs +2 -0
  11. package/src/runtime/agent/orchestrator/providers/anthropic-turn-result.mjs +2 -0
  12. package/src/runtime/agent/orchestrator/providers/anthropic.mjs +2 -0
  13. package/src/runtime/agent/orchestrator/providers/custom-provider-config.mjs +121 -9
  14. package/src/runtime/agent/orchestrator/providers/custom-provider.mjs +4 -1
  15. package/src/runtime/agent/orchestrator/providers/lib/generation-window.mjs +9 -0
  16. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-send.mjs +9 -1
  17. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/stream-result.mjs +2 -0
  18. package/src/runtime/agent/orchestrator/providers/openai-compat-chat-stream/stream-state.mjs +5 -0
  19. package/src/runtime/agent/orchestrator/providers/openai-compat-options.mjs +3 -0
  20. package/src/runtime/agent/orchestrator/providers/openai-compat-response-normalization.mjs +2 -0
  21. package/src/runtime/agent/orchestrator/providers/openai-compat-responses.mjs +10 -1
  22. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-events.mjs +3 -0
  23. package/src/runtime/agent/orchestrator/providers/openai-http-sse-response-state/response-outcome.mjs +2 -0
  24. package/src/runtime/agent/orchestrator/providers/openai-ws-response-state.mjs +9 -2
  25. package/src/runtime/agent/orchestrator/providers/openrouter-provider-routing.mjs +28 -0
  26. package/src/runtime/agent/orchestrator/providers/openrouter.mjs +4 -1
  27. package/src/runtime/agent/orchestrator/providers/registry.mjs +30 -25
  28. package/src/runtime/agent/orchestrator/runtime-core/ask-user-result.mjs +66 -0
  29. package/src/runtime/agent/orchestrator/session/manager/runtime-liveness.mjs +8 -1
  30. package/src/runtime/agent/orchestrator/session/store.mjs +12 -6
  31. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-output-silence.mjs +64 -0
  32. package/src/runtime/agent/orchestrator/tools/builtin/lib/shell-task-output.mjs +20 -6
  33. package/src/runtime/agent/orchestrator/tools/builtin/task-tool.mjs +12 -1
  34. package/src/runtime/channels/lib/routines-db.mjs +35 -0
  35. package/src/runtime/channels/lib/schedules-db.mjs +4 -0
  36. package/src/runtime/channels/lib/webhooks-db.mjs +4 -0
  37. package/src/runtime/computer-bridge/action-schema.mjs +2 -2
  38. package/src/runtime/computer-bridge/core-actions.mjs +16 -2
  39. package/src/runtime/computer-bridge/result-canonical.mjs +6 -0
  40. package/src/runtime/memory/tool-defs.mjs +1 -1
  41. package/src/runtime/shared/llm/usage-accounting.mjs +110 -19
  42. package/src/runtime/shared/llm/usage-context.mjs +1 -1
  43. package/src/runtime/shared/llm/usage-ledger-quota.mjs +2 -0
  44. package/src/runtime/shared/llm/usage-ledger-requests.mjs +183 -0
  45. package/src/runtime/shared/llm/usage-ledger-rollup.mjs +7 -3
  46. package/src/runtime/shared/llm/usage-ledger-worker.mjs +2 -0
  47. package/src/runtime/shared/llm/usage-ledger.mjs +57 -1
  48. package/src/runtime/shared/llm/usage-request-status.mjs +48 -0
  49. package/src/runtime/shared/tool-result-summary.mjs +1 -1
  50. package/src/session-runtime/agent-home-delivery.mjs +76 -8
  51. package/src/session-runtime/agent-task-sessions.mjs +63 -22
  52. package/src/session-runtime/boot/apis.mjs +15 -0
  53. package/src/session-runtime/boot/tools.mjs +8 -2
  54. package/src/session-runtime/internal-tool-executor/ask-user-tool.mjs +3 -58
  55. package/src/session-runtime/model-route/route-persist.mjs +12 -4
  56. package/src/session-runtime/provider-models/row-hydration.mjs +2 -0
  57. package/src/session-runtime/routine-owner.mjs +9 -3
  58. package/src/session-runtime/services/agent-task-status.mjs +29 -1
  59. package/src/session-runtime/services/agent-tool/job-views/session-progress.mjs +3 -0
  60. package/src/session-runtime/services/agent-tool/render.mjs +6 -1
  61. package/src/session-runtime/services/channel-admin.mjs +44 -3
  62. package/src/session-runtime/services/plugin-admin.mjs +46 -7
  63. package/src/session-runtime/services/provider-admin.mjs +5 -0
  64. package/src/session-runtime/setup-tool/agent-settings-actions.mjs +1 -1
  65. package/src/session-runtime/setup-tool/executor.mjs +1 -1
  66. package/src/session-runtime/setup-tool/extended-actions.mjs +1 -1
  67. package/src/session-runtime/setup-tool/settings-contract.mjs +2 -2
  68. package/src/session-runtime/usage-stats-api.mjs +117 -1
  69. package/src/session-runtime/workflow-agents-api/agent-connectors.mjs +36 -29
  70. package/src/session-runtime/workflow-agents-api/agent-editor.mjs +183 -23
  71. package/src/standalone/session-protocol.mjs +1 -0
  72. package/src/standalone/session-service/retention/busy.mjs +3 -2
  73. package/src/tui/app/model-picker/model-footer.mjs +1 -1
  74. package/src/tui/app/model-picker/provider-models-list.mjs +7 -3
  75. package/src/tui/app/model-picker/route-selection/fast-parameters.mjs +23 -3
  76. package/src/tui/app/model-picker/route-selection.mjs +1 -0
  77. package/src/tui/dist/index.mjs +41 -7
  78. package/src/tui/session/session-api/integrations.mjs +3 -0
  79. package/src/tui/session/tool-approval-settle.mjs +24 -4
  80. package/src/tui/session/tool-approval.mjs +35 -10
@@ -265,7 +265,7 @@ function stripInlineMarkdown(value) {
265
265
  // Envelope field lines (`status: …`, `task_id: …`) that precede or surround a
266
266
  // real agent answer. One list so both scanners below skip exactly the same set.
267
267
  const ENVELOPE_FIELD_LINE_RE =
268
- /^(?:agent task|background task|status|type|target|role|agent|preset|model|effort|fast|limits|session|task-id|task_id|surface|operation|label|exit_code|timed_out|signal|notification|queueDepth|worker|worker_stage|last_progress|silent_for|watchdog|queued_followups|diagnostic|started|finished|elapsed|reused|result|message|output|protocol|version):\s*/i;
268
+ /^(?:agent task|background task|status|type|target|role|agent|preset|model|effort|fast|limits|session|task-id|task_id|surface|operation|label|exit_code|timed_out|signal|notification|queueDepth|worker|worker_stage|last_progress|silent_for|tool_silent_for|watchdog|queued_followups|diagnostic|started|finished|elapsed|reused|result|message|output|protocol|version):\s*/i;
269
269
 
270
270
  // Headers that open an envelope block without a colon (`background task`).
271
271
  const ENVELOPE_HEADER_LINE_RE = /^(?:agent result|background task)\b/i;
@@ -63,6 +63,7 @@ import { readJsonState, updateJsonAtomic } from '../runtime/shared/atomic-file.m
63
63
  import { endHandoff, noteHandoff } from '../runtime/shared/delegated-approval-host.mjs';
64
64
  import { ROUTINE_LIMITS } from '../runtime/shared/routine-limits.mjs';
65
65
  import { submissionIdsOf, submissionOutcome } from './agent-task-sessions.mjs';
66
+ import { HANDOFF_LIMITS } from './handoff-attachments.mjs';
66
67
  import {
67
68
  heldRequestMessage,
68
69
  heldRequestNotice,
@@ -298,16 +299,70 @@ function withDequeued(doc, homeId, runIds, omitted) {
298
299
  function withoutRepeatedProgress(doc, homeId, item, posted) {
299
300
  const { progressRunId, ...report } = item;
300
301
  if (!progressRunId) return { doc, item };
301
- if (posted || (doc.delivered[homeId] || []).includes(progressRunId)) {
302
+ const key = answerKey(progressRunId);
303
+ if (posted || (doc.delivered[homeId] || []).some((runId) => answerKey(runId) === key)) {
302
304
  const { text: _text, textChars: _textChars, ...rest } = report;
303
305
  return { doc, item: { ...rest, text: '', answerAbove: true } };
304
306
  }
305
307
  const queued = doc.homes[homeId] || [];
306
- if (!queued.some((row) => row.runId === progressRunId)) return { doc, item: report };
307
- const homes = { ...doc.homes, [homeId]: queued.filter((row) => row.runId !== progressRunId) };
308
+ if (!queued.some((row) => answerKey(row.runId) === key)) return { doc, item: report };
309
+ const homes = { ...doc.homes, [homeId]: queued.filter((row) => answerKey(row.runId) !== key) };
308
310
  return { doc: { ...doc, homes }, item: report };
309
311
  }
310
312
 
313
+ /** The answer a progress row `runId` carries (`_progress_<turn id>`), '' for
314
+ * any other row. A row is named by its task session now and was by its send
315
+ * before (agent-task-sessions.mjs progressRunId); turn ids are unique, so
316
+ * either name of one answer's update gives the same key, and an update
317
+ * already posted under the old name is never posted again. */
318
+ function answerKey(runId) {
319
+ const at = String(runId || '').indexOf('_progress_');
320
+ return at < 0 ? '' : String(runId).slice(at);
321
+ }
322
+
323
+ /** Whether progress row `item` carries an answer `homeId` already holds or
324
+ * posted (answerKey), under whichever name. */
325
+ function repeatsProgress(doc, homeId, item) {
326
+ const key = item.status === 'working' ? answerKey(item.runId) : '';
327
+ if (!key) return false;
328
+ const held = [...(doc.homes[homeId] || []).map((row) => row.runId), ...(doc.delivered[homeId] || [])];
329
+ return held.some((runId) => answerKey(runId) === key);
330
+ }
331
+
332
+ /** `doc` with task report `item` folded into the row of the same run id
333
+ * still queued for `homeId` — the one card of an answer several open sends'
334
+ * chains reached: it names every send and lists the files each produced
335
+ * (the folded ones by path, at most HANDOFF_LIMITS.count, the rest counted
336
+ * as omitted). Null when no such row is queued. */
337
+ function withFoldedReport(doc, homeId, item) {
338
+ const list = doc.homes[homeId] || [];
339
+ const index = list.findIndex((row) => row.runId === item.runId);
340
+ if (index < 0 || item.kind !== 'agent-task') return null;
341
+ const row = list[index];
342
+ const rowSends = [row.sendId, ...(row.sendIds || [])].filter(Boolean);
343
+ const itemSends = [item.sendId, ...(item.sendIds || [])].filter(Boolean);
344
+ // The row's sends are the contributions already folded into it: a replay of
345
+ // one (or a file its cap dropped, whose path is not kept) adds nothing, so
346
+ // its omissions are never counted twice.
347
+ if (itemSends.length && itemSends.every((id) => rowSends.includes(id))) return null;
348
+ const sendIds = [...new Set([...rowSends, ...itemSends])];
349
+ const paths = new Set((row.files || []).map((file) => file.path));
350
+ const added = (item.files || [])
351
+ .filter((file) => !paths.has(file.path) && paths.add(file.path))
352
+ .map(({ id: _id, ...file }) => file);
353
+ const files = [...(row.files || []), ...added];
354
+ const omitted = (row.omitted || 0) + (item.omitted || 0) + Math.max(0, files.length - HANDOFF_LIMITS.count);
355
+ const folded = {
356
+ ...row,
357
+ ...(sendIds.length > 1 ? { sendIds } : {}),
358
+ ...(files.length ? { files: files.slice(0, HANDOFF_LIMITS.count) } : {}),
359
+ ...(omitted > 0 ? { omitted } : {}),
360
+ };
361
+ if (JSON.stringify(folded) === JSON.stringify(row)) return null;
362
+ const next = list.map((entry, at) => (at === index ? folded : entry));
363
+ return { ...doc, homes: { ...doc.homes, [homeId]: next } };
364
+ }
365
+
311
366
  /** The persisted queue at `filePath`: `{ homes: { [homeSessionId]: item[] },
312
367
  * omitted: { [homeSessionId]: { id, count } }, delivered: { [homeSessionId]:
313
368
  * runId[] } }`. A home keeps at most `limit` items: past it the oldest drop,
@@ -477,7 +532,8 @@ export function createRoutineResultQueue(
477
532
  return (await read()).omitted[homeId] || null;
478
533
  },
479
534
  /** Queue `item` for `homeId`; `unwatch` (run ids) drops those watches in the
480
- * same write, also when the item was queued or posted before.
535
+ * same write, also when the item was queued or posted before (a task
536
+ * report of a row still queued folds into it: withFoldedReport).
481
537
  * `progressPosted`: the thread holds the progress update a final report
482
538
  * names (withoutRepeatedProgress). `progressed` (`{ runId, turnId }`):
483
539
  * watch `runId` reported turn `turnId` as progress — its durable mark,
@@ -485,8 +541,13 @@ export function createRoutineResultQueue(
485
541
  async add(homeId, queued, { unwatch = [], progressPosted = false, progressed = null } = {}) {
486
542
  await update((stored) => {
487
543
  const { doc, item } = withoutRepeatedProgress(stored, homeId, queued, progressPosted);
544
+ // An answer's update or end that open sends converging on it each
545
+ // report: queued once (folded into the queued end), never reposted.
546
+ const folded = withFoldedReport(doc, homeId, item);
488
547
  let next = null;
489
- if (item.roundTrip !== true) next = appended(doc, homeId, [item]);
548
+ if (repeatsProgress(doc, homeId, item)) next = null;
549
+ else if (folded) next = folded;
550
+ else if (item.roundTrip !== true) next = appended(doc, homeId, [item]);
490
551
  else {
491
552
  // A task turn's end counts one round trip, once per run id, per home
492
553
  // and target: the user's next message in that home starts over
@@ -1191,11 +1252,18 @@ export function createAgentHomeDelivery({
1191
1252
  });
1192
1253
  return run;
1193
1254
  }
1194
- /** Whether queued row `runId` is in thread `homeId` (posted, saved or not). */
1255
+ /** Whether progress row `runId`, or another carrying the same answer
1256
+ * (answerKey), is in thread `homeId` (posted, saved or not). */
1195
1257
  const postedIn = (homeId, runId) => {
1196
1258
  const messages = loadSession(homeId)?.messages;
1197
- const messageId = messageIdOf(runId);
1198
- return Array.isArray(messages) && messages.some((message) => message?.meta?.transcript?.messageId === messageId);
1259
+ const key = answerKey(runId);
1260
+ return (
1261
+ Array.isArray(messages) &&
1262
+ messages.some((message) => {
1263
+ const messageId = message?.meta?.transcript?.messageId;
1264
+ return messageId === messageIdOf(runId) || (key && answerKey(messageId) === key);
1265
+ })
1266
+ );
1199
1267
  };
1200
1268
  const intake = createHomeEnqueue(queue, drain, { postingFor, postedIn });
1201
1269
  const { watchTask, recover } = createHomeBookkeeping({ queue, log, homeDeleted, sessionDeleted, drain });
@@ -189,7 +189,8 @@ export function latestTurnOutcome(messages, runId) {
189
189
  return chain && { id: chain.id, outcome: chain.outcome, at: chain.at, ambiguous: chain.ambiguous };
190
190
  }
191
191
 
192
- /** latestTurnOutcome with what a report's wait needs besides: `answers`,
192
+ /** latestTurnOutcome with what a report's wait needs besides: `first`, the
193
+ * id of the turn that took runId (its prompt's checkpoint); `answers`,
193
194
  * every turn of the chain that recorded its end, oldest first (`{ id,
194
195
  * status, text }`: its submission id and submissionOutcome); `taskIds`, the
195
196
  * agent tasks the chain's turns started — the only tasks proven the chain's
@@ -201,21 +202,26 @@ export function latestTurnOutcome(messages, runId) {
201
202
  * steer is not stored yet. */
202
203
  function turnChain(messages, runId) {
203
204
  const list = Array.isArray(messages) ? messages : [];
204
- const start = list.findIndex((message) => submissionIdsOf(message).includes(runId));
205
- if (start < 0) return null;
205
+ const asked = list.findIndex((message) => submissionIdsOf(message).includes(runId));
206
+ if (asked < 0) return null;
207
+ // The chain starts with the whole turn that took runId, named by that turn:
208
+ // a send steered into it or batched with it follows the same chain as the
209
+ // turn's own submission, and its answers carry the same ids.
210
+ const start = turnStartOf(list, asked);
211
+ const first = list[start]?.meta?.transcript?.checkpointId || runId;
206
212
  const started = new Set();
207
213
  // The agent tasks whose results a stored turn took (as its prompt or steered in).
208
214
  const taken = new Set();
209
215
  const startingCalls = new Set();
210
216
  let at = start;
211
- let id = runId;
217
+ let id = first;
212
218
  let inChain = true;
213
219
  let ambiguous = false;
214
220
  // The turn the walk is in: where its prompt is stored and its submission id.
215
221
  let turnAt = start;
216
- let turnId = runId;
222
+ let turnId = first;
217
223
  // Every turn of the chain, in order: where its prompt is stored, its id.
218
- const turns = [{ at: start, id: runId }];
224
+ const turns = [{ at: start, id: first }];
219
225
  for (let index = start; index < list.length; index += 1) {
220
226
  const message = list[index];
221
227
  const checkpointId = index > start && message?.role === 'user' ? message.meta?.transcript?.checkpointId : '';
@@ -274,6 +280,7 @@ function turnChain(messages, runId) {
274
280
  }
275
281
  return {
276
282
  id,
283
+ first,
277
284
  outcome,
278
285
  at: Number(ended?.meta?.transcript?.at) || 0,
279
286
  ambiguous,
@@ -283,6 +290,23 @@ function turnChain(messages, runId) {
283
290
  };
284
291
  }
285
292
 
293
+ /** Where the turn that took the submission stored at `list[at]` keeps its
294
+ * prompt: `at` itself for a turn's prompt; for a message steered into a
295
+ * running turn (no checkpoint of its own), that turn's prompt — unless the
296
+ * turn before it ended first (a completion or interruption on the way back),
297
+ * when `at` stays the start. */
298
+ function turnStartOf(list, at) {
299
+ if (list[at]?.meta?.transcript?.checkpointId) return at;
300
+ for (let index = at - 1; index >= 0; index -= 1) {
301
+ const message = list[index];
302
+ if (message?.meta?.transcript?.completion) return at;
303
+ if (message?.role !== 'user') continue;
304
+ if (message.meta?.transcript?.checkpointId) return index;
305
+ if (INTERRUPTED.test(messageText(message.content))) return at;
306
+ }
307
+ return at;
308
+ }
309
+
286
310
  /** The agent task an owed result reports; null when it names none. */
287
311
  function owedTaskId(result) {
288
312
  const executionId = result?.meta?.execution_id;
@@ -532,7 +556,8 @@ function followTaskToFinal(
532
556
  const answersOf = (latest) => {
533
557
  const stored = latest?.answers || [];
534
558
  if (!immediate) return stored;
535
- return [{ id: runId, ...immediate }, ...stored.filter((answer) => answer.id !== runId)];
559
+ const firstId = latest?.first || runId;
560
+ return [{ id: firstId, ...immediate }, ...stored.filter((answer) => answer.id !== firstId)];
536
561
  };
537
562
  // The answers already handed to `interim`, by turn.
538
563
  const interimIds = new Set();
@@ -554,7 +579,10 @@ function followTaskToFinal(
554
579
  * `held` (the final candidate, reported only when it proves not final);
555
580
  * false, stopping there, at the first that could not be queued. */
556
581
  async function reportEarlier(answers, held) {
557
- const through = progressedThrough ? answers.findIndex((answer) => answer.id === progressedThrough) : -1;
582
+ // A mark stored before answers were named by their turn names runId for
583
+ // the chain's first answer.
584
+ const mark = progressedThrough === runId ? answers[0]?.id : progressedThrough;
585
+ const through = mark ? answers.findIndex((answer) => answer.id === mark) : -1;
558
586
  for (const [index, answer] of answers.entries()) {
559
587
  if (index <= through) interimIds.add(answer.id);
560
588
  else if (answer !== held && !(await reportInterim(answer))) return false;
@@ -838,7 +866,7 @@ async function rearmTaskWatch(
838
866
  endBotWork(watch.runId);
839
867
  if (quiet) return disown(watch.runId);
840
868
  return deliver(watch.agentId, {
841
- runId: `${watch.runId}_end`,
869
+ runId: turnReportRunId(sessionId, watch.runId, status, { answerId }),
842
870
  taskSessionId: sessionId,
843
871
  title: watch.title,
844
872
  status,
@@ -847,7 +875,7 @@ async function rearmTaskWatch(
847
875
  ...(watch.hop > 0 ? { hop: watch.hop } : {}),
848
876
  ...roomFrom(watch.homeSessionId),
849
877
  watchId: watch.runId,
850
- ...progressOf(watch.runId, answerId),
878
+ ...progressOf(sessionId, answerId),
851
879
  ...(watch.textOnly || text === GONE_TEXT || text === LOST_TEXT ? {} : await artifactFields(sessionId, turnId)),
852
880
  });
853
881
  };
@@ -903,7 +931,7 @@ async function rearmTaskWatch(
903
931
  ? null
904
932
  : (answer) =>
905
933
  deliver(watch.agentId, {
906
- runId: progressRunId(watch.runId, answer.id),
934
+ runId: progressRunId(sessionId, answer.id),
907
935
  taskSessionId: sessionId,
908
936
  title: watch.title,
909
937
  status: 'working',
@@ -984,23 +1012,36 @@ function createSendSettlement(log) {
984
1012
  return { join, nextSeq };
985
1013
  }
986
1014
 
987
- /** The queue row of send `id`'s progress update carrying the answer of turn
988
- * `answerId` (followToFinal `interim`): one per answer, across restarts. */
989
- const progressRunId = (id, answerId) => `${id}_progress_${answerId}`;
990
-
991
- /** The queue row of send `id`'s report of `status`. 'working': a progress
992
- * update (progressRunId), not the end. A wait for approval belongs to the
993
- * target session, not to this send: every watcher of it names the same row,
994
- * so it posts once. */
1015
+ /** The queue row of the progress update of task session `sessionId` carrying
1016
+ * the answer of turn `answerId` (followToFinal `interim`): one per answer,
1017
+ * across restarts and however many open sends' chains reach it. Rows queued
1018
+ * before were named by the send (`${sendId}_progress_${answerId}`); both end
1019
+ * in `_progress_${answerId}`, which the queue matches (agent-home-delivery.mjs
1020
+ * answerKey). */
1021
+ const progressRunId = (sessionId, answerId) => `${sessionId}_progress_${answerId}`;
1022
+
1023
+ /** The queue row of send `id`'s report of `status` to task session
1024
+ * `sessionId`. 'working': a progress update (progressRunId), not the end. An
1025
+ * end that carries the answer of turn `answerId` belongs to that answer, not
1026
+ * to this send: every open send whose chain ends in it names the same row,
1027
+ * so it posts once and closes them all; an end of no turn is the send's own.
1028
+ * A wait for approval belongs to the target session: every watcher of it
1029
+ * names the same row, so it posts once.
1030
+ * Upgrade: ends were named `${sendId}_end` before and record no answer, so a
1031
+ * send still watched across the upgrade posts one extra card for an answer a
1032
+ * converged send already reported under its old name. That one-time
1033
+ * duplicate is accepted: matching old rows by their text would drop genuinely
1034
+ * new answers that happen to read the same. */
995
1035
  const turnReportRunId = (sessionId, id, status, { approvalId = '', answerId = '' } = {}) => {
996
1036
  if (status === 'blocked') return `${sessionId}_${approvalId}_blocked`;
997
- return status === 'working' ? progressRunId(id, answerId) : `${id}_end`;
1037
+ if (status === 'working') return progressRunId(sessionId, answerId);
1038
+ return answerId ? `${sessionId}_${answerId}_end` : `${id}_end`;
998
1039
  };
999
1040
 
1000
1041
  /** The report fields naming the progress update that may have carried the
1001
1042
  * final answer of turn `answerId` already (the queue then does not repeat
1002
1043
  * it); none for a report of no turn. */
1003
- const progressOf = (id, answerId) => (answerId ? { progressRunId: progressRunId(id, answerId) } : {});
1044
+ const progressOf = (sessionId, answerId) => (answerId ? { progressRunId: progressRunId(sessionId, answerId) } : {});
1004
1045
 
1005
1046
  /** The handler of send `id`'s task-session state: a wait for the user's
1006
1047
  * approval reports blocked once; a later, different one reports again. */
@@ -1126,7 +1167,7 @@ function sendReporter({ deliver, retryDelaysMs, artifactFields, log }, { session
1126
1167
  : {
1127
1168
  watchId: id,
1128
1169
  ...(turn.sendIds.length > 1 ? { watchIds: turn.sendIds } : {}),
1129
- ...progressOf(id, answerId),
1170
+ ...progressOf(sessionId, answerId),
1130
1171
  ...(origin.textOnly ? {} : await artifactFields(sessionId, id, turn.runtime)),
1131
1172
  }),
1132
1173
  })
@@ -36,6 +36,7 @@ import { createSettingsApi } from '../settings-api.mjs';
36
36
  import { createSessionTitleController } from '../../runtime/agent/orchestrator/runtime-core/session-title.mjs';
37
37
  import { closeNativeToolTransports, closePatchRuntimeIfLoaded, withTeardownDeadline } from '../native-teardown.mjs';
38
38
  import { createChannelConfigApi } from '../channel-config-api.mjs';
39
+ import { deleteOwnedRoutines } from '../services/channel-admin.mjs';
39
40
  import { createMediaApi } from '../media-api.mjs';
40
41
  import { createProviderAuthApi } from '../provider-auth-api.mjs';
41
42
  import { createUsageStatsApi } from '../usage-stats-api.mjs';
@@ -128,6 +129,10 @@ export function wireApis(boot) {
128
129
  };
129
130
  boot.modelRouteApi = modelRouteApiFor(boot);
130
131
  boot.workflowAgentsApi = workflowAgentsApiFor(boot);
132
+ // A bot's purge that stopped before its folder was removed is finished.
133
+ boot.workflowAgentsApi.finishUnfinishedPurges().catch((error) => {
134
+ bootProfile('bot-purge:finish-failed', { error: error?.message || String(error) });
135
+ });
131
136
  // Connector allow lists (agent lists, MCP project scopes) become the
132
137
  // equivalent "switched off" lists once; a later connector is on everywhere.
133
138
  if (!boot.params.initialConfig || typeof boot.params.initialConfig !== 'object') {
@@ -645,6 +650,16 @@ function workflowAgentsApiFor(boot) {
645
650
  settingsReachCurrentSession: () => boot.settingsReachCurrentSession(),
646
651
  switchSessionWorkflow: boot.switchSessionWorkflow,
647
652
  switchSessionOrchestrationMode: boot.switchSessionOrchestrationMode,
653
+ // A bot deleted for good takes its schedules and webhooks; the channels worker
654
+ // drops their cron jobs and endpoints on its reload.
655
+ deleteOwnedRoutines: async (agentId) => {
656
+ const removed = await deleteOwnedRoutines(agentId);
657
+ if (removed.schedules.length || removed.webhooks.length) boot.reloadChannelsSoon();
658
+ return removed;
659
+ },
660
+ // A restored bot's routines are armed again by the same reload; the
661
+ // restore waits for it and reports its failure.
662
+ reloadRoutines: () => boot.reloadChannels(),
648
663
  });
649
664
  }
650
665
 
@@ -64,9 +64,15 @@ export function wireTools(boot) {
64
64
  .catch((error) => bootProfile('mcp:failed', { error: error?.message || String(error) }));
65
65
  // A lost reload leaves the old timers armed; the scheduler re-reads each
66
66
  // schedule before it fires (scheduler.mjs fireTimed), so it is only reported.
67
+ // `reloadChannels` settles once the worker re-armed them and rejects when it
68
+ // could not (a refusal comes back as an isError reply, not a rejection).
69
+ boot.reloadChannels = async () => {
70
+ const reply = await boot.channels.execute('reload_config', {});
71
+ if (reply?.isError === true) throw new Error(reply.content?.[0]?.text || 'reload_config failed');
72
+ };
67
73
  boot.reloadChannelsSoon = () => {
68
- boot.channels
69
- .execute('reload_config', {})
74
+ boot
75
+ .reloadChannels()
70
76
  .catch((error) =>
71
77
  process.stderr.write(`[channels] schedule reload failed: ${error?.message || String(error)}\n`)
72
78
  );
@@ -5,8 +5,8 @@ import { randomUUID } from 'node:crypto';
5
5
  import {
6
6
  validateUserHandoff,
7
7
  validateAskUserQuestions,
8
- ASK_USER_MAX_TEXT,
9
8
  } from '../../runtime/agent/orchestrator/runtime-core/ask-user-tool-defs.mjs';
9
+ import { askUserResultText } from '../../runtime/agent/orchestrator/runtime-core/ask-user-result.mjs';
10
10
  import { createCallerContextResolvers } from './caller-context.mjs';
11
11
  import { noteTodoUserWait } from '../../runtime/agent/orchestrator/session/loop/no-tool-turn/todo-check.mjs';
12
12
  import { runAbortable } from '../../runtime/shared/abort-race.mjs';
@@ -227,55 +227,6 @@ export function handoffSite(handoff) {
227
227
 
228
228
  const NO_USER =
229
229
  'No user is available to answer in this session. Proceed with your best judgment and state the choices you made.';
230
- const DISMISSED =
231
- 'User closed the questions without answering. Proceed with your best judgment; ask again only if something new depends on it.';
232
-
233
- /** Wire answers -> array aligned with questions; invalid entries become null. */
234
- function normalizeAskUserAnswers(answers, questions) {
235
- const list = Array.isArray(answers) ? answers.slice(0, 4) : [];
236
- return questions.map((q, i) => {
237
- const entry = list[i];
238
- if (!entry || typeof entry !== 'object') return null;
239
- const labels = new Set(q.options.map((o) => o.label));
240
- const rawSelected = entry.selected == null ? [] : entry.selected;
241
- if (!Array.isArray(rawSelected) || !rawSelected.every((l) => typeof l === 'string' && labels.has(l))) return null;
242
- if (entry.text != null && (typeof entry.text !== 'string' || entry.text.length > ASK_USER_MAX_TEXT)) return null;
243
- const selected = q.multi_select === true ? [...new Set(rawSelected)] : rawSelected.slice(0, 1);
244
- const text = typeof entry.text === 'string' ? entry.text.trim() : '';
245
- if (!selected.length && !text) return null;
246
- return text ? { selected, text } : { selected };
247
- });
248
- }
249
-
250
- // Strings are JSON-quoted so a quote inside one cannot end it early; typed
251
- // text stays apart from the picked labels (`"picked" + "typed" (typed)`).
252
- function formatAskUserAnswers(questions, answers) {
253
- const quote = (text) => JSON.stringify(text);
254
- const parts = questions.map((q, i) => {
255
- const a = answers[i];
256
- if (!a) return `${quote(q.question)}=(no answer)`;
257
- const picked = a.selected.length ? quote(a.selected.join(', ')) : '';
258
- const typed = a.text ? `${quote(a.text)} (typed)` : '';
259
- return `${quote(q.question)}=${[picked, typed].filter(Boolean).join(' + ')}`;
260
- });
261
- return `User has answered your questions: ${parts.join('; ')}. You can now continue with these answers in mind.`;
262
- }
263
-
264
- /** A composer message sent instead of (or with) picking: kept when it is a
265
- * non-empty string within the typed-answer limit, else dropped. */
266
- function normalizeAskUserReply(reply) {
267
- if (typeof reply !== 'string' || reply.length > ASK_USER_MAX_TEXT) return '';
268
- return reply.trim();
269
- }
270
-
271
- // `User replied in chat: "<reply>". ` leads, then the usual picks sentence
272
- // when any question was answered, else just the closing sentence.
273
- function formatAskUserResult(questions, answers, reply) {
274
- if (!reply) return formatAskUserAnswers(questions, answers);
275
- const lead = `User replied in chat: ${JSON.stringify(reply)}. `;
276
- if (answers.some(Boolean)) return `${lead}${formatAskUserAnswers(questions, answers)}`;
277
- return `${lead}You can now continue with these answers in mind.`;
278
- }
279
230
 
280
231
  export function createAskUserToolHandlers({ rt }) {
281
232
  const { sessionIdFor, signalFor } = createCallerContextResolvers(rt);
@@ -304,15 +255,9 @@ export function createAskUserToolHandlers({ rt }) {
304
255
  toolCallId: callerCtx?.toolCallId || null,
305
256
  })
306
257
  );
307
- if (result?.approved === true)
308
- return formatAskUserResult(
309
- questions,
310
- normalizeAskUserAnswers(result.answers, questions),
311
- normalizeAskUserReply(result.reply)
312
- );
313
258
  // A question left unanswered: the turn may end waiting on the user.
314
- noteTodoUserWait(sessionIdFor(callerCtx));
315
- return DISMISSED;
259
+ if (result?.approved !== true) noteTodoUserWait(sessionIdFor(callerCtx));
260
+ return askUserResultText(questions, result);
316
261
  },
317
262
  };
318
263
  }
@@ -4,9 +4,12 @@
4
4
  * fast/effort tuning of a session that runs on the selected route.
5
5
  */
6
6
  import { saveModelSettings } from '../../runtime/agent/orchestrator/runtime-core/model-capabilities.mjs';
7
+ import { OPENROUTER_SORT_PARAMETER } from '../../runtime/agent/orchestrator/providers/openrouter-provider-routing.mjs';
7
8
  import { writeStatuslineRoute } from '../statusline-route.mjs';
8
9
  import { sessionUsesRoute } from '../../runtime/agent/orchestrator/runtime-core/session-route-policy.mjs';
9
10
 
11
+ const TUNED_PARAMETERS = ['serviceTier', OPENROUTER_SORT_PARAMETER];
12
+
10
13
  /** Re-tuning the live model (effort, Fast, context, or re-picking it) is not a
11
14
  * main-model choice: new tasks keep their main model unless it is that model. */
12
15
  function tunesNonMainModel(liveRoute, route, mainRoute) {
@@ -57,10 +60,15 @@ export function createRoutePersistence(deps) {
57
60
  if (route.autoEffort === false) session.autoEffort = false;
58
61
  else delete session.autoEffort;
59
62
  session.effort = route.effectiveEffort || null;
60
- // The request path reads session.modelParameters; keep only serviceTier in step.
61
- const { serviceTier: _previous, ...otherParameters } = session.modelParameters || {};
62
- const serviceTier = route.modelParameters?.serviceTier;
63
- session.modelParameters = serviceTier ? { ...otherParameters, serviceTier } : otherParameters;
63
+ // The request path reads session.modelParameters; keep only the tuned
64
+ // parameters (serviceTier, OpenRouter's providerSort) in step.
65
+ const otherParameters = { ...(session.modelParameters || {}) };
66
+ for (const key of TUNED_PARAMETERS) {
67
+ delete otherParameters[key];
68
+ const value = route.modelParameters?.[key];
69
+ if (value) otherParameters[key] = value;
70
+ }
71
+ session.modelParameters = otherParameters;
64
72
  writeStatuslineRoute(statusRoutes, session, route);
65
73
  invalidateContextStatusCache();
66
74
  },
@@ -14,6 +14,7 @@ import {
14
14
  effortConfigurationMode,
15
15
  } from '../../runtime/agent/orchestrator/providers/effort-configuration.mjs';
16
16
  import { getProvider } from '../../runtime/agent/orchestrator/providers/registry.mjs';
17
+ import { OPENROUTER_SORT_OPTION } from '../../runtime/agent/orchestrator/providers/openrouter-provider-routing.mjs';
17
18
  import { providerAvailable } from '../../runtime/agent/orchestrator/providers/provider-availability.mjs';
18
19
  import {
19
20
  DAYBREAK_PARAMETER_OPTION,
@@ -42,6 +43,7 @@ export function hydrateProviderModelRow(cfg, row) {
42
43
  const addedOptions = [
43
44
  ...(row.provider === DAYBREAK_PROVIDER && daybreakBlueSupported(row) ? [DAYBREAK_PARAMETER_OPTION] : []),
44
45
  ...(fastCapable && ultrafastCapableFor(row.provider, row) ? [ULTRAFAST_SPEED_OPTION] : []),
46
+ ...(row.provider === 'openrouter' ? [OPENROUTER_SORT_OPTION] : []),
45
47
  ];
46
48
  const modelParameterOptions = addedOptions.length
47
49
  ? [...existingOptions.filter((option) => !addedOptions.some((added) => added.id === option?.id)), ...addedOptions]
@@ -2,8 +2,10 @@
2
2
  * Routines are bot-based: a schedule or webhook runs in its owner bot's home
3
3
  * thread (routine-home-turn.mjs) and nowhere else. An owner that does not
4
4
  * exist — Mixy before the representative bot was created, a bot archived or
5
- * deleted — makes the routine paused: it does not fire, the lists show why,
6
- * and a new routine cannot name it.
5
+ * deleted — makes the routine paused: it does not fire and a new routine
6
+ * cannot name it. An archived bot's routines are also hidden from the lists
7
+ * and come back, untouched, when it is restored; deleting it for good deletes
8
+ * them (agent-editor.mjs). The lists show why any other one is paused.
7
9
  */
8
10
  import { MIXY_AGENT_ID } from '../runtime/agent/orchestrator/session/agent-home.mjs';
9
11
  import { mixyExists } from '../runtime/shared/mixy-presence.mjs';
@@ -12,6 +14,7 @@ import { scheduleOwnerAgentId } from './agent-home-delivery.mjs';
12
14
  /** `ownerProblem` codes and the error each one raises. */
13
15
  export const ROUTINE_OWNER_PROBLEMS = Object.freeze({
14
16
  'no-mixy': 'Create the representative bot first.',
17
+ 'owner-archived': 'The bot that owns this routine is deleted (in Archived). Restore it, or pick another bot.',
15
18
  'owner-deleted': 'The bot that owns this routine no longer exists. Pick another bot.',
16
19
  });
17
20
 
@@ -56,6 +59,7 @@ async function defaultProbe() {
56
59
  return {
57
60
  mixyExists: (ownsRoutine) => readMixyExists(null, { ownsRoutine }),
58
61
  presence: (agentId) => api.agentDefinitionPresence([agentId])[agentId],
62
+ archived: (agentId) => Boolean(api.archivedAgentIdentities([agentId])[agentId]),
59
63
  };
60
64
  }
61
65
 
@@ -69,7 +73,9 @@ export async function routineOwnerProblem(ownerAgentId, probe = null, { stored =
69
73
  const owner = scheduleOwnerAgentId({ ownerAgentId });
70
74
  const check = probe || (await defaultProbe());
71
75
  if (owner === MIXY_AGENT_ID) return (await check.mixyExists(stored)) ? '' : 'no-mixy';
72
- return check.presence(owner) === 'deleted' ? 'owner-deleted' : '';
76
+ if (check.presence(owner) !== 'deleted') return '';
77
+ // Archived (restorable): its routines wait, hidden, for the restore.
78
+ return check.archived?.(owner) ? 'owner-archived' : 'owner-deleted';
73
79
  }
74
80
 
75
81
  /** Rejects with the owner's problem; resolves when it can own a routine. */
@@ -1,3 +1,4 @@
1
+ import { formatDuration } from '../../runtime/shared/time-format.mjs';
1
2
  import {
2
3
  agentWatchdogPolicyActive,
3
4
  evaluateAgentWatchdogAbort,
@@ -66,6 +67,7 @@ export function buildAgentTaskProgressFields({
66
67
  queuedFollowups = null,
67
68
  taskStatus = null,
68
69
  lastToolCall = null,
70
+ toolSilence = null,
69
71
  } = {}) {
70
72
  const stage = cleanStage(runtimeStage || snapshot?.stage || sessionStatus || 'unknown');
71
73
  const silentFor = resolveSilentForSeconds(now, snapshot, runtime);
@@ -93,6 +95,7 @@ export function buildAgentTaskProgressFields({
93
95
  queued,
94
96
  policy,
95
97
  now,
98
+ toolSilence,
96
99
  });
97
100
 
98
101
  const out = {
@@ -102,6 +105,11 @@ export function buildAgentTaskProgressFields({
102
105
  };
103
106
  if (silentFor != null && ACTIVE_RUNTIME_STAGES.has(stage)) out.silent_for = silentFor;
104
107
  if (watchdog) out.watchdog = watchdog;
108
+ // The tool's own silence: the activity heartbeat keeps `silent_for` fresh
109
+ // while a tool runs, so a wait on a job that prints nothing needs its own clock.
110
+ if (toolSilence && stage === 'tool_running') {
111
+ out.tool_silent_for = `${formatToolSilence(toolSilence.silentMs)} (shell job ${toolSilence.taskId} no output)`;
112
+ }
105
113
  if (queued != null) out.queued_followups = queued;
106
114
  return out;
107
115
  }
@@ -150,7 +158,21 @@ function describeLastProgress({ stage, snapshot, runtime, silentFor, lastToolCal
150
158
  return stage;
151
159
  }
152
160
 
153
- function describeAgentDiagnostic({ taskStatus, sessionStatus, stage, snapshot, silentFor, queued, policy, now }) {
161
+ function formatToolSilence(ms) {
162
+ return formatDuration(ms, { mostSignificantOnly: true }) || '0s';
163
+ }
164
+
165
+ function describeAgentDiagnostic({
166
+ taskStatus,
167
+ sessionStatus,
168
+ stage,
169
+ snapshot,
170
+ silentFor,
171
+ queued,
172
+ policy,
173
+ now,
174
+ toolSilence,
175
+ }) {
154
176
  const normalizedTask = cleanStage(taskStatus).toLowerCase();
155
177
  if (normalizedTask === 'cancelled' || normalizedTask === 'canceled') return 'task cancelled';
156
178
  if (normalizedTask === 'failed' || normalizedTask === 'error') return 'task failed';
@@ -158,6 +180,12 @@ function describeAgentDiagnostic({ taskStatus, sessionStatus, stage, snapshot, s
158
180
  return sessionStatus === 'error' ? 'task completed (worker error)' : 'task completed; worker idle';
159
181
  }
160
182
 
183
+ // Stalled for notification purposes, never aborted: a quiet job can be a
184
+ // legitimate build, so the Lead is told and decides.
185
+ if (toolSilence?.hung && stage === 'tool_running') {
186
+ return `tool possibly hung: shell job ${toolSilence.taskId} no output for ${formatToolSilence(toolSilence.silentMs)}; inspect or cancel it`;
187
+ }
188
+
161
189
  if (queued) {
162
190
  if (ACTIVE_RUNTIME_STAGES.has(stage)) {
163
191
  return `${stage}, ${queued} follow-up${queued === 1 ? '' : 's'} queued`;
@@ -6,6 +6,7 @@ import { buildAgentTaskProgressFields } from '../../agent-task-status.mjs';
6
6
  import { getProgressWatchdogState } from '../../agent-watchdog-registry.mjs';
7
7
  import { _liveSessions } from '../../../../runtime/agent/orchestrator/session/store/live-state.mjs';
8
8
  import { todoProgress } from '../../../../runtime/agent/orchestrator/runtime-core/todo-list.mjs';
9
+ import { waitedJobSilence } from '../../../../runtime/agent/orchestrator/tools/builtin/lib/shell-output-silence.mjs';
9
10
 
10
11
  // Job statuses that can never progress again (mirrors TERMINAL_STATUSES in
11
12
  // runtime/shared/background-tasks.mjs; 'canceled' accepted defensively).
@@ -55,6 +56,7 @@ export function liveAgentStatusRow(row) {
55
56
  if (todo) row = { ...row, todo };
56
57
  const {
57
58
  silent_for: _silentFor,
59
+ tool_silent_for: _toolSilentFor,
58
60
  staleSeconds: _staleSeconds,
59
61
  lastStreamDeltaAt: _lastStreamDeltaAt,
60
62
  last_progress: _lastProgress,
@@ -95,6 +97,7 @@ export function createSessionProgress({ mgr }) {
95
97
  queuedFollowups,
96
98
  taskStatus,
97
99
  lastToolCall: runtime?.lastToolCall || null,
100
+ toolSilence: runtime?.taskWaits > 0 ? waitedJobSilence(runtime.taskWaitJobIds, { now }) : null,
98
101
  });
99
102
  }
100
103