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
@@ -42,7 +42,11 @@ function workerLine(worker) {
42
42
  const stage = worker.worker_stage || worker.stage;
43
43
  const progress = oneLine(worker.last_progress);
44
44
  const summary = progress.length > 60 ? `${progress.slice(0, 59)}…` : progress;
45
- return `- ${worker.tag} ${status}${stage && stage !== status ? `/${stage}` : ''}${summary ? ` ${summary}` : ''}`;
45
+ const toolSilence = oneLine(worker.tool_silent_for);
46
+ // The hung diagnostic carries the warning and the suggested action; other
47
+ // diagnostics stay out of the compact row.
48
+ const hung = /^tool possibly hung/.test(worker.diagnostic || '') ? oneLine(worker.diagnostic) : '';
49
+ return `- ${worker.tag} ${status}${stage && stage !== status ? `/${stage}` : ''}${summary ? ` ${summary}` : ''}${toolSilence ? ` tool_silent_for: ${toolSilence}` : ''}${hung ? ` ! ${hung}` : ''}`;
46
50
  }
47
51
 
48
52
  function jobLine(job) {
@@ -121,6 +125,7 @@ function taskDiagnosticLines(value) {
121
125
  if (value.worker_stage) lines.push(`worker_stage: ${value.worker_stage}`);
122
126
  if (value.last_progress) lines.push(`last_progress: ${value.last_progress}`);
123
127
  if (Number.isFinite(value.silent_for)) lines.push(`silent_for: ${value.silent_for}s`);
128
+ if (value.tool_silent_for) lines.push(`tool_silent_for: ${value.tool_silent_for}`);
124
129
  if (value.watchdog) lines.push(`watchdog: ${value.watchdog}`);
125
130
  if (Number.isFinite(value.queued_followups)) lines.push(`queued_followups: ${value.queued_followups}`);
126
131
  if (value.diagnostic) lines.push(`diagnostic: ${value.diagnostic}`);
@@ -24,7 +24,8 @@ import {
24
24
  setEndpointEnabled as dbSetEndpointEnabled,
25
25
  } from '../../runtime/channels/lib/webhooks-db.mjs';
26
26
  import { normalizeAutomationAttachments } from '../../runtime/shared/automation-attachments.mjs';
27
- import { assertRoutineOwner, routineOwnerProblem } from '../routine-owner.mjs';
27
+ import { ROUTINE_OWNER_PROBLEMS, assertRoutineOwner, routineOwnerProblem } from '../routine-owner.mjs';
28
+ import { MIXY_BOT_ID } from '../../runtime/shared/agent-store.mjs';
28
29
  import { assertRoutineExecutor } from '../routine-executor.mjs';
29
30
  import { hasEnabledAutomation } from '../../runtime/shared/automation-presence.mjs';
30
31
  import { resolveScheduleTimezone, validateScheduleCron } from '../../runtime/shared/schedule-time.mjs';
@@ -278,9 +279,13 @@ function ownerProblems() {
278
279
  export async function listSchedules() {
279
280
  const rows = await dbListSchedules();
280
281
  const problemOf = ownerProblems();
281
- return Promise.all(rows.map(async (row) => scheduleToDisplay(row, await problemOf(row.ownerAgentId))));
282
+ const listed = await Promise.all(rows.map(async (row) => scheduleToDisplay(row, await problemOf(row.ownerAgentId))));
283
+ return listed.filter(shownRoutine);
282
284
  }
283
285
 
286
+ // An archived bot's routines are hidden until it is restored (routine-owner.mjs).
287
+ const shownRoutine = (row) => row.ownerProblem !== 'owner-archived';
288
+
284
289
  /**
285
290
  * Run `step` (the move of schedule `name`'s row) with `name` reserved against
286
291
  * runs in this process (the app's "Run now"). Refused when one is in flight.
@@ -380,6 +385,7 @@ export async function saveSchedule(
380
385
  saved = await upsertSchedule(def);
381
386
  }
382
387
  automationProbe.invalidate();
388
+ await refuseIfOwnerDeleted(ownerAgentId);
383
389
  return scheduleToDisplay(saved);
384
390
  }
385
391
 
@@ -406,7 +412,7 @@ async function listWebhooks() {
406
412
  const endpoints = await dbListEndpoints();
407
413
  const problemOf = ownerProblems();
408
414
  const problems = await Promise.all(endpoints.map((ep) => problemOf(ep.ownerAgentId)));
409
- return endpoints.map((ep, index) => ({
415
+ const listed = endpoints.map((ep, index) => ({
410
416
  name: ep.name,
411
417
  description: ep.description || '',
412
418
  parser: ep.parser || 'github',
@@ -430,6 +436,7 @@ async function listWebhooks() {
430
436
  hasLastPayload: ep.hasLastPayload === true,
431
437
  ...routineHealth(ep),
432
438
  }));
439
+ return listed.filter(shownRoutine);
433
440
  }
434
441
 
435
442
  export async function saveWebhook({
@@ -483,6 +490,7 @@ export async function saveWebhook({
483
490
  executorAgentId: executor,
484
491
  });
485
492
  automationProbe.invalidate();
493
+ await refuseIfOwnerDeleted(ownerAgentId);
486
494
  return {
487
495
  name: id,
488
496
  owner: saved.ownerAgentId || ownerAgentId,
@@ -504,6 +512,39 @@ export async function deleteWebhook(name) {
504
512
  return { name: id, deleted: true };
505
513
  }
506
514
 
515
+ /**
516
+ * Delete every schedule and webhook `agentId` currently owns, as its bot is
517
+ * deleted for good (agent-editor.mjs): all of them in one statement, or none
518
+ * (routines-db.mjs). Resolves the names removed. Mixy is never a target.
519
+ * Without a PostgreSQL cluster none exists, and none is started.
520
+ */
521
+ export async function deleteOwnedRoutines(agentId) {
522
+ if (!agentHomeSessionId(agentId) || agentId === MIXY_AGENT_ID || agentId === MIXY_BOT_ID) {
523
+ throw new Error(`the routines of "${agentId}" cannot be deleted with a bot`);
524
+ }
525
+ if (!pgClusterExists(resolvePluginData())) return { schedules: [], webhooks: [] };
526
+ // Loaded on use: the stores' own modules stay the only imports of every reader.
527
+ const { deleteRoutinesOwnedBy } = await import('../../runtime/channels/lib/routines-db.mjs');
528
+ const removed = await deleteRoutinesOwnedBy(agentId);
529
+ automationProbe.invalidate();
530
+ return removed;
531
+ }
532
+
533
+ /**
534
+ * After a save: the owner it checked may have been deleted for good meanwhile,
535
+ * its routines purged before this row landed. Then the row goes the way of
536
+ * the bot's others (deleteOwnedRoutines) and the save is refused. The delete
537
+ * purges again once the bot's folder is gone, so either a purge sees this row
538
+ * or this check sees the bot gone. An owner archived meanwhile keeps the row,
539
+ * hidden with its others until a restore, as if saved just before.
540
+ */
541
+ async function refuseIfOwnerDeleted(ownerAgentId) {
542
+ const problem = await routineOwnerProblem(ownerAgentId).catch(() => '');
543
+ if (problem !== 'owner-deleted') return;
544
+ await deleteOwnedRoutines(ownerAgentId);
545
+ throw new Error(ROUTINE_OWNER_PROBLEMS[problem]);
546
+ }
547
+
507
548
  export async function setWebhookEnabled(name, enabled) {
508
549
  const id = assertName(name, 'webhook name');
509
550
  const updated = await dbSetEndpointEnabled(id, enabled !== false);
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from 'node:child_process';
2
- import { existsSync, mkdirSync, readdirSync, renameSync, rmSync } from 'node:fs';
2
+ import { chmodSync, existsSync, lstatSync, mkdirSync, readdirSync, renameSync, rmSync, unlinkSync } from 'node:fs';
3
3
  import { basename, dirname, join, resolve } from 'node:path';
4
4
  import { homedir } from 'node:os';
5
5
  import { createHash, randomUUID } from 'node:crypto';
@@ -168,6 +168,45 @@ function withPluginMutation(dataDir, id, operation) {
168
168
  });
169
169
  }
170
170
 
171
+ // Node 24 on Windows (Electron) makes rmSync follow junctions into their targets,
172
+ // so every link is detached first and never chmod-ed or recursed into. It also
173
+ // fails with EPERM on read-only files such as git pack files; clear the read-only
174
+ // bit and retry once. Each entry is lstat-ed right before it is acted on, not
175
+ // trusted from the listing, so a directory swapped for a link after the listing
176
+ // is detached instead of entered. What remains is the instant between that
177
+ // lstat and the next readdir/chmod, which no portable fs call can close. A file
178
+ // with other names (link count > 1) shares its mode with them, so `onFile` is
179
+ // told its stat and the chmod recovery skips it.
180
+ function walkTree(dir, onFile) {
181
+ for (const name of readdirSync(dir)) {
182
+ const full = join(dir, name);
183
+ const stat = lstatSync(full, { throwIfNoEntry: false });
184
+ if (!stat) continue;
185
+ if (stat.isSymbolicLink()) unlinkSync(full);
186
+ else if (stat.isDirectory()) walkTree(full, onFile);
187
+ else onFile?.(full, stat);
188
+ }
189
+ }
190
+
191
+ function removeTree(path) {
192
+ const stat = lstatSync(path, { throwIfNoEntry: false });
193
+ if (!stat) return;
194
+ if (stat.isSymbolicLink()) return unlinkSync(path);
195
+ const options = { recursive: true, force: true };
196
+ if (stat.isDirectory()) walkTree(path);
197
+ try {
198
+ rmSync(path, options);
199
+ } catch (error) {
200
+ if (error?.code !== 'EPERM') throw error;
201
+ if (stat.isDirectory()) {
202
+ walkTree(path, (file, fileStat) => {
203
+ if (fileStat.nlink === 1) chmodSync(file, 0o666);
204
+ });
205
+ }
206
+ rmSync(path, options);
207
+ }
208
+ }
209
+
171
210
  function cleanupManagedPartials(root) {
172
211
  const parent = dirname(root);
173
212
  const prefix = `${basename(root)}.tmp-`;
@@ -175,7 +214,7 @@ function cleanupManagedPartials(root) {
175
214
  for (const entry of readdirSync(parent)) {
176
215
  if (!entry.startsWith(prefix)) continue;
177
216
  try {
178
- rmSync(join(parent, entry), { recursive: true, force: true });
217
+ removeTree(join(parent, entry));
179
218
  } catch {}
180
219
  }
181
220
  }
@@ -185,7 +224,7 @@ function recoverManagedPluginRoot(root) {
185
224
  if (!existsSync(root) && existsSync(backupRoot)) {
186
225
  renameSync(backupRoot, root);
187
226
  } else if (existsSync(root) && existsSync(backupRoot)) {
188
- rmSync(backupRoot, { recursive: true, force: true });
227
+ removeTree(backupRoot);
189
228
  }
190
229
  return backupRoot;
191
230
  }
@@ -210,7 +249,7 @@ export function _publishManagedPluginRoot(root, tempRoot) {
210
249
  throw error;
211
250
  }
212
251
  try {
213
- rmSync(backupRoot, { recursive: true, force: true });
252
+ removeTree(backupRoot);
214
253
  } catch {}
215
254
  }
216
255
 
@@ -228,7 +267,7 @@ function materializePlugin(normalized, id, dataDir) {
228
267
  _publishManagedPluginRoot(root, tempRoot);
229
268
  } catch (error) {
230
269
  try {
231
- rmSync(tempRoot, { recursive: true, force: true });
270
+ removeTree(tempRoot);
232
271
  } catch {}
233
272
  throw error;
234
273
  } finally {
@@ -374,8 +413,8 @@ export function removePlugin(idOrName, { dataDir = resolvePluginData() } = {}) {
374
413
  });
375
414
  if (entry.managed !== false && entry.root) {
376
415
  ensureInside(installRoot(dataDir), entry.root);
377
- rmSync(entry.root, { recursive: true, force: true });
378
- rmSync(`${entry.root}.backup`, { recursive: true, force: true });
416
+ removeTree(entry.root);
417
+ removeTree(`${entry.root}.backup`);
379
418
  cleanupManagedPartials(entry.root);
380
419
  }
381
420
  return { ...entry, removed: true };
@@ -598,6 +598,7 @@ function publicCustomModelRows(rows) {
598
598
  if (out > 0) model.maxOutputTokens = Math.floor(out);
599
599
  model.hidden = item.hidden === true;
600
600
  model.manual = item.manual === true;
601
+ if (item.inherited) model.inherited = structuredClone(item.inherited);
601
602
  for (const key of [
602
603
  'supportsVision',
603
604
  'supportsReasoning',
@@ -660,6 +661,7 @@ function customProviderRow(id, entry, checkSecrets = true) {
660
661
  row.discovery = structuredClone(config?.discovery ?? entry.discovery ?? { newModelsHidden: false });
661
662
  row.modelOverrides = structuredClone(config?.modelOverrides ?? entry.modelOverrides ?? {});
662
663
  if (config?.headers) row.headers = { ...config.headers };
664
+ if (config?.requestBody) row.requestBody = structuredClone(config.requestBody);
663
665
  if (config?.wires) row.wires = [...config.wires];
664
666
  if (config?.modelWires) row.modelWires = { ...config.modelWires };
665
667
  // Additional API keys by id only; their values never leave the keychain.
@@ -1308,6 +1310,7 @@ function withStoredSettings(input, entry) {
1308
1310
  if (out.modelOverrides === undefined) out.modelOverrides = stored.modelOverrides;
1309
1311
  // `headers: {}` clears them; an omitted field keeps the stored ones.
1310
1312
  if (out.headers === undefined && stored.headers) out.headers = stored.headers;
1313
+ if (out.requestBody === undefined && stored.requestBody) out.requestBody = stored.requestBody;
1311
1314
  // Served wires and per-model wires have no setup field yet: an edit on
1312
1315
  // the same protocol keeps them (another protocol serves other wires).
1313
1316
  if ((out.protocol ?? stored.protocol) === stored.protocol) {
@@ -1472,6 +1475,8 @@ const MODEL_PATCH_KEYS = new Set([
1472
1475
  'maxOutputTokens',
1473
1476
  'supportsVision',
1474
1477
  'reasoning',
1478
+ 'requestBody',
1479
+ 'requestHeaders',
1475
1480
  ]);
1476
1481
  const REASONING_PATCH_KEYS = new Set(['levels', 'wireFormat', 'wireValues', 'replay']);
1477
1482
 
@@ -66,7 +66,7 @@ export const AGENT_SETTINGS_HANDLERS = {
66
66
  }
67
67
  const name = requireText(args.name, 'name');
68
68
  await rt.restoreAgentDefinition(name);
69
- return { restored: name, note: 'Its chat is back; its routines stay off until they are turned on.' };
69
+ return { restored: name, note: 'Its chat is back, and its routines run again as they were.' };
70
70
  },
71
71
  set_bot_order: (rt, args) => ({ botOrder: rt.setBotOrder(args.botOrder).order }),
72
72
  set_cache_warming_enabled: (rt, args) => ({
@@ -79,7 +79,7 @@ const ACTION_APPLIES_TO = {
79
79
  set_agent_connector: "that agent's next connector tool call, in every session",
80
80
  set_agent_connector_tool: "that agent's next call of the tool, in every session",
81
81
  set_project_connector: 'the next connector tool call of sessions in that Project',
82
- restore_definition: 'now: the bot and its chat return; its routines stay off',
82
+ restore_definition: 'now: the bot, its chat and its routines (as they were) return',
83
83
  set_bot_order: 'the Bots page and the Sessions bot section on every device',
84
84
  set_orchestration_mode:
85
85
  "new sessions and an empty current one (the default mode); a conversation keeps its own mode until it is switched with the composer's mode selector",
@@ -284,7 +284,7 @@ export const EXTENDED_SETUP_HANDLERS = Object.freeze({
284
284
  recovery:
285
285
  args.definitionKind === 'workflow'
286
286
  ? 'User-authored definition files are deleted. A built-in override may revert to its built-in definition.'
287
- : 'A custom agent or bot is archived with its chat and its routines are switched off; the user can restore it from Sessions → Archived, or delete it there for good. A built-in override reverts to its built-in definition.',
287
+ : 'A custom agent or bot is archived with its chat; its schedules and webhooks are paused and hidden, unchanged. The user can restore it, routines included, from Sessions → Archived, or delete it there for good, which deletes its routines too. A built-in override reverts to its built-in definition.',
288
288
  };
289
289
  },
290
290
  async save_automation(rt, args, context = {}) {
@@ -299,8 +299,8 @@ export const SETUP_EXTENDED_PROPERTIES = Object.freeze({
299
299
  uiScale: {
300
300
  type: 'number',
301
301
  minimum: 0.85,
302
- maximum: 1.2,
303
- description: 'UI size multiplier, 0.85-1.2 in steps of 0.05 (default 1).',
302
+ maximum: 1.5,
303
+ description: 'UI size multiplier, 0.85-1.5 in steps of 0.05 (default 1).',
304
304
  },
305
305
  codeSize: {
306
306
  type: 'integer',
@@ -6,7 +6,9 @@ import { refreshUnpricedUsageAsync } from '../runtime/shared/llm/usage-pricing-r
6
6
  import { resolvePluginData } from '../runtime/shared/plugin-paths.mjs';
7
7
  import { sessionUsageSnapshot, usageStatsSnapshot } from './services/usage-stats-model.mjs';
8
8
  import { resolveUsageStatsPeriod } from './services/usage-stats-period.mjs';
9
- import { usageRollupDayKey } from '../runtime/shared/llm/usage-rollup.mjs';
9
+ import { isConversationUsageSource, usageRollupDayKey } from '../runtime/shared/llm/usage-rollup.mjs';
10
+ import { isLeadVisibleRow } from '../runtime/agent/orchestrator/session/store-summary-catalog.mjs';
11
+ import { agentIdOfHomeSession } from '../runtime/agent/orchestrator/session/agent-home.mjs';
10
12
  import {
11
13
  ACCOUNT_PROVIDERS,
12
14
  accountScopedSessionId,
@@ -164,6 +166,83 @@ function usageRollupQuery(period) {
164
166
  };
165
167
  }
166
168
 
169
+ async function readSessionMetadata(sessionId) {
170
+ const { readStoredSessionTranscript } = await import(
171
+ '../runtime/agent/orchestrator/session/store-summary-reader.mjs'
172
+ );
173
+ return readStoredSessionTranscript(sessionId, { metadataOnly: true });
174
+ }
175
+
176
+ /**
177
+ * What the request log names a session by: its title, and for an agent's
178
+ * session the title of the session it ran for with its role (`agent: true`
179
+ * with no role when only the ledger's owner link survives). A background
180
+ * request on such an openable session adds its source type as
181
+ * `backgroundKind`. A request whose own session the user cannot open (an
182
+ * internal dispatch, or a session file that is gone) carries its source type
183
+ * as `internalKind` instead, and no title: the first prompt line of a
184
+ * background run says nothing about it.
185
+ */
186
+ async function describeRequestSessions(requests, sessionMetadata) {
187
+ // `exec` is hidden by the catalog but counts as conversation in usage
188
+ // totals; every other hidden source is one the rollup calls background.
189
+ const internalKindOf = (sourceType) => {
190
+ const id = String(sourceType || '')
191
+ .trim()
192
+ .toLowerCase();
193
+ const hidden = id && !isLeadVisibleRow({ sourceType: id, preview: id });
194
+ return hidden && (id === 'exec' || !isConversationUsageSource(id)) ? id : '';
195
+ };
196
+ const metadata = new Map();
197
+ const read = async (id) => {
198
+ if (!id) return null;
199
+ if (!metadata.has(id))
200
+ metadata.set(
201
+ id,
202
+ Promise.resolve(sessionMetadata(id)).catch(() => null)
203
+ );
204
+ return metadata.get(id);
205
+ };
206
+ const labels = new Map();
207
+ for (const request of requests) {
208
+ const key = `${request.sessionId}\u0000${request.ownerSessionId}\u0000${request.sourceType}`;
209
+ if (labels.has(key)) continue;
210
+ const own = await read(request.sessionId);
211
+ const kind = internalKindOf(request.sourceType || own?.sourceType);
212
+ // A session the user can open keeps its label whatever the request's
213
+ // route (a cache warm-up records under the real session id); only the
214
+ // work's kind is added. A session file that is gone cannot be opened, nor
215
+ // can a session that is itself an internal run (a memory-cycle dispatch
216
+ // is stored as an owned agent session).
217
+ const openable =
218
+ Boolean(own) &&
219
+ !internalKindOf(own.sourceType) &&
220
+ ((own.agent && (own.ownerSessionId || request.ownerSessionId)) || isLeadVisibleRow({ ...own, preview: 'x' }));
221
+ if (kind && !openable) {
222
+ labels.set(key, { title: '', role: '', agent: false, internalKind: kind });
223
+ continue;
224
+ }
225
+ const ownerId = own?.ownerSessionId || request.ownerSessionId;
226
+ let label = { title: own?.title || agentIdOfHomeSession(request.sessionId) || '', role: '', agent: false };
227
+ if (ownerId && ownerId !== request.sessionId && (own?.agent || !own)) {
228
+ const owner = await read(ownerId);
229
+ label = { title: owner?.title || agentIdOfHomeSession(ownerId) || '', role: own?.agent || '', agent: true };
230
+ }
231
+ labels.set(key, { ...label, backgroundKind: kind });
232
+ }
233
+ return requests.map(({ ownerSessionId, sourceType, ...request }) => {
234
+ const label = labels.get(`${request.sessionId}\u0000${ownerSessionId}\u0000${sourceType}`);
235
+ return {
236
+ ...request,
237
+ sessionTitle: label.title,
238
+ agentRole: label.role,
239
+ agent: label.agent,
240
+ internalKind: label.internalKind || '',
241
+ backgroundKind: label.backgroundKind || '',
242
+ };
243
+ });
244
+ }
245
+
167
246
  export function createUsageStatsApi({
168
247
  ledger = getUsageLedger,
169
248
  importHistory = importUsageHistory,
@@ -171,6 +250,8 @@ export function createUsageStatsApi({
171
250
  // provider -> { [accountId]: email } for the picker's secondary text.
172
251
  accountEmails = () => ({}),
173
252
  getSessionId = () => null,
253
+ // sessionId -> stored metadata ({ title, agent, ownerSessionId }) or null.
254
+ sessionMetadata = readSessionMetadata,
174
255
  } = {}) {
175
256
  let importing = null;
176
257
  let imported = false;
@@ -234,6 +315,41 @@ export function createUsageStatsApi({
234
315
  return snapshot;
235
316
  },
236
317
 
318
+ /**
319
+ * The request log: one page of requests in a statistics period (`view`,
320
+ * `anchor`, custom dates; the 24-hour view by default), newest first,
321
+ * optionally of one `status` and one answering `model`. `cursor` is an
322
+ * earlier page's `nextCursor`. `models` lists the models that answered in
323
+ * the period.
324
+ */
325
+ async getUsageRequests(options = {}) {
326
+ const store = ledger();
327
+ if (!store) throw new Error('Usage ledger is unavailable');
328
+ await store.settleWrites();
329
+ // `asOf` is the first page's `generatedAt`: later pages resolve the same
330
+ // period bounds, so a rolling window does not slide while it is browsed.
331
+ const asOf = Number(options?.asOf);
332
+ const real = Date.now();
333
+ if (options?.asOf != null && !(asOf > 0 && asOf <= real)) throw new RangeError('asOf must be a past timestamp');
334
+ const now = asOf > 0 ? asOf : real;
335
+ const period = usagePeriodFor({ ...options, view: options?.view ?? 'hour' }, now);
336
+ const page = await store.requestsAsync({
337
+ fromMs: period.fromMs,
338
+ toMs: period.toMs,
339
+ status: quotaText(options?.status),
340
+ model: quotaText(options?.model),
341
+ cursor: quotaText(options?.cursor) || null,
342
+ limit: options?.limit,
343
+ });
344
+ return {
345
+ generatedAt: now,
346
+ period,
347
+ requests: await describeRequestSessions(page.requests, sessionMetadata),
348
+ nextCursor: page.nextCursor,
349
+ models: page.models,
350
+ };
351
+ },
352
+
237
353
  /**
238
354
  * This runtime's session from its first request, compactions included; null before it has one.
239
355
  * `sessionIds` adds the same totals for each named session (the agents it spawned) under
@@ -50,8 +50,18 @@ export function createAgentConnectorsApi(deps, editor) {
50
50
  const switches = (policy) => installedIds().map((id) => ({ id, enabled: connectorEnabled(policy, id) }));
51
51
  // A legacy list or an unreadable policy becomes its deny-list equivalent
52
52
  // over today's connectors before any edit, so an edit never widens it.
53
- const editablePolicy = (agentId) =>
54
- migrateLegacyConnectorPolicy(editor.getAgentConnectorPolicy(agentId), installedIds()) || { off: [], tools: {} };
53
+ const editablePolicyOf = (stored) =>
54
+ migrateLegacyConnectorPolicy(stored, installedIds()) || { off: [], tools: {} };
55
+ const editablePolicy = (agentId) => editablePolicyOf(editor.getAgentConnectorPolicy(agentId));
56
+ // An edit is derived from the policy stored when its turn in the agent's
57
+ // write queue comes, so two edits started together never undo each other,
58
+ // and the remote no-widen check judges that same policy.
59
+ const editPolicy = (agentId, options, derive) =>
60
+ editor.updateAgentConnectorPolicy(agentId, (stored) => {
61
+ const next = derive(editablePolicyOf(stored));
62
+ if (options?.noWiden) assertConnectorPolicyNotWidened(stored, next);
63
+ return storedConnectorPolicy(next);
64
+ });
55
65
 
56
66
  function listConnectors() {
57
67
  return (mcpStatus()?.servers || []).map((row) => ({
@@ -102,12 +112,10 @@ export function createAgentConnectorsApi(deps, editor) {
102
112
  async function setAgentConnectorEnabled(agentId, connectorId, enabled, options) {
103
113
  const id = requireId(connectorId, 'connector id');
104
114
  if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean');
105
- const policy = editablePolicy(agentId);
106
- const off = enabled ? policy.off.filter((entry) => entry !== id) : [...policy.off, id];
107
- if (options?.noWiden) {
108
- assertConnectorPolicyNotWidened(editor.getAgentConnectorPolicy(agentId), { off, tools: policy.tools });
109
- }
110
- await editor.setAgentConnectorPolicy(agentId, storedConnectorPolicy({ off, tools: policy.tools }));
115
+ await editPolicy(agentId, options, (policy) => ({
116
+ off: enabled ? policy.off.filter((entry) => entry !== id) : [...policy.off, id],
117
+ tools: policy.tools,
118
+ }));
111
119
  return getAgentConnectors(agentId);
112
120
  }
113
121
 
@@ -119,26 +127,24 @@ export function createAgentConnectorsApi(deps, editor) {
119
127
  }
120
128
  const server = requireId(connectorId, 'connector id');
121
129
  const tool = requireId(toolName, 'tool name');
122
- const policy = editablePolicy(agentId);
123
130
  // The accounts of one connector (`gmail`, `gmail-2`…) share the permission,
124
131
  // stored once under the connector's id; an entry an account kept of its own
125
132
  // for this tool goes in the same write.
126
133
  const group = connectorGroupId(server);
127
- const tools = Object.fromEntries(
128
- Object.entries(policy.tools).map(([id, entries]) => {
129
- if (id === group || connectorGroupId(id) !== group) return [id, entries];
130
- const { [tool]: _dropped, ...rest } = entries;
131
- return [id, rest];
132
- })
133
- );
134
- const own = { ...tools[group] };
135
- if (permission == null) delete own[tool];
136
- else own[tool] = permission;
137
- tools[group] = own;
138
- if (options?.noWiden) {
139
- assertConnectorPolicyNotWidened(editor.getAgentConnectorPolicy(agentId), { off: policy.off, tools });
140
- }
141
- return editor.setAgentConnectorPolicy(agentId, storedConnectorPolicy({ off: policy.off, tools }));
134
+ return editPolicy(agentId, options, (policy) => {
135
+ const tools = Object.fromEntries(
136
+ Object.entries(policy.tools).map(([id, entries]) => {
137
+ if (id === group || connectorGroupId(id) !== group) return [id, entries];
138
+ const { [tool]: _dropped, ...rest } = entries;
139
+ return [id, rest];
140
+ })
141
+ );
142
+ const own = { ...tools[group] };
143
+ if (permission == null) delete own[tool];
144
+ else own[tool] = permission;
145
+ tools[group] = own;
146
+ return { off: policy.off, tools };
147
+ });
142
148
  }
143
149
 
144
150
  // A card's "항상 허용" for a connector tool saves through this same writer.
@@ -186,11 +192,12 @@ export function createAgentConnectorsApi(deps, editor) {
186
192
  /** Replace the agent's connector policy (null removes it). With `options.noWiden`
187
193
  * the replacement may not give any tool more authority than the stored policy. */
188
194
  async function setAgentConnectors(agentId, connectors, options) {
189
- if (options?.noWiden) {
190
- const next = connectors == null ? null : parseConnectorPolicy(connectors);
191
- assertConnectorPolicyNotWidened(editor.getAgentConnectorPolicy(agentId), next);
192
- }
193
- return editor.setAgentConnectorPolicy(agentId, connectors);
195
+ return editor.updateAgentConnectorPolicy(agentId, (stored) => {
196
+ if (options?.noWiden) {
197
+ assertConnectorPolicyNotWidened(stored, connectors == null ? null : parseConnectorPolicy(connectors));
198
+ }
199
+ return connectors;
200
+ });
194
201
  }
195
202
 
196
203
  /** The registered Project at `projectPath` (its path is the policy key). */