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
@@ -15,6 +15,7 @@ import { createWsToolCalls } from './openai-ws-response-state/tool-calls.mjs';
15
15
  import { normalizeWsUsage } from './openai-ws-response-state/usage.mjs';
16
16
  import { createRefusals, refusalResultFields } from './openai-ws-response-state/refusals.mjs';
17
17
  import { isIncompleteToolItem } from './lib/responses-terminal-fields.mjs';
18
+ import { generationWindow } from './lib/generation-window.mjs';
18
19
 
19
20
  export { parseToolSearchArgs } from './openai-ws-response-state/tool-calls.mjs';
20
21
 
@@ -27,6 +28,7 @@ export { parseToolSearchArgs } from './openai-ws-response-state/tool-calls.mjs';
27
28
  */
28
29
  export function createWsResponseState({ onToolCall, onStreamDelta, midState, traceProvider }) {
29
30
  let content = '';
31
+ let firstOutputAt = 0;
30
32
  let model = '';
31
33
  let responseId = '';
32
34
  let responseServiceTier = '';
@@ -152,8 +154,12 @@ export function createWsResponseState({ onToolCall, onStreamDelta, midState, tra
152
154
  if (response?.model) model = response.model;
153
155
  if (response?.id) responseId = response.id;
154
156
  },
155
- /** response.output_item.added */
156
- noteItemAdded: tools.noteItemAdded,
157
+ /** response.output_item.added: an encrypted reasoning item opens as the
158
+ * model starts thinking, so the first one starts the generation. */
159
+ noteItemAdded(item) {
160
+ firstOutputAt ||= Date.now();
161
+ return tools.noteItemAdded(item);
162
+ },
157
163
  /** response.function_call_arguments.delta / custom_tool_call_input.delta */
158
164
  noteToolInputDelta: tools.noteToolInputDelta,
159
165
  /** response.function_call_arguments.done */
@@ -257,6 +263,7 @@ export function createWsResponseState({ onToolCall, onStreamDelta, midState, tra
257
263
  serviceTier: responseServiceTier || undefined,
258
264
  // A refused turn: typed stop reason and the refusal text.
259
265
  ...refusalResultFields(refusals, content),
266
+ ...generationWindow(firstOutputAt),
260
267
  };
261
268
  },
262
269
  };
@@ -0,0 +1,28 @@
1
+ /**
2
+ * OpenRouter provider routing: the per-model `providerSort` picker parameter
3
+ * and the request's `provider: { sort }` field. Auto (the default) sends
4
+ * nothing; a stored value outside the known sorts is dropped.
5
+ */
6
+ export const OPENROUTER_SORT_PARAMETER = 'providerSort';
7
+
8
+ const SORTS = new Set(['price', 'throughput', 'latency']);
9
+
10
+ export const OPENROUTER_SORT_OPTION = Object.freeze({
11
+ id: OPENROUTER_SORT_PARAMETER,
12
+ label: 'Routing',
13
+ kind: 'enum',
14
+ options: [
15
+ { value: 'auto', label: 'Auto' },
16
+ { value: 'price', label: 'Price first' },
17
+ { value: 'throughput', label: 'Speed first' },
18
+ { value: 'latency', label: 'Latency first' },
19
+ ],
20
+ });
21
+
22
+ /** `{ sort }` for the request body's `provider` field, or null for Auto or an unknown value. */
23
+ export function openRouterProviderRouting(opts = {}) {
24
+ const sort = String(opts?.modelParameters?.[OPENROUTER_SORT_PARAMETER] ?? '')
25
+ .trim()
26
+ .toLowerCase();
27
+ return SORTS.has(sort) ? { sort } : null;
28
+ }
@@ -10,6 +10,7 @@
10
10
  import { WireGatewayProvider, messagesBaseFromOpenAIBase } from './wire-gateway.mjs';
11
11
  import { OPENAI_COMPAT_PRESETS } from './openai-compat-presets.mjs';
12
12
  import { openRouterReasoning } from './openai-compat-options.mjs';
13
+ import { openRouterProviderRouting } from './openrouter-provider-routing.mjs';
13
14
 
14
15
  /**
15
16
  * The Claude id a routing slug stands for: an alias (`~anthropic/claude-opus-latest`)
@@ -25,12 +26,14 @@ export function openRouterCapabilityModel(model, aliasTarget = null) {
25
26
 
26
27
  // Responses requests carry the same reasoning control as Chat requests
27
28
  // (`openRouterReasoningEffort`, else the turn effort, else the configured
28
- // effort; `none` disables reasoning).
29
+ // effort; `none` disables reasoning) and the same provider routing.
29
30
  function openRouterResponsesParams(config) {
30
31
  return (params, { opts }) => {
31
32
  const reasoning = openRouterReasoning(opts, config);
32
33
  if (reasoning) params.reasoning = reasoning;
33
34
  else delete params.reasoning;
35
+ const routing = openRouterProviderRouting(opts);
36
+ if (routing) params.provider = routing;
34
37
  };
35
38
  }
36
39
 
@@ -385,29 +385,6 @@ async function _initProvidersUnsynchronized(config, signal = null, proxyChannel
385
385
  if (result.sig !== null) nextSignatures.set(result.name, result.sig);
386
386
  }
387
387
  _providerInitErrors = nextInitErrors;
388
- // Second guard: every entry was disabled. Same reasoning — keep the
389
- // existing registry rather than going dark. Isolation still holds: a live
390
- // instance of a provider that is now an invalid custom config is removed
391
- // (the rest of the registry stays), and the recorded reasons are reported.
392
- if (next.size === 0) {
393
- let removed = false;
394
- for (const name of nextInitErrors.keys()) {
395
- removed = providers.delete(name) || removed;
396
- signatures.delete(name);
397
- }
398
- if (removed) {
399
- _providerCatalogRevision += 1;
400
- _startupCatalogRefreshPromise = null;
401
- // The live registry no longer reflects the last applied config.
402
- _lastAppliedSig = null;
403
- }
404
- const reasons = [...nextInitErrors.values()];
405
- throw noEnabledProvidersError(
406
- `[provider] all providers disabled in config — refusing to clear registry${
407
- reasons.length ? `; invalid custom providers skipped: ${reasons.join('; ')}` : ''
408
- }`
409
- );
410
- }
411
388
  // OAuth preservation guard. anthropic-oauth / openai-oauth are NOT stored
412
389
  // in mixdog-config.json — buildDefaultConfig injects them at runtime by
413
390
  // calling hasAnthropic/OpenAIOAuthCredentials(), which reads the on-disk
@@ -430,20 +407,48 @@ async function _initProvidersUnsynchronized(config, signal = null, proxyChannel
430
407
  // `enabled` itself, so an explicit UI/hand-edited disable still removes the
431
408
  // provider even while its credential file happens to be unreadable, and a
432
409
  // logout (probe 'absent') never carries the marker at all.
410
+ //
411
+ // It runs before the all-disabled guard below: a secrets-less load
412
+ // (explore) marks every OAuth entry probe-unavailable, so an OAuth-only
413
+ // setup has no enabled entry and only its preserved instances.
433
414
  const nextDisabled = new Set();
434
415
  for (const [name, cfg] of entries) {
435
416
  if (cfg?.enabled) continue;
436
417
  if (OAUTH_PROVIDER_NAMES.has(name) && cfg?.credentialProbeUnavailable === true) continue;
437
418
  nextDisabled.add(name);
438
419
  }
439
- _explicitlyDisabled = nextDisabled;
440
420
  for (const name of OAUTH_PROVIDER_NAMES) {
441
421
  if (next.has(name) || !providers.has(name)) continue;
442
- if (_explicitlyDisabled.has(name)) continue;
422
+ if (nextDisabled.has(name)) continue;
443
423
  if (oauthCredentialProbeState(name) === 'absent') continue;
444
424
  next.set(name, providers.get(name));
445
425
  if (signatures.has(name)) nextSignatures.set(name, signatures.get(name));
446
426
  }
427
+ // Second guard: every entry was disabled and nothing was preserved. Same
428
+ // reasoning — keep the existing registry rather than going dark. Isolation
429
+ // still holds: a live instance of a provider that is now an invalid custom
430
+ // config is removed (the rest of the registry stays), and the recorded
431
+ // reasons are reported.
432
+ if (next.size === 0) {
433
+ let removed = false;
434
+ for (const name of nextInitErrors.keys()) {
435
+ removed = providers.delete(name) || removed;
436
+ signatures.delete(name);
437
+ }
438
+ if (removed) {
439
+ _providerCatalogRevision += 1;
440
+ _startupCatalogRefreshPromise = null;
441
+ // The live registry no longer reflects the last applied config.
442
+ _lastAppliedSig = null;
443
+ }
444
+ const reasons = [...nextInitErrors.values()];
445
+ throw noEnabledProvidersError(
446
+ `[provider] all providers disabled in config — refusing to clear registry${
447
+ reasons.length ? `; invalid custom providers skipped: ${reasons.join('; ')}` : ''
448
+ }`
449
+ );
450
+ }
451
+ _explicitlyDisabled = nextDisabled;
447
452
  throwIfAborted(signal);
448
453
  // Reconfiguration opens a new catalog epoch. A provider added (or rebuilt
449
454
  // with an empty model cache) after the startup refresh settled would
@@ -0,0 +1,66 @@
1
+ // The text an ask_user call returns to the model for the user's decision:
2
+ // shared by the tool (ask-user-tool.mjs) and the hand-off copies of a
3
+ // question (tui/session/tool-approval.mjs), whose settled card shows the same
4
+ // record the asking session's transcript keeps.
5
+ import { ASK_USER_MAX_TEXT } from './ask-user-tool-defs.mjs';
6
+
7
+ const ASK_USER_DISMISSED =
8
+ 'User closed the questions without answering. Proceed with your best judgment; ask again only if something new depends on it.';
9
+
10
+ /** Wire answers -> array aligned with questions; invalid entries become null. */
11
+ function normalizeAskUserAnswers(answers, questions) {
12
+ const list = Array.isArray(answers) ? answers.slice(0, 4) : [];
13
+ return questions.map((q, i) => {
14
+ const entry = list[i];
15
+ if (!entry || typeof entry !== 'object') return null;
16
+ const labels = new Set(q.options.map((o) => o.label));
17
+ const rawSelected = entry.selected == null ? [] : entry.selected;
18
+ if (!Array.isArray(rawSelected) || !rawSelected.every((l) => typeof l === 'string' && labels.has(l))) return null;
19
+ if (entry.text != null && (typeof entry.text !== 'string' || entry.text.length > ASK_USER_MAX_TEXT)) return null;
20
+ const selected = q.multi_select === true ? [...new Set(rawSelected)] : rawSelected.slice(0, 1);
21
+ const text = typeof entry.text === 'string' ? entry.text.trim() : '';
22
+ if (!selected.length && !text) return null;
23
+ return text ? { selected, text } : { selected };
24
+ });
25
+ }
26
+
27
+ // Strings are JSON-quoted so a quote inside one cannot end it early; typed
28
+ // text stays apart from the picked labels (`"picked" + "typed" (typed)`).
29
+ function formatAskUserAnswers(questions, answers) {
30
+ const quote = (text) => JSON.stringify(text);
31
+ const parts = questions.map((q, i) => {
32
+ const a = answers[i];
33
+ if (!a) return `${quote(q.question)}=(no answer)`;
34
+ const picked = a.selected.length ? quote(a.selected.join(', ')) : '';
35
+ const typed = a.text ? `${quote(a.text)} (typed)` : '';
36
+ return `${quote(q.question)}=${[picked, typed].filter(Boolean).join(' + ')}`;
37
+ });
38
+ return `User has answered your questions: ${parts.join('; ')}. You can now continue with these answers in mind.`;
39
+ }
40
+
41
+ /** A composer message sent instead of (or with) picking: kept when it is a
42
+ * non-empty string within the typed-answer limit, else dropped. */
43
+ function normalizeAskUserReply(reply) {
44
+ if (typeof reply !== 'string' || reply.length > ASK_USER_MAX_TEXT) return '';
45
+ return reply.trim();
46
+ }
47
+
48
+ // `User replied in chat: "<reply>". ` leads, then the usual picks sentence
49
+ // when any question was answered, else just the closing sentence.
50
+ function formatAskUserResult(questions, answers, reply) {
51
+ if (!reply) return formatAskUserAnswers(questions, answers);
52
+ const lead = `User replied in chat: ${JSON.stringify(reply)}. `;
53
+ if (answers.some(Boolean)) return `${lead}${formatAskUserAnswers(questions, answers)}`;
54
+ return `${lead}You can now continue with these answers in mind.`;
55
+ }
56
+
57
+ /** The ask_user result for `questions` (validated) and the hook's `result`
58
+ * (`{ approved, answers, reply }`): the answers, or the dismissal. */
59
+ export function askUserResultText(questions, result) {
60
+ if (result?.approved !== true) return ASK_USER_DISMISSED;
61
+ return formatAskUserResult(
62
+ questions,
63
+ normalizeAskUserAnswers(result.answers, questions),
64
+ normalizeAskUserReply(result.reply)
65
+ );
66
+ }
@@ -222,6 +222,7 @@ export function markSessionAskStart(id) {
222
222
  entry.lastProgressAt = now;
223
223
  entry.updatedAt = now;
224
224
  entry.taskWaits = 0;
225
+ entry.taskWaitJobIds = [];
225
226
  emitSessionTurnStart(id);
226
227
  emitSessionActivityChange(id);
227
228
  }
@@ -400,15 +401,20 @@ export function beginSessionApprovalWait(id) {
400
401
  // `awaitingTask` so status surfaces show the session waiting, not working.
401
402
  // Counted like approval waits; never creates an entry. Returns the idempotent
402
403
  // release.
403
- export function beginSessionTaskWait(id) {
404
+ // `taskId` names the job being waited on, so status can report that job's
405
+ // output silence as the tool-level silence the activity heartbeat hides.
406
+ export function beginSessionTaskWait(id, taskId = null) {
404
407
  const entry = id ? _runtimeState.get(id) : null;
405
408
  if (!entry) return () => {};
406
409
  entry.taskWaits = (entry.taskWaits || 0) + 1;
410
+ if (taskId) (entry.taskWaitJobIds ||= []).push(taskId);
407
411
  if (entry.taskWaits === 1) emitSessionActivityChange(id);
408
412
  let released = false;
409
413
  return () => {
410
414
  if (released) return;
411
415
  released = true;
416
+ const at = taskId && entry.taskWaitJobIds ? entry.taskWaitJobIds.indexOf(taskId) : -1;
417
+ if (at >= 0) entry.taskWaitJobIds.splice(at, 1);
412
418
  entry.taskWaits = Math.max(0, (entry.taskWaits || 0) - 1);
413
419
  if (entry.taskWaits === 0) emitSessionActivityChange(id);
414
420
  };
@@ -428,6 +434,7 @@ function _settleTerminalEntry(entry, stage, lastError) {
428
434
  entry.lastProgressAt = settledAt;
429
435
  entry.updatedAt = settledAt;
430
436
  entry.taskWaits = 0;
437
+ entry.taskWaitJobIds = [];
431
438
  emitSessionActivityChange(entry.session?.id || '');
432
439
  }
433
440
  export function markSessionDone(id, { empty = false } = {}) {
@@ -515,8 +515,13 @@ function _collectNewestDrainPayloads() {
515
515
  // (the ref was replaced behind the write). Map/source order must never
516
516
  // decide that, and minting a newer epoch here would hand an old snapshot
517
517
  // fresh write authority.
518
- const record = (id, session, opts, epoch, revision) => {
518
+ const record = (id, session, opts, epoch, revision, incarnation) => {
519
519
  if (!id || !session) return;
520
+ // A hard delete retired this payload's incarnation. The drain writes
521
+ // under a FRESH guard, so the delete's cancellation cannot stop it here:
522
+ // an in-flight worker write of a deleted id (its slot outlives the purge
523
+ // until the reply settles) would re-create the unlinked file.
524
+ if (!_isCurrentSessionIncarnation(id, incarnation)) return;
520
525
  const issued = Number.isFinite(epoch) ? epoch : 0;
521
526
  const rev = Number.isFinite(revision) ? revision : 0;
522
527
  const current = newest.get(id);
@@ -526,14 +531,15 @@ function _collectNewestDrainPayloads() {
526
531
  for (const [id, pending] of _savePending) {
527
532
  // Both slots are candidates; the payload's own epoch decides, so a
528
533
  // `queued` follow-up wins because it is NEWER, not because of its slot.
529
- record(id, pending.payload?.session, pending.payload?.opts, pending.payload?.epoch, 0);
530
- record(id, pending.queued?.session, pending.queued?.opts, pending.queued?.epoch, 0);
534
+ const { payload, queued } = pending;
535
+ record(id, payload?.session, payload?.opts, payload?.epoch, 0, payload?.settlement ?? payload?.incarnation);
536
+ record(id, queued?.session, queued?.opts, queued?.epoch, 0, queued?.settlement ?? queued?.incarnation);
531
537
  }
532
538
  for (const [, pending] of _saveWorkerPending)
533
- record(pending.id, pending.session, pending.opts, pending.epoch, pending.revision);
534
- for (const [id, q] of _saveAsyncQueued) record(id, q.session, q.opts, q.epoch, q.revision);
539
+ record(pending.id, pending.session, pending.opts, pending.epoch, pending.revision, pending.incarnation);
540
+ for (const [id, q] of _saveAsyncQueued) record(id, q.session, q.opts, q.epoch, q.revision, q.incarnation);
535
541
  for (const [, pending] of _deferredSessionSaves)
536
- record(pending.session?.id, pending.session, pending.opts, pending.epoch, pending.revision);
542
+ record(pending.session?.id, pending.session, pending.opts, pending.epoch, pending.revision, pending.incarnation);
537
543
  return newest;
538
544
  }
539
545
 
@@ -0,0 +1,64 @@
1
+ // How long a running shell job has gone without writing to stdout or stderr.
2
+ // Silence is read from the capture files' mtime (the writer is the child, so
3
+ // nothing has to poll), floored at the job's start. It is a warning only:
4
+ // builds and installs can be legitimately quiet, so nothing is ever killed
5
+ // from here, and any output at all resets the clock.
6
+ import { statSync } from 'node:fs';
7
+ import { formatDuration } from '../../../../../shared/time-format.mjs';
8
+ import { getBackgroundTask } from '../../../../../shared/background-tasks.mjs';
9
+ import { STALL_ABORT_S, resolveTimeoutMs } from '../../../stall-policy.mjs';
10
+
11
+ // Defaults to the agent stall budget (600 s): a quiet job past the point where
12
+ // a silent model turn would be reaped is worth a look.
13
+ export const SHELL_OUTPUT_SILENCE_WARN_MS = resolveTimeoutMs(
14
+ 'MIXDOG_SHELL_OUTPUT_SILENCE_WARN_MS',
15
+ STALL_ABORT_S * 1000
16
+ );
17
+
18
+ /** Milliseconds since the job last wrote to stdout/stderr (or started), or null
19
+ * when silence is unknown. The spawner creates both capture files before the
20
+ * command runs (mixdog-spawn open_capture_files, or the paired spill open), so
21
+ * a stream whose file cannot be stat'd (even ENOENT) is unknown, not quiet:
22
+ * its recent output could be what we cannot see. `task` is the background
23
+ * task; the stream paths come from `result` or the task meta. */
24
+ export function shellOutputSilenceMs(task, { now = Date.now(), result = task?.result } = {}) {
25
+ let last = null;
26
+ for (const path of [result?.stdout_path || task?.meta?.stdout, result?.stderr_path || task?.meta?.stderr]) {
27
+ if (!path) continue;
28
+ try {
29
+ last = Math.max(last ?? 0, statSync(path).mtimeMs);
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+ if (last == null) return null;
35
+ return Math.max(0, now - Math.max(last, Number(task?.startedAtMs) || 0));
36
+ }
37
+
38
+ /** The warning text for a silence at or past the threshold, else null. */
39
+ export function describeShellOutputSilence(silentMs, warnMs = SHELL_OUTPUT_SILENCE_WARN_MS) {
40
+ if (!(silentMs >= warnMs)) return null;
41
+ return `no output for ${formatDuration(silentMs, { mostSignificantOnly: true })} — may be hung; inspect or cancel`;
42
+ }
43
+
44
+ const isRunningShell = (task) => task?.surface === 'shell' && task.status === 'running';
45
+
46
+ /** The warning for one running shell task, else null. */
47
+ export function shellTaskSilenceNote(task, { now = Date.now(), warnMs = SHELL_OUTPUT_SILENCE_WARN_MS, result } = {}) {
48
+ if (!isRunningShell(task)) return null;
49
+ return describeShellOutputSilence(shellOutputSilenceMs(task, { now, result: result ?? task.result }), warnMs);
50
+ }
51
+
52
+ /** The quietest of the running shell jobs an agent's `task wait` is parked on:
53
+ * `{ taskId, silentMs, hung }`, or null when it waits on none. */
54
+ export function waitedJobSilence(taskIds, { now = Date.now(), warnMs = SHELL_OUTPUT_SILENCE_WARN_MS } = {}) {
55
+ let worst = null;
56
+ for (const taskId of taskIds || []) {
57
+ const task = getBackgroundTask(taskId);
58
+ if (!isRunningShell(task)) continue;
59
+ const silentMs = shellOutputSilenceMs(task, { now });
60
+ if (silentMs != null && (!worst || silentMs > worst.silentMs))
61
+ worst = { taskId, silentMs, hung: silentMs >= warnMs };
62
+ }
63
+ return worst;
64
+ }
@@ -20,6 +20,11 @@ import {
20
20
  prepareShellText,
21
21
  textPiece,
22
22
  } from './shell-delivery.mjs';
23
+ import {
24
+ SHELL_OUTPUT_SILENCE_WARN_MS,
25
+ describeShellOutputSilence,
26
+ shellOutputSilenceMs,
27
+ } from './shell-output-silence.mjs';
23
28
 
24
29
  const cursors = new WeakMap();
25
30
  const ESC = '\x1b';
@@ -121,16 +126,16 @@ function lastMatch(pattern, text) {
121
126
 
122
127
  /** What changed since the agent last saw the job: growth, last line, any
123
128
  * visible percent/ETA. Used where a still-running job is reported. */
124
- function progressDigest(growth) {
129
+ function progressDigest(growth, hung) {
125
130
  const bytes = growth.reduce((sum, entry) => sum + entry.bytes, 0);
126
131
  const lines = growth.reduce((sum, entry) => sum + entry.lines, 0);
127
132
  const text = growth
128
133
  .map((entry) => entry.text)
129
134
  .filter(Boolean)
130
135
  .join('\n');
131
- const parts = [
132
- bytes > 0 ? `+${formatKb(bytes)}, +${lines} lines since you last saw it` : 'no new output since you last saw it',
133
- ];
136
+ const parts = [];
137
+ if (bytes > 0) parts.push(`+${formatKb(bytes)}, +${lines} lines since you last saw it`);
138
+ else if (!hung) parts.push('no new output since you last saw it');
134
139
  const last = text
135
140
  .split('\n')
136
141
  .reverse()
@@ -140,6 +145,8 @@ function progressDigest(growth) {
140
145
  if (percent && Number(percent[1]) <= 100) parts.push(`${percent[1]}%`);
141
146
  const eta = lastMatch(ETA_RE, text);
142
147
  if (eta) parts.push(`ETA ${eta[1].trim()}`);
148
+ // A job quiet past the threshold is no longer reassured as "not an error".
149
+ if (hung) return `[progress] ${[...parts, hung].join(' · ')}`;
143
150
  return `[progress] ${parts.join(' · ')} — still running, not an error`;
144
151
  }
145
152
 
@@ -169,7 +176,13 @@ export function shellLogPiece(path) {
169
176
  export function readShellTaskOutput(
170
177
  task,
171
178
  result = {},
172
- { output = 'new', terminal = task.status !== 'running', digest = false } = {}
179
+ {
180
+ output = 'new',
181
+ terminal = task.status !== 'running',
182
+ digest = false,
183
+ now = Date.now(),
184
+ silenceWarnMs = SHELL_OUTPUT_SILENCE_WARN_MS,
185
+ } = {}
173
186
  ) {
174
187
  const replay = output === 'tail';
175
188
  const growth = [];
@@ -253,5 +266,6 @@ export function readShellTaskOutput(
253
266
  const body =
254
267
  sections.map((item) => (item.piece ? `${item.prefix}${bodies[pieces.indexOf(item)]}` : item)).join('\n\n') ||
255
268
  (replay ? '(no output)' : '(no new output)');
256
- return escapeHarnessTags(digest ? `${progressDigest(growth)}\n\n${body}` : body);
269
+ const hung = digest ? describeShellOutputSilence(shellOutputSilenceMs(task, { now, result }), silenceWarnMs) : null;
270
+ return escapeHarnessTags(digest ? `${progressDigest(growth, hung)}\n\n${body}` : body);
257
271
  }
@@ -32,6 +32,7 @@ import { recordDeliveredCompletion } from '../../session/manager/delivered-compl
32
32
  import { listShellJobRecords, readShellJobRecord } from './lib/shell-job-records.mjs';
33
33
  import { resourceAdmission } from '../../../../shared/resource-admission.mjs';
34
34
  import { readShellTaskOutput } from './lib/shell-task-output.mjs';
35
+ import { shellTaskSilenceNote } from './lib/shell-output-silence.mjs';
35
36
 
36
37
  // Ceiling for confirming that a cancelled task's process really exited. The
37
38
  // wait returns the moment the native task settles, so this only bounds a
@@ -89,6 +90,11 @@ function refreshShellTask(taskId, { includeRunning = false } = {}) {
89
90
  if (task) {
90
91
  task.result = publicResult;
91
92
  task.resultText = JSON.stringify(publicResult, null, 2);
93
+ // The job's own status line: set while it is quiet past the threshold,
94
+ // gone again the moment it prints.
95
+ const silence = shellTaskSilenceNote(task);
96
+ if (silence) task.meta = { ...task.meta, output_silence: silence };
97
+ else if (task.meta?.output_silence) delete task.meta.output_silence;
92
98
  }
93
99
  }
94
100
  return job;
@@ -144,6 +150,11 @@ async function listTasks(options) {
144
150
  (record) => recoveredTaskMatches(record, options) && !liveIds.has(record.jobId)
145
151
  );
146
152
  const sections = [rendered];
153
+ const quiet = listBackgroundTasks({ context: options, surface: 'shell' })
154
+ .map((row) => [row.task_id, shellTaskSilenceNote(getBackgroundTask(row.task_id))])
155
+ .filter(([, note]) => note)
156
+ .map(([id, note]) => `- ${id} ${note}`);
157
+ if (quiet.length > 0) sections.push(`[output silence]\n${quiet.join('\n')}`);
147
158
  if (recovered.length > 0) {
148
159
  const rows = recovered.map(
149
160
  (record) =>
@@ -175,7 +186,7 @@ async function waitForShellTask(task, taskId, args, options) {
175
186
  turnSignal = null;
176
187
  }
177
188
  const waitControl = beginInterruptibleTaskWait(options?.sessionId, turnSignal);
178
- const releaseWaitState = beginSessionTaskWait(options?.sessionId);
189
+ const releaseWaitState = beginSessionTaskWait(options?.sessionId, taskId);
179
190
  const waitSignal = waitControl.signal;
180
191
  const waitTimeoutMs = resolveTaskWaitTimeoutMs(args.timeout_ms, await defaultTaskWaitMs(options?.sessionId));
181
192
  let interruptedByUser = false;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Every routine (schedule and webhook) one bot owns, deleted as its bot is
3
+ * deleted. One statement over both stores, keyed by the rows' current owner:
4
+ * it removes all of them with their run state (on the rows) and the webhooks'
5
+ * delivery logs, or — failing — none; a row moved to another bot is never
6
+ * matched.
7
+ */
8
+ import { openSchedulesDb } from './schedules-db.mjs';
9
+ import { openWebhooksDb } from './webhooks-db.mjs';
10
+
11
+ /** Resolves `{ schedules, webhooks }`: the names removed. */
12
+ export async function deleteRoutinesOwnedBy(ownerAgentId, { dataDir } = {}) {
13
+ if (typeof ownerAgentId !== 'string' || !ownerAgentId) throw new Error('deleteRoutinesOwnedBy: an owner is required');
14
+ // Both stores' tables exist before the one statement names them.
15
+ const [db] = await Promise.all([openSchedulesDb({ dataDir }), openWebhooksDb({ dataDir })]);
16
+ const { rows } = await db.query(
17
+ `WITH schedules AS (
18
+ DELETE FROM scheduler.schedules WHERE owner_agent_id = $1 RETURNING name
19
+ ), endpoints AS (
20
+ DELETE FROM webhooks.endpoints WHERE owner_agent_id = $1 RETURNING name
21
+ ), deliveries AS (
22
+ DELETE FROM webhooks.deliveries WHERE endpoint IN (SELECT name FROM endpoints)
23
+ )
24
+ SELECT 'schedule' AS kind, name FROM schedules
25
+ UNION ALL
26
+ SELECT 'webhook' AS kind, name FROM endpoints`,
27
+ [ownerAgentId]
28
+ );
29
+ const names = (kind) =>
30
+ rows
31
+ .filter((row) => row.kind === kind)
32
+ .map((row) => row.name)
33
+ .sort();
34
+ return { schedules: names('schedule'), webhooks: names('webhook') };
35
+ }
@@ -79,6 +79,10 @@ const getDb = createPgSchemaDb({
79
79
  withLock: withSchemaBootstrapLock,
80
80
  });
81
81
 
82
+ /** The store's handle, its tables created: for a statement that spans the
83
+ * routine stores (routines-db.mjs). */
84
+ export const openSchedulesDb = ({ dataDir } = {}) => getDb(dataDir);
85
+
82
86
  // ---------------------------------------------------------------------------
83
87
  // Row <-> def mapping
84
88
  // ---------------------------------------------------------------------------
@@ -82,6 +82,10 @@ const getDb = createPgSchemaDb({
82
82
  withLock: withSchemaBootstrapLock,
83
83
  });
84
84
 
85
+ /** The store's handle, its tables created: for a statement that spans the
86
+ * routine stores (routines-db.mjs). */
87
+ export const openWebhooksDb = ({ dataDir } = {}) => getDb(dataDir);
88
+
85
89
  // ---------------------------------------------------------------------------
86
90
  // Row <-> def mapping
87
91
  // ---------------------------------------------------------------------------
@@ -229,13 +229,13 @@ export const COMPUTER_ACTION_CONTRACTS = [
229
229
  minItems: 1,
230
230
  maxItems: 6,
231
231
  description:
232
- 'First: an input action. Then type/key/wait reusing focus, or click/double_click/triple_click/scroll/set_value/type/key on a ref from the same observation (no marks or coordinates). Waits total ≤10s; transition/failure or a changed, disabled, or off-screen ref stops the rest.',
232
+ 'First: an input action. Then type/key/wait reusing focus, or click/double_click/triple_click/scroll/set_value/type/key on a ref from the same observation (no marks or coordinates). act already settles after each action; wait is a fixed pause for a known async delay (quiet:true ends it early once windows stop changing; see wait.quiet) and totals ≤10s; use verify for a real condition. Transition/failure or a changed, disabled, or off-screen ref stops the rest.',
233
233
  },
234
234
  observe: {
235
235
  type: 'string',
236
236
  enum: ['state', 'ax'],
237
237
  description:
238
- 'Returned observation. Default: ax when the first action targets a ref (full state if the tree is unusable), otherwise state. state includes the frame for coordinates or visual checks; ax skips the screenshot.',
238
+ 'Returned observation. Default: ax when the first action targets a ref (full state if the tree is unusable), otherwise state. state includes the frame for coordinates or visual checks; ax skips the screenshot. A repeat observation of the same window may send elements_delta instead of elements: unchanged lists "old ref=live ref" ranges for rows that look identical to the list you hold (s1:e0..e4=s9:e0..e4), added has every other row in full, removed the old refs that are gone. Every ref from an earlier observation is retired: act only with the live ref on the right of "=" or on an added row. A new window, a dialog or a large change returns the full elements list, and capture always does.',
239
239
  },
240
240
  ...delivery,
241
241
  },
@@ -90,7 +90,18 @@ export const COMPUTER_CORE_ACTION_SCHEMA = {
90
90
  'Key name or chord. Keyboard chords with ctrl/shift/alt require explicit foreground delivery; background supports plain keys.',
91
91
  pattern: '^[^\\u0000-\\u001F\\u007F-\\u009F]+$',
92
92
  },
93
- duration: { type: 'number', minimum: 0, maximum: 5 },
93
+ duration: {
94
+ type: 'number',
95
+ minimum: 0,
96
+ maximum: 5,
97
+ description:
98
+ 'wait: cap in seconds. act already settles after every action; use wait only for a known async delay.',
99
+ },
100
+ quiet: {
101
+ type: 'boolean',
102
+ description:
103
+ 'wait: opt-in (default false, a fixed pause). true ends before duration once the window set, foreground, focused window, title and bounds stop changing (3 equal samples 200 ms apart); use it when waiting for a window or dialog to open, close or move. Content changes inside a window (canvas, text) are not seen: use verify for those.',
104
+ },
94
105
  },
95
106
  required: ['type'],
96
107
  additionalProperties: false,
@@ -114,7 +125,7 @@ const FIELDS_BY_TYPE = {
114
125
  key: new Set(['type', 'ref', 'keys']),
115
126
  key_down: new Set(['type', 'ref', 'keys']),
116
127
  key_up: new Set(['type', 'ref', 'keys']),
117
- wait: new Set(['type', 'duration']),
128
+ wait: new Set(['type', 'duration', 'quiet']),
118
129
  };
119
130
 
120
131
  function targetFormError(action, { required = true, frameId = '' } = {}) {
@@ -153,6 +164,9 @@ function fieldValueError(field, value, label) {
153
164
  if (schema.type === 'number' && (typeof value !== 'number' || !Number.isFinite(value))) {
154
165
  return `${label}.${field} must be a finite number`;
155
166
  }
167
+ if (schema.type === 'boolean' && typeof value !== 'boolean') {
168
+ return `${label}.${field} must be a boolean`;
169
+ }
156
170
  if (typeof value === 'number') {
157
171
  if (schema.minimum !== undefined && value < schema.minimum) {
158
172
  return `${label}.${field} must be at least ${schema.minimum}`;
@@ -111,6 +111,12 @@ function ocrTextLine(row) {
111
111
  function renderObservationLines(frame) {
112
112
  if (!frame || typeof frame !== 'object') return;
113
113
  if (Array.isArray(frame.elements)) frame.elements = frame.elements.map(elementLine);
114
+ const delta = frame.elements_delta;
115
+ if (delta && typeof delta === 'object') {
116
+ if (Array.isArray(delta.added)) delta.added = delta.added.map(elementLine);
117
+ // The delta already says what changed; the host's count summary repeats it.
118
+ delete frame.changes;
119
+ }
114
120
  for (const key of ['lines', 'words']) {
115
121
  if (Array.isArray(frame.ocr?.[key])) frame.ocr[key] = frame.ocr[key].map(ocrTextLine);
116
122
  }
@@ -22,7 +22,7 @@ export const TOOL_DEFS = [
22
22
  openWorldHint: false,
23
23
  },
24
24
  description:
25
- 'Manage standing user preferences and constraints. Before add/edit, obtain approval for the exact content and scope unless already explicitly requested. Load memory-management for curation policy; stored history uses recall.',
25
+ "Manage standing user preferences and constraints. Save what the user asks you to remember and report its exact text and scope; an entry you propose yourself, or one whose scope is unclear, waits for the user's approval. Load memory-management for curation policy; stored history uses recall.",
26
26
  inputSchema: {
27
27
  type: 'object',
28
28
  properties: {