@moxt-ai/mobius 0.0.72 → 0.0.73

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/runtime.js CHANGED
@@ -6,7 +6,7 @@ var __export = (target, all2) => {
6
6
 
7
7
  // src/runtime.ts
8
8
  import { mkdir as mkdir6, realpath as realpath10, stat as stat9 } from "node:fs/promises";
9
- import { dirname as dirname8, join as join17, resolve as resolve7 } from "node:path";
9
+ import { dirname as dirname8, join as join18, resolve as resolve7 } from "node:path";
10
10
 
11
11
  // src/agent-catalog/local-agent.ts
12
12
  import { realpathSync, statSync } from "node:fs";
@@ -21140,8 +21140,31 @@ var mcpElicitationParamsSchema = external_exports.object({
21140
21140
  url: external_exports.string().optional()
21141
21141
  });
21142
21142
  var threadStartResponseSchema = external_exports.object({
21143
+ approvalPolicy: external_exports.unknown().optional(),
21144
+ approvalsReviewer: external_exports.unknown().optional(),
21145
+ model: boundedText(256).nullish(),
21146
+ reasoningEffort: boundedText(256).nullish(),
21147
+ sandbox: external_exports.unknown().optional(),
21148
+ serviceTier: boundedText(256).nullish(),
21143
21149
  thread: external_exports.object({ id: boundedText(256) })
21144
21150
  });
21151
+ var reasoningEffortOptionSchema = external_exports.object({
21152
+ description: boundedText(4096).nullish(),
21153
+ reasoningEffort: boundedText(256)
21154
+ });
21155
+ var modelSchema = external_exports.object({
21156
+ additionalSpeedTiers: external_exports.array(boundedText(256)).max(100).nullish(),
21157
+ defaultReasoningEffort: boundedText(256).nullish(),
21158
+ description: boundedText(4096).nullish(),
21159
+ displayName: boundedText(256).nullish(),
21160
+ id: boundedText(256),
21161
+ isDefault: external_exports.boolean().nullish(),
21162
+ supportedReasoningEfforts: external_exports.array(reasoningEffortOptionSchema).max(100).nullish()
21163
+ });
21164
+ var modelListResponseSchema = external_exports.object({
21165
+ data: external_exports.array(modelSchema).max(1e3),
21166
+ nextCursor: boundedText(1024).nullish()
21167
+ });
21145
21168
 
21146
21169
  // src/acp/codex/app-server-client.ts
21147
21170
  var INITIALIZE_TIMEOUT_MILLISECONDS = 3e4;
@@ -21481,6 +21504,56 @@ function agentMessageMeta(phase) {
21481
21504
  var APPROVAL_REASON_CHARACTER_LIMIT = 500;
21482
21505
  var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
21483
21506
  var CODEX_AGENT_VERSION = "0.154.0";
21507
+ var MODEL_SETTING_ID = "model";
21508
+ var REASONING_EFFORT_SETTING_ID = "reasoning_effort";
21509
+ var MODE_SETTING_ID = "mode";
21510
+ var FAST_MODE_SETTING_ID = "fast-mode";
21511
+ var MODEL_CATALOG_LIMIT = 1e3;
21512
+ var FAST_TIER = "fast";
21513
+ var SERVICE_TIER_FAST = "priority";
21514
+ var WORKSPACE_WRITE_POLICY = Object.freeze({
21515
+ excludeSlashTmp: false,
21516
+ excludeTmpdirEnvVar: false,
21517
+ networkAccess: false,
21518
+ type: "workspaceWrite",
21519
+ writableRoots: []
21520
+ });
21521
+ var READ_ONLY_MODE = Object.freeze({
21522
+ approvalPolicy: "on-request",
21523
+ approvalsReviewer: "user",
21524
+ description: "Always ask to edit external files and use the internet",
21525
+ id: "read-only",
21526
+ name: "Ask for approval",
21527
+ sandboxPolicy: WORKSPACE_WRITE_POLICY
21528
+ });
21529
+ var AGENT_MODE = Object.freeze({
21530
+ approvalPolicy: "on-request",
21531
+ approvalsReviewer: "auto_review",
21532
+ description: "Only ask for actions detected as potentially unsafe",
21533
+ id: "agent",
21534
+ name: "Approve for me",
21535
+ sandboxPolicy: WORKSPACE_WRITE_POLICY
21536
+ });
21537
+ var FULL_ACCESS_MODE = Object.freeze({
21538
+ approvalPolicy: "never",
21539
+ approvalsReviewer: "user",
21540
+ description: "Unrestricted access to the internet and any file on your computer",
21541
+ id: "agent-full-access",
21542
+ name: "Full access",
21543
+ sandboxPolicy: { type: "dangerFullAccess" }
21544
+ });
21545
+ var AGENT_MODES = Object.freeze([READ_ONLY_MODE, AGENT_MODE, FULL_ACCESS_MODE]);
21546
+ var DEFAULT_MODE = AGENT_MODE;
21547
+ function initialMode(environment) {
21548
+ const requested = environment["INITIAL_AGENT_MODE"];
21549
+ if (requested === void 0) {
21550
+ return DEFAULT_MODE.id;
21551
+ }
21552
+ return AGENT_MODES.some((mode) => mode.id === requested) ? requested : DEFAULT_MODE.id;
21553
+ }
21554
+ function capitalize(value) {
21555
+ return value.length === 0 ? value : value.charAt(0).toUpperCase() + value.slice(1);
21556
+ }
21484
21557
  var APPROVAL_OPTIONS = Object.freeze([
21485
21558
  { kind: "allow_once", name: "Allow once", optionId: "accept" },
21486
21559
  { kind: "allow_always", name: "Allow for this session", optionId: "acceptForSession" },
@@ -21518,6 +21591,84 @@ function promptInput(prompt) {
21518
21591
  }
21519
21592
  return input2;
21520
21593
  }
21594
+ function modelValues(models) {
21595
+ return models.map((model) => ({
21596
+ description: model.description ?? "",
21597
+ name: model.displayName ?? model.id,
21598
+ value: model.id
21599
+ }));
21600
+ }
21601
+ function effortValues(model) {
21602
+ return (model?.supportedReasoningEfforts ?? []).map((option) => ({
21603
+ description: option.description ?? "",
21604
+ name: capitalize(option.reasoningEffort),
21605
+ value: option.reasoningEffort
21606
+ }));
21607
+ }
21608
+ function modelSetting(models, currentValue) {
21609
+ const values = modelValues(models);
21610
+ const current = currentValue.length > 0 ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
21611
+ if (current.length === 0) {
21612
+ return null;
21613
+ }
21614
+ const options = values.some((value) => value.value === current) ? values : [{ description: "", name: current, value: current }, ...values];
21615
+ return {
21616
+ category: "model",
21617
+ currentValue: current,
21618
+ description: "Model Codex uses for the session",
21619
+ id: MODEL_SETTING_ID,
21620
+ name: "Model",
21621
+ options,
21622
+ type: "select"
21623
+ };
21624
+ }
21625
+ function modeSetting(currentValue) {
21626
+ return {
21627
+ category: "mode",
21628
+ currentValue,
21629
+ description: "Approval and sandboxing preset for the session",
21630
+ id: MODE_SETTING_ID,
21631
+ name: "Mode",
21632
+ options: AGENT_MODES.map((mode) => ({
21633
+ description: mode.description,
21634
+ name: mode.name,
21635
+ value: mode.id
21636
+ })),
21637
+ type: "select"
21638
+ };
21639
+ }
21640
+ function fastModeSetting(model, enabled) {
21641
+ if (model?.additionalSpeedTiers?.includes(FAST_TIER) !== true) {
21642
+ return null;
21643
+ }
21644
+ return {
21645
+ category: "model_config",
21646
+ currentValue: enabled,
21647
+ description: "1.5x speed, increased usage",
21648
+ id: FAST_MODE_SETTING_ID,
21649
+ name: "Fast mode",
21650
+ type: "boolean"
21651
+ };
21652
+ }
21653
+ function effortSetting(model, currentValue) {
21654
+ const values = effortValues(model);
21655
+ if (values.length === 0) {
21656
+ return null;
21657
+ }
21658
+ const current = values.some((value) => value.value === currentValue) ? currentValue : values[0]?.value ?? "";
21659
+ if (current.length === 0) {
21660
+ return null;
21661
+ }
21662
+ return {
21663
+ category: "thought_level",
21664
+ currentValue: current,
21665
+ description: "How much reasoning effort the model should use",
21666
+ id: REASONING_EFFORT_SETTING_ID,
21667
+ name: "Reasoning effort",
21668
+ options: values,
21669
+ type: "select"
21670
+ };
21671
+ }
21521
21672
  function userInputSchema(questions) {
21522
21673
  const properties = {};
21523
21674
  const required2 = [];
@@ -21542,10 +21693,21 @@ var CodexAcpAgent = class {
21542
21693
  #app;
21543
21694
  #appServer;
21544
21695
  #connection = null;
21696
+ #models = [];
21545
21697
  #nativeSessionId = "";
21698
+ // Whether the current turn must carry a policy at all. Until the user picks a mode, Codex's own
21699
+ // configuration decides, so `turn/start` omits the fields and inherits what the host set up.
21700
+ #policySelected = false;
21701
+ #selection;
21546
21702
  #turn = null;
21547
21703
  #updateTail = Promise.resolve();
21548
21704
  constructor(options) {
21705
+ this.#selection = {
21706
+ effort: "",
21707
+ fastMode: false,
21708
+ mode: initialMode(options.environment),
21709
+ model: ""
21710
+ };
21549
21711
  this.#appServer = new CodexAppServerClient({
21550
21712
  command: options.command,
21551
21713
  cwd: options.cwd,
@@ -21579,7 +21741,18 @@ var CodexAcpAgent = class {
21579
21741
  )
21580
21742
  );
21581
21743
  this.#nativeSessionId = created.thread.id;
21582
- return { sessionId: created.thread.id };
21744
+ this.#selection = {
21745
+ ...this.#selection,
21746
+ effort: created.reasoningEffort ?? "",
21747
+ model: created.model ?? ""
21748
+ };
21749
+ return { configOptions: this.#configOptions(), sessionId: created.thread.id };
21750
+ }).onRequest(methods.agent.session.setConfigOption, async (context) => {
21751
+ this.#applySelection(context.params.configId, context.params.value);
21752
+ return { configOptions: this.#configOptions() };
21753
+ }).onRequest(methods.agent.session.setMode, async (context) => {
21754
+ this.#applySelection(MODE_SETTING_ID, context.params.modeId);
21755
+ return {};
21583
21756
  }).onRequest(methods.agent.session.prompt, async (context) => {
21584
21757
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
21585
21758
  }).onRequest(methods.agent.session.close, async () => {
@@ -21590,9 +21763,10 @@ var CodexAcpAgent = class {
21590
21763
  }
21591
21764
  /** The ACP agent app Mobius connects its own ACP client to, in-process. */
21592
21765
  app = () => this.#app;
21593
- /** Starts the app-server and performs its handshake. */
21766
+ /** Starts the app-server, performs its handshake, and reads the model catalog Codex offers. */
21594
21767
  initialize = async (signal) => {
21595
21768
  await this.#appServer.initialize(signal);
21769
+ await this.#loadModels(signal);
21596
21770
  };
21597
21771
  /**
21598
21772
  * Releases the app-server and every process it started. Mirrors the adapter path's teardown so a
@@ -21604,6 +21778,129 @@ var CodexAcpAgent = class {
21604
21778
  this.#appServer.detach();
21605
21779
  await stopProcessTree(child, captured);
21606
21780
  };
21781
+ /**
21782
+ * Reads the model catalog once per app-server. A failure leaves the catalog empty, which costs
21783
+ * the Run settings panel its model selector; it must not cost the conversation itself, so the
21784
+ * turn lifecycle continues without settings rather than failing initialization.
21785
+ */
21786
+ #loadModels = async (signal) => {
21787
+ const models = [];
21788
+ let cursor = null;
21789
+ try {
21790
+ do {
21791
+ const decoded = modelListResponseSchema.parse(
21792
+ await this.#appServer.request(
21793
+ "model/list",
21794
+ { cursor, limit: null },
21795
+ AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
21796
+ )
21797
+ );
21798
+ models.push(...decoded.data);
21799
+ cursor = decoded.nextCursor ?? null;
21800
+ } while (cursor !== null && models.length < MODEL_CATALOG_LIMIT);
21801
+ } catch (error62) {
21802
+ signal.throwIfAborted();
21803
+ process.stderr.write(`[codex-acp] model catalog unavailable: ${String(error62)}
21804
+ `);
21805
+ }
21806
+ this.#models = Object.freeze(models.slice(0, MODEL_CATALOG_LIMIT));
21807
+ };
21808
+ #model = (id) => this.#models.find((model) => model.id === id);
21809
+ /** The ACP settings Mobius discovers and renders in Run settings. */
21810
+ #configOptions = () => {
21811
+ const options = [];
21812
+ const model = modelSetting(this.#models, this.#selection.model);
21813
+ if (model !== null) {
21814
+ options.push(model);
21815
+ }
21816
+ const effort = effortSetting(this.#model(this.#selection.model), this.#selection.effort);
21817
+ if (effort !== null) {
21818
+ options.push(effort);
21819
+ }
21820
+ const fastMode = fastModeSetting(this.#model(this.#selection.model), this.#selection.fastMode);
21821
+ if (fastMode !== null) {
21822
+ options.push(fastMode);
21823
+ }
21824
+ options.push(modeSetting(this.#selection.mode));
21825
+ return options;
21826
+ };
21827
+ /**
21828
+ * Applies one `session/set_config_option`. Switching models re-resolves the effort the way Codex
21829
+ * does — the current effort when the new model supports it, otherwise the model's own default —
21830
+ * so the reply never advertises an effort the selected model cannot run.
21831
+ */
21832
+ #applySelection = (configId, value) => {
21833
+ if (configId === FAST_MODE_SETTING_ID) {
21834
+ if (typeof value !== "boolean") {
21835
+ throw new AcpExecutionError(
21836
+ "The requested Codex setting is invalid",
21837
+ {},
21838
+ "invalid_session_configuration"
21839
+ );
21840
+ }
21841
+ if (value && this.#model(this.#selection.model)?.additionalSpeedTiers?.includes(FAST_TIER) !== true) {
21842
+ throw new AcpExecutionError(
21843
+ "The selected Codex model has no fast mode",
21844
+ {},
21845
+ "invalid_session_configuration"
21846
+ );
21847
+ }
21848
+ this.#selection = { ...this.#selection, fastMode: value };
21849
+ return;
21850
+ }
21851
+ if (typeof value !== "string") {
21852
+ throw new AcpExecutionError("The requested Codex setting is invalid", {}, "invalid_session_configuration");
21853
+ }
21854
+ if (configId === MODE_SETTING_ID) {
21855
+ if (!AGENT_MODES.some((mode) => mode.id === value)) {
21856
+ throw new AcpExecutionError(
21857
+ "The requested Codex mode is unavailable",
21858
+ {},
21859
+ "invalid_session_configuration"
21860
+ );
21861
+ }
21862
+ this.#selection = { ...this.#selection, mode: value };
21863
+ this.#policySelected = true;
21864
+ return;
21865
+ }
21866
+ if (configId === MODEL_SETTING_ID) {
21867
+ if (value === this.#selection.model) {
21868
+ return;
21869
+ }
21870
+ const model = this.#model(value);
21871
+ if (model === void 0) {
21872
+ throw new AcpExecutionError(
21873
+ "The requested Codex model is unavailable",
21874
+ {},
21875
+ "invalid_session_configuration"
21876
+ );
21877
+ }
21878
+ const supported = (model.supportedReasoningEfforts ?? []).map((option) => option.reasoningEffort);
21879
+ const effort = supported.includes(this.#selection.effort) ? this.#selection.effort : model.defaultReasoningEffort ?? supported[0] ?? "";
21880
+ this.#selection = {
21881
+ ...this.#selection,
21882
+ effort,
21883
+ fastMode: this.#selection.fastMode && model.additionalSpeedTiers?.includes(FAST_TIER) === true,
21884
+ model: value
21885
+ };
21886
+ return;
21887
+ }
21888
+ if (configId === REASONING_EFFORT_SETTING_ID) {
21889
+ const supported = (this.#model(this.#selection.model)?.supportedReasoningEfforts ?? []).map(
21890
+ (option) => option.reasoningEffort
21891
+ );
21892
+ if (!supported.includes(value)) {
21893
+ throw new AcpExecutionError(
21894
+ "The requested Codex reasoning effort is unavailable",
21895
+ {},
21896
+ "invalid_session_configuration"
21897
+ );
21898
+ }
21899
+ this.#selection = { ...this.#selection, effort: value };
21900
+ return;
21901
+ }
21902
+ throw new AcpExecutionError("The requested Codex setting is unavailable", {}, "invalid_session_configuration");
21903
+ };
21607
21904
  #emit = async (update) => {
21608
21905
  const connection = this.#connection;
21609
21906
  if (connection === null || this.#nativeSessionId.length === 0) {
@@ -21809,10 +22106,27 @@ var CodexAcpAgent = class {
21809
22106
  const turn = { completion, turn: { id: "" } };
21810
22107
  this.#turn = turn;
21811
22108
  try {
22109
+ const selection = this.#selection;
22110
+ const mode = AGENT_MODES.find((candidate) => candidate.id === selection.mode) ?? DEFAULT_MODE;
22111
+ const supportsFast = this.#model(selection.model)?.additionalSpeedTiers?.includes(FAST_TIER) === true;
21812
22112
  const started = turnSchema.parse(
21813
22113
  (await this.#appServer.request(
21814
22114
  "turn/start",
21815
- { input: input2, threadId: this.#nativeSessionId },
22115
+ {
22116
+ // Until a mode is chosen, `config.toml` decides the sandbox and approval
22117
+ // policy, and those fields stay off the turn so the host's own setup is
22118
+ // inherited rather than overridden.
22119
+ ...this.#policySelected ? {
22120
+ approvalPolicy: mode.approvalPolicy,
22121
+ approvalsReviewer: mode.approvalsReviewer,
22122
+ sandboxPolicy: mode.sandboxPolicy
22123
+ } : {},
22124
+ ...selection.effort.length === 0 ? {} : { effort: selection.effort },
22125
+ input: input2,
22126
+ ...selection.model.length === 0 ? {} : { model: selection.model },
22127
+ ...selection.fastMode && supportsFast ? { serviceTier: SERVICE_TIER_FAST } : {},
22128
+ threadId: this.#nativeSessionId
22129
+ },
21816
22130
  signal
21817
22131
  )).turn
21818
22132
  );
@@ -24832,6 +25146,26 @@ var nativeSessionTurnForkCommandSchema = external_exports.strictObject({
24832
25146
  messageOccurrence: external_exports.number().int().positive(),
24833
25147
  title: external_exports.string().max(500)
24834
25148
  }).readonly();
25149
+ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
25150
+ external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
25151
+ external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
25152
+ external_exports.strictObject({
25153
+ ...identity,
25154
+ action: external_exports.literal("list"),
25155
+ cursor: identifier.nullable()
25156
+ }).readonly(),
25157
+ external_exports.strictObject({
25158
+ ...identity,
25159
+ action: external_exports.enum(["import", "fork"]),
25160
+ entryId: identifier,
25161
+ targetSessionId: identifier
25162
+ }).readonly(),
25163
+ external_exports.strictObject({
25164
+ ...identity,
25165
+ action: external_exports.literal("delete"),
25166
+ entryId: identifier
25167
+ }).readonly()
25168
+ ]);
24835
25169
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
24836
25170
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
24837
25171
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -24846,6 +25180,12 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
24846
25180
  entryId: identifier,
24847
25181
  targetSessionId: identifier
24848
25182
  }).readonly(),
25183
+ external_exports.strictObject({
25184
+ ...identity,
25185
+ action: external_exports.enum(["import-only", "fork-only"]),
25186
+ entryId: identifier,
25187
+ targetSessionId: identifier
25188
+ }).readonly(),
24849
25189
  external_exports.strictObject({
24850
25190
  ...identity,
24851
25191
  action: external_exports.literal("delete"),
@@ -34220,6 +34560,15 @@ var MAX_PRE_SESSION_UPDATES = 100;
34220
34560
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
34221
34561
  var SESSION_CONTROL_COMMAND_ID = "session-control";
34222
34562
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
34563
+ function nativeHistoryNotRetained() {
34564
+ return {
34565
+ cause: {
34566
+ code: "native_history_not_retained",
34567
+ message: "Native message history is not retained in the cloud for this Session."
34568
+ },
34569
+ status: "unavailable"
34570
+ };
34571
+ }
34223
34572
  var NullAcpSessionObserver = class {
34224
34573
  onCommands = () => Promise.resolve();
34225
34574
  onConfig = () => Promise.resolve();
@@ -36885,7 +37234,7 @@ var AcpSessionManager = class {
36885
37234
  this.#endSessionUse(options.sessionId);
36886
37235
  }
36887
37236
  };
36888
- openNativeSession = async (options, origin) => {
37237
+ openNativeSession = async (options, origin, loadHistory) => {
36889
37238
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
36890
37239
  if (this.#nativeOperations.has(key)) {
36891
37240
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
@@ -36915,7 +37264,7 @@ var AcpSessionManager = class {
36915
37264
  }
36916
37265
  this.#nativeOperations.add(key);
36917
37266
  try {
36918
- const history = await runtime.loadHistory(options.signal);
37267
+ const history = loadHistory ? await runtime.loadHistory(options.signal) : nativeHistoryNotRetained();
36919
37268
  return {
36920
37269
  prepared: runtime.prepared(),
36921
37270
  sessionId: existing.sessionId,
@@ -36946,7 +37295,7 @@ var AcpSessionManager = class {
36946
37295
  const openedKey = `${options.agent.id}:${runtime.nativeSessionId()}`;
36947
37296
  this.#nativeOperations.add(openedKey);
36948
37297
  try {
36949
- const history = await runtime.loadHistory(options.signal);
37298
+ const history = loadHistory ? await runtime.loadHistory(options.signal) : nativeHistoryNotRetained();
36950
37299
  return {
36951
37300
  sessionId: options.sessionId,
36952
37301
  prepared: runtime.prepared(),
@@ -38096,6 +38445,54 @@ var WorkspaceDirectoryService = class {
38096
38445
  };
38097
38446
  };
38098
38447
 
38448
+ // src/daemon-diagnostic-log.ts
38449
+ import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
38450
+ import { join as join16 } from "node:path";
38451
+ var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
38452
+ var DaemonDiagnosticLog = class {
38453
+ #directory;
38454
+ #path;
38455
+ #maximumBytes;
38456
+ constructor(stateDirectory, maximumBytes = MAXIMUM_DAEMON_LOG_BYTES) {
38457
+ this.#directory = join16(stateDirectory, "logs");
38458
+ this.#path = join16(this.#directory, "daemon.log");
38459
+ this.#maximumBytes = maximumBytes;
38460
+ }
38461
+ record = (diagnostic) => {
38462
+ const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
38463
+ `;
38464
+ const encodedBytes = Buffer.byteLength(encoded);
38465
+ mkdirSync3(this.#directory, { mode: 448, recursive: true });
38466
+ let existingBytes = 0;
38467
+ try {
38468
+ existingBytes = statSync3(this.#path).size;
38469
+ } catch (cause) {
38470
+ if (!(cause instanceof Error && Reflect.get(cause, "code") === "ENOENT")) {
38471
+ throw cause;
38472
+ }
38473
+ }
38474
+ if (existingBytes + encodedBytes <= this.#maximumBytes) {
38475
+ appendFileSync(this.#path, encoded, { encoding: "utf8", mode: 384 });
38476
+ return;
38477
+ }
38478
+ const lines = `${existingBytes === 0 ? "" : readFileSync2(this.#path, "utf8")}${encoded}`.split("\n").filter((line) => line.length > 0);
38479
+ let totalBytes = lines.reduce((total, line) => total + Buffer.byteLength(line) + 1, 0);
38480
+ while (totalBytes > this.#maximumBytes && lines.length > 0) {
38481
+ const oldest = lines.shift();
38482
+ if (oldest !== void 0) {
38483
+ totalBytes -= Buffer.byteLength(oldest) + 1;
38484
+ }
38485
+ }
38486
+ const temporaryPath = `${this.#path}.tmp`;
38487
+ writeFileSync(temporaryPath, lines.length === 0 ? "" : `${lines.join("\n")}
38488
+ `, {
38489
+ encoding: "utf8",
38490
+ mode: 384
38491
+ });
38492
+ renameSync(temporaryPath, this.#path);
38493
+ };
38494
+ };
38495
+
38099
38496
  // src/native-sessions/codex-history.ts
38100
38497
  import { spawn as spawn5 } from "node:child_process";
38101
38498
  var responseSchema = external_exports.union([
@@ -38682,10 +39079,11 @@ var NativeSessionService = class {
38682
39079
  deletedSessionIds
38683
39080
  };
38684
39081
  }
38685
- if (command.action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession) {
39082
+ const action = command.action === "import-only" ? "import" : command.action === "fork-only" ? "fork" : command.action;
39083
+ if (action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession) {
38686
39084
  throw new AcpExecutionError("This Agent cannot import native sessions", {}, "native_session_unsupported");
38687
39085
  }
38688
- if (command.action === "fork" && !prepared.capabilities.unstableForkSession) {
39086
+ if (action === "fork" && !prepared.capabilities.unstableForkSession) {
38689
39087
  throw new AcpExecutionError(
38690
39088
  "This Agent does not support session forking",
38691
39089
  {},
@@ -38706,7 +39104,8 @@ var NativeSessionService = class {
38706
39104
  sessionId: command.targetSessionId,
38707
39105
  additionalDirectories: target.additionalDirectories
38708
39106
  },
38709
- { kind: command.action, nativeSessionId: target.info.sessionId }
39107
+ { kind: action, nativeSessionId: target.info.sessionId },
39108
+ command.action !== "import-only" && command.action !== "fork-only"
38710
39109
  );
38711
39110
  signal.throwIfAborted();
38712
39111
  const ready = {
@@ -38724,10 +39123,10 @@ var NativeSessionService = class {
38724
39123
  restored: true,
38725
39124
  sessionId: opened.sessionId
38726
39125
  };
38727
- this.record(command, command.action === "fork" ? "native_session_forked" : "native_session_imported");
39126
+ this.record(command, action === "fork" ? "native_session_forked" : "native_session_imported");
38728
39127
  return {
38729
39128
  ...envelope2,
38730
- action: command.action,
39129
+ action,
38731
39130
  ready,
38732
39131
  targetSessionId: command.targetSessionId,
38733
39132
  title: target.info.title ?? "Untitled session",
@@ -39327,13 +39726,15 @@ function addFailureDetails(details, failure2) {
39327
39726
  var RelayConnectionDiagnostics = class {
39328
39727
  #audit;
39329
39728
  #channelId;
39729
+ #localLog;
39330
39730
  #lastClosedEpoch = 0;
39331
39731
  #lastFailedEpoch = 0;
39332
39732
  #relayOrigin;
39333
39733
  #route;
39334
- constructor(audit, channelId, relayUrl) {
39734
+ constructor(audit, channelId, relayUrl, localLog) {
39335
39735
  this.#audit = audit;
39336
39736
  this.#channelId = channelId;
39737
+ this.#localLog = localLog;
39337
39738
  this.#relayOrigin = relayUrl.origin;
39338
39739
  this.#route = describeEnvironmentProxyRoute(relayUrl);
39339
39740
  }
@@ -39420,6 +39821,20 @@ var RelayConnectionDiagnostics = class {
39420
39821
  true
39421
39822
  );
39422
39823
  };
39824
+ daemonDiagnostic = (event, requestId, details, failure2) => {
39825
+ const recordedDetails = { ...details };
39826
+ if (failure2 !== void 0) {
39827
+ addFailureDetails(recordedDetails, failure2);
39828
+ }
39829
+ this.#localLog.record(
39830
+ `Mobius daemon diagnostic ${JSON.stringify({
39831
+ channelId: this.#channelId,
39832
+ event,
39833
+ requestId,
39834
+ ...recordedDetails
39835
+ })}`
39836
+ );
39837
+ };
39423
39838
  #record = (event, commandId, details, warning) => {
39424
39839
  this.#audit.record({
39425
39840
  commandId,
@@ -39428,6 +39843,7 @@ var RelayConnectionDiagnostics = class {
39428
39843
  sessionId: this.#channelId
39429
39844
  });
39430
39845
  const encoded = JSON.stringify({ channelId: this.#channelId, event, ...details });
39846
+ this.#localLog.record(`Mobius relay diagnostic ${encoded}`);
39431
39847
  if (warning) {
39432
39848
  process.stderr.write(`Mobius relay diagnostic ${encoded}
39433
39849
  `);
@@ -39545,7 +39961,7 @@ var RelayConnectionLiveness = class {
39545
39961
  };
39546
39962
 
39547
39963
  // src/relay-connection/session-event-outbox.ts
39548
- import { mkdirSync as mkdirSync3 } from "node:fs";
39964
+ import { mkdirSync as mkdirSync4 } from "node:fs";
39549
39965
  import { dirname as dirname6 } from "node:path";
39550
39966
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
39551
39967
  var DEFAULT_OUTBOX_LIMITS = {
@@ -39612,7 +40028,7 @@ var SessionEventOutbox = class {
39612
40028
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
39613
40029
  validateLimits(limits);
39614
40030
  this.#limits = limits;
39615
- mkdirSync3(dirname6(path2), { recursive: true });
40031
+ mkdirSync4(dirname6(path2), { recursive: true });
39616
40032
  this.#database = new DatabaseSync3(path2);
39617
40033
  this.#database.exec(`
39618
40034
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -42076,6 +42492,11 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42076
42492
  event: "agent_settings_model_unsupported",
42077
42493
  sessionId: `agent-settings:${command2.agentId}`
42078
42494
  });
42495
+ diagnostics.daemonDiagnostic(
42496
+ "agent_settings_model_unsupported",
42497
+ command2.requestId,
42498
+ details
42499
+ );
42079
42500
  process.stderr.write(
42080
42501
  `Mobius daemon diagnostic ${JSON.stringify({ event: "agent_settings_model_unsupported", requestId: command2.requestId, ...details })}
42081
42502
  `
@@ -42106,6 +42527,12 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42106
42527
  event: "agent_settings_discovery_failed",
42107
42528
  sessionId: `agent-settings:${command2.agentId}`
42108
42529
  });
42530
+ diagnostics.daemonDiagnostic(
42531
+ "agent_settings_discovery_failed",
42532
+ command2.requestId,
42533
+ details,
42534
+ failure2
42535
+ );
42109
42536
  if (failure2 instanceof AcpConfigurationValueUnavailableError) {
42110
42537
  process.stderr.write(
42111
42538
  `Mobius daemon diagnostic ${JSON.stringify({ event: "agent_settings_discovery_failed", requestId: command2.requestId, ...details })}
@@ -42183,6 +42610,12 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42183
42610
  event: "agent_catalog_refresh_failed",
42184
42611
  sessionId: "agent-catalog"
42185
42612
  });
42613
+ diagnostics.daemonDiagnostic(
42614
+ "agent_catalog_refresh_failed",
42615
+ command2.requestId,
42616
+ { code: operationErrorCode(failure2) },
42617
+ failure2
42618
+ );
42186
42619
  if (socket.readyState === WebSocket2.OPEN) {
42187
42620
  send(socket, {
42188
42621
  code: operationErrorCode(failure2),
@@ -42267,6 +42700,17 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42267
42700
  event: "native_session_operation_failed",
42268
42701
  details: { code: operationErrorCode(failure2) }
42269
42702
  });
42703
+ diagnostics.daemonDiagnostic(
42704
+ "native_session_operation_failed",
42705
+ command2.requestId,
42706
+ {
42707
+ action: command2.action,
42708
+ agentId: command2.agentId,
42709
+ code: operationErrorCode(failure2),
42710
+ sessionId: command2.sessionId
42711
+ },
42712
+ failure2
42713
+ );
42270
42714
  reportOperationFailure(socket, command2.requestId, command2.sessionId, failure2);
42271
42715
  } finally {
42272
42716
  timeout.cancel();
@@ -42347,6 +42791,16 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42347
42791
  event: "native_session_turn_fork_failed",
42348
42792
  sessionId: command2.sessionId
42349
42793
  });
42794
+ diagnostics.daemonDiagnostic(
42795
+ "native_session_turn_fork_failed",
42796
+ command2.requestId,
42797
+ {
42798
+ agentId: command2.agentId,
42799
+ code: operationErrorCode(failure2),
42800
+ sessionId: command2.sessionId
42801
+ },
42802
+ failure2
42803
+ );
42350
42804
  reportOperationFailure(socket, command2.requestId, command2.sessionId, failure2);
42351
42805
  } finally {
42352
42806
  timeout.cancel();
@@ -42619,7 +43073,12 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
42619
43073
  });
42620
43074
  const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
42621
43075
  const installationObserver = new DaemonInstallationObserver();
42622
- const diagnostics = new RelayConnectionDiagnostics(audit, config2.channelId, config2.relayUrl);
43076
+ const diagnostics = new RelayConnectionDiagnostics(
43077
+ audit,
43078
+ config2.channelId,
43079
+ config2.relayUrl,
43080
+ new DaemonDiagnosticLog(stateDirectory)
43081
+ );
42623
43082
  const nativeSessions = new NativeSessionService(config2, directories, sessions, audit);
42624
43083
  const installations = new AgentInstallationManager(
42625
43084
  specifications,
@@ -42759,7 +43218,7 @@ import { fetch as fetch5 } from "undici";
42759
43218
  // src/storage/runtime-installation-store.ts
42760
43219
  import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
42761
43220
  import { mkdir as mkdir4, open as open5, rename as rename3, unlink, writeFile as writeFile3 } from "node:fs/promises";
42762
- import { dirname as dirname7, join as join16, resolve as resolve5 } from "node:path";
43221
+ import { dirname as dirname7, join as join17, resolve as resolve5 } from "node:path";
42763
43222
  var APPLICATION_ID_PATTERN = /^[a-z][a-z0-9]*(?:[.-][a-z0-9]+){1,31}$/;
42764
43223
  var CONNECTION_ID_PATTERN = /^mcn_[a-f0-9]{32}$/;
42765
43224
  var INSTALLATION_ID_PATTERN = /^min_[a-f0-9]{32}$/;
@@ -43059,7 +43518,7 @@ async function readJsonFile(path2, signal, missingCode) {
43059
43518
  async function writeJsonAtomically(path2, value, signal) {
43060
43519
  signal.throwIfAborted();
43061
43520
  const directory = dirname7(path2);
43062
- const temporaryPath = join16(directory, `.${randomUUID4()}.tmp`);
43521
+ const temporaryPath = join17(directory, `.${randomUUID4()}.tmp`);
43063
43522
  try {
43064
43523
  await mkdir4(directory, { mode: 448, recursive: true });
43065
43524
  signal.throwIfAborted();
@@ -43085,14 +43544,14 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
43085
43544
  this.applicationId = applicationId;
43086
43545
  this.installationId = installationId2;
43087
43546
  this.stateDirectory = stateDirectory;
43088
- this.#channelDirectory = join16(stateDirectory, "channels");
43089
- this.#connectionDirectory = join16(stateDirectory, "connections");
43547
+ this.#channelDirectory = join17(stateDirectory, "channels");
43548
+ this.#connectionDirectory = join17(stateDirectory, "connections");
43090
43549
  }
43091
43550
  static open = async (options, signal) => {
43092
43551
  signal.throwIfAborted();
43093
43552
  const applicationId = validateApplicationId(options.applicationId);
43094
43553
  const rootDirectory = resolve5(options.stateDirectory);
43095
- const applicationDirectory = join16(rootDirectory, "installations", applicationId);
43554
+ const applicationDirectory = join17(rootDirectory, "installations", applicationId);
43096
43555
  try {
43097
43556
  await mkdir4(applicationDirectory, { mode: 448, recursive: true });
43098
43557
  } catch (cause) {
@@ -43105,7 +43564,7 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
43105
43564
  );
43106
43565
  }
43107
43566
  const storedInstallationId = await readOrCreateInstallationId(applicationDirectory, signal);
43108
- const stateDirectory = join16(applicationDirectory, storedInstallationId);
43567
+ const stateDirectory = join17(applicationDirectory, storedInstallationId);
43109
43568
  try {
43110
43569
  await mkdir4(stateDirectory, { mode: 448, recursive: true });
43111
43570
  } catch (cause) {
@@ -43120,9 +43579,9 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
43120
43579
  signal.throwIfAborted();
43121
43580
  return new _RuntimeInstallationStore(applicationId, storedInstallationId, stateDirectory);
43122
43581
  };
43123
- connectionPath = (connectionId2) => join16(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
43124
- auditDatabasePath = (connectionId2) => join16(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
43125
- channelIndexPath = (channelId) => join16(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
43582
+ connectionPath = (connectionId2) => join17(this.#connectionDirectory, `${validateConnectionId(connectionId2)}.json`);
43583
+ auditDatabasePath = (connectionId2) => join17(this.stateDirectory, "audit", `${validateConnectionId(connectionId2)}.sqlite`);
43584
+ channelIndexPath = (channelId) => join17(this.#channelDirectory, channelIndexFileName(validateIdentifier(channelId, "invalid_channel_id")));
43126
43585
  readConnection = async (connectionId2, signal) => {
43127
43586
  const stored = decodeConnection(
43128
43587
  await readJsonFile(this.connectionPath(connectionId2), signal, "connection_not_found")
@@ -43174,7 +43633,7 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
43174
43633
  };
43175
43634
  importLegacyConnection = async (legacyStateDirectory, channelId, signal) => {
43176
43635
  const normalizedChannelId = validateIdentifier(channelId, "invalid_channel_id");
43177
- const legacyPath = join16(resolve5(legacyStateDirectory), "connections", `${normalizedChannelId}.json`);
43636
+ const legacyPath = join17(resolve5(legacyStateDirectory), "connections", `${normalizedChannelId}.json`);
43178
43637
  const legacy = decodeLegacyConnection(
43179
43638
  await readJsonFile(legacyPath, signal, "connection_not_found"),
43180
43639
  normalizedChannelId
@@ -43253,7 +43712,7 @@ var RuntimeInstallationStore = class _RuntimeInstallationStore {
43253
43712
  };
43254
43713
  };
43255
43714
  async function readOrCreateInstallationId(applicationDirectory, signal) {
43256
- const pointerPath = join16(applicationDirectory, "current.json");
43715
+ const pointerPath = join17(applicationDirectory, "current.json");
43257
43716
  try {
43258
43717
  return decodeInstallationPointer(await readJsonFile(pointerPath, signal, "installation_not_found")).installationId;
43259
43718
  } catch (cause) {
@@ -43574,7 +44033,7 @@ function loadMobiusRuntimeConnection(environment = process.env) {
43574
44033
  throw new MobiusRuntimeConfigurationError("MOBIUS_CHANNEL_ID is invalid");
43575
44034
  }
43576
44035
  return Object.freeze({
43577
- auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join17(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
44036
+ auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join18(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
43578
44037
  channelId,
43579
44038
  defaultWorkspace: loadDefaultWorkspace(environment),
43580
44039
  relayUrl: requiredEnvironmentValue(environment, "MOBIUS_RELAY_URL"),