@moxxy/cli 0.42.1 → 0.44.0

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.
package/dist/bin.js CHANGED
@@ -8,9 +8,7 @@ import path3__default, { join, dirname, resolve, relative, isAbsolute, posix, se
8
8
  import { utf8Locale, ensurePrivateDir, moxxyHome, pruneStaleTempFiles, moxxyPath, hasProxy, installEgressProxy, readProxyEnv, writeFileAtomic, ensurePrivateFile, resolveChannelToken, rotateChannelToken, liveChannelStatus, spawnDedicatedChannel, stopDedicatedChannel, clearChannelStatus, MOXXY_WS_SUBPROTOCOL, bearerTokenMatches, PRIVATE_FILE_MODE, findExecutable, bearerGuard, tokenFromWsProtocolHeader, resolveExecutableTarget, spawnExecutableTarget, resolveOsPrincipal, redactProxyUrl, listLiveChannelStatuses, writeSignedNetworkCacheAtomic, CrossProcessFireLock, writeChannelStatus, writeBoundedNetworkCacheAtomicSync, writeBoundedDataCacheAtomic, readRequestBody } from '@moxxy/sdk/server';
9
9
  import { spawn, execFile, spawnSync } from 'child_process';
10
10
  import { fileURLToPath, pathToFileURL } from 'url';
11
- import { MoxxyError, createMutex, defineMode, definePlugin, defineChannel, defineViewRenderer, DEFAULT_VIEW_TAGS, defineTunnelProvider, defineAuditExporter, defineAuditSink, z as z$1, withAgentConduct, defineTool, defineCommand, defineEmbedder, asPluginId, computerControlSnapshotSchema, runReactLoop, createDeferredPermissionResolver, isSafeViewUrl, redactSecrets, asTurnId, waitFor, unfinishedWorkCheckpoint, defineCompactor, abortError, activeCompactionRanges, defineCacheStrategy, denyByDefaultResolver, runManualCompaction, assertDefined, defineWorkflowExecutor, MOXXY_PCM16_24KHZ_MIME, isFileDiffDisplay, summarizeWithProvider, toolResultBytes, wakeAfter, isSelectableMode, summarizeSessionTokensFromEvents, summarizeTokensByModel, getInstallHint, toDiffRows, diffGutterNo, fileDiffVerb, fileDiffSummary, computerControlCommandSchema, computeElisionState, toolResultStubbed, toolResultStubText, conversationalStubbed, conversationalStub, isFirstPartyPackage, REDACTED_PLACEHOLDER, isSecretKey, addModelTotals, skillFrontmatterSchema, asSkillId, parseFrontmatter, createCallbackResolver, createAllowListResolver, countNodes, autoAllowResolver, SESSION_SOURCES, startChannelWith, EXIT_AFTER_PAIR_FLAG, renderFrontmatter, formatPrincipal, aggregateCapabilitySpecs, hostCredentialName, mentionedSkills, skillAttachment, withoutTools, toolsForMode, moxxyPackageSchema, auditActionOf, asToolCallId, dispatchToolCall, matchLoadableTools, verifyEd25519, defineSecretProvider, encodeLoginAuthUrl, redactSecretText, encodeLoginPrompt, ISOLATION_RANK, sleepWithAbort, asSessionId, migrateModeName, autoApproveFromEvents, AUTO_APPROVE_SUBTYPE, AUTO_APPROVE_PLUGIN_ID, parseFrontmatterFile, createJsonFileStore, autoApproveSwitch, computerApprovalFocusSchema, workflowApprovalItemsSchema, evaluateToolRule, asEventId } from '@moxxy/sdk';
12
- import * as os from 'os';
13
- import os__default, { homedir, tmpdir, userInfo } from 'os';
11
+ import { MoxxyError, createMutex, defineMode, definePlugin, defineChannel, defineViewRenderer, DEFAULT_VIEW_TAGS, defineTunnelProvider, defineAuditExporter, defineAuditSink, z as z$1, withAgentConduct, defineTool, defineCommand, defineEmbedder, asPluginId, computerControlSnapshotSchema, runReactLoop, createDeferredPermissionResolver, isSafeViewUrl, redactSecrets, asTurnId, waitFor, unfinishedWorkCheckpoint, unfinishedStepCheckpoint, defineCompactor, abortError, activeCompactionRanges, defineCacheStrategy, denyByDefaultResolver, runManualCompaction, assertDefined, defineWorkflowExecutor, MOXXY_PCM16_24KHZ_MIME, isFileDiffDisplay, findAttachment, listAttachments, summarizeWithProvider, toolResultBytes, wakeAfter, isSelectableMode, summarizeSessionTokensFromEvents, summarizeTokensByModel, getInstallHint, toDiffRows, diffGutterNo, fileDiffVerb, fileDiffSummary, computerControlCommandSchema, computeElisionState, toolResultStubbed, toolResultStubText, conversationalStubbed, conversationalStub, isFirstPartyPackage, REDACTED_PLACEHOLDER, isSecretKey, addModelTotals, skillFrontmatterSchema, asSkillId, parseFrontmatter, createCallbackResolver, createAllowListResolver, countNodes, autoAllowResolver, SESSION_SOURCES, startChannelWith, EXIT_AFTER_PAIR_FLAG, renderFrontmatter, formatPrincipal, aggregateCapabilitySpecs, hostCredentialName, mentionedSkills, skillAttachment, withoutTools, toolsForMode, moxxyPackageSchema, auditActionOf, asToolCallId, dispatchToolCall, matchLoadableTools, verifyEd25519, defineSecretProvider, encodeLoginAuthUrl, redactSecretText, encodeLoginPrompt, ISOLATION_RANK, sleepWithAbort, asSessionId, migrateModeName, autoApproveFromEvents, AUTO_APPROVE_SUBTYPE, AUTO_APPROVE_PLUGIN_ID, parseFrontmatterFile, createJsonFileStore, autoApproveSwitch, eventForClient, historyPageForClient, readAttachmentChunk, computerApprovalFocusSchema, workflowApprovalItemsSchema, evaluateToolRule, asEventId } from '@moxxy/sdk';
14
12
  import { createRequire as createRequire$1 } from 'module';
15
13
  import { z } from 'zod';
16
14
  import { AsyncLocalStorage } from 'async_hooks';
@@ -23,6 +21,8 @@ import net2, { createConnection, connect } from 'net';
23
21
  import { Worker } from 'worker_threads';
24
22
  import { Buffer as Buffer$1 } from 'buffer';
25
23
  import { StringDecoder } from 'string_decoder';
24
+ import * as os from 'os';
25
+ import os__default, { homedir, tmpdir, userInfo } from 'os';
26
26
  import process$1, { env, cwd, stdout, stdin } from 'process';
27
27
  import { Stream, PassThrough } from 'stream';
28
28
  import tty, { ReadStream } from 'tty';
@@ -92,17 +92,17 @@ function diffSnapshot(before, after) {
92
92
  function snapshotFilter(root) {
93
93
  return (src) => src === root || !SNAPSHOT_EXCLUDE.has(path3.basename(src));
94
94
  }
95
- function selfUpdateRoot(moxxyDir2) {
96
- return path3.join(moxxyDir2, "self-update", "txns");
95
+ function selfUpdateRoot(moxxyDir) {
96
+ return path3.join(moxxyDir, "self-update", "txns");
97
97
  }
98
- function txnDir(moxxyDir2, txnId) {
99
- return path3.join(selfUpdateRoot(moxxyDir2), txnId);
98
+ function txnDir(moxxyDir, txnId) {
99
+ return path3.join(selfUpdateRoot(moxxyDir), txnId);
100
100
  }
101
- function resolveTarget(moxxyDir2, kind, name) {
101
+ function resolveTarget(moxxyDir, kind, name) {
102
102
  if (!NAME_SEGMENT_RE.test(name)) {
103
103
  throw new Error(`invalid ${kind} name "${name}": only letters, digits, dot, dash and underscore are allowed`);
104
104
  }
105
- const p3 = kind === "plugin" ? path3.join(moxxyDir2, "plugins", name) : path3.join(moxxyDir2, "skills", `${name}.md`);
105
+ const p3 = kind === "plugin" ? path3.join(moxxyDir, "plugins", name) : path3.join(moxxyDir, "skills", `${name}.md`);
106
106
  return { kind, name, path: p3 };
107
107
  }
108
108
  function newTxnId(now = /* @__PURE__ */ new Date()) {
@@ -141,18 +141,18 @@ async function beginTransaction(opts) {
141
141
  await writeJournal(opts.moxxyDir, journal);
142
142
  return journal;
143
143
  }
144
- async function writeJournal(moxxyDir2, journal) {
144
+ async function writeJournal(moxxyDir, journal) {
145
145
  journal.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
146
- const file = path3.join(txnDir(moxxyDir2, journal.txnId), "journal.json");
146
+ const file = path3.join(txnDir(moxxyDir, journal.txnId), "journal.json");
147
147
  await writeFileAtomic(file, JSON.stringify(journal, null, 2) + "\n");
148
148
  }
149
- async function readJournal(moxxyDir2, txnId) {
150
- const file = path3.join(txnDir(moxxyDir2, txnId), "journal.json");
149
+ async function readJournal(moxxyDir, txnId) {
150
+ const file = path3.join(txnDir(moxxyDir, txnId), "journal.json");
151
151
  const raw = await promises.readFile(file, "utf8");
152
152
  return JSON.parse(raw);
153
153
  }
154
- async function listTransactions(moxxyDir2) {
155
- const root = selfUpdateRoot(moxxyDir2);
154
+ async function listTransactions(moxxyDir) {
155
+ const root = selfUpdateRoot(moxxyDir);
156
156
  let ids;
157
157
  try {
158
158
  ids = (await promises.readdir(root, { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
@@ -162,7 +162,7 @@ async function listTransactions(moxxyDir2) {
162
162
  const out = [];
163
163
  for (const id of ids) {
164
164
  try {
165
- out.push(await readJournal(moxxyDir2, id));
165
+ out.push(await readJournal(moxxyDir, id));
166
166
  } catch {
167
167
  }
168
168
  }
@@ -174,13 +174,13 @@ function recordAttempt(journal, attempt) {
174
174
  function failedAttemptCount(journal) {
175
175
  return journal.attempts.filter((a2) => !a2.ok).length;
176
176
  }
177
- async function restoreSnapshot(moxxyDir2, journal) {
177
+ async function restoreSnapshot(moxxyDir, journal) {
178
178
  const { target, existedBefore } = journal;
179
179
  if (!existedBefore) {
180
180
  await promises.rm(target.path, { recursive: true, force: true });
181
181
  return;
182
182
  }
183
- const before = path3.join(txnDir(moxxyDir2, journal.txnId), "before");
183
+ const before = path3.join(txnDir(moxxyDir, journal.txnId), "before");
184
184
  if (target.kind !== "plugin") {
185
185
  await promises.rm(target.path, { recursive: true, force: true });
186
186
  await promises.cp(before, target.path, { recursive: true, filter: snapshotFilter(before) });
@@ -199,11 +199,11 @@ async function restoreSnapshot(moxxyDir2, journal) {
199
199
  await promises.mkdir(target.path, { recursive: true });
200
200
  await promises.cp(before, target.path, { recursive: true, filter: snapshotFilter(before) });
201
201
  }
202
- async function gcTransactions(moxxyDir2, keep) {
203
- const all = await listTransactions(moxxyDir2);
202
+ async function gcTransactions(moxxyDir, keep) {
203
+ const all = await listTransactions(moxxyDir);
204
204
  const terminal = all.filter((j2) => j2.state === "committed" || j2.state === "rolled_back" || j2.state === "escalated");
205
205
  for (const j2 of terminal.slice(keep)) {
206
- await promises.rm(txnDir(moxxyDir2, j2.txnId), { recursive: true, force: true });
206
+ await promises.rm(txnDir(moxxyDir, j2.txnId), { recursive: true, force: true });
207
207
  }
208
208
  }
209
209
  var MAX_FAILED_ATTEMPTS, NAME_SEGMENT_RE, SNAPSHOT_EXCLUDE;
@@ -613,49 +613,49 @@ async function corePreflight(install) {
613
613
  });
614
614
  return { ok: checks.every((c3) => c3.ok), checks };
615
615
  }
616
- function coreTxnRoot(moxxyDir2) {
617
- return path3.join(moxxyDir2, "self-update", "core-txns");
616
+ function coreTxnRoot(moxxyDir) {
617
+ return path3.join(moxxyDir, "self-update", "core-txns");
618
618
  }
619
- function coreTxnDir(moxxyDir2, txnId) {
620
- return path3.join(coreTxnRoot(moxxyDir2), txnId);
619
+ function coreTxnDir(moxxyDir, txnId) {
620
+ return path3.join(coreTxnRoot(moxxyDir), txnId);
621
621
  }
622
- function repoDir(moxxyDir2) {
623
- return path3.join(moxxyDir2, "self-update", "repo");
622
+ function repoDir(moxxyDir) {
623
+ return path3.join(moxxyDir, "self-update", "repo");
624
624
  }
625
- async function writeCoreJournal(moxxyDir2, j2) {
625
+ async function writeCoreJournal(moxxyDir, j2) {
626
626
  j2.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
627
- const file = path3.join(coreTxnDir(moxxyDir2, j2.txnId), "journal.json");
627
+ const file = path3.join(coreTxnDir(moxxyDir, j2.txnId), "journal.json");
628
628
  await writeFileAtomic(file, JSON.stringify(j2, null, 2) + "\n");
629
629
  }
630
- async function readCoreJournal(moxxyDir2, txnId) {
631
- return JSON.parse(await promises.readFile(path3.join(coreTxnDir(moxxyDir2, txnId), "journal.json"), "utf8"));
630
+ async function readCoreJournal(moxxyDir, txnId) {
631
+ return JSON.parse(await promises.readFile(path3.join(coreTxnDir(moxxyDir, txnId), "journal.json"), "utf8"));
632
632
  }
633
- async function listCoreTxns(moxxyDir2) {
633
+ async function listCoreTxns(moxxyDir) {
634
634
  let ids;
635
635
  try {
636
- ids = (await promises.readdir(coreTxnRoot(moxxyDir2), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
636
+ ids = (await promises.readdir(coreTxnRoot(moxxyDir), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
637
637
  } catch {
638
638
  return [];
639
639
  }
640
640
  const out = [];
641
641
  for (const id of ids) {
642
642
  try {
643
- out.push(await readCoreJournal(moxxyDir2, id));
643
+ out.push(await readCoreJournal(moxxyDir, id));
644
644
  } catch {
645
645
  }
646
646
  }
647
647
  return out.sort((a2, b3) => b3.createdAt.localeCompare(a2.createdAt));
648
648
  }
649
- async function countCorruptCoreTxns(moxxyDir2) {
649
+ async function countCorruptCoreTxns(moxxyDir) {
650
650
  let ids;
651
651
  try {
652
- ids = (await promises.readdir(coreTxnRoot(moxxyDir2), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
652
+ ids = (await promises.readdir(coreTxnRoot(moxxyDir), { withFileTypes: true })).filter((e) => e.isDirectory()).map((e) => e.name);
653
653
  } catch {
654
654
  return 0;
655
655
  }
656
656
  let corrupt = 0;
657
657
  for (const id of ids) {
658
- const file = path3.join(coreTxnDir(moxxyDir2, id), "journal.json");
658
+ const file = path3.join(coreTxnDir(moxxyDir, id), "journal.json");
659
659
  let raw;
660
660
  try {
661
661
  raw = await promises.readFile(file, "utf8");
@@ -858,12 +858,12 @@ async function overlayApplied(snapshotDir2, pkgNames) {
858
858
  return false;
859
859
  }
860
860
  }
861
- async function finalizeStagedCoreUpdate(moxxyDir2, install, keepTerminal = 5) {
861
+ async function finalizeStagedCoreUpdate(moxxyDir, install, keepTerminal = 5) {
862
862
  const committed = [];
863
- for (const j2 of await listCoreTxns(moxxyDir2)) {
863
+ for (const j2 of await listCoreTxns(moxxyDir)) {
864
864
  if (j2.state !== "staged_restart")
865
865
  continue;
866
- const snapDir = path3.join(coreTxnDir(moxxyDir2, j2.txnId), "snapshot");
866
+ const snapDir = path3.join(coreTxnDir(moxxyDir, j2.txnId), "snapshot");
867
867
  if (install) {
868
868
  const recon = await reconcileOverlay({
869
869
  install,
@@ -872,31 +872,31 @@ async function finalizeStagedCoreUpdate(moxxyDir2, install, keepTerminal = 5) {
872
872
  }).catch(() => ({ reconciled: false }));
873
873
  if (recon.reconciled) {
874
874
  j2.state = "rolled_back";
875
- await writeCoreJournal(moxxyDir2, j2).catch(() => void 0);
875
+ await writeCoreJournal(moxxyDir, j2).catch(() => void 0);
876
876
  continue;
877
877
  }
878
878
  if (!await overlayApplied(snapDir, j2.packages)) {
879
879
  await restoreOverlay({ install, pkgNames: j2.packages, snapshotDir: snapDir }).catch(() => void 0);
880
880
  j2.state = "rolled_back";
881
- await writeCoreJournal(moxxyDir2, j2).catch(() => void 0);
881
+ await writeCoreJournal(moxxyDir, j2).catch(() => void 0);
882
882
  continue;
883
883
  }
884
884
  }
885
885
  j2.state = "committed";
886
- await writeCoreJournal(moxxyDir2, j2).catch(() => void 0);
886
+ await writeCoreJournal(moxxyDir, j2).catch(() => void 0);
887
887
  committed.push(j2.txnId);
888
888
  }
889
- await gcCoreTxns(moxxyDir2, keepTerminal).catch(() => void 0);
889
+ await gcCoreTxns(moxxyDir, keepTerminal).catch(() => void 0);
890
890
  return committed;
891
891
  }
892
892
  function newCoreTxnId(now = /* @__PURE__ */ new Date()) {
893
893
  return `core-${newTxnId(now)}`;
894
894
  }
895
- async function gcCoreTxns(moxxyDir2, keep) {
896
- const all = await listCoreTxns(moxxyDir2);
895
+ async function gcCoreTxns(moxxyDir, keep) {
896
+ const all = await listCoreTxns(moxxyDir);
897
897
  const terminal = all.filter((j2) => j2.state === "committed" || j2.state === "rolled_back");
898
898
  for (const j2 of terminal.slice(Math.max(0, keep))) {
899
- await promises.rm(coreTxnDir(moxxyDir2, j2.txnId), { recursive: true, force: true }).catch(() => void 0);
899
+ await promises.rm(coreTxnDir(moxxyDir, j2.txnId), { recursive: true, force: true }).catch(() => void 0);
900
900
  }
901
901
  }
902
902
  function safeRepoPath(repo, rel) {
@@ -981,8 +981,8 @@ var init_deps = __esm({
981
981
  PLUGIN_ID = "@moxxy/plugin-self-update";
982
982
  }
983
983
  });
984
- function snapshotDir(moxxyDir2, txnId) {
985
- return path3.join(coreTxnDir(moxxyDir2, txnId), "snapshot");
984
+ function snapshotDir(moxxyDir, txnId) {
985
+ return path3.join(coreTxnDir(moxxyDir, txnId), "snapshot");
986
986
  }
987
987
  function resolveCore(c3) {
988
988
  return resolveCoreInstall(c3.deps, c3.fromUrl);
@@ -1743,7 +1743,7 @@ var init_dist = __esm({
1743
1743
  let appendEvent = null;
1744
1744
  let options = {};
1745
1745
  const deps = {
1746
- moxxyDir: path3.join(os.homedir(), ".moxxy"),
1746
+ moxxyDir: moxxyHome(),
1747
1747
  reload: () => host?.reload() ?? Promise.resolve(),
1748
1748
  unload: (name) => host?.unload(name) ?? Promise.resolve(),
1749
1749
  snapshot: () => snapshotFn ? snapshotFn() : {},
@@ -1820,39 +1820,41 @@ var LOGO_ART_RAW, LOGO_WIDTH, LOGO_LINES, COMPACT_LOGO_ART_RAW, COMPACT_LOGO_WID
1820
1820
  var init_logo_data = __esm({
1821
1821
  "../plugin-cli/dist/logo-data.js"() {
1822
1822
  LOGO_ART_RAW = [
1823
- " -#@@@@",
1824
- " -%@@@@@@",
1825
- " :*%@@+=%@@@@@+%@@@@@@@@@@%*:",
1826
- " +@@@+=%@@@@@++@@@@@@@@@@#+@@@+",
1827
- " @@%=%@@@@@= :---------:*@%=+@@",
1828
- " @@@@*:::: +@@@%=+",
1829
- " @@@@* -@@@@@%-",
1830
- " @@@@* =@@@@@%-",
1831
- " =+++@@@@* ++=@@@@@*",
1832
- " .@@@@%+@@* *@@+%@@@@.",
1833
- " *@@@@@=++ *@@@@+++=",
1834
- " -%@@@@@= *@@@@",
1835
- " -%@@@@@- *@@@@",
1836
- " +=%@@@+ ::::*@@@@",
1837
- " @@+=%@*:---------: =@@@@@%=%@@",
1838
- " +@@@+#@@@@@@@@@@++@@@@@%=+@@@+",
1839
- " :*%@@@@@@@@@@%+@@@@@%=+@@%*:",
1840
- " @@@@@@%-",
1841
- " @@@@#-"
1823
+ " .-=+++=-. .:---.",
1824
+ " -#@@@@@@@@@%*-.:-+*#%@@@@@@@%+.",
1825
+ " =%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@+",
1826
+ " =%@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@%:",
1827
+ ".#@@@@@@@@@%*#%@@@@@@@@@@@@@@@@@@@@@@@@@-",
1828
+ "*@@@@@%=:. .:=+*%@@@@@@@@@@@@@@@@@@@@-",
1829
+ "%@@@@@= .:-==+*##%%@@@@@@@@@",
1830
+ "%@@@@# .*@@@@@:",
1831
+ "%@@@@+ @@@ @@@ +@@@@@-",
1832
+ "#@@@@= @@@ @@@ +@@@@@-",
1833
+ "#@@@@# @@@ @@@ +@@@@@:",
1834
+ "*@@@@@. @@@ @@ #@@@@@.",
1835
+ "=@@@@@%###-:::. :#@@@@@*",
1836
+ " *@@@@@@@%#****+=-------=====+++*%@@@@@@#.",
1837
+ " -#@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@+",
1838
+ " .-=+*##%%@@@@@@@@@@@@@@@@@@@@@@@@+.",
1839
+ " .:-===--*@@@@@@@@@@@%+.",
1840
+ " .+%@@@@@@%=.",
1841
+ " =@@@@+.",
1842
+ " .=+:"
1842
1843
  ];
1843
1844
  LOGO_WIDTH = LOGO_ART_RAW.reduce((m3, l2) => Math.max(m3, l2.length), 0);
1844
1845
  LOGO_LINES = LOGO_ART_RAW.map((l2) => l2.padEnd(LOGO_WIDTH));
1845
1846
  COMPACT_LOGO_ART_RAW = [
1846
- " -%@@@@",
1847
- " :*%@@+=%@@@+%@@@@@@@%*:",
1848
- " @@%=%@@@= :-------:*@%=@@",
1849
- " @@@@* +@@@@%+",
1850
- " =++@@@@* ++=@@@@*",
1851
- " *@@@@=+ *@@@@++=",
1852
- " -%@@@@- *@@@@",
1853
- " @@+=%*:-------: =@@@%=%@@",
1854
- " :*%@@@@@@@%+@@@@%=+@@%*:",
1855
- " @@@@@@%-"
1847
+ " .:-:. ...",
1848
+ " -*@@@@@%+*#%@@@@#-",
1849
+ ":#@@@@%@@@@@@@@@@@@@*.",
1850
+ "%@@*. .:=+**#%%@@@@#",
1851
+ "%@@ @ @ @@@.",
1852
+ "%@% @ @ @@@.",
1853
+ "#@@+-:.. -@@%",
1854
+ ".#@@@%%##*****###%@@%:",
1855
+ " .:-==+***#@@@@@@#-",
1856
+ " .+@@#:",
1857
+ " .:"
1856
1858
  ];
1857
1859
  COMPACT_LOGO_WIDTH = COMPACT_LOGO_ART_RAW.reduce((max, line) => Math.max(max, line.length), 0);
1858
1860
  COMPACT_LOGO_LINES = COMPACT_LOGO_ART_RAW.map((line) => line.padEnd(COMPACT_LOGO_WIDTH));
@@ -2939,6 +2941,16 @@ var init_subagents = __esm({
2939
2941
  init_registry();
2940
2942
  }
2941
2943
  });
2944
+
2945
+ // ../core/dist/turn-model.js
2946
+ function resolveTurnModel(session, provider, named) {
2947
+ const configured = session.defaultModels ? session.defaultModels[provider.name] : void 0;
2948
+ return named ?? session.lastResolvedModel ?? configured ?? provider.models[0]?.id;
2949
+ }
2950
+ var init_turn_model = __esm({
2951
+ "../core/dist/turn-model.js"() {
2952
+ }
2953
+ });
2942
2954
  async function* runTurn(session, prompt, opts = {}) {
2943
2955
  const turnId = opts.turnId ?? session.startTurn().turnId;
2944
2956
  const queue = [];
@@ -2974,7 +2986,7 @@ async function* runTurn(session, prompt, opts = {}) {
2974
2986
  let model;
2975
2987
  try {
2976
2988
  provider = session.providers.getActive();
2977
- const resolvedModel = opts.model ?? session.lastResolvedModel ?? provider.models[0]?.id;
2989
+ const resolvedModel = resolveTurnModel(session, provider, opts.model);
2978
2990
  if (!resolvedModel) {
2979
2991
  throw new Error(`Active provider '${provider.name}' has no models configured`);
2980
2992
  }
@@ -3015,6 +3027,7 @@ async function* runTurn(session, prompt, opts = {}) {
3015
3027
  cacheStrategy: session.cacheStrategies.getActive(),
3016
3028
  ...session.elisionSettings ? { elision: session.elisionSettings } : {},
3017
3029
  ...session.lazyTools !== void 0 ? { lazyTools: session.lazyTools } : {},
3030
+ ...session.unfinishedStepCheck !== void 0 ? { unfinishedStepCheck: session.unfinishedStepCheck } : {},
3018
3031
  // Reasoning preference (effort) — honored only by providers/models that
3019
3032
  // advertise `supportsReasoning` (gated in collectProviderStream).
3020
3033
  ...session.reasoning ? { reasoning: session.reasoning } : {},
@@ -3093,6 +3106,7 @@ async function collectTurn(session, prompt, opts = {}) {
3093
3106
  var init_run_turn = __esm({
3094
3107
  "../core/dist/run-turn.js"() {
3095
3108
  init_subagents();
3109
+ init_turn_model();
3096
3110
  }
3097
3111
  });
3098
3112
 
@@ -3324,7 +3338,7 @@ function toposortPluginManifests(manifests) {
3324
3338
  const order = [];
3325
3339
  const visited = /* @__PURE__ */ new Set();
3326
3340
  const onStack = /* @__PURE__ */ new Set();
3327
- const path77 = [];
3341
+ const path73 = [];
3328
3342
  const visitRoot = (root) => {
3329
3343
  if (visited.has(root))
3330
3344
  return;
@@ -3333,7 +3347,7 @@ function toposortPluginManifests(manifests) {
3333
3347
  return;
3334
3348
  const stack = [{ name: root, deps: pluginDeps(rootManifest.requirements), next: 0 }];
3335
3349
  onStack.add(root);
3336
- path77.push(root);
3350
+ path73.push(root);
3337
3351
  while (stack.length > 0) {
3338
3352
  const frame = stack[stack.length - 1];
3339
3353
  if (!frame)
@@ -3345,20 +3359,20 @@ function toposortPluginManifests(manifests) {
3345
3359
  if (visited.has(dep))
3346
3360
  continue;
3347
3361
  if (onStack.has(dep)) {
3348
- const startIdx = path77.indexOf(dep);
3349
- throw new PluginCycleError(path77.slice(startIdx).concat(dep));
3362
+ const startIdx = path73.indexOf(dep);
3363
+ throw new PluginCycleError(path73.slice(startIdx).concat(dep));
3350
3364
  }
3351
3365
  const depManifest = byPackage.get(dep);
3352
3366
  if (!depManifest)
3353
3367
  continue;
3354
3368
  onStack.add(dep);
3355
- path77.push(dep);
3369
+ path73.push(dep);
3356
3370
  stack.push({ name: dep, deps: pluginDeps(depManifest.requirements), next: 0 });
3357
3371
  continue;
3358
3372
  }
3359
3373
  const done = stack.pop();
3360
3374
  onStack.delete(done.name);
3361
- path77.pop();
3375
+ path73.pop();
3362
3376
  visited.add(done.name);
3363
3377
  const manifest = byPackage.get(done.name);
3364
3378
  if (manifest)
@@ -5150,8 +5164,8 @@ var init_skills = __esm({
5150
5164
  });
5151
5165
  function formatZodIssues(error) {
5152
5166
  return error.issues.map((iss) => {
5153
- const path77 = iss.path.length ? iss.path.join(".") : "(root)";
5154
- return `${path77}: ${iss.message}`;
5167
+ const path73 = iss.path.length ? iss.path.join(".") : "(root)";
5168
+ return `${path73}: ${iss.message}`;
5155
5169
  }).join("; ");
5156
5170
  }
5157
5171
  function emptyLog() {
@@ -6958,18 +6972,18 @@ var init_engine = __esm({
6958
6972
  // without serialization two overlapping calls both read the same snapshot,
6959
6973
  // each append one rule, and the second write clobbers the first's rule.
6960
6974
  mutex = createMutex();
6961
- constructor(policy = emptyPolicy, policyPath2 = null) {
6975
+ constructor(policy = emptyPolicy, policyPath = null) {
6962
6976
  this.policy = policy;
6963
- this.policyPath = policyPath2;
6977
+ this.policyPath = policyPath;
6964
6978
  }
6965
- static async load(policyPath2) {
6979
+ static async load(policyPath) {
6966
6980
  try {
6967
- const raw = await promises.readFile(policyPath2, "utf8");
6981
+ const raw = await promises.readFile(policyPath, "utf8");
6968
6982
  const parsed = permissionPolicySchema.parse(JSON.parse(raw));
6969
- return new _PermissionEngine(parsed, policyPath2);
6983
+ return new _PermissionEngine(parsed, policyPath);
6970
6984
  } catch (err) {
6971
6985
  if (isNodeError(err) && err.code === "ENOENT") {
6972
- return new _PermissionEngine(emptyPolicy, policyPath2);
6986
+ return new _PermissionEngine(emptyPolicy, policyPath);
6973
6987
  }
6974
6988
  throw err;
6975
6989
  }
@@ -7184,6 +7198,7 @@ var init_session = __esm({
7184
7198
  "../core/dist/session.js"() {
7185
7199
  init_factory();
7186
7200
  init_run_turn();
7201
+ init_turn_model();
7187
7202
  init_log();
7188
7203
  init_lifecycle();
7189
7204
  init_host();
@@ -7293,6 +7308,8 @@ var init_session = __esm({
7293
7308
  elisionSettings = null;
7294
7309
  /** Lazy tool loading, from `config.context.lazyTools`. Unset = automatic (on for a long tool list). */
7295
7310
  lazyTools = void 0;
7311
+ /** The end-of-turn reminder about a step that did not get done, from `config.context.unfinishedStepCheck`. Unset = on. */
7312
+ unfinishedStepCheck = void 0;
7296
7313
  /**
7297
7314
  * Reasoning/thinking preference, from `config.context.reasoning`. Forwarded
7298
7315
  * to each turn's ModeContext and on to the provider, which honors it only
@@ -7312,6 +7329,8 @@ var init_session = __esm({
7312
7329
  * Last-writer-wins for concurrent turns; null until the first turn runs.
7313
7330
  */
7314
7331
  lastResolvedModel = null;
7332
+ /** The model each provider is set to run when a turn names none, from `plugins.provider.items.<name>.model`. */
7333
+ defaultModels = {};
7315
7334
  /**
7316
7335
  * Live runtime capabilities the host installs on a local Session (see
7317
7336
  * SessionLike). A RemoteSession leaves them undefined. Declared here — rather
@@ -7620,6 +7639,8 @@ var init_session = __esm({
7620
7639
  } catch {
7621
7640
  }
7622
7641
  }
7642
+ const declared = this.providers.list().find((p3) => p3.name === active2);
7643
+ const defaultModel = active2 ? resolveTurnModel(this, { name: active2, models: activeProviderModels ?? (declared ? declared.models : []) }) : void 0;
7623
7644
  const ready = this.readyProviders;
7624
7645
  return {
7625
7646
  sessionId: this.id,
@@ -7670,7 +7691,8 @@ var init_session = __esm({
7670
7691
  activeSynthesizer: this.synthesizers.getActiveName(),
7671
7692
  autoApprove: this.autoApprove,
7672
7693
  reasoningEffort: reasoningEffortOf(this.reasoning),
7673
- fast: this.fast
7694
+ fast: this.fast,
7695
+ ...defaultModel !== void 0 ? { defaultModel } : {}
7674
7696
  };
7675
7697
  }
7676
7698
  };
@@ -8351,7 +8373,7 @@ function deriveTriggers(name) {
8351
8373
  return [...out];
8352
8374
  }
8353
8375
  function defaultUserSkillsDir() {
8354
- return path3.join(os.homedir(), ".moxxy", "skills");
8376
+ return moxxyPath("skills");
8355
8377
  }
8356
8378
  function defaultProjectSkillsDir(cwd2) {
8357
8379
  return path3.join(cwd2, ".moxxy", "skills");
@@ -8403,7 +8425,7 @@ The body is the instructions for future invocations. Keep it under 30 lines. Num
8403
8425
  });
8404
8426
  async function synthesizeSkill(session, intent, scope2, opts = {}, turnId) {
8405
8427
  const provider = session.providers.getActive();
8406
- const model = opts.model ?? session.lastResolvedModel ?? provider.models[0]?.id ?? "default";
8428
+ const model = resolveTurnModel(session, provider, opts.model) ?? "default";
8407
8429
  const draft = await draftSkill(provider, model, intent, session.signal);
8408
8430
  const baseDir = scope2 === "project" ? opts.projectDir ?? defaultProjectSkillsDir(session.cwd) : opts.userDir ?? defaultUserSkillsDir();
8409
8431
  await promises.mkdir(baseDir, { recursive: true });
@@ -8634,6 +8656,7 @@ var init_synthesize = __esm({
8634
8656
  "../core/dist/skills/synthesize.js"() {
8635
8657
  init_loader();
8636
8658
  init_synthesize_draft();
8659
+ init_turn_model();
8637
8660
  MAX_AUDIT_LINES = 2e3;
8638
8661
  }
8639
8662
  });
@@ -13070,6 +13093,7 @@ __export(dist_exports, {
13070
13093
  readSessionEventPage: () => readEventPage,
13071
13094
  readSessionIndex: () => readIndex,
13072
13095
  resetAuditHeadForTests: () => resetAuditHeadForTests,
13096
+ resolveTurnModel: () => resolveTurnModel,
13073
13097
  restoreSessionEvents: () => restoreEvents,
13074
13098
  runTurn: () => runTurn,
13075
13099
  seedSessionMeta: () => seedSessionMeta,
@@ -13094,6 +13118,7 @@ var init_dist2 = __esm({
13094
13118
  init_scope();
13095
13119
  init_workflow_lease();
13096
13120
  init_run_turn();
13121
+ init_turn_model();
13097
13122
  init_setup_agent();
13098
13123
  init_subagents();
13099
13124
  init_usage_stats();
@@ -13471,6 +13496,11 @@ var init_schema = __esm({
13471
13496
  elision: elisionConfigSchema.optional(),
13472
13497
  /** Lazy tool loading: send only core + loaded tool schemas, index the rest. Unset = on above 200 tools. */
13473
13498
  lazyTools: z.boolean().optional(),
13499
+ /**
13500
+ * The reminder at the end of a turn that ended on a step that did not get
13501
+ * done: take another way, or say what stops you. Asked once a turn. Unset = on.
13502
+ */
13503
+ unfinishedStepCheck: z.boolean().optional(),
13474
13504
  /**
13475
13505
  * Reasoning/thinking preview. `true` enables it at the model's default depth;
13476
13506
  * `{ effort }` sets the depth. Honored only by providers/models that support
@@ -13781,17 +13811,17 @@ var require_visit = __commonJS({
13781
13811
  visit.BREAK = BREAK;
13782
13812
  visit.SKIP = SKIP;
13783
13813
  visit.REMOVE = REMOVE;
13784
- function visit_(key, node, visitor, path77) {
13785
- const ctrl = callVisitor(key, node, visitor, path77);
13814
+ function visit_(key, node, visitor, path73) {
13815
+ const ctrl = callVisitor(key, node, visitor, path73);
13786
13816
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
13787
- replaceNode(key, path77, ctrl);
13788
- return visit_(key, ctrl, visitor, path77);
13817
+ replaceNode(key, path73, ctrl);
13818
+ return visit_(key, ctrl, visitor, path73);
13789
13819
  }
13790
13820
  if (typeof ctrl !== "symbol") {
13791
13821
  if (identity.isCollection(node)) {
13792
- path77 = Object.freeze(path77.concat(node));
13822
+ path73 = Object.freeze(path73.concat(node));
13793
13823
  for (let i2 = 0; i2 < node.items.length; ++i2) {
13794
- const ci = visit_(i2, node.items[i2], visitor, path77);
13824
+ const ci = visit_(i2, node.items[i2], visitor, path73);
13795
13825
  if (typeof ci === "number")
13796
13826
  i2 = ci - 1;
13797
13827
  else if (ci === BREAK)
@@ -13802,13 +13832,13 @@ var require_visit = __commonJS({
13802
13832
  }
13803
13833
  }
13804
13834
  } else if (identity.isPair(node)) {
13805
- path77 = Object.freeze(path77.concat(node));
13806
- const ck = visit_("key", node.key, visitor, path77);
13835
+ path73 = Object.freeze(path73.concat(node));
13836
+ const ck = visit_("key", node.key, visitor, path73);
13807
13837
  if (ck === BREAK)
13808
13838
  return BREAK;
13809
13839
  else if (ck === REMOVE)
13810
13840
  node.key = null;
13811
- const cv = visit_("value", node.value, visitor, path77);
13841
+ const cv = visit_("value", node.value, visitor, path73);
13812
13842
  if (cv === BREAK)
13813
13843
  return BREAK;
13814
13844
  else if (cv === REMOVE)
@@ -13829,17 +13859,17 @@ var require_visit = __commonJS({
13829
13859
  visitAsync.BREAK = BREAK;
13830
13860
  visitAsync.SKIP = SKIP;
13831
13861
  visitAsync.REMOVE = REMOVE;
13832
- async function visitAsync_(key, node, visitor, path77) {
13833
- const ctrl = await callVisitor(key, node, visitor, path77);
13862
+ async function visitAsync_(key, node, visitor, path73) {
13863
+ const ctrl = await callVisitor(key, node, visitor, path73);
13834
13864
  if (identity.isNode(ctrl) || identity.isPair(ctrl)) {
13835
- replaceNode(key, path77, ctrl);
13836
- return visitAsync_(key, ctrl, visitor, path77);
13865
+ replaceNode(key, path73, ctrl);
13866
+ return visitAsync_(key, ctrl, visitor, path73);
13837
13867
  }
13838
13868
  if (typeof ctrl !== "symbol") {
13839
13869
  if (identity.isCollection(node)) {
13840
- path77 = Object.freeze(path77.concat(node));
13870
+ path73 = Object.freeze(path73.concat(node));
13841
13871
  for (let i2 = 0; i2 < node.items.length; ++i2) {
13842
- const ci = await visitAsync_(i2, node.items[i2], visitor, path77);
13872
+ const ci = await visitAsync_(i2, node.items[i2], visitor, path73);
13843
13873
  if (typeof ci === "number")
13844
13874
  i2 = ci - 1;
13845
13875
  else if (ci === BREAK)
@@ -13850,13 +13880,13 @@ var require_visit = __commonJS({
13850
13880
  }
13851
13881
  }
13852
13882
  } else if (identity.isPair(node)) {
13853
- path77 = Object.freeze(path77.concat(node));
13854
- const ck = await visitAsync_("key", node.key, visitor, path77);
13883
+ path73 = Object.freeze(path73.concat(node));
13884
+ const ck = await visitAsync_("key", node.key, visitor, path73);
13855
13885
  if (ck === BREAK)
13856
13886
  return BREAK;
13857
13887
  else if (ck === REMOVE)
13858
13888
  node.key = null;
13859
- const cv = await visitAsync_("value", node.value, visitor, path77);
13889
+ const cv = await visitAsync_("value", node.value, visitor, path73);
13860
13890
  if (cv === BREAK)
13861
13891
  return BREAK;
13862
13892
  else if (cv === REMOVE)
@@ -13883,23 +13913,23 @@ var require_visit = __commonJS({
13883
13913
  }
13884
13914
  return visitor;
13885
13915
  }
13886
- function callVisitor(key, node, visitor, path77) {
13916
+ function callVisitor(key, node, visitor, path73) {
13887
13917
  if (typeof visitor === "function")
13888
- return visitor(key, node, path77);
13918
+ return visitor(key, node, path73);
13889
13919
  if (identity.isMap(node))
13890
- return visitor.Map?.(key, node, path77);
13920
+ return visitor.Map?.(key, node, path73);
13891
13921
  if (identity.isSeq(node))
13892
- return visitor.Seq?.(key, node, path77);
13922
+ return visitor.Seq?.(key, node, path73);
13893
13923
  if (identity.isPair(node))
13894
- return visitor.Pair?.(key, node, path77);
13924
+ return visitor.Pair?.(key, node, path73);
13895
13925
  if (identity.isScalar(node))
13896
- return visitor.Scalar?.(key, node, path77);
13926
+ return visitor.Scalar?.(key, node, path73);
13897
13927
  if (identity.isAlias(node))
13898
- return visitor.Alias?.(key, node, path77);
13928
+ return visitor.Alias?.(key, node, path73);
13899
13929
  return void 0;
13900
13930
  }
13901
- function replaceNode(key, path77, node) {
13902
- const parent = path77[path77.length - 1];
13931
+ function replaceNode(key, path73, node) {
13932
+ const parent = path73[path73.length - 1];
13903
13933
  if (identity.isCollection(parent)) {
13904
13934
  parent.items[key] = node;
13905
13935
  } else if (identity.isPair(parent)) {
@@ -14502,10 +14532,10 @@ var require_Collection = __commonJS({
14502
14532
  var createNode2 = require_createNode();
14503
14533
  var identity = require_identity();
14504
14534
  var Node = require_Node();
14505
- function collectionFromPath(schema, path77, value2) {
14535
+ function collectionFromPath(schema, path73, value2) {
14506
14536
  let v = value2;
14507
- for (let i2 = path77.length - 1; i2 >= 0; --i2) {
14508
- const k = path77[i2];
14537
+ for (let i2 = path73.length - 1; i2 >= 0; --i2) {
14538
+ const k = path73[i2];
14509
14539
  if (typeof k === "number" && Number.isInteger(k) && k >= 0) {
14510
14540
  const a2 = [];
14511
14541
  a2[k] = v;
@@ -14524,7 +14554,7 @@ var require_Collection = __commonJS({
14524
14554
  sourceObjects: /* @__PURE__ */ new Map()
14525
14555
  });
14526
14556
  }
14527
- var isEmptyPath = (path77) => path77 == null || typeof path77 === "object" && !!path77[Symbol.iterator]().next().done;
14557
+ var isEmptyPath = (path73) => path73 == null || typeof path73 === "object" && !!path73[Symbol.iterator]().next().done;
14528
14558
  var Collection = class extends Node.NodeBase {
14529
14559
  constructor(type, schema) {
14530
14560
  super(type);
@@ -14554,11 +14584,11 @@ var require_Collection = __commonJS({
14554
14584
  * be a Pair instance or a `{ key, value }` object, which may not have a key
14555
14585
  * that already exists in the map.
14556
14586
  */
14557
- addIn(path77, value2) {
14558
- if (isEmptyPath(path77))
14587
+ addIn(path73, value2) {
14588
+ if (isEmptyPath(path73))
14559
14589
  this.add(value2);
14560
14590
  else {
14561
- const [key, ...rest] = path77;
14591
+ const [key, ...rest] = path73;
14562
14592
  const node = this.get(key, true);
14563
14593
  if (identity.isCollection(node))
14564
14594
  node.addIn(rest, value2);
@@ -14572,8 +14602,8 @@ var require_Collection = __commonJS({
14572
14602
  * Removes a value from the collection.
14573
14603
  * @returns `true` if the item was found and removed.
14574
14604
  */
14575
- deleteIn(path77) {
14576
- const [key, ...rest] = path77;
14605
+ deleteIn(path73) {
14606
+ const [key, ...rest] = path73;
14577
14607
  if (rest.length === 0)
14578
14608
  return this.delete(key);
14579
14609
  const node = this.get(key, true);
@@ -14587,8 +14617,8 @@ var require_Collection = __commonJS({
14587
14617
  * scalar values from their surrounding node; to disable set `keepScalar` to
14588
14618
  * `true` (collections are always returned intact).
14589
14619
  */
14590
- getIn(path77, keepScalar) {
14591
- const [key, ...rest] = path77;
14620
+ getIn(path73, keepScalar) {
14621
+ const [key, ...rest] = path73;
14592
14622
  const node = this.get(key, true);
14593
14623
  if (rest.length === 0)
14594
14624
  return !keepScalar && identity.isScalar(node) ? node.value : node;
@@ -14606,8 +14636,8 @@ var require_Collection = __commonJS({
14606
14636
  /**
14607
14637
  * Checks if the collection includes a value with the key `key`.
14608
14638
  */
14609
- hasIn(path77) {
14610
- const [key, ...rest] = path77;
14639
+ hasIn(path73) {
14640
+ const [key, ...rest] = path73;
14611
14641
  if (rest.length === 0)
14612
14642
  return this.has(key);
14613
14643
  const node = this.get(key, true);
@@ -14617,8 +14647,8 @@ var require_Collection = __commonJS({
14617
14647
  * Sets a value in this collection. For `!!set`, `value` needs to be a
14618
14648
  * boolean to add/remove the item from the set.
14619
14649
  */
14620
- setIn(path77, value2) {
14621
- const [key, ...rest] = path77;
14650
+ setIn(path73, value2) {
14651
+ const [key, ...rest] = path73;
14622
14652
  if (rest.length === 0) {
14623
14653
  this.set(key, value2);
14624
14654
  } else {
@@ -17098,9 +17128,9 @@ var require_Document = __commonJS({
17098
17128
  this.contents.add(value2);
17099
17129
  }
17100
17130
  /** Adds a value to the document. */
17101
- addIn(path77, value2) {
17131
+ addIn(path73, value2) {
17102
17132
  if (assertCollection(this.contents))
17103
- this.contents.addIn(path77, value2);
17133
+ this.contents.addIn(path73, value2);
17104
17134
  }
17105
17135
  /**
17106
17136
  * Create a new `Alias` node, ensuring that the target `node` has the required anchor.
@@ -17175,14 +17205,14 @@ var require_Document = __commonJS({
17175
17205
  * Removes a value from the document.
17176
17206
  * @returns `true` if the item was found and removed.
17177
17207
  */
17178
- deleteIn(path77) {
17179
- if (Collection.isEmptyPath(path77)) {
17208
+ deleteIn(path73) {
17209
+ if (Collection.isEmptyPath(path73)) {
17180
17210
  if (this.contents == null)
17181
17211
  return false;
17182
17212
  this.contents = null;
17183
17213
  return true;
17184
17214
  }
17185
- return assertCollection(this.contents) ? this.contents.deleteIn(path77) : false;
17215
+ return assertCollection(this.contents) ? this.contents.deleteIn(path73) : false;
17186
17216
  }
17187
17217
  /**
17188
17218
  * Returns item at `key`, or `undefined` if not found. By default unwraps
@@ -17197,10 +17227,10 @@ var require_Document = __commonJS({
17197
17227
  * scalar values from their surrounding node; to disable set `keepScalar` to
17198
17228
  * `true` (collections are always returned intact).
17199
17229
  */
17200
- getIn(path77, keepScalar) {
17201
- if (Collection.isEmptyPath(path77))
17230
+ getIn(path73, keepScalar) {
17231
+ if (Collection.isEmptyPath(path73))
17202
17232
  return !keepScalar && identity.isScalar(this.contents) ? this.contents.value : this.contents;
17203
- return identity.isCollection(this.contents) ? this.contents.getIn(path77, keepScalar) : void 0;
17233
+ return identity.isCollection(this.contents) ? this.contents.getIn(path73, keepScalar) : void 0;
17204
17234
  }
17205
17235
  /**
17206
17236
  * Checks if the document includes a value with the key `key`.
@@ -17211,10 +17241,10 @@ var require_Document = __commonJS({
17211
17241
  /**
17212
17242
  * Checks if the document includes a value at `path`.
17213
17243
  */
17214
- hasIn(path77) {
17215
- if (Collection.isEmptyPath(path77))
17244
+ hasIn(path73) {
17245
+ if (Collection.isEmptyPath(path73))
17216
17246
  return this.contents !== void 0;
17217
- return identity.isCollection(this.contents) ? this.contents.hasIn(path77) : false;
17247
+ return identity.isCollection(this.contents) ? this.contents.hasIn(path73) : false;
17218
17248
  }
17219
17249
  /**
17220
17250
  * Sets a value in this document. For `!!set`, `value` needs to be a
@@ -17231,13 +17261,13 @@ var require_Document = __commonJS({
17231
17261
  * Sets a value in this document. For `!!set`, `value` needs to be a
17232
17262
  * boolean to add/remove the item from the set.
17233
17263
  */
17234
- setIn(path77, value2) {
17235
- if (Collection.isEmptyPath(path77)) {
17264
+ setIn(path73, value2) {
17265
+ if (Collection.isEmptyPath(path73)) {
17236
17266
  this.contents = value2;
17237
17267
  } else if (this.contents == null) {
17238
- this.contents = Collection.collectionFromPath(this.schema, Array.from(path77), value2);
17268
+ this.contents = Collection.collectionFromPath(this.schema, Array.from(path73), value2);
17239
17269
  } else if (assertCollection(this.contents)) {
17240
- this.contents.setIn(path77, value2);
17270
+ this.contents.setIn(path73, value2);
17241
17271
  }
17242
17272
  }
17243
17273
  /**
@@ -19178,9 +19208,9 @@ var require_cst_visit = __commonJS({
19178
19208
  visit.BREAK = BREAK;
19179
19209
  visit.SKIP = SKIP;
19180
19210
  visit.REMOVE = REMOVE;
19181
- visit.itemAtPath = (cst, path77) => {
19211
+ visit.itemAtPath = (cst, path73) => {
19182
19212
  let item = cst;
19183
- for (const [field, index] of path77) {
19213
+ for (const [field, index] of path73) {
19184
19214
  const tok = item?.[field];
19185
19215
  if (tok && "items" in tok) {
19186
19216
  item = tok.items[index];
@@ -19189,23 +19219,23 @@ var require_cst_visit = __commonJS({
19189
19219
  }
19190
19220
  return item;
19191
19221
  };
19192
- visit.parentCollection = (cst, path77) => {
19193
- const parent = visit.itemAtPath(cst, path77.slice(0, -1));
19194
- const field = path77[path77.length - 1][0];
19222
+ visit.parentCollection = (cst, path73) => {
19223
+ const parent = visit.itemAtPath(cst, path73.slice(0, -1));
19224
+ const field = path73[path73.length - 1][0];
19195
19225
  const coll = parent?.[field];
19196
19226
  if (coll && "items" in coll)
19197
19227
  return coll;
19198
19228
  throw new Error("Parent collection not found");
19199
19229
  };
19200
- function _visit(path77, item, visitor) {
19201
- let ctrl = visitor(item, path77);
19230
+ function _visit(path73, item, visitor) {
19231
+ let ctrl = visitor(item, path73);
19202
19232
  if (typeof ctrl === "symbol")
19203
19233
  return ctrl;
19204
19234
  for (const field of ["key", "value"]) {
19205
19235
  const token = item[field];
19206
19236
  if (token && "items" in token) {
19207
19237
  for (let i2 = 0; i2 < token.items.length; ++i2) {
19208
- const ci = _visit(Object.freeze(path77.concat([[field, i2]])), token.items[i2], visitor);
19238
+ const ci = _visit(Object.freeze(path73.concat([[field, i2]])), token.items[i2], visitor);
19209
19239
  if (typeof ci === "number")
19210
19240
  i2 = ci - 1;
19211
19241
  else if (ci === BREAK)
@@ -19216,10 +19246,10 @@ var require_cst_visit = __commonJS({
19216
19246
  }
19217
19247
  }
19218
19248
  if (typeof ctrl === "function" && field === "key")
19219
- ctrl = ctrl(item, path77);
19249
+ ctrl = ctrl(item, path73);
19220
19250
  }
19221
19251
  }
19222
- return typeof ctrl === "function" ? ctrl(item, path77) : ctrl;
19252
+ return typeof ctrl === "function" ? ctrl(item, path73) : ctrl;
19223
19253
  }
19224
19254
  exports.visit = visit;
19225
19255
  }
@@ -21605,10 +21635,10 @@ async function removeProviderItem(providerName2, opts = {}) {
21605
21635
  const configPath = opts.configPath ?? defaultUserConfigPath();
21606
21636
  return configMutex.run(async () => {
21607
21637
  const doc = await readUserConfigDoc(configPath);
21608
- const path77 = ["plugins", "provider", "items", providerName2];
21609
- if (!doc.hasIn(path77))
21638
+ const path73 = ["plugins", "provider", "items", providerName2];
21639
+ if (!doc.hasIn(path73))
21610
21640
  return false;
21611
- doc.deleteIn(path77);
21641
+ doc.deleteIn(path73);
21612
21642
  await writeUserConfigDoc(configPath, doc);
21613
21643
  return true;
21614
21644
  });
@@ -21649,6 +21679,42 @@ async function loadActiveProvider(opts = {}) {
21649
21679
  const provider = doc.getIn(["plugins", "provider", "default"]);
21650
21680
  return typeof provider === "string" ? provider : null;
21651
21681
  }
21682
+ function storedEffort(reasoning) {
21683
+ if (reasoning === true)
21684
+ return "default";
21685
+ if (!reasoning || typeof reasoning !== "object")
21686
+ return "off";
21687
+ const effort = reasoning.effort;
21688
+ return typeof effort === "string" && MODEL_DEFAULT_EFFORTS.includes(effort) ? effort : "default";
21689
+ }
21690
+ async function loadModelDefaults(opts = {}) {
21691
+ const doc = await readUserConfigDoc(opts.configPath ?? defaultUserConfigPath());
21692
+ const provider = doc.getIn(["plugins", "provider", "default"]);
21693
+ const model = typeof provider === "string" ? doc.getIn(["plugins", "provider", "items", provider, "model"]) : void 0;
21694
+ const context = readRawEntry(doc, ["context"]);
21695
+ return {
21696
+ provider: typeof provider === "string" ? provider : null,
21697
+ model: typeof model === "string" ? model : null,
21698
+ effort: storedEffort(context.reasoning),
21699
+ fast: context.fast === true
21700
+ };
21701
+ }
21702
+ async function setModelDefaults(change, opts = {}) {
21703
+ const configPath = opts.configPath ?? defaultUserConfigPath();
21704
+ await configMutex.run(async () => {
21705
+ const doc = await readUserConfigDoc(configPath);
21706
+ if (change.model) {
21707
+ doc.setIn(["plugins", "provider", "default"], change.model.provider);
21708
+ doc.setIn(["plugins", "provider", "items", change.model.provider, "model"], change.model.model);
21709
+ }
21710
+ if (change.effort !== void 0) {
21711
+ doc.setIn(["context", "reasoning"], change.effort === "off" ? false : { effort: change.effort });
21712
+ }
21713
+ if (change.fast !== void 0)
21714
+ doc.setIn(["context", "fast"], change.fast);
21715
+ await writeUserConfigDoc(configPath, doc);
21716
+ });
21717
+ }
21652
21718
  async function loadDisabledProviders(opts = {}) {
21653
21719
  const doc = await readUserConfigDoc(opts.configPath ?? defaultUserConfigPath());
21654
21720
  const items = doc.getIn(["plugins", "provider", "items"]);
@@ -21694,28 +21760,29 @@ async function readPackagesMap(configPath) {
21694
21760
  }
21695
21761
  return out;
21696
21762
  }
21697
- function readRawEntry(doc, path77) {
21698
- const node = doc.getIn(path77, false);
21763
+ function readRawEntry(doc, path73) {
21764
+ const node = doc.getIn(path73, false);
21699
21765
  if (!(0, import_yaml.isMap)(node))
21700
21766
  return {};
21701
21767
  const raw = node.toJSON();
21702
21768
  return typeof raw === "object" && raw !== null && !Array.isArray(raw) ? raw : {};
21703
21769
  }
21704
- function pruneEmpty(doc, path77) {
21705
- const node = doc.getIn(path77);
21770
+ function pruneEmpty(doc, path73) {
21771
+ const node = doc.getIn(path73);
21706
21772
  if ((0, import_yaml.isMap)(node) && node.items.length === 0)
21707
- doc.deleteIn(path77);
21773
+ doc.deleteIn(path73);
21708
21774
  }
21709
21775
  function isNotFound(err) {
21710
21776
  return typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT";
21711
21777
  }
21712
- var import_yaml, configMutex;
21778
+ var import_yaml, configMutex, MODEL_DEFAULT_EFFORTS;
21713
21779
  var init_user_config = __esm({
21714
21780
  "../config/dist/user-config.js"() {
21715
21781
  import_yaml = __toESM(require_dist());
21716
21782
  init_plugins_tree_schema();
21717
21783
  init_plugin_settings_schema();
21718
21784
  configMutex = createMutex();
21785
+ MODEL_DEFAULT_EFFORTS = ["low", "medium", "high", "xhigh"];
21719
21786
  }
21720
21787
  });
21721
21788
  function verifyPolicyBundle(bytes, signatureB64, publicKeyPem, expectedId) {
@@ -21771,7 +21838,7 @@ async function loadPolicyBundles(refs, opts = {}) {
21771
21838
  const sources = [];
21772
21839
  if (refs.length === 0)
21773
21840
  return { allow, deny, sources };
21774
- const cacheDir = opts.cacheDir ?? path3.join(os.homedir(), ".moxxy", "policy");
21841
+ const cacheDir = opts.cacheDir ?? moxxyPath("policy");
21775
21842
  await promises.mkdir(cacheDir, { recursive: true, mode: 448 }).catch(() => void 0);
21776
21843
  for (const ref of refs) {
21777
21844
  const cachePath = cacheFileFor(cacheDir, ref.url);
@@ -21888,6 +21955,7 @@ __export(dist_exports2, {
21888
21955
  loadConfig: () => loadConfig,
21889
21956
  loadDisabledPackageNames: () => loadDisabledPackageNames,
21890
21957
  loadDisabledProviders: () => loadDisabledProviders,
21958
+ loadModelDefaults: () => loadModelDefaults,
21891
21959
  loadPolicyBundles: () => loadPolicyBundles,
21892
21960
  loadProviderItems: () => loadProviderItems,
21893
21961
  lockedKeysOf: () => lockedKeysOf,
@@ -21906,6 +21974,7 @@ __export(dist_exports2, {
21906
21974
  setCategoryDefault: () => setCategoryDefault,
21907
21975
  setCategoryItemConfig: () => setCategoryItemConfig,
21908
21976
  setConfigValue: () => setConfigValue,
21977
+ setModelDefaults: () => setModelDefaults,
21909
21978
  setPluginEnabled: () => setPluginEnabled,
21910
21979
  setProviderEnabled: () => setProviderEnabled,
21911
21980
  setProviderItemConfig: () => setProviderItemConfig,
@@ -22896,9 +22965,9 @@ function setupFieldVaultKey(packageName, field) {
22896
22965
  return `${pkg}_${field.key}`.replace(/([a-z])([A-Z])/g, "$1_$2").toUpperCase();
22897
22966
  }
22898
22967
  async function applySetupValues(opts) {
22899
- const writeConfig = opts.writeConfig ?? (async (path77, value2) => {
22968
+ const writeConfig = opts.writeConfig ?? (async (path73, value2) => {
22900
22969
  const { setConfigValue: setConfigValue2 } = await Promise.resolve().then(() => (init_dist3(), dist_exports2));
22901
- await setConfigValue2({ scope: "user", cwd: opts.cwd, path: path77, value: value2 });
22970
+ await setConfigValue2({ scope: "user", cwd: opts.cwd, path: path73, value: value2 });
22902
22971
  });
22903
22972
  const missing = [];
22904
22973
  for (const field of opts.setup.fields) {
@@ -24264,6 +24333,18 @@ var init_dist6 = __esm({
24264
24333
  }
24265
24334
  });
24266
24335
 
24336
+ // src/setup/default-models.ts
24337
+ function configuredDefaultModels(config) {
24338
+ const items = config.plugins?.provider?.items ?? {};
24339
+ return Object.fromEntries(
24340
+ Object.entries(items).flatMap(([name, item]) => item?.model ? [[name, item.model]] : [])
24341
+ );
24342
+ }
24343
+ var init_default_models = __esm({
24344
+ "src/setup/default-models.ts"() {
24345
+ }
24346
+ });
24347
+
24267
24348
  // src/config-applier.ts
24268
24349
  function buildSessionConfigApplier(session, initial, builtins = [], disabledPackages) {
24269
24350
  let last = initial;
@@ -24309,6 +24390,10 @@ function buildSessionConfigApplier(session, initial, builtins = [], disabledPack
24309
24390
  session.lazyTools = next.context?.lazyTools;
24310
24391
  applied2.push("lazyTools");
24311
24392
  }
24393
+ if (next.context?.unfinishedStepCheck !== last.context?.unfinishedStepCheck) {
24394
+ session.unfinishedStepCheck = next.context?.unfinishedStepCheck;
24395
+ applied2.push("unfinishedStepCheck");
24396
+ }
24312
24397
  if (!deepEqual(next.context?.reasoning, last.context?.reasoning)) {
24313
24398
  session.reasoning = next.context?.reasoning;
24314
24399
  applied2.push("reasoning");
@@ -24324,6 +24409,11 @@ function buildSessionConfigApplier(session, initial, builtins = [], disabledPack
24324
24409
  if (next.hookTimeoutMs !== last.hookTimeoutMs) {
24325
24410
  pending.push("hookTimeoutMs (restart required)");
24326
24411
  }
24412
+ const defaultModels = configuredDefaultModels(next);
24413
+ if (!deepEqual(defaultModels, configuredDefaultModels(last))) {
24414
+ session.defaultModels = defaultModels;
24415
+ applied2.push("defaultModel");
24416
+ }
24327
24417
  if (providerChanged(last, next)) {
24328
24418
  pending.push("provider.* (restart required)");
24329
24419
  }
@@ -24440,6 +24530,7 @@ function arraysEqual(a2, b3) {
24440
24530
  var init_config_applier = __esm({
24441
24531
  "src/config-applier.ts"() {
24442
24532
  init_dist2();
24533
+ init_default_models();
24443
24534
  }
24444
24535
  });
24445
24536
 
@@ -24470,6 +24561,7 @@ function applyContextConfig(session, context) {
24470
24561
  if (!context) return;
24471
24562
  if (context.elision) session.elisionSettings = context.elision;
24472
24563
  if (context.lazyTools !== void 0) session.lazyTools = context.lazyTools;
24564
+ if (context.unfinishedStepCheck !== void 0) session.unfinishedStepCheck = context.unfinishedStepCheck;
24473
24565
  if (context.loopGuard) session.loopGuard = context.loopGuard;
24474
24566
  if (context.reasoning) session.reasoning = context.reasoning;
24475
24567
  if (context.fast !== void 0) session.fast = context.fast;
@@ -24606,10 +24698,10 @@ var init_apply_transcriber = __esm({
24606
24698
  });
24607
24699
  function interactiveConfigTrustPrompt() {
24608
24700
  if (!process.stdin.isTTY || !process.stderr.isTTY) return void 0;
24609
- return async ({ path: path77, sha256: sha2563 }) => {
24701
+ return async ({ path: path73, sha256: sha2563 }) => {
24610
24702
  process.stderr.write(
24611
24703
  "\n" + colors.bold("This project wants to run code before moxxy starts.") + `
24612
- ${path77}
24704
+ ${path73}
24613
24705
  ` + colors.dim(` sha256 ${sha2563.slice(0, 16)}\u2026
24614
24706
  `) + colors.dim(" Review it before approving. Approval is remembered for this exact\n") + colors.dim(" content, so an edit will ask again.\n")
24615
24707
  );
@@ -24686,9 +24778,16 @@ var init_embedder = __esm({
24686
24778
  };
24687
24779
  }
24688
24780
  });
24781
+ function userPolicyPath() {
24782
+ return moxxyPath("permissions.json");
24783
+ }
24784
+ var init_user_policy_path = __esm({
24785
+ "src/setup/user-policy-path.ts"() {
24786
+ }
24787
+ });
24689
24788
  async function buildSession(args) {
24690
- const userPolicyPath = args.config.permissions?.policyPath ?? path3.join(os.homedir(), ".moxxy", "permissions.json");
24691
- const permissionEngine = await PermissionEngine.load(userPolicyPath);
24789
+ const policyPath = args.config.permissions?.policyPath ?? userPolicyPath();
24790
+ const permissionEngine = await PermissionEngine.load(policyPath);
24692
24791
  permissionEngine.setImmutableRules({
24693
24792
  allow: [...args.config.permissions?.allow ?? [], ...args.bundledRules?.allow ?? []],
24694
24793
  deny: [...args.config.permissions?.deny ?? [], ...args.bundledRules?.deny ?? []]
@@ -24746,6 +24845,7 @@ async function buildSession(args) {
24746
24845
  }
24747
24846
  var init_build_session = __esm({
24748
24847
  "src/setup/build-session.ts"() {
24848
+ init_user_policy_path();
24749
24849
  init_dist2();
24750
24850
  }
24751
24851
  });
@@ -26552,11 +26652,11 @@ function parseBody(body) {
26552
26652
  return { ok: false, value: null };
26553
26653
  }
26554
26654
  }
26555
- function readJsonPath(parsed, path77) {
26655
+ function readJsonPath(parsed, path73) {
26556
26656
  if (!parsed.ok)
26557
26657
  return null;
26558
26658
  let cur = parsed.value;
26559
- for (const seg of path77.split(".")) {
26659
+ for (const seg of path73.split(".")) {
26560
26660
  if (cur === null || cur === void 0 || typeof cur !== "object")
26561
26661
  return null;
26562
26662
  cur = cur[seg];
@@ -31005,10 +31105,10 @@ var init_dist8 = __esm({
31005
31105
  function defaultIdentityPath() {
31006
31106
  return moxxyPath("proxy-identity.key");
31007
31107
  }
31008
- async function loadOrCreateIdentity(path77 = defaultIdentityPath()) {
31108
+ async function loadOrCreateIdentity(path73 = defaultIdentityPath()) {
31009
31109
  let hex = null;
31010
31110
  try {
31011
- hex = (await readFile(path77, "utf8")).trim();
31111
+ hex = (await readFile(path73, "utf8")).trim();
31012
31112
  } catch (err) {
31013
31113
  if (err.code !== "ENOENT")
31014
31114
  throw err;
@@ -31023,7 +31123,7 @@ async function loadOrCreateIdentity(path77 = defaultIdentityPath()) {
31023
31123
  }
31024
31124
  }
31025
31125
  const identity = generateIdentity();
31026
- await writeFileAtomic(path77, bytesToHex(identity.secretKey), { mode: 384 });
31126
+ await writeFileAtomic(path73, bytesToHex(identity.secretKey), { mode: 384 });
31027
31127
  return identity;
31028
31128
  }
31029
31129
  var init_node2 = __esm({
@@ -39164,6 +39264,26 @@ var init_read = __esm({
39164
39264
  });
39165
39265
  }
39166
39266
  });
39267
+ function recallAttachment(events, query, summarize) {
39268
+ const found = findAttachment(events, query);
39269
+ if (!found) {
39270
+ const known = listAttachments(events);
39271
+ throw new MoxxyError({
39272
+ code: "TOOL_ERROR",
39273
+ message: `recall: no attachment "${query}" in this conversation. ` + (known.length > 0 ? `Attached so far: ${known.join(", ")}.` : "Nothing has been attached yet.")
39274
+ });
39275
+ }
39276
+ const { seq, index, attachment: att } = found;
39277
+ const name = att.name ?? att.kind;
39278
+ if (att.kind !== "image" && att.kind !== "document") {
39279
+ return present(`[${att.kind} ${name}]
39280
+ ${att.content}`, summarize);
39281
+ }
39282
+ return {
39283
+ forModel: `[${att.kind} "${name}" restored \u2014 it is attached to this result.]`,
39284
+ restoredAttachment: { seq, index }
39285
+ };
39286
+ }
39167
39287
  function recallTargetMatches(input, target) {
39168
39288
  if (!input || typeof input !== "object")
39169
39289
  return false;
@@ -39219,11 +39339,12 @@ var init_recall = __esm({
39219
39339
  recallTool = defineTool({
39220
39340
  name: "recall",
39221
39341
  icon: "search",
39222
- description: 'Retrieve earlier content that was elided from context to save tokens. Pass the `callId` shown in an "[output elided \u2014 recall(...)]" stub to get a tool result back, or a `seq` / `turnId` to recall an earlier message or whole turn. Set `summarize: true` for a truncated preview instead of the full text. Only call this when you actually need the detail \u2014 the recent context is always present verbatim.',
39342
+ description: 'Retrieve earlier content that was elided from context to save tokens. Pass the `callId` shown in an "[output elided \u2014 recall(...)]" stub to get a tool result back, or a `seq` / `turnId` to recall an earlier message or whole turn. Pass `attachment` (a file name, or the key a "recall({ attachment })" note gives) to see a file attached earlier again, even one from a summarized turn. Set `summarize: true` for a truncated preview instead of the full text. Only call this when you actually need the detail \u2014 the recent context is always present verbatim.',
39223
39343
  inputSchema: z$1.object({
39224
39344
  callId: z$1.string().optional().describe("The callId from an elided tool-result stub."),
39225
39345
  seq: z$1.number().int().nonnegative().optional().describe("Event sequence number to recall."),
39226
39346
  turnId: z$1.string().optional().describe("Recall every message from this turn."),
39347
+ attachment: z$1.string().optional().describe('A file attached earlier: its name (e.g. "umowa.pdf") or its key (e.g. "12:0").'),
39227
39348
  summarize: z$1.boolean().optional().describe("Return a truncated preview instead of the full content.")
39228
39349
  }),
39229
39350
  permission: { action: "allow" },
@@ -39231,7 +39352,9 @@ var init_recall = __esm({
39231
39352
  required: "inproc",
39232
39353
  capabilities: { net: { mode: "none" }, timeMs: 5e3 }
39233
39354
  },
39234
- handler: ({ callId, seq, turnId, summarize }, ctx) => {
39355
+ handler: ({ callId, seq, turnId, attachment, summarize }, ctx) => {
39356
+ if (attachment !== void 0)
39357
+ return recallAttachment(ctx.log.slice(), attachment, summarize);
39235
39358
  const prior = ctx.log.slice(-40).find((e) => e.type === "tool_call_requested" && e.name === "recall" && e.callId !== ctx.callId && recallTargetMatches(e.input, { callId, seq, turnId }));
39236
39359
  if (prior) {
39237
39360
  return `[already recalled just above \u2014 not re-injecting to save context; scroll up for the full content]`;
@@ -39269,7 +39392,7 @@ var init_recall = __esm({
39269
39392
  }
39270
39393
  throw new MoxxyError({
39271
39394
  code: "TOOL_ERROR",
39272
- message: "recall: provide one of `callId`, `seq`, or `turnId`."
39395
+ message: "recall: provide one of `callId`, `seq`, `turnId`, or `attachment`."
39273
39396
  });
39274
39397
  }
39275
39398
  });
@@ -39516,7 +39639,7 @@ var DEFAULT_MODE_NAME, checkpoints;
39516
39639
  var init_turn_iterator = __esm({
39517
39640
  "../mode-default/dist/turn-iterator.js"() {
39518
39641
  DEFAULT_MODE_NAME = "default";
39519
- checkpoints = [unfinishedWorkCheckpoint()];
39642
+ checkpoints = [unfinishedWorkCheckpoint(), unfinishedStepCheckpoint()];
39520
39643
  }
39521
39644
  });
39522
39645
  var defaultMode, defaultModePlugin;
@@ -39997,6 +40120,44 @@ var init_jsonrpc = __esm({
39997
40120
  };
39998
40121
  }
39999
40122
  });
40123
+
40124
+ // ../runner/dist/backlog-guard.js
40125
+ var OutboundBacklogGuard;
40126
+ var init_backlog_guard = __esm({
40127
+ "../runner/dist/backlog-guard.js"() {
40128
+ OutboundBacklogGuard = class {
40129
+ limitBytes;
40130
+ graceMs;
40131
+ hardLimitBytes;
40132
+ stalledSinceMs = null;
40133
+ sentBytes = 0;
40134
+ drainedAtStallStart = 0;
40135
+ constructor(limitBytes, graceMs, hardLimitBytes = limitBytes * 4) {
40136
+ this.limitBytes = limitBytes;
40137
+ this.graceMs = graceMs;
40138
+ this.hardLimitBytes = hardLimitBytes;
40139
+ }
40140
+ check(bufferedBytes, nowMs) {
40141
+ if (bufferedBytes > this.hardLimitBytes)
40142
+ return "terminate";
40143
+ if (bufferedBytes <= this.limitBytes) {
40144
+ this.stalledSinceMs = null;
40145
+ return "ok";
40146
+ }
40147
+ const drained = this.sentBytes - bufferedBytes;
40148
+ if (this.stalledSinceMs === null || drained > this.drainedAtStallStart) {
40149
+ this.stalledSinceMs = nowMs;
40150
+ this.drainedAtStallStart = drained;
40151
+ return "ok";
40152
+ }
40153
+ return nowMs - this.stalledSinceMs >= this.graceMs ? "terminate" : "ok";
40154
+ }
40155
+ recordSent(bytes) {
40156
+ this.sentBytes += bytes;
40157
+ }
40158
+ };
40159
+ }
40160
+ });
40000
40161
  function platformSocket(name, posixPath, platform2 = process.platform) {
40001
40162
  if (platform2 === "win32") {
40002
40163
  return `\\\\.\\pipe\\moxxy-${name.replace(/[^A-Za-z0-9_-]/g, "_")}`;
@@ -40171,9 +40332,10 @@ async function reclaimStaleSocket(socketPath) {
40171
40332
  } catch {
40172
40333
  }
40173
40334
  }
40174
- var stderrLogger, DEFAULT_MAX_INBOUND_FRAME_BYTES, DEFAULT_MAX_OUTBOUND_BUFFER_BYTES, DEFAULT_OUTBOUND_STALL_GRACE_MS, OUTBOUND_HARD_MULTIPLIER, NdjsonTransport, DEFAULT_CONNECT_TIMEOUT_MS, warnedWindowsPipeAcl;
40335
+ var stderrLogger, DEFAULT_MAX_INBOUND_FRAME_BYTES, DEFAULT_MAX_OUTBOUND_BUFFER_BYTES, DEFAULT_OUTBOUND_STALL_GRACE_MS, DEFAULT_MAX_OUTBOUND_HARD_BYTES, NdjsonTransport, DEFAULT_CONNECT_TIMEOUT_MS, warnedWindowsPipeAcl;
40175
40336
  var init_unix_socket = __esm({
40176
40337
  "../runner/dist/unix-socket.js"() {
40338
+ init_backlog_guard();
40177
40339
  init_socket_path();
40178
40340
  stderrLogger = {
40179
40341
  warn: (msg, meta) => process.stderr.write(`[moxxy-runner] WARN ${msg} ${meta ? JSON.stringify(meta) : ""}
@@ -40184,22 +40346,19 @@ var init_unix_socket = __esm({
40184
40346
  DEFAULT_MAX_INBOUND_FRAME_BYTES = 64 * 1024 * 1024;
40185
40347
  DEFAULT_MAX_OUTBOUND_BUFFER_BYTES = 4 * 1024 * 1024;
40186
40348
  DEFAULT_OUTBOUND_STALL_GRACE_MS = 1e4;
40187
- OUTBOUND_HARD_MULTIPLIER = 4;
40349
+ DEFAULT_MAX_OUTBOUND_HARD_BYTES = 4 * DEFAULT_MAX_INBOUND_FRAME_BYTES;
40188
40350
  NdjsonTransport = class {
40189
40351
  socket;
40190
40352
  maxInboundFrameBytes;
40191
- maxOutboundBufferBytes;
40192
- outboundStallGraceMs;
40193
40353
  buffer = "";
40194
40354
  frameHandler;
40195
40355
  closeHandler;
40196
40356
  closedEmitted = false;
40197
- outboundStalledSinceMs = null;
40357
+ outbound;
40198
40358
  constructor(socket, maxInboundFrameBytes = DEFAULT_MAX_INBOUND_FRAME_BYTES, maxOutboundBufferBytes = DEFAULT_MAX_OUTBOUND_BUFFER_BYTES, outboundStallGraceMs = DEFAULT_OUTBOUND_STALL_GRACE_MS) {
40199
40359
  this.socket = socket;
40200
40360
  this.maxInboundFrameBytes = maxInboundFrameBytes;
40201
- this.maxOutboundBufferBytes = maxOutboundBufferBytes;
40202
- this.outboundStallGraceMs = outboundStallGraceMs;
40361
+ this.outbound = new OutboundBacklogGuard(maxOutboundBufferBytes, outboundStallGraceMs, Math.max(DEFAULT_MAX_OUTBOUND_HARD_BYTES, maxOutboundBufferBytes * 4));
40203
40362
  socket.setEncoding("utf8");
40204
40363
  socket.on("data", (chunk) => this.onData(chunk));
40205
40364
  socket.on("close", () => this.emitClose());
@@ -40241,36 +40400,19 @@ var init_unix_socket = __esm({
40241
40400
  send(frame) {
40242
40401
  if (this.socket.destroyed)
40243
40402
  return;
40244
- if (this.evictIfStalled())
40403
+ if (this.outbound.check(this.socket.writableLength, Date.now()) === "terminate") {
40404
+ this.dropSlowReader(this.socket.writableLength);
40245
40405
  return;
40246
- this.socket.write(`${JSON.stringify(frame)}
40247
- `);
40248
- }
40249
- /** Returns true and destroys the socket when the outbound backlog has stayed
40250
- * over the limit too long. Draining below the limit resets the grace clock. */
40251
- evictIfStalled() {
40252
- const buffered = this.socket.writableLength;
40253
- if (buffered > this.maxOutboundBufferBytes * OUTBOUND_HARD_MULTIPLIER) {
40254
- return this.dropSlowReader(buffered);
40255
- }
40256
- if (buffered <= this.maxOutboundBufferBytes) {
40257
- this.outboundStalledSinceMs = null;
40258
- return false;
40259
40406
  }
40260
- const now = Date.now();
40261
- if (this.outboundStalledSinceMs === null) {
40262
- this.outboundStalledSinceMs = now;
40263
- return false;
40264
- }
40265
- if (now - this.outboundStalledSinceMs < this.outboundStallGraceMs)
40266
- return false;
40267
- return this.dropSlowReader(buffered);
40407
+ const line = `${JSON.stringify(frame)}
40408
+ `;
40409
+ this.socket.write(line);
40410
+ this.outbound.recordSent(Buffer.byteLength(line));
40268
40411
  }
40269
40412
  dropSlowReader(buffered) {
40270
- const err = new Error(`slow reader: ${buffered} bytes unsent past grace window`);
40413
+ const err = new Error(`slow reader: ${buffered} bytes unsent, none taken within the grace window`);
40271
40414
  this.socket.destroy(err);
40272
40415
  this.emitClose(err);
40273
- return true;
40274
40416
  }
40275
40417
  onFrame(handler) {
40276
40418
  this.frameHandler = handler;
@@ -40425,10 +40567,10 @@ function surfaceInputWithinCap(m3) {
40425
40567
  return true;
40426
40568
  return JSON.stringify(m3).length <= MAX_SURFACE_INPUT_BYTES;
40427
40569
  }
40428
- var RUNNER_PROTOCOL_VERSION, MIN_COMPATIBLE_PROTOCOL_VERSION, RunnerMethod, RunnerNotification, attachmentSchema, principalSchema, attachParamsSchema, runTurnParamsSchema, abortParamsSchema, setResolverParamsSchema, modeSetActiveParamsSchema, sessionSetReasoningParamsSchema, sessionSetFastParamsSchema, MAX_HISTORY_PAGE_LIMIT, sessionLoadHistoryParamsSchema, MAX_RECORDED_EXCHANGE_CHARS, recordedText, sessionRecordExchangeParamsSchema, sessionSetAutoApproveParamsSchema, providerSetActiveParamsSchema, providerSetEnabledParamsSchema, providerConfigureParamsSchema, permissionAddAllowParamsSchema, commandRunParamsSchema, MAX_TRANSCRIBE_AUDIO_B64_BYTES, MAX_SYNTHESIZE_TEXT_BYTES, MEDIA_DESCRIPTOR_MAX, transcribeParamsSchema, synthesizeParamsSchema, cancelSynthesizeParamsSchema, mcpEnableAndAttachParamsSchema, mcpDetachParamsSchema, workflowSetEnabledParamsSchema, workflowRunParamsSchema, workflowValidateDraftParamsSchema, workflowSaveParamsSchema, workflowGetRunParamsSchema, workflowResumeParamsSchema, surfaceOpenParamsSchema, MAX_SURFACE_INPUT_BYTES, surfaceInputParamsSchema, surfaceResizeParamsSchema, surfaceCloseParamsSchema;
40570
+ var RUNNER_PROTOCOL_VERSION, MIN_COMPATIBLE_PROTOCOL_VERSION, RunnerMethod, RunnerNotification, attachmentSchema, principalSchema, attachParamsSchema, runTurnParamsSchema, abortParamsSchema, setResolverParamsSchema, modeSetActiveParamsSchema, sessionSetReasoningParamsSchema, sessionSetFastParamsSchema, MAX_HISTORY_PAGE_LIMIT, sessionLoadHistoryParamsSchema, sessionReadAttachmentParamsSchema, MAX_RECORDED_EXCHANGE_CHARS, recordedText, sessionRecordExchangeParamsSchema, sessionSetAutoApproveParamsSchema, providerSetActiveParamsSchema, providerSetEnabledParamsSchema, providerConfigureParamsSchema, permissionAddAllowParamsSchema, commandRunParamsSchema, MAX_TRANSCRIBE_AUDIO_B64_BYTES, MAX_SYNTHESIZE_TEXT_BYTES, MEDIA_DESCRIPTOR_MAX, transcribeParamsSchema, synthesizeParamsSchema, cancelSynthesizeParamsSchema, mcpEnableAndAttachParamsSchema, mcpDetachParamsSchema, workflowSetEnabledParamsSchema, workflowRunParamsSchema, workflowValidateDraftParamsSchema, workflowSaveParamsSchema, workflowGetRunParamsSchema, workflowResumeParamsSchema, surfaceOpenParamsSchema, MAX_SURFACE_INPUT_BYTES, surfaceInputParamsSchema, surfaceResizeParamsSchema, surfaceCloseParamsSchema;
40429
40571
  var init_protocol2 = __esm({
40430
40572
  "../runner/dist/protocol.js"() {
40431
- RUNNER_PROTOCOL_VERSION = 24;
40573
+ RUNNER_PROTOCOL_VERSION = 26;
40432
40574
  MIN_COMPATIBLE_PROTOCOL_VERSION = 1;
40433
40575
  RunnerMethod = {
40434
40576
  /** client->server: handshake; returns the initial info snapshot. */
@@ -40456,6 +40598,12 @@ var init_protocol2 = __esm({
40456
40598
  * reported version and falls back to its NDJSON store against an older runner.
40457
40599
  */
40458
40600
  SessionLoadHistory: "session.loadHistory",
40601
+ /**
40602
+ * client->server: read one slice of an attachment whose bytes were left out
40603
+ * of the client's copy of an event (v26). `{ seq, index, offset }` →
40604
+ * `{ data, total }`; repeat with `offset += data.length` until `total`.
40605
+ */
40606
+ SessionReadAttachment: "session.readAttachment",
40459
40607
  /**
40460
40608
  * client->server: append a conversation exchange that happened outside the
40461
40609
  * agent loop (v20) — e.g. a GPT-Live voice turn — as one ordinary turn, so
@@ -40622,6 +40770,11 @@ var init_protocol2 = __esm({
40622
40770
  before: z.number().int().nonnegative().nullable(),
40623
40771
  limit: z.number().int().positive().max(MAX_HISTORY_PAGE_LIMIT)
40624
40772
  });
40773
+ sessionReadAttachmentParamsSchema = z.object({
40774
+ seq: z.number().int().nonnegative(),
40775
+ index: z.number().int().nonnegative().max(1e3),
40776
+ offset: z.number().int().nonnegative()
40777
+ }).strict();
40625
40778
  MAX_RECORDED_EXCHANGE_CHARS = 1e5;
40626
40779
  recordedText = z.string().max(MAX_RECORDED_EXCHANGE_CHARS).optional();
40627
40780
  sessionRecordExchangeParamsSchema = z.object({ userText: recordedText, assistantText: recordedText }).strict().refine(({ userText, assistantText }) => Boolean(userText?.trim() || assistantText?.trim()), { message: "An exchange needs user or assistant text" });
@@ -41002,8 +41155,6 @@ var init_surface_handlers = __esm({
41002
41155
  init_protocol2();
41003
41156
  }
41004
41157
  });
41005
-
41006
- // ../runner/dist/handlers/session-handlers.js
41007
41158
  function handleModeSetActive(ctx, raw) {
41008
41159
  const { name } = modeSetActiveParamsSchema.parse(raw);
41009
41160
  ctx.session.modes.setActive(name);
@@ -41023,10 +41174,26 @@ function handleSessionSetFast(ctx, raw) {
41023
41174
  async function handleSessionLoadHistory(ctx, raw) {
41024
41175
  const { before, limit } = sessionLoadHistoryParamsSchema.parse(raw);
41025
41176
  const log2 = ctx.session.log;
41026
- if (log2.baseSeq === 0) {
41027
- return pageEvents(log2.toJSON(), before, limit);
41028
- }
41029
- return readEventPage(String(ctx.session.id), { before, limit }, ctx.sessionsDir);
41177
+ const page = log2.baseSeq === 0 ? pageEvents(log2.toJSON(), before, limit) : await readEventPage(String(ctx.session.id), { before, limit }, ctx.sessionsDir);
41178
+ return historyPageForClient(page);
41179
+ }
41180
+ async function handleSessionReadAttachment(ctx, raw) {
41181
+ const { seq, index, offset } = sessionReadAttachmentParamsSchema.parse(raw);
41182
+ return readAttachmentChunk(await eventAt(ctx, seq), index, offset);
41183
+ }
41184
+ async function eventAt(ctx, seq) {
41185
+ const log2 = ctx.session.log;
41186
+ if (seq >= log2.baseSeq) {
41187
+ const inMemory = log2.slice(seq, seq + 1)[0];
41188
+ if (inMemory)
41189
+ return inMemory;
41190
+ throw new Error(`no event ${seq} in this session`);
41191
+ }
41192
+ const { events } = await readEventPage(String(ctx.session.id), { before: seq + 1, limit: 1 }, ctx.sessionsDir);
41193
+ const onDisk = events[0];
41194
+ if (onDisk && onDisk.seq === seq)
41195
+ return onDisk;
41196
+ throw new Error(`no event ${seq} in this session`);
41030
41197
  }
41031
41198
  async function handleSessionRecordExchange(ctx, raw) {
41032
41199
  const exchange = sessionRecordExchangeParamsSchema.parse(raw);
@@ -41215,6 +41382,7 @@ var init_server2 = __esm({
41215
41382
  peer.handle(RunnerMethod.Abort, (raw) => this.handleAbort(client2, raw));
41216
41383
  peer.handle(RunnerMethod.SessionReset, () => this.handleSessionReset());
41217
41384
  peer.handle(RunnerMethod.SessionLoadHistory, (raw) => handleSessionLoadHistory(ctx, raw));
41385
+ peer.handle(RunnerMethod.SessionReadAttachment, (raw) => handleSessionReadAttachment(ctx, raw));
41218
41386
  peer.handle(RunnerMethod.SessionRecordExchange, (raw) => handleSessionRecordExchange(ctx, raw));
41219
41387
  peer.handle(RunnerMethod.SessionSetAutoApprove, (raw) => handleSessionSetAutoApprove(ctx, raw));
41220
41388
  peer.handle(RunnerMethod.SetResolver, (raw) => this.handleSetResolver(client2, raw));
@@ -41248,7 +41416,11 @@ var init_server2 = __esm({
41248
41416
  peer.handle(RunnerMethod.SurfaceInput, (raw) => handleSurfaceInput(ctx, raw));
41249
41417
  peer.handle(RunnerMethod.SurfaceResize, (raw) => handleSurfaceResize(ctx, raw));
41250
41418
  peer.handle(RunnerMethod.SurfaceClose, (raw) => handleSurfaceClose(ctx, raw));
41251
- peer.onClose(() => this.onDisconnect(client2));
41419
+ peer.onClose((err) => {
41420
+ if (err)
41421
+ this.session.logger.warn("runner: client dropped", { role: client2.role, reason: err.message });
41422
+ this.onDisconnect(client2);
41423
+ });
41252
41424
  }
41253
41425
  onDisconnect(client2) {
41254
41426
  this.clients.delete(client2);
@@ -41274,7 +41446,7 @@ var init_server2 = __esm({
41274
41446
  const start = replay === "full" ? baseSeq : replay === "none" ? endSeq : Math.max(baseSeq, endSeq - replay.tail);
41275
41447
  client2.peer.notify(RunnerNotification.ReplayStart, { fromSeq: start });
41276
41448
  for (const event of this.session.log.slice(start)) {
41277
- client2.peer.notify(RunnerNotification.Event, { event });
41449
+ client2.peer.notify(RunnerNotification.Event, { event: eventForClient(event) });
41278
41450
  }
41279
41451
  return {
41280
41452
  sessionId: this.session.id,
@@ -41520,7 +41692,7 @@ var init_server2 = __esm({
41520
41692
  }
41521
41693
  // --- fan-out -------------------------------------------------------------
41522
41694
  broadcastEvent(event) {
41523
- this.broadcast(RunnerNotification.Event, { event });
41695
+ this.broadcast(RunnerNotification.Event, { event: eventForClient(event) });
41524
41696
  }
41525
41697
  broadcast(method, params) {
41526
41698
  for (const client2 of this.clients) {
@@ -42442,6 +42614,19 @@ var init_remote_session = __esm({
42442
42614
  limit
42443
42615
  });
42444
42616
  }
42617
+ /**
42618
+ * Read one slice of attachment `index` of event `seq` (v26) — the bytes a
42619
+ * client's copy of the event left out (`omittedBytes`). Call again with
42620
+ * `offset += data.length` until it reaches `total`.
42621
+ */
42622
+ async readAttachment(seq, index, offset) {
42623
+ this.requireServerProtocol(26, "Opening large attachments");
42624
+ return this.peer.request(RunnerMethod.SessionReadAttachment, {
42625
+ seq,
42626
+ index,
42627
+ offset
42628
+ });
42629
+ }
42445
42630
  /**
42446
42631
  * Record a conversation exchange that happened outside the agent loop (v20),
42447
42632
  * e.g. a GPT-Live voice turn. The runner appends it as one ordinary turn:
@@ -42605,6 +42790,7 @@ var init_dist18 = __esm({
42605
42790
  "../runner/dist/index.js"() {
42606
42791
  init_jsonrpc();
42607
42792
  init_unix_socket();
42793
+ init_backlog_guard();
42608
42794
  init_socket_path();
42609
42795
  init_channel_runner();
42610
42796
  init_server2();
@@ -42749,8 +42935,8 @@ var init_client = __esm({
42749
42935
  peerFiles(agentId) {
42750
42936
  return this.peer.request(CollabHubMethod.PeerFiles, { agentId });
42751
42937
  }
42752
- peerRead(agentId, path77) {
42753
- return this.peer.request(CollabHubMethod.PeerRead, { agentId, path: path77 });
42938
+ peerRead(agentId, path73) {
42939
+ return this.peer.request(CollabHubMethod.PeerRead, { agentId, path: path73 });
42754
42940
  }
42755
42941
  peerDiff(agentId) {
42756
42942
  return this.peer.request(CollabHubMethod.PeerDiff, { agentId });
@@ -43089,11 +43275,11 @@ var init_tools7 = __esm({
43089
43275
  permission: { action: "allow" },
43090
43276
  isolation: HUB_RPC_PEER_ISOLATION,
43091
43277
  modes: COLLAB_AGENT_MODES,
43092
- handler: async ({ agentId, path: path77 }) => {
43278
+ handler: async ({ agentId, path: path73 }) => {
43093
43279
  const c3 = await getProcessHubClient();
43094
43280
  if (!c3)
43095
43281
  return NOT_IN_COLLAB;
43096
- return c3.peerRead(agentId, path77);
43282
+ return c3.peerRead(agentId, path73);
43097
43283
  }
43098
43284
  });
43099
43285
  collabPeerDiff = defineTool({
@@ -44137,14 +44323,14 @@ var init_summarize = __esm({
44137
44323
  Use terse bullet points. Do NOT restate the raw conversation, do NOT invent details, omit chit-chat and pleasantries. Output ONLY the brief text \u2014 no preamble, no sign-off. Keep it well under 400 words.`;
44138
44324
  }
44139
44325
  });
44140
- function moxxyHome2() {
44326
+ function moxxyHome3() {
44141
44327
  return process.env.MOXXY_HOME ?? join(homedir(), ".moxxy");
44142
44328
  }
44143
44329
  function collabLockPath() {
44144
- return process.env.MOXXY_COLLAB_LOCK || join(moxxyHome2(), "collab", "active.lock");
44330
+ return process.env.MOXXY_COLLAB_LOCK || join(moxxyHome3(), "collab", "active.lock");
44145
44331
  }
44146
44332
  function collabRunsDir() {
44147
- return join(moxxyHome2(), "collab", "runs");
44333
+ return join(moxxyHome3(), "collab", "runs");
44148
44334
  }
44149
44335
  function parseCollabLock(raw) {
44150
44336
  let info;
@@ -44317,8 +44503,8 @@ async function addWorktree(args) {
44317
44503
  if (r2.code !== 0)
44318
44504
  throw new Error(`git worktree add failed: ${r2.stderr.trim() || r2.stdout.trim()}`);
44319
44505
  }
44320
- async function removeWorktree(repoCwd, path77) {
44321
- await git(repoCwd, ["worktree", "remove", "--force", path77]);
44506
+ async function removeWorktree(repoCwd, path73) {
44507
+ await git(repoCwd, ["worktree", "remove", "--force", path73]);
44322
44508
  await git(repoCwd, ["worktree", "prune"]);
44323
44509
  }
44324
44510
  async function commitAll(worktreeCwd, message) {
@@ -44339,9 +44525,9 @@ async function changedFiles(worktreeCwd) {
44339
44525
  if (!rec)
44340
44526
  continue;
44341
44527
  const status = rec.slice(0, 2).trim();
44342
- const path77 = rec.slice(3);
44343
- if (path77)
44344
- out.push({ status, path: path77 });
44528
+ const path73 = rec.slice(3);
44529
+ if (path73)
44530
+ out.push({ status, path: path73 });
44345
44531
  if (status.startsWith("R") || status.startsWith("C"))
44346
44532
  i2++;
44347
44533
  }
@@ -44435,9 +44621,9 @@ function peerReaderFor(worktrees, baseSha) {
44435
44621
  async files(agentId) {
44436
44622
  return changedFiles(dirFor(agentId));
44437
44623
  },
44438
- async read(agentId, path77) {
44624
+ async read(agentId, path73) {
44439
44625
  const dir = dirFor(agentId);
44440
- return readFile(await resolveWithinReal(dir, path77), "utf8");
44626
+ return readFile(await resolveWithinReal(dir, path73), "utf8");
44441
44627
  },
44442
44628
  async diff(agentId) {
44443
44629
  return diffVsBase(dirFor(agentId), baseSha);
@@ -44449,8 +44635,8 @@ function cwdPeerReader(cwd2) {
44449
44635
  async files() {
44450
44636
  return await isGitRepo(cwd2) ? changedFiles(cwd2) : [];
44451
44637
  },
44452
- async read(_agentId, path77) {
44453
- return readFile(await resolveWithinReal(cwd2, path77), "utf8");
44638
+ async read(_agentId, path73) {
44639
+ return readFile(await resolveWithinReal(cwd2, path73), "utf8");
44454
44640
  },
44455
44641
  async diff() {
44456
44642
  return "";
@@ -44695,8 +44881,8 @@ function readActiveCollab() {
44695
44881
  return info;
44696
44882
  }
44697
44883
  function tryAcquireCollabLock(args) {
44698
- const path77 = collabLockPath();
44699
- mkdirSync(dirname(path77), { recursive: true });
44884
+ const path73 = collabLockPath();
44885
+ mkdirSync(dirname(path73), { recursive: true });
44700
44886
  const info = {
44701
44887
  pid: process.pid,
44702
44888
  sessionId: args.sessionId,
@@ -44707,7 +44893,7 @@ function tryAcquireCollabLock(args) {
44707
44893
  const payload2 = JSON.stringify(info);
44708
44894
  for (let attempt = 0; attempt < 5; attempt++) {
44709
44895
  try {
44710
- const fd = openSync(path77, "wx");
44896
+ const fd = openSync(path73, "wx");
44711
44897
  try {
44712
44898
  writeFileSync(fd, payload2);
44713
44899
  } finally {
@@ -44722,7 +44908,7 @@ function tryAcquireCollabLock(args) {
44722
44908
  return { ok: false, holder: existing };
44723
44909
  }
44724
44910
  try {
44725
- unlinkSync(path77);
44911
+ unlinkSync(path73);
44726
44912
  } catch {
44727
44913
  }
44728
44914
  }
@@ -45077,11 +45263,11 @@ function lastUserPromptText(ctx) {
45077
45263
  }
45078
45264
  return void 0;
45079
45265
  }
45080
- function readRoster(path77, maxAgents) {
45081
- if (!existsSync(path77))
45266
+ function readRoster(path73, maxAgents) {
45267
+ if (!existsSync(path73))
45082
45268
  return [];
45083
45269
  try {
45084
- const raw = JSON.parse(readFileSync(path77, "utf8"));
45270
+ const raw = JSON.parse(readFileSync(path73, "utf8"));
45085
45271
  if (!Array.isArray(raw))
45086
45272
  return [];
45087
45273
  const seen = /* @__PURE__ */ new Set();
@@ -45561,11 +45747,11 @@ var init_agent_loop = __esm({
45561
45747
  }
45562
45748
  });
45563
45749
  function peerSystemPrompt(env3) {
45564
- const path77 = env3[COLLAB_ENV.CharterFile]?.trim();
45565
- if (!path77)
45750
+ const path73 = env3[COLLAB_ENV.CharterFile]?.trim();
45751
+ if (!path73)
45566
45752
  return COLLAB_PEER_PROMPT;
45567
45753
  try {
45568
- return peerPromptWithCharter(readFileSync(path77, "utf8"));
45754
+ return peerPromptWithCharter(readFileSync(path73, "utf8"));
45569
45755
  } catch {
45570
45756
  return COLLAB_PEER_PROMPT;
45571
45757
  }
@@ -70980,10 +71166,10 @@ var require_react_reconciler_development = __commonJS({
70980
71166
  var setErrorHandler = null;
70981
71167
  var setSuspenseHandler = null;
70982
71168
  {
70983
- var copyWithDeleteImpl = function(obj, path77, index2) {
70984
- var key = path77[index2];
71169
+ var copyWithDeleteImpl = function(obj, path73, index2) {
71170
+ var key = path73[index2];
70985
71171
  var updated = isArray(obj) ? obj.slice() : assign({}, obj);
70986
- if (index2 + 1 === path77.length) {
71172
+ if (index2 + 1 === path73.length) {
70987
71173
  if (isArray(updated)) {
70988
71174
  updated.splice(key, 1);
70989
71175
  } else {
@@ -70991,11 +71177,11 @@ var require_react_reconciler_development = __commonJS({
70991
71177
  }
70992
71178
  return updated;
70993
71179
  }
70994
- updated[key] = copyWithDeleteImpl(obj[key], path77, index2 + 1);
71180
+ updated[key] = copyWithDeleteImpl(obj[key], path73, index2 + 1);
70995
71181
  return updated;
70996
71182
  };
70997
- var copyWithDelete = function(obj, path77) {
70998
- return copyWithDeleteImpl(obj, path77, 0);
71183
+ var copyWithDelete = function(obj, path73) {
71184
+ return copyWithDeleteImpl(obj, path73, 0);
70999
71185
  };
71000
71186
  var copyWithRenameImpl = function(obj, oldPath, newPath, index2) {
71001
71187
  var oldKey = oldPath[index2];
@@ -71033,17 +71219,17 @@ var require_react_reconciler_development = __commonJS({
71033
71219
  }
71034
71220
  return copyWithRenameImpl(obj, oldPath, newPath, 0);
71035
71221
  };
71036
- var copyWithSetImpl = function(obj, path77, index2, value2) {
71037
- if (index2 >= path77.length) {
71222
+ var copyWithSetImpl = function(obj, path73, index2, value2) {
71223
+ if (index2 >= path73.length) {
71038
71224
  return value2;
71039
71225
  }
71040
- var key = path77[index2];
71226
+ var key = path73[index2];
71041
71227
  var updated = isArray(obj) ? obj.slice() : assign({}, obj);
71042
- updated[key] = copyWithSetImpl(obj[key], path77, index2 + 1, value2);
71228
+ updated[key] = copyWithSetImpl(obj[key], path73, index2 + 1, value2);
71043
71229
  return updated;
71044
71230
  };
71045
- var copyWithSet = function(obj, path77, value2) {
71046
- return copyWithSetImpl(obj, path77, 0, value2);
71231
+ var copyWithSet = function(obj, path73, value2) {
71232
+ return copyWithSetImpl(obj, path73, 0, value2);
71047
71233
  };
71048
71234
  var findHook = function(fiber, id) {
71049
71235
  var currentHook2 = fiber.memoizedState;
@@ -71053,10 +71239,10 @@ var require_react_reconciler_development = __commonJS({
71053
71239
  }
71054
71240
  return currentHook2;
71055
71241
  };
71056
- overrideHookState = function(fiber, id, path77, value2) {
71242
+ overrideHookState = function(fiber, id, path73, value2) {
71057
71243
  var hook = findHook(fiber, id);
71058
71244
  if (hook !== null) {
71059
- var newState = copyWithSet(hook.memoizedState, path77, value2);
71245
+ var newState = copyWithSet(hook.memoizedState, path73, value2);
71060
71246
  hook.memoizedState = newState;
71061
71247
  hook.baseState = newState;
71062
71248
  fiber.memoizedProps = assign({}, fiber.memoizedProps);
@@ -71066,10 +71252,10 @@ var require_react_reconciler_development = __commonJS({
71066
71252
  }
71067
71253
  }
71068
71254
  };
71069
- overrideHookStateDeletePath = function(fiber, id, path77) {
71255
+ overrideHookStateDeletePath = function(fiber, id, path73) {
71070
71256
  var hook = findHook(fiber, id);
71071
71257
  if (hook !== null) {
71072
- var newState = copyWithDelete(hook.memoizedState, path77);
71258
+ var newState = copyWithDelete(hook.memoizedState, path73);
71073
71259
  hook.memoizedState = newState;
71074
71260
  hook.baseState = newState;
71075
71261
  fiber.memoizedProps = assign({}, fiber.memoizedProps);
@@ -71092,8 +71278,8 @@ var require_react_reconciler_development = __commonJS({
71092
71278
  }
71093
71279
  }
71094
71280
  };
71095
- overrideProps = function(fiber, path77, value2) {
71096
- fiber.pendingProps = copyWithSet(fiber.memoizedProps, path77, value2);
71281
+ overrideProps = function(fiber, path73, value2) {
71282
+ fiber.pendingProps = copyWithSet(fiber.memoizedProps, path73, value2);
71097
71283
  if (fiber.alternate) {
71098
71284
  fiber.alternate.pendingProps = fiber.pendingProps;
71099
71285
  }
@@ -71102,8 +71288,8 @@ var require_react_reconciler_development = __commonJS({
71102
71288
  scheduleUpdateOnFiber(root, fiber, SyncLane, NoTimestamp);
71103
71289
  }
71104
71290
  };
71105
- overridePropsDeletePath = function(fiber, path77) {
71106
- fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path77);
71291
+ overridePropsDeletePath = function(fiber, path73) {
71292
+ fiber.pendingProps = copyWithDelete(fiber.memoizedProps, path73);
71107
71293
  if (fiber.alternate) {
71108
71294
  fiber.alternate.pendingProps = fiber.pendingProps;
71109
71295
  }
@@ -78608,8 +78794,8 @@ var init_ErrorOverview = __esm({
78608
78794
  init_dist26();
78609
78795
  init_Box();
78610
78796
  init_Text();
78611
- cleanupPath = (path77) => {
78612
- return path77?.replace(`file://${cwd()}/`, "");
78797
+ cleanupPath = (path73) => {
78798
+ return path73?.replace(`file://${cwd()}/`, "");
78613
78799
  };
78614
78800
  stackUtils = new import_stack_utils.default({
78615
78801
  cwd: cwd(),
@@ -89472,7 +89658,7 @@ var init_PermissionEditor = __esm({
89472
89658
  import_react72 = __toESM(require_react());
89473
89659
  await init_build2();
89474
89660
  init_dist2();
89475
- PermissionEditor = ({ policyPath: policyPath2 }) => {
89661
+ PermissionEditor = ({ policyPath }) => {
89476
89662
  const { exit } = use_app_default();
89477
89663
  const [engine, setEngine] = (0, import_react72.useState)(null);
89478
89664
  const [rows, setRows] = (0, import_react72.useState)([]);
@@ -89483,7 +89669,7 @@ var init_PermissionEditor = __esm({
89483
89669
  (0, import_react72.useEffect)(() => {
89484
89670
  let cancelled = false;
89485
89671
  (async () => {
89486
- const e = await PermissionEngine.load(policyPath2);
89672
+ const e = await PermissionEngine.load(policyPath);
89487
89673
  if (cancelled)
89488
89674
  return;
89489
89675
  setEngine(e);
@@ -89492,7 +89678,7 @@ var init_PermissionEditor = __esm({
89492
89678
  return () => {
89493
89679
  cancelled = true;
89494
89680
  };
89495
- }, [policyPath2]);
89681
+ }, [policyPath]);
89496
89682
  const refresh = (e) => {
89497
89683
  const next = toRows(e);
89498
89684
  setRows(next);
@@ -89607,7 +89793,7 @@ var init_PermissionEditor = __esm({
89607
89793
  exit();
89608
89794
  }
89609
89795
  });
89610
- return (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "column", padding: 1, children: [(0, import_jsx_runtime42.jsxs)(Box_default, { marginBottom: 1, children: [(0, import_jsx_runtime42.jsx)(Text, { bold: true, color: "magenta", children: "moxxy perms editor" }), (0, import_jsx_runtime42.jsxs)(Text, { dimColor: true, children: [" (", policyPath2, ")"] })] }), rows.length === 0 ? (0, import_jsx_runtime42.jsx)(Text, { dimColor: true, children: "(no rules \u2014 press `a` to add an allow rule, `D` for deny)" }) : rows.map((row, i2) => {
89796
+ return (0, import_jsx_runtime42.jsxs)(Box_default, { flexDirection: "column", padding: 1, children: [(0, import_jsx_runtime42.jsxs)(Box_default, { marginBottom: 1, children: [(0, import_jsx_runtime42.jsx)(Text, { bold: true, color: "magenta", children: "moxxy perms editor" }), (0, import_jsx_runtime42.jsxs)(Text, { dimColor: true, children: [" (", policyPath, ")"] })] }), rows.length === 0 ? (0, import_jsx_runtime42.jsx)(Text, { dimColor: true, children: "(no rules \u2014 press `a` to add an allow rule, `D` for deny)" }) : rows.map((row, i2) => {
89611
89797
  const focused = i2 === cursor3;
89612
89798
  return (0, import_jsx_runtime42.jsxs)(Box_default, { children: [(0, import_jsx_runtime42.jsx)(Text, { color: focused ? "cyan" : void 0, children: focused ? "\u203A " : " " }), (0, import_jsx_runtime42.jsx)(Text, { color: row.kind === "allow" ? "green" : "red", children: row.kind.padEnd(5) }), (0, import_jsx_runtime42.jsxs)(Text, { children: [" ", row.name] }), row.reason ? (0, import_jsx_runtime42.jsxs)(Text, { dimColor: true, children: [" \u2014 ", row.reason] }) : null] }, `${row.kind}:${row.name}:${i2}`);
89613
89799
  }), (0, import_jsx_runtime42.jsx)(Box_default, { marginTop: 1, children: mode.kind === "add" ? (0, import_jsx_runtime42.jsxs)(Text, { children: ["new ", mode.bucket, " rule: ", (0, import_jsx_runtime42.jsx)(Text, { color: "cyan", children: mode.buffer }), (0, import_jsx_runtime42.jsx)(Text, { dimColor: true, children: " (enter to confirm, esc to cancel)" })] }) : mode.kind === "confirm-delete" ? (0, import_jsx_runtime42.jsxs)(Text, { color: "yellow", children: ["delete `", mode.row.name, "` (", mode.row.kind, ")? [y/N]"] }) : mode.kind === "message" ? (0, import_jsx_runtime42.jsxs)(Text, { color: /FAILED/i.test(mode.text) ? "red" : "green", children: [mode.text, " (press any key)"] }) : (0, import_jsx_runtime42.jsxs)(Text, { dimColor: true, children: ["\u2191/\u2193 move \xB7 space/enter flip \xB7 a add allow \xB7 D add deny \xB7 d delete \xB7 q quit", dirty || /FAILED/i.test(status) ? (0, import_jsx_runtime42.jsx)(Text, { color: /FAILED/i.test(status) ? "red" : "green", children: ` \xB7 ${status}` }) : null] }) })] });
@@ -89789,10 +89975,11 @@ async function createWebSocketTransportServer(opts) {
89789
89975
  reservations.delete(socket);
89790
89976
  };
89791
89977
  const liveTransports = /* @__PURE__ */ new Set();
89978
+ const maxPayload = opts.maxPayloadBytes ?? 64 * 1024 * 1024;
89792
89979
  const wss = new import_websocket_server.default({
89793
89980
  host,
89794
89981
  port: opts.port,
89795
- maxPayload: opts.maxPayloadBytes ?? 64 * 1024 * 1024,
89982
+ maxPayload,
89796
89983
  verifyClient: (info) => {
89797
89984
  if (!checkWsOrigin(info.req, currentAllowedOrigins)) {
89798
89985
  console.warn(`[moxxy] ws bridge: rejected browser-origin upgrade (Origin: ${sanitizeForLog(info.req.headers.origin)})`);
@@ -89823,7 +90010,7 @@ async function createWebSocketTransportServer(opts) {
89823
90010
  releaseReservation(req.socket);
89824
90011
  connections += 1;
89825
90012
  opts.onClientCountChange?.(connections);
89826
- const transport = new WsTransport(ws, new SlowReaderGuard(opts.maxBufferedBytes, opts.bufferStallGraceMs));
90013
+ const transport = new WsTransport(ws, new SlowReaderGuard(opts.maxBufferedBytes, opts.bufferStallGraceMs, 4 * maxPayload));
89827
90014
  liveTransports.add(transport);
89828
90015
  ws.once("close", () => {
89829
90016
  connections -= 1;
@@ -89882,39 +90069,20 @@ async function createWebSocketTransportServer(opts) {
89882
90069
  }
89883
90070
  };
89884
90071
  }
89885
- var DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_BUFFERED_BYTES, DEFAULT_BUFFER_STALL_GRACE_MS, RESERVATION_RECONCILE_MS, SLOW_READER_HARD_MULTIPLIER, MAX_LOGGED_ORIGIN_LEN, SlowReaderGuard, WsTransport;
90072
+ var DEFAULT_MAX_CONNECTIONS, DEFAULT_MAX_BUFFERED_BYTES, DEFAULT_BUFFER_STALL_GRACE_MS, RESERVATION_RECONCILE_MS, MAX_LOGGED_ORIGIN_LEN, SlowReaderGuard, WsTransport;
89886
90073
  var init_ws_transport = __esm({
89887
90074
  "../ipc-server-ws/dist/ws-transport.js"() {
89888
90075
  init_wrapper();
90076
+ init_dist18();
89889
90077
  init_auth();
89890
90078
  DEFAULT_MAX_CONNECTIONS = 8;
89891
90079
  DEFAULT_MAX_BUFFERED_BYTES = 4 * 1024 * 1024;
89892
90080
  DEFAULT_BUFFER_STALL_GRACE_MS = 1e4;
89893
90081
  RESERVATION_RECONCILE_MS = 1e4;
89894
- SLOW_READER_HARD_MULTIPLIER = 4;
89895
90082
  MAX_LOGGED_ORIGIN_LEN = 128;
89896
- SlowReaderGuard = class {
89897
- limitBytes;
89898
- graceMs;
89899
- stalledSinceMs = null;
89900
- hardLimitBytes;
89901
- constructor(limitBytes = DEFAULT_MAX_BUFFERED_BYTES, graceMs = DEFAULT_BUFFER_STALL_GRACE_MS) {
89902
- this.limitBytes = limitBytes;
89903
- this.graceMs = graceMs;
89904
- this.hardLimitBytes = limitBytes * SLOW_READER_HARD_MULTIPLIER;
89905
- }
89906
- check(bufferedAmount, nowMs) {
89907
- if (bufferedAmount > this.hardLimitBytes)
89908
- return "terminate";
89909
- if (bufferedAmount <= this.limitBytes) {
89910
- this.stalledSinceMs = null;
89911
- return "ok";
89912
- }
89913
- if (this.stalledSinceMs === null) {
89914
- this.stalledSinceMs = nowMs;
89915
- return "ok";
89916
- }
89917
- return nowMs - this.stalledSinceMs >= this.graceMs ? "terminate" : "ok";
90083
+ SlowReaderGuard = class extends OutboundBacklogGuard {
90084
+ constructor(limitBytes = DEFAULT_MAX_BUFFERED_BYTES, graceMs = DEFAULT_BUFFER_STALL_GRACE_MS, hardLimitBytes) {
90085
+ super(limitBytes, graceMs, hardLimitBytes);
89918
90086
  }
89919
90087
  };
89920
90088
  WsTransport = class {
@@ -89943,7 +90111,9 @@ var init_ws_transport = __esm({
89943
90111
  return;
89944
90112
  if (this.evictIfStalled())
89945
90113
  return;
89946
- this.ws.send(JSON.stringify(frame));
90114
+ const payload2 = JSON.stringify(frame);
90115
+ this.ws.send(payload2);
90116
+ this.guard.recordSent(Buffer.byteLength(payload2));
89947
90117
  }
89948
90118
  /**
89949
90119
  * Re-consult the slow-reader guard out of band (a periodic sweep), so a peer
@@ -90210,6 +90380,7 @@ var init_validation = __esm({
90210
90380
  "app.updatePlan": z.undefined(),
90211
90381
  "app.setup": z.undefined(),
90212
90382
  "app.relaunch": z.undefined(),
90383
+ "app.revertUpdate": z.undefined(),
90213
90384
  "app.appBooted": z.undefined(),
90214
90385
  "app.updateDiagnostics": z.undefined(),
90215
90386
  // Optional offline voice installation spawns the CLI and changes the active
@@ -90447,6 +90618,12 @@ var init_validation = __esm({
90447
90618
  effort: z.enum(["off", "low", "medium", "high", "xhigh"])
90448
90619
  }),
90449
90620
  "settings.setFast": z.object({ workspaceId: optionalWorkspace, enabled: z.boolean() }),
90621
+ // Written into the config file: a provider name that cannot leave its key, and a model id of sane length.
90622
+ "settings.setModelDefaults": z.object({
90623
+ model: z.object({ provider: providerName, model: z.string().min(1).max(256) }).strict().optional(),
90624
+ effort: z.enum(["off", "low", "medium", "high", "xhigh"]).optional(),
90625
+ fast: z.boolean().optional()
90626
+ }).strict().refine((change) => Object.keys(change).length > 0, "nothing to change"),
90450
90627
  "settings.writeSkill": z.object({ name: skillName, body: z.string().max(1e6) }),
90451
90628
  "settings.readSkill": z.object({ name: skillName }),
90452
90629
  "settings.deleteSkill": z.object({ name: skillName }),
@@ -90541,6 +90718,13 @@ var init_validation = __esm({
90541
90718
  before: z.number().int().nonnegative().nullable(),
90542
90719
  limit: z.number().int().positive().max(2e3)
90543
90720
  }),
90721
+ // Reads the session log (runner or the JSONL on disk) — bound every index.
90722
+ "chat.readAttachment": z.object({
90723
+ workspaceId: z.string().min(1).max(256),
90724
+ seq: z.number().int().nonnegative(),
90725
+ index: z.number().int().nonnegative().max(1e3),
90726
+ offset: z.number().int().nonnegative()
90727
+ }).strict(),
90544
90728
  // Collaboration control. All three touch the on-disk collab store
90545
90729
  // (~/.moxxy/collab/{active.lock,runs}) — a filesystem-touching surface — so
90546
90730
  // each gets the boundary check the module header promises:
@@ -91705,8 +91889,8 @@ function buildConnectUrl(opts) {
91705
91889
  if (opts.tunnelUrl) {
91706
91890
  const u5 = new URL(opts.tunnelUrl);
91707
91891
  const scheme = u5.protocol === "https:" ? "wss" : "ws";
91708
- const path77 = u5.pathname === "/" ? "/" : `${u5.pathname.replace(/\/$/, "")}/`;
91709
- return `${scheme}://${u5.host}${path77}?t=${t2}${fp}`;
91892
+ const path73 = u5.pathname === "/" ? "/" : `${u5.pathname.replace(/\/$/, "")}/`;
91893
+ return `${scheme}://${u5.host}${path73}?t=${t2}${fp}`;
91710
91894
  }
91711
91895
  return `ws://${opts.localHost}:${opts.port}/?t=${t2}${fp}`;
91712
91896
  }
@@ -93449,10 +93633,10 @@ var require_segments = __commonJS({
93449
93633
  const segs = getSegmentsFromString(data, Utils.isKanjiModeEnabled());
93450
93634
  const nodes = buildNodes(segs);
93451
93635
  const graph = buildGraph(nodes, version);
93452
- const path77 = dijkstra.find_path(graph.map, "start", "end");
93636
+ const path73 = dijkstra.find_path(graph.map, "start", "end");
93453
93637
  const optimizedSegs = [];
93454
- for (let i2 = 1; i2 < path77.length - 1; i2++) {
93455
- optimizedSegs.push(graph.table[path77[i2]].node);
93638
+ for (let i2 = 1; i2 < path73.length - 1; i2++) {
93639
+ optimizedSegs.push(graph.table[path73[i2]].node);
93456
93640
  }
93457
93641
  return exports.fromArray(mergeSegments(optimizedSegs));
93458
93642
  };
@@ -95904,7 +96088,7 @@ var require_png2 = __commonJS({
95904
96088
  });
95905
96089
  png.pack();
95906
96090
  };
95907
- exports.renderToFile = function renderToFile(path77, qrData, options, cb) {
96091
+ exports.renderToFile = function renderToFile(path73, qrData, options, cb) {
95908
96092
  if (typeof cb === "undefined") {
95909
96093
  cb = options;
95910
96094
  options = void 0;
@@ -95915,7 +96099,7 @@ var require_png2 = __commonJS({
95915
96099
  called = true;
95916
96100
  cb.apply(null, args);
95917
96101
  };
95918
- const stream2 = fs52.createWriteStream(path77);
96102
+ const stream2 = fs52.createWriteStream(path73);
95919
96103
  stream2.on("error", done);
95920
96104
  stream2.on("close", done);
95921
96105
  exports.renderToFileStream(stream2, qrData, options);
@@ -95977,14 +96161,14 @@ var require_utf8 = __commonJS({
95977
96161
  }
95978
96162
  return output;
95979
96163
  };
95980
- exports.renderToFile = function renderToFile(path77, qrData, options, cb) {
96164
+ exports.renderToFile = function renderToFile(path73, qrData, options, cb) {
95981
96165
  if (typeof cb === "undefined") {
95982
96166
  cb = options;
95983
96167
  options = void 0;
95984
96168
  }
95985
96169
  const fs52 = __require("fs");
95986
96170
  const utf82 = exports.render(qrData, options);
95987
- fs52.writeFile(path77, utf82, cb);
96171
+ fs52.writeFile(path73, utf82, cb);
95988
96172
  };
95989
96173
  }
95990
96174
  });
@@ -96105,7 +96289,7 @@ var require_svg_tag = __commonJS({
96105
96289
  return str;
96106
96290
  }
96107
96291
  function qrToPath(data, size, margin) {
96108
- let path77 = "";
96292
+ let path73 = "";
96109
96293
  let moveBy = 0;
96110
96294
  let newRow = false;
96111
96295
  let lineLength = 0;
@@ -96116,19 +96300,19 @@ var require_svg_tag = __commonJS({
96116
96300
  if (data[i2]) {
96117
96301
  lineLength++;
96118
96302
  if (!(i2 > 0 && col > 0 && data[i2 - 1])) {
96119
- path77 += newRow ? svgCmd("M", col + margin, 0.5 + row + margin) : svgCmd("m", moveBy, 0);
96303
+ path73 += newRow ? svgCmd("M", col + margin, 0.5 + row + margin) : svgCmd("m", moveBy, 0);
96120
96304
  moveBy = 0;
96121
96305
  newRow = false;
96122
96306
  }
96123
96307
  if (!(col + 1 < size && data[i2 + 1])) {
96124
- path77 += svgCmd("h", lineLength);
96308
+ path73 += svgCmd("h", lineLength);
96125
96309
  lineLength = 0;
96126
96310
  }
96127
96311
  } else {
96128
96312
  moveBy++;
96129
96313
  }
96130
96314
  }
96131
- return path77;
96315
+ return path73;
96132
96316
  }
96133
96317
  exports.render = function render4(qrData, options, cb) {
96134
96318
  const opts = Utils.getOptions(options);
@@ -96136,10 +96320,10 @@ var require_svg_tag = __commonJS({
96136
96320
  const data = qrData.modules.data;
96137
96321
  const qrcodesize = size + opts.margin * 2;
96138
96322
  const bg = !opts.color.light.a ? "" : "<path " + getColorAttrib(opts.color.light, "fill") + ' d="M0 0h' + qrcodesize + "v" + qrcodesize + 'H0z"/>';
96139
- const path77 = "<path " + getColorAttrib(opts.color.dark, "stroke") + ' d="' + qrToPath(data, size, opts.margin) + '"/>';
96323
+ const path73 = "<path " + getColorAttrib(opts.color.dark, "stroke") + ' d="' + qrToPath(data, size, opts.margin) + '"/>';
96140
96324
  const viewBox = 'viewBox="0 0 ' + qrcodesize + " " + qrcodesize + '"';
96141
96325
  const width = !opts.width ? "" : 'width="' + opts.width + '" height="' + opts.width + '" ';
96142
- const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path77 + "</svg>\n";
96326
+ const svgTag = '<svg xmlns="http://www.w3.org/2000/svg" ' + width + viewBox + ' shape-rendering="crispEdges">' + bg + path73 + "</svg>\n";
96143
96327
  if (typeof cb === "function") {
96144
96328
  cb(null, svgTag);
96145
96329
  }
@@ -96153,7 +96337,7 @@ var require_svg = __commonJS({
96153
96337
  "../../node_modules/.pnpm/qrcode@1.5.4/node_modules/qrcode/lib/renderer/svg.js"(exports) {
96154
96338
  var svgTagRenderer = require_svg_tag();
96155
96339
  exports.render = svgTagRenderer.render;
96156
- exports.renderToFile = function renderToFile(path77, qrData, options, cb) {
96340
+ exports.renderToFile = function renderToFile(path73, qrData, options, cb) {
96157
96341
  if (typeof cb === "undefined") {
96158
96342
  cb = options;
96159
96343
  options = void 0;
@@ -96161,7 +96345,7 @@ var require_svg = __commonJS({
96161
96345
  const fs52 = __require("fs");
96162
96346
  const svgTag = exports.render(qrData, options);
96163
96347
  const xmlStr = '<?xml version="1.0" encoding="utf-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">' + svgTag;
96164
- fs52.writeFile(path77, xmlStr, cb);
96348
+ fs52.writeFile(path73, xmlStr, cb);
96165
96349
  };
96166
96350
  }
96167
96351
  });
@@ -96319,8 +96503,8 @@ var require_server = __commonJS({
96319
96503
  cb
96320
96504
  };
96321
96505
  }
96322
- function getTypeFromFilename(path77) {
96323
- return path77.slice((path77.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
96506
+ function getTypeFromFilename(path73) {
96507
+ return path73.slice((path73.lastIndexOf(".") - 1 >>> 0) + 2).toLowerCase();
96324
96508
  }
96325
96509
  function getRendererFromType(type) {
96326
96510
  switch (type) {
@@ -96384,17 +96568,17 @@ var require_server = __commonJS({
96384
96568
  const renderer2 = getRendererFromType(params.opts.type);
96385
96569
  return render4(renderer2.renderToBuffer, text3, params);
96386
96570
  };
96387
- exports.toFile = function toFile(path77, text3, opts, cb) {
96388
- if (typeof path77 !== "string" || !(typeof text3 === "string" || typeof text3 === "object")) {
96571
+ exports.toFile = function toFile(path73, text3, opts, cb) {
96572
+ if (typeof path73 !== "string" || !(typeof text3 === "string" || typeof text3 === "object")) {
96389
96573
  throw new Error("Invalid argument");
96390
96574
  }
96391
96575
  if (arguments.length < 3 && !canPromise()) {
96392
96576
  throw new Error("Too few arguments provided");
96393
96577
  }
96394
96578
  const params = checkParams(text3, opts, cb);
96395
- const type = params.opts.type || getTypeFromFilename(path77);
96579
+ const type = params.opts.type || getTypeFromFilename(path73);
96396
96580
  const renderer2 = getRendererFromType(type);
96397
- const renderToFile = renderer2.renderToFile.bind(null, path77);
96581
+ const renderToFile = renderer2.renderToFile.bind(null, path73);
96398
96582
  return render4(renderToFile, text3, params);
96399
96583
  };
96400
96584
  exports.toFileStream = function toFileStream(stream2, text3, opts) {
@@ -97501,8 +97685,8 @@ function formatIssues(error, raw) {
97501
97685
  const field = rest.join(".");
97502
97686
  return field ? `${where}: ${field} ${msg}` : `${where} ${msg}`;
97503
97687
  }
97504
- const path77 = iss.path.join(".");
97505
- return path77 ? `${path77} ${msg}` : `workflow ${msg}`;
97688
+ const path73 = iss.path.join(".");
97689
+ return path73 ? `${path73} ${msg}` : `workflow ${msg}`;
97506
97690
  });
97507
97691
  }
97508
97692
  function validateWorkflow(raw) {
@@ -97872,7 +98056,7 @@ var init_schema2 = __esm({
97872
98056
  }
97873
98057
  });
97874
98058
  function defaultUserWorkflowsDir() {
97875
- return path3.join(os.homedir(), ".moxxy", "workflows");
98059
+ return moxxyPath("workflows");
97876
98060
  }
97877
98061
  function defaultProjectWorkflowsDir(cwd2) {
97878
98062
  return path3.join(cwd2, ".moxxy", "workflows");
@@ -100180,7 +100364,8 @@ function buildWorkflowRunner(args) {
100180
100364
  return { runNow, resumeNow };
100181
100365
  }
100182
100366
  function activeModel(session) {
100183
- return session.lastResolvedModel ?? safeActiveProvider(session)?.models[0]?.id ?? "default";
100367
+ const provider = safeActiveProvider(session);
100368
+ return (provider ? resolveTurnModel(session, provider) : session.lastResolvedModel) ?? "default";
100184
100369
  }
100185
100370
  function safeActiveProvider(session) {
100186
100371
  try {
@@ -103109,7 +103294,7 @@ __export(dist_exports4, {
103109
103294
  note: () => note,
103110
103295
  outro: () => outro,
103111
103296
  password: () => password,
103112
- path: () => path59,
103297
+ path: () => path58,
103113
103298
  progress: () => progress,
103114
103299
  select: () => select,
103115
103300
  selectKey: () => selectKey,
@@ -103208,7 +103393,7 @@ function progress({
103208
103393
  message: (t2) => g2(0, t2)
103209
103394
  };
103210
103395
  }
103211
- var import_sisteransi2, unicode, isCI, isTTY, unicodeOr, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, S_BAR_START, S_BAR, S_BAR_END, S_BAR_START_RIGHT, S_BAR_END_RIGHT, S_RADIO_ACTIVE, S_RADIO_INACTIVE, S_CHECKBOX_ACTIVE, S_CHECKBOX_SELECTED, S_CHECKBOX_INACTIVE, S_PASSWORD_MASK, S_BAR_H, S_CORNER_TOP_RIGHT, S_CONNECT_LEFT, S_CORNER_BOTTOM_RIGHT, S_CORNER_BOTTOM_LEFT, S_CORNER_TOP_LEFT, S_INFO, S_SUCCESS, S_WARN, S_ERROR, symbol, symbolBar, I, limitOptions, autocomplete, autocompleteMultiselect, K, Q, U2, box, confirm, date, p2, group, MULTISELECT_INSTRUCTIONS, m2, multiselect, groupMultiselect, log, cancel, intro, outro, multiline, W$1, C2, note, password, path59, W, spinner, u4, SELECT_INSTRUCTIONS, c2, select, selectKey, i, stream, tasks, A, taskLog, text2;
103396
+ var import_sisteransi2, unicode, isCI, isTTY, unicodeOr, S_STEP_ACTIVE, S_STEP_CANCEL, S_STEP_ERROR, S_STEP_SUBMIT, S_BAR_START, S_BAR, S_BAR_END, S_BAR_START_RIGHT, S_BAR_END_RIGHT, S_RADIO_ACTIVE, S_RADIO_INACTIVE, S_CHECKBOX_ACTIVE, S_CHECKBOX_SELECTED, S_CHECKBOX_INACTIVE, S_PASSWORD_MASK, S_BAR_H, S_CORNER_TOP_RIGHT, S_CONNECT_LEFT, S_CORNER_BOTTOM_RIGHT, S_CORNER_BOTTOM_LEFT, S_CORNER_TOP_LEFT, S_INFO, S_SUCCESS, S_WARN, S_ERROR, symbol, symbolBar, I, limitOptions, autocomplete, autocompleteMultiselect, K, Q, U2, box, confirm, date, p2, group, MULTISELECT_INSTRUCTIONS, m2, multiselect, groupMultiselect, log, cancel, intro, outro, multiline, W$1, C2, note, password, path58, W, spinner, u4, SELECT_INSTRUCTIONS, c2, select, selectKey, i, stream, tasks, A, taskLog, text2;
103212
103397
  var init_dist39 = __esm({
103213
103398
  "../../node_modules/.pnpm/@clack+prompts@1.8.1/node_modules/@clack/prompts/dist/index.mjs"() {
103214
103399
  init_dist38();
@@ -104089,7 +104274,7 @@ ${n3}
104089
104274
  }
104090
104275
  }
104091
104276
  }).prompt();
104092
- path59 = (e) => {
104277
+ path58 = (e) => {
104093
104278
  const a2 = e.validate;
104094
104279
  return autocomplete({
104095
104280
  ...e,
@@ -105088,6 +105273,7 @@ async function setupSessionWithConfig(opts) {
105088
105273
  applyPluginsTree(session, config, logger);
105089
105274
  assertCriticalFloors(session);
105090
105275
  applyContextConfig(session, config.context);
105276
+ session.defaultModels = configuredDefaultModels(config);
105091
105277
  await applySessionHeaderPreferences(session, opts.sessionId, credentialResolver, logger);
105092
105278
  progress2({ kind: "prefs-applied" });
105093
105279
  const discovered = await discoverSkills({
@@ -105148,6 +105334,7 @@ var init_setup = __esm({
105148
105334
  init_load_config();
105149
105335
  init_egress();
105150
105336
  init_context_config();
105337
+ init_default_models();
105151
105338
  init_secrets();
105152
105339
  init_apply_transcriber();
105153
105340
  init_config_trust_prompt();
@@ -106775,11 +106962,11 @@ function servicePlatform() {
106775
106962
  if (process.platform === "linux") return "linux";
106776
106963
  return "unsupported";
106777
106964
  }
106778
- function moxxyHome3() {
106965
+ function moxxyHome4() {
106779
106966
  return process.env.MOXXY_HOME ?? path3__default.join(homedir(), ".moxxy");
106780
106967
  }
106781
106968
  function serviceLogPath(spec) {
106782
- return path3__default.join(moxxyHome3(), "services", `${spec.id}.log`);
106969
+ return path3__default.join(moxxyHome4(), "services", `${spec.id}.log`);
106783
106970
  }
106784
106971
  function nodeBin() {
106785
106972
  return process.execPath;
@@ -108371,9 +108558,6 @@ var perms_exports = {};
108371
108558
  __export(perms_exports, {
108372
108559
  runPermsCommand: () => runPermsCommand
108373
108560
  });
108374
- function policyPath() {
108375
- return path3.join(os.homedir(), ".moxxy", "permissions.json");
108376
- }
108377
108561
  async function runPermsCommand(argv) {
108378
108562
  if (helpRequested(argv)) {
108379
108563
  process.stdout.write(HELP7);
@@ -108387,13 +108571,13 @@ async function runPermsCommand(argv) {
108387
108571
  init_dist29().then(() => dist_exports3)
108388
108572
  ]);
108389
108573
  const { waitUntilExit } = render4(
108390
- React56.createElement(PermissionEditor2, { policyPath: policyPath() })
108574
+ React56.createElement(PermissionEditor2, { policyPath: userPolicyPath() })
108391
108575
  );
108392
108576
  await waitUntilExit();
108393
108577
  return 0;
108394
108578
  }
108395
108579
  const cmd = sub ?? "list";
108396
- const engine = await PermissionEngine.load(policyPath());
108580
+ const engine = await PermissionEngine.load(userPolicyPath());
108397
108581
  switch (cmd) {
108398
108582
  case "list": {
108399
108583
  const policy = engine.policySnapshot;
@@ -108464,7 +108648,7 @@ ${HELP7}`);
108464
108648
  return 0;
108465
108649
  }
108466
108650
  case "path": {
108467
- process.stdout.write(policyPath() + "\n");
108651
+ process.stdout.write(userPolicyPath() + "\n");
108468
108652
  return 0;
108469
108653
  }
108470
108654
  default:
@@ -108477,6 +108661,7 @@ var HELP7;
108477
108661
  var init_perms = __esm({
108478
108662
  async "src/commands/perms.ts"() {
108479
108663
  init_dist2();
108664
+ init_user_policy_path();
108480
108665
  await init_argv_helpers();
108481
108666
  init_errors();
108482
108667
  init_colors();
@@ -110698,6 +110883,8 @@ var init_daemon = __esm({
110698
110883
  init_schedule_daemon_svc();
110699
110884
  }
110700
110885
  });
110886
+
110887
+ // src/commands/schedule/setup-cmd.ts
110701
110888
  async function runScheduleSetup(argv) {
110702
110889
  const allowFlag = argv.flags.allow;
110703
110890
  const tools = typeof allowFlag === "string" ? allowFlag.split(",").map((s) => s.trim()).filter(Boolean) : DEFAULT_HEADLESS_ALLOW_TOOLS;
@@ -110720,8 +110907,8 @@ async function stepAllowTools(tools) {
110720
110907
  `);
110721
110908
  return;
110722
110909
  }
110723
- const policyPath2 = path3.join(os.homedir(), ".moxxy", "permissions.json");
110724
- const engine = await PermissionEngine.load(policyPath2);
110910
+ const policyPath = userPolicyPath();
110911
+ const engine = await PermissionEngine.load(policyPath);
110725
110912
  const before = engine.policySnapshot;
110726
110913
  const existingAllowNames = new Set(before.allow.map((r2) => r2.name));
110727
110914
  const added = [];
@@ -110736,7 +110923,7 @@ async function stepAllowTools(tools) {
110736
110923
  }
110737
110924
  process.stdout.write(
110738
110925
  `${tag(true)} ${colors.bold("allow")} ` + (added.length > 0 ? colors.bold(added.join(", ")) : colors.dim("(none new)")) + (skipped.length > 0 ? colors.dim(` [already allowed: ${skipped.join(", ")}]`) : "") + `
110739
- ${colors.dim("\u2192 " + policyPath2)}
110926
+ ${colors.dim("\u2192 " + policyPath)}
110740
110927
  `
110741
110928
  );
110742
110929
  }
@@ -110802,6 +110989,7 @@ var init_setup_cmd = __esm({
110802
110989
  init_colors();
110803
110990
  await init_setup();
110804
110991
  init_schedule_daemon_svc();
110992
+ init_user_policy_path();
110805
110993
  DEFAULT_HEADLESS_ALLOW_TOOLS = ["telegram_send_message", "web_fetch"];
110806
110994
  tag = (ok) => ok ? colors.bold("ok ") : colors.red("fail");
110807
110995
  }
@@ -111031,6 +111219,7 @@ var doctor_exports = {};
111031
111219
  __export(doctor_exports, {
111032
111220
  buildAuditExportDoctorCheck: () => buildAuditExportDoctorCheck,
111033
111221
  buildEgressDoctorCheck: () => buildEgressDoctorCheck,
111222
+ buildMemoryDoctorCheck: () => buildMemoryDoctorCheck,
111034
111223
  buildPluginDoctorChecks: () => buildPluginDoctorChecks,
111035
111224
  buildPolicyDoctorCheck: () => buildPolicyDoctorCheck,
111036
111225
  buildSelfUpdateDoctorCheck: () => buildSelfUpdateDoctorCheck,
@@ -111163,34 +111352,7 @@ async function runDoctorChecks(deps) {
111163
111352
  }
111164
111353
  checks.push(buildVoiceDoctorCheck(session, await checkVoiceCaptureAvailable()));
111165
111354
  checks.push(...buildPluginDoctorChecks(pluginRegistration));
111166
- if (!memory) {
111167
- checks.push({
111168
- id: "memory",
111169
- status: "warn",
111170
- message: "memory extension not installed \u2014 long-term memory off (moxxy extensions install @moxxy/plugin-memory)"
111171
- });
111172
- } else {
111173
- const memDir = path3.join(os.homedir(), ".moxxy", "memory");
111174
- const memRes = await tryCatch(async () => {
111175
- await promises.mkdir(memDir, { recursive: true });
111176
- await promises.access(memDir, promises.constants.W_OK);
111177
- const entries = await memory.list();
111178
- return { count: entries.length };
111179
- });
111180
- if (memRes.ok) {
111181
- checks.push({
111182
- id: "memory",
111183
- status: "ok",
111184
- message: `${memDir} writable (${memRes.value.count} entries)`
111185
- });
111186
- } else {
111187
- checks.push({
111188
- id: "memory",
111189
- status: "fail",
111190
- message: `${memDir} not writable: ${memRes.error}`
111191
- });
111192
- }
111193
- }
111355
+ checks.push(await buildMemoryDoctorCheck(memory));
111194
111356
  const allSkills = session.skills.list();
111195
111357
  checks.push({
111196
111358
  id: "skills",
@@ -111291,6 +111453,26 @@ function buildEgressDoctorCheck(config) {
111291
111453
  const hint = ca ? "" : " (set NODE_EXTRA_CA_CERTS if the proxy terminates TLS)";
111292
111454
  return { id: "network", status, message: `${via}${bypass}${caNote}${hint}` };
111293
111455
  }
111456
+ async function buildMemoryDoctorCheck(memory) {
111457
+ if (!memory) {
111458
+ return {
111459
+ id: "memory",
111460
+ status: "warn",
111461
+ message: "memory extension not installed \u2014 long-term memory off (moxxy extensions install @moxxy/plugin-memory)"
111462
+ };
111463
+ }
111464
+ const memDir = moxxyPath("memory");
111465
+ const memRes = await tryCatch(async () => {
111466
+ await promises.mkdir(memDir, { recursive: true });
111467
+ await promises.access(memDir, promises.constants.W_OK);
111468
+ const entries = await memory.list();
111469
+ return { count: entries.length };
111470
+ });
111471
+ if (memRes.ok) {
111472
+ return { id: "memory", status: "ok", message: `${memDir} writable (${memRes.value.count} entries)` };
111473
+ }
111474
+ return { id: "memory", status: "fail", message: `${memDir} not writable: ${memRes.error}` };
111475
+ }
111294
111476
  async function buildSelfUpdateDoctorCheck(session) {
111295
111477
  if (!session.tools.has("self_update_begin")) {
111296
111478
  return { id: "self-update", status: "warn", message: "disabled (plugin not loaded)" };
@@ -112988,7 +113170,7 @@ var init_skills4 = __esm({
112988
113170
  }
112989
113171
  ]
112990
113172
  });
112991
- AUDIT_PATH = () => path3.join(os.homedir(), ".moxxy", "skills", ".meta", "created.jsonl");
113173
+ AUDIT_PATH = () => moxxyPath("skills", ".meta", "created.jsonl");
112992
113174
  auditMutex = createMutex();
112993
113175
  }
112994
113176
  });
@@ -113015,7 +113197,7 @@ async function runPluginNewCommand(argv) {
113015
113197
  }
113016
113198
  const here = hasBoolFlag(argv, "here");
113017
113199
  const force = hasBoolFlag(argv, "force");
113018
- const root = here ? path3.join(process.cwd(), name) : path3.join(os.homedir(), ".moxxy", "plugins", name);
113200
+ const root = here ? path3.join(process.cwd(), name) : moxxyPath("plugins", name);
113019
113201
  try {
113020
113202
  const stat2 = await promises.stat(root);
113021
113203
  if (stat2.isDirectory() && !force) {
@@ -114606,9 +114788,6 @@ var self_update_exports = {};
114606
114788
  __export(self_update_exports, {
114607
114789
  runSelfUpdateCommand: () => runSelfUpdateCommand
114608
114790
  });
114609
- function moxxyDir() {
114610
- return path3.join(os.homedir(), ".moxxy");
114611
- }
114612
114791
  async function runSelfUpdateCommand(argv) {
114613
114792
  const sub = argv.positional[0] ?? "status";
114614
114793
  if (sub === "help" || helpRequested(argv)) {
@@ -114616,7 +114795,7 @@ async function runSelfUpdateCommand(argv) {
114616
114795
  return 0;
114617
114796
  }
114618
114797
  if (sub === "status") {
114619
- const dir = moxxyDir();
114798
+ const dir = moxxyHome();
114620
114799
  const txns = await listTransactions(dir);
114621
114800
  const core = await listCoreTxns(dir);
114622
114801
  process.stdout.write(colors.bold("Tier 1 \u2014 plugins / skills\n"));
@@ -114639,7 +114818,7 @@ async function runSelfUpdateCommand(argv) {
114639
114818
  printError("usage: moxxy self-update rollback <coreTxnId>");
114640
114819
  return 2;
114641
114820
  }
114642
- const dir = moxxyDir();
114821
+ const dir = moxxyHome();
114643
114822
  const journal = await readCoreJournal(dir, txnId).catch(() => null);
114644
114823
  if (!journal) {
114645
114824
  printError(`no core transaction "${txnId}" (only Tier-2 core txns can be rolled back from the CLI)`);