@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/cli.js CHANGED
@@ -11,7 +11,7 @@ import { mkdir as mkdir6 } from "node:fs/promises";
11
11
  // package.json
12
12
  var package_default = {
13
13
  name: "@moxt-ai/mobius",
14
- version: "0.0.72",
14
+ version: "0.0.73",
15
15
  description: "Mobius CLI for pairing and running local AI agent services.",
16
16
  type: "module",
17
17
  bin: {
@@ -21268,8 +21268,31 @@ var mcpElicitationParamsSchema = external_exports.object({
21268
21268
  url: external_exports.string().optional()
21269
21269
  });
21270
21270
  var threadStartResponseSchema = external_exports.object({
21271
+ approvalPolicy: external_exports.unknown().optional(),
21272
+ approvalsReviewer: external_exports.unknown().optional(),
21273
+ model: boundedText(256).nullish(),
21274
+ reasoningEffort: boundedText(256).nullish(),
21275
+ sandbox: external_exports.unknown().optional(),
21276
+ serviceTier: boundedText(256).nullish(),
21271
21277
  thread: external_exports.object({ id: boundedText(256) })
21272
21278
  });
21279
+ var reasoningEffortOptionSchema = external_exports.object({
21280
+ description: boundedText(4096).nullish(),
21281
+ reasoningEffort: boundedText(256)
21282
+ });
21283
+ var modelSchema = external_exports.object({
21284
+ additionalSpeedTiers: external_exports.array(boundedText(256)).max(100).nullish(),
21285
+ defaultReasoningEffort: boundedText(256).nullish(),
21286
+ description: boundedText(4096).nullish(),
21287
+ displayName: boundedText(256).nullish(),
21288
+ id: boundedText(256),
21289
+ isDefault: external_exports.boolean().nullish(),
21290
+ supportedReasoningEfforts: external_exports.array(reasoningEffortOptionSchema).max(100).nullish()
21291
+ });
21292
+ var modelListResponseSchema = external_exports.object({
21293
+ data: external_exports.array(modelSchema).max(1e3),
21294
+ nextCursor: boundedText(1024).nullish()
21295
+ });
21273
21296
 
21274
21297
  // src/acp/codex/app-server-client.ts
21275
21298
  var INITIALIZE_TIMEOUT_MILLISECONDS = 3e4;
@@ -21609,6 +21632,56 @@ function agentMessageMeta(phase) {
21609
21632
  var APPROVAL_REASON_CHARACTER_LIMIT = 500;
21610
21633
  var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
21611
21634
  var CODEX_AGENT_VERSION = "0.154.0";
21635
+ var MODEL_SETTING_ID = "model";
21636
+ var REASONING_EFFORT_SETTING_ID = "reasoning_effort";
21637
+ var MODE_SETTING_ID = "mode";
21638
+ var FAST_MODE_SETTING_ID = "fast-mode";
21639
+ var MODEL_CATALOG_LIMIT = 1e3;
21640
+ var FAST_TIER = "fast";
21641
+ var SERVICE_TIER_FAST = "priority";
21642
+ var WORKSPACE_WRITE_POLICY = Object.freeze({
21643
+ excludeSlashTmp: false,
21644
+ excludeTmpdirEnvVar: false,
21645
+ networkAccess: false,
21646
+ type: "workspaceWrite",
21647
+ writableRoots: []
21648
+ });
21649
+ var READ_ONLY_MODE = Object.freeze({
21650
+ approvalPolicy: "on-request",
21651
+ approvalsReviewer: "user",
21652
+ description: "Always ask to edit external files and use the internet",
21653
+ id: "read-only",
21654
+ name: "Ask for approval",
21655
+ sandboxPolicy: WORKSPACE_WRITE_POLICY
21656
+ });
21657
+ var AGENT_MODE = Object.freeze({
21658
+ approvalPolicy: "on-request",
21659
+ approvalsReviewer: "auto_review",
21660
+ description: "Only ask for actions detected as potentially unsafe",
21661
+ id: "agent",
21662
+ name: "Approve for me",
21663
+ sandboxPolicy: WORKSPACE_WRITE_POLICY
21664
+ });
21665
+ var FULL_ACCESS_MODE = Object.freeze({
21666
+ approvalPolicy: "never",
21667
+ approvalsReviewer: "user",
21668
+ description: "Unrestricted access to the internet and any file on your computer",
21669
+ id: "agent-full-access",
21670
+ name: "Full access",
21671
+ sandboxPolicy: { type: "dangerFullAccess" }
21672
+ });
21673
+ var AGENT_MODES = Object.freeze([READ_ONLY_MODE, AGENT_MODE, FULL_ACCESS_MODE]);
21674
+ var DEFAULT_MODE = AGENT_MODE;
21675
+ function initialMode(environment) {
21676
+ const requested = environment["INITIAL_AGENT_MODE"];
21677
+ if (requested === void 0) {
21678
+ return DEFAULT_MODE.id;
21679
+ }
21680
+ return AGENT_MODES.some((mode) => mode.id === requested) ? requested : DEFAULT_MODE.id;
21681
+ }
21682
+ function capitalize(value) {
21683
+ return value.length === 0 ? value : value.charAt(0).toUpperCase() + value.slice(1);
21684
+ }
21612
21685
  var APPROVAL_OPTIONS = Object.freeze([
21613
21686
  { kind: "allow_once", name: "Allow once", optionId: "accept" },
21614
21687
  { kind: "allow_always", name: "Allow for this session", optionId: "acceptForSession" },
@@ -21646,6 +21719,84 @@ function promptInput(prompt) {
21646
21719
  }
21647
21720
  return input2;
21648
21721
  }
21722
+ function modelValues(models) {
21723
+ return models.map((model) => ({
21724
+ description: model.description ?? "",
21725
+ name: model.displayName ?? model.id,
21726
+ value: model.id
21727
+ }));
21728
+ }
21729
+ function effortValues(model) {
21730
+ return (model?.supportedReasoningEfforts ?? []).map((option) => ({
21731
+ description: option.description ?? "",
21732
+ name: capitalize(option.reasoningEffort),
21733
+ value: option.reasoningEffort
21734
+ }));
21735
+ }
21736
+ function modelSetting(models, currentValue) {
21737
+ const values = modelValues(models);
21738
+ const current = currentValue.length > 0 ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
21739
+ if (current.length === 0) {
21740
+ return null;
21741
+ }
21742
+ const options = values.some((value) => value.value === current) ? values : [{ description: "", name: current, value: current }, ...values];
21743
+ return {
21744
+ category: "model",
21745
+ currentValue: current,
21746
+ description: "Model Codex uses for the session",
21747
+ id: MODEL_SETTING_ID,
21748
+ name: "Model",
21749
+ options,
21750
+ type: "select"
21751
+ };
21752
+ }
21753
+ function modeSetting(currentValue) {
21754
+ return {
21755
+ category: "mode",
21756
+ currentValue,
21757
+ description: "Approval and sandboxing preset for the session",
21758
+ id: MODE_SETTING_ID,
21759
+ name: "Mode",
21760
+ options: AGENT_MODES.map((mode) => ({
21761
+ description: mode.description,
21762
+ name: mode.name,
21763
+ value: mode.id
21764
+ })),
21765
+ type: "select"
21766
+ };
21767
+ }
21768
+ function fastModeSetting(model, enabled) {
21769
+ if (model?.additionalSpeedTiers?.includes(FAST_TIER) !== true) {
21770
+ return null;
21771
+ }
21772
+ return {
21773
+ category: "model_config",
21774
+ currentValue: enabled,
21775
+ description: "1.5x speed, increased usage",
21776
+ id: FAST_MODE_SETTING_ID,
21777
+ name: "Fast mode",
21778
+ type: "boolean"
21779
+ };
21780
+ }
21781
+ function effortSetting(model, currentValue) {
21782
+ const values = effortValues(model);
21783
+ if (values.length === 0) {
21784
+ return null;
21785
+ }
21786
+ const current = values.some((value) => value.value === currentValue) ? currentValue : values[0]?.value ?? "";
21787
+ if (current.length === 0) {
21788
+ return null;
21789
+ }
21790
+ return {
21791
+ category: "thought_level",
21792
+ currentValue: current,
21793
+ description: "How much reasoning effort the model should use",
21794
+ id: REASONING_EFFORT_SETTING_ID,
21795
+ name: "Reasoning effort",
21796
+ options: values,
21797
+ type: "select"
21798
+ };
21799
+ }
21649
21800
  function userInputSchema(questions) {
21650
21801
  const properties = {};
21651
21802
  const required2 = [];
@@ -21670,10 +21821,21 @@ var CodexAcpAgent = class {
21670
21821
  #app;
21671
21822
  #appServer;
21672
21823
  #connection = null;
21824
+ #models = [];
21673
21825
  #nativeSessionId = "";
21826
+ // Whether the current turn must carry a policy at all. Until the user picks a mode, Codex's own
21827
+ // configuration decides, so `turn/start` omits the fields and inherits what the host set up.
21828
+ #policySelected = false;
21829
+ #selection;
21674
21830
  #turn = null;
21675
21831
  #updateTail = Promise.resolve();
21676
21832
  constructor(options) {
21833
+ this.#selection = {
21834
+ effort: "",
21835
+ fastMode: false,
21836
+ mode: initialMode(options.environment),
21837
+ model: ""
21838
+ };
21677
21839
  this.#appServer = new CodexAppServerClient({
21678
21840
  command: options.command,
21679
21841
  cwd: options.cwd,
@@ -21707,7 +21869,18 @@ var CodexAcpAgent = class {
21707
21869
  )
21708
21870
  );
21709
21871
  this.#nativeSessionId = created.thread.id;
21710
- return { sessionId: created.thread.id };
21872
+ this.#selection = {
21873
+ ...this.#selection,
21874
+ effort: created.reasoningEffort ?? "",
21875
+ model: created.model ?? ""
21876
+ };
21877
+ return { configOptions: this.#configOptions(), sessionId: created.thread.id };
21878
+ }).onRequest(methods.agent.session.setConfigOption, async (context) => {
21879
+ this.#applySelection(context.params.configId, context.params.value);
21880
+ return { configOptions: this.#configOptions() };
21881
+ }).onRequest(methods.agent.session.setMode, async (context) => {
21882
+ this.#applySelection(MODE_SETTING_ID, context.params.modeId);
21883
+ return {};
21711
21884
  }).onRequest(methods.agent.session.prompt, async (context) => {
21712
21885
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
21713
21886
  }).onRequest(methods.agent.session.close, async () => {
@@ -21718,9 +21891,10 @@ var CodexAcpAgent = class {
21718
21891
  }
21719
21892
  /** The ACP agent app Mobius connects its own ACP client to, in-process. */
21720
21893
  app = () => this.#app;
21721
- /** Starts the app-server and performs its handshake. */
21894
+ /** Starts the app-server, performs its handshake, and reads the model catalog Codex offers. */
21722
21895
  initialize = async (signal) => {
21723
21896
  await this.#appServer.initialize(signal);
21897
+ await this.#loadModels(signal);
21724
21898
  };
21725
21899
  /**
21726
21900
  * Releases the app-server and every process it started. Mirrors the adapter path's teardown so a
@@ -21732,6 +21906,129 @@ var CodexAcpAgent = class {
21732
21906
  this.#appServer.detach();
21733
21907
  await stopProcessTree(child, captured);
21734
21908
  };
21909
+ /**
21910
+ * Reads the model catalog once per app-server. A failure leaves the catalog empty, which costs
21911
+ * the Run settings panel its model selector; it must not cost the conversation itself, so the
21912
+ * turn lifecycle continues without settings rather than failing initialization.
21913
+ */
21914
+ #loadModels = async (signal) => {
21915
+ const models = [];
21916
+ let cursor = null;
21917
+ try {
21918
+ do {
21919
+ const decoded = modelListResponseSchema.parse(
21920
+ await this.#appServer.request(
21921
+ "model/list",
21922
+ { cursor, limit: null },
21923
+ AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
21924
+ )
21925
+ );
21926
+ models.push(...decoded.data);
21927
+ cursor = decoded.nextCursor ?? null;
21928
+ } while (cursor !== null && models.length < MODEL_CATALOG_LIMIT);
21929
+ } catch (error62) {
21930
+ signal.throwIfAborted();
21931
+ process.stderr.write(`[codex-acp] model catalog unavailable: ${String(error62)}
21932
+ `);
21933
+ }
21934
+ this.#models = Object.freeze(models.slice(0, MODEL_CATALOG_LIMIT));
21935
+ };
21936
+ #model = (id) => this.#models.find((model) => model.id === id);
21937
+ /** The ACP settings Mobius discovers and renders in Run settings. */
21938
+ #configOptions = () => {
21939
+ const options = [];
21940
+ const model = modelSetting(this.#models, this.#selection.model);
21941
+ if (model !== null) {
21942
+ options.push(model);
21943
+ }
21944
+ const effort = effortSetting(this.#model(this.#selection.model), this.#selection.effort);
21945
+ if (effort !== null) {
21946
+ options.push(effort);
21947
+ }
21948
+ const fastMode = fastModeSetting(this.#model(this.#selection.model), this.#selection.fastMode);
21949
+ if (fastMode !== null) {
21950
+ options.push(fastMode);
21951
+ }
21952
+ options.push(modeSetting(this.#selection.mode));
21953
+ return options;
21954
+ };
21955
+ /**
21956
+ * Applies one `session/set_config_option`. Switching models re-resolves the effort the way Codex
21957
+ * does — the current effort when the new model supports it, otherwise the model's own default —
21958
+ * so the reply never advertises an effort the selected model cannot run.
21959
+ */
21960
+ #applySelection = (configId, value) => {
21961
+ if (configId === FAST_MODE_SETTING_ID) {
21962
+ if (typeof value !== "boolean") {
21963
+ throw new AcpExecutionError(
21964
+ "The requested Codex setting is invalid",
21965
+ {},
21966
+ "invalid_session_configuration"
21967
+ );
21968
+ }
21969
+ if (value && this.#model(this.#selection.model)?.additionalSpeedTiers?.includes(FAST_TIER) !== true) {
21970
+ throw new AcpExecutionError(
21971
+ "The selected Codex model has no fast mode",
21972
+ {},
21973
+ "invalid_session_configuration"
21974
+ );
21975
+ }
21976
+ this.#selection = { ...this.#selection, fastMode: value };
21977
+ return;
21978
+ }
21979
+ if (typeof value !== "string") {
21980
+ throw new AcpExecutionError("The requested Codex setting is invalid", {}, "invalid_session_configuration");
21981
+ }
21982
+ if (configId === MODE_SETTING_ID) {
21983
+ if (!AGENT_MODES.some((mode) => mode.id === value)) {
21984
+ throw new AcpExecutionError(
21985
+ "The requested Codex mode is unavailable",
21986
+ {},
21987
+ "invalid_session_configuration"
21988
+ );
21989
+ }
21990
+ this.#selection = { ...this.#selection, mode: value };
21991
+ this.#policySelected = true;
21992
+ return;
21993
+ }
21994
+ if (configId === MODEL_SETTING_ID) {
21995
+ if (value === this.#selection.model) {
21996
+ return;
21997
+ }
21998
+ const model = this.#model(value);
21999
+ if (model === void 0) {
22000
+ throw new AcpExecutionError(
22001
+ "The requested Codex model is unavailable",
22002
+ {},
22003
+ "invalid_session_configuration"
22004
+ );
22005
+ }
22006
+ const supported = (model.supportedReasoningEfforts ?? []).map((option) => option.reasoningEffort);
22007
+ const effort = supported.includes(this.#selection.effort) ? this.#selection.effort : model.defaultReasoningEffort ?? supported[0] ?? "";
22008
+ this.#selection = {
22009
+ ...this.#selection,
22010
+ effort,
22011
+ fastMode: this.#selection.fastMode && model.additionalSpeedTiers?.includes(FAST_TIER) === true,
22012
+ model: value
22013
+ };
22014
+ return;
22015
+ }
22016
+ if (configId === REASONING_EFFORT_SETTING_ID) {
22017
+ const supported = (this.#model(this.#selection.model)?.supportedReasoningEfforts ?? []).map(
22018
+ (option) => option.reasoningEffort
22019
+ );
22020
+ if (!supported.includes(value)) {
22021
+ throw new AcpExecutionError(
22022
+ "The requested Codex reasoning effort is unavailable",
22023
+ {},
22024
+ "invalid_session_configuration"
22025
+ );
22026
+ }
22027
+ this.#selection = { ...this.#selection, effort: value };
22028
+ return;
22029
+ }
22030
+ throw new AcpExecutionError("The requested Codex setting is unavailable", {}, "invalid_session_configuration");
22031
+ };
21735
22032
  #emit = async (update) => {
21736
22033
  const connection = this.#connection;
21737
22034
  if (connection === null || this.#nativeSessionId.length === 0) {
@@ -21937,10 +22234,27 @@ var CodexAcpAgent = class {
21937
22234
  const turn = { completion, turn: { id: "" } };
21938
22235
  this.#turn = turn;
21939
22236
  try {
22237
+ const selection = this.#selection;
22238
+ const mode = AGENT_MODES.find((candidate) => candidate.id === selection.mode) ?? DEFAULT_MODE;
22239
+ const supportsFast = this.#model(selection.model)?.additionalSpeedTiers?.includes(FAST_TIER) === true;
21940
22240
  const started = turnSchema.parse(
21941
22241
  (await this.#appServer.request(
21942
22242
  "turn/start",
21943
- { input: input2, threadId: this.#nativeSessionId },
22243
+ {
22244
+ // Until a mode is chosen, `config.toml` decides the sandbox and approval
22245
+ // policy, and those fields stay off the turn so the host's own setup is
22246
+ // inherited rather than overridden.
22247
+ ...this.#policySelected ? {
22248
+ approvalPolicy: mode.approvalPolicy,
22249
+ approvalsReviewer: mode.approvalsReviewer,
22250
+ sandboxPolicy: mode.sandboxPolicy
22251
+ } : {},
22252
+ ...selection.effort.length === 0 ? {} : { effort: selection.effort },
22253
+ input: input2,
22254
+ ...selection.model.length === 0 ? {} : { model: selection.model },
22255
+ ...selection.fastMode && supportsFast ? { serviceTier: SERVICE_TIER_FAST } : {},
22256
+ threadId: this.#nativeSessionId
22257
+ },
21944
22258
  signal
21945
22259
  )).turn
21946
22260
  );
@@ -24912,6 +25226,26 @@ var nativeSessionTurnForkCommandSchema = external_exports.strictObject({
24912
25226
  messageOccurrence: external_exports.number().int().positive(),
24913
25227
  title: external_exports.string().max(500)
24914
25228
  }).readonly();
25229
+ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
25230
+ external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
25231
+ external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
25232
+ external_exports.strictObject({
25233
+ ...identity,
25234
+ action: external_exports.literal("list"),
25235
+ cursor: identifier.nullable()
25236
+ }).readonly(),
25237
+ external_exports.strictObject({
25238
+ ...identity,
25239
+ action: external_exports.enum(["import", "fork"]),
25240
+ entryId: identifier,
25241
+ targetSessionId: identifier
25242
+ }).readonly(),
25243
+ external_exports.strictObject({
25244
+ ...identity,
25245
+ action: external_exports.literal("delete"),
25246
+ entryId: identifier
25247
+ }).readonly()
25248
+ ]);
24915
25249
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
24916
25250
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
24917
25251
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -24926,6 +25260,12 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
24926
25260
  entryId: identifier,
24927
25261
  targetSessionId: identifier
24928
25262
  }).readonly(),
25263
+ external_exports.strictObject({
25264
+ ...identity,
25265
+ action: external_exports.enum(["import-only", "fork-only"]),
25266
+ entryId: identifier,
25267
+ targetSessionId: identifier
25268
+ }).readonly(),
24929
25269
  external_exports.strictObject({
24930
25270
  ...identity,
24931
25271
  action: external_exports.literal("delete"),
@@ -35215,6 +35555,15 @@ var MAX_PRE_SESSION_UPDATES = 100;
35215
35555
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
35216
35556
  var SESSION_CONTROL_COMMAND_ID = "session-control";
35217
35557
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
35558
+ function nativeHistoryNotRetained() {
35559
+ return {
35560
+ cause: {
35561
+ code: "native_history_not_retained",
35562
+ message: "Native message history is not retained in the cloud for this Session."
35563
+ },
35564
+ status: "unavailable"
35565
+ };
35566
+ }
35218
35567
  var NullAcpSessionObserver = class {
35219
35568
  onCommands = () => Promise.resolve();
35220
35569
  onConfig = () => Promise.resolve();
@@ -37880,7 +38229,7 @@ var AcpSessionManager = class {
37880
38229
  this.#endSessionUse(options.sessionId);
37881
38230
  }
37882
38231
  };
37883
- openNativeSession = async (options, origin) => {
38232
+ openNativeSession = async (options, origin, loadHistory) => {
37884
38233
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
37885
38234
  if (this.#nativeOperations.has(key)) {
37886
38235
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
@@ -37910,7 +38259,7 @@ var AcpSessionManager = class {
37910
38259
  }
37911
38260
  this.#nativeOperations.add(key);
37912
38261
  try {
37913
- const history = await runtime.loadHistory(options.signal);
38262
+ const history = loadHistory ? await runtime.loadHistory(options.signal) : nativeHistoryNotRetained();
37914
38263
  return {
37915
38264
  prepared: runtime.prepared(),
37916
38265
  sessionId: existing.sessionId,
@@ -37941,7 +38290,7 @@ var AcpSessionManager = class {
37941
38290
  const openedKey = `${options.agent.id}:${runtime.nativeSessionId()}`;
37942
38291
  this.#nativeOperations.add(openedKey);
37943
38292
  try {
37944
- const history = await runtime.loadHistory(options.signal);
38293
+ const history = loadHistory ? await runtime.loadHistory(options.signal) : nativeHistoryNotRetained();
37945
38294
  return {
37946
38295
  sessionId: options.sessionId,
37947
38296
  prepared: runtime.prepared(),
@@ -39091,6 +39440,54 @@ var WorkspaceDirectoryService = class {
39091
39440
  };
39092
39441
  };
39093
39442
 
39443
+ // src/daemon-diagnostic-log.ts
39444
+ import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
39445
+ import { join as join17 } from "node:path";
39446
+ var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
39447
+ var DaemonDiagnosticLog = class {
39448
+ #directory;
39449
+ #path;
39450
+ #maximumBytes;
39451
+ constructor(stateDirectory, maximumBytes = MAXIMUM_DAEMON_LOG_BYTES) {
39452
+ this.#directory = join17(stateDirectory, "logs");
39453
+ this.#path = join17(this.#directory, "daemon.log");
39454
+ this.#maximumBytes = maximumBytes;
39455
+ }
39456
+ record = (diagnostic) => {
39457
+ const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
39458
+ `;
39459
+ const encodedBytes = Buffer.byteLength(encoded);
39460
+ mkdirSync3(this.#directory, { mode: 448, recursive: true });
39461
+ let existingBytes = 0;
39462
+ try {
39463
+ existingBytes = statSync3(this.#path).size;
39464
+ } catch (cause) {
39465
+ if (!(cause instanceof Error && Reflect.get(cause, "code") === "ENOENT")) {
39466
+ throw cause;
39467
+ }
39468
+ }
39469
+ if (existingBytes + encodedBytes <= this.#maximumBytes) {
39470
+ appendFileSync(this.#path, encoded, { encoding: "utf8", mode: 384 });
39471
+ return;
39472
+ }
39473
+ const lines = `${existingBytes === 0 ? "" : readFileSync2(this.#path, "utf8")}${encoded}`.split("\n").filter((line) => line.length > 0);
39474
+ let totalBytes = lines.reduce((total, line) => total + Buffer.byteLength(line) + 1, 0);
39475
+ while (totalBytes > this.#maximumBytes && lines.length > 0) {
39476
+ const oldest = lines.shift();
39477
+ if (oldest !== void 0) {
39478
+ totalBytes -= Buffer.byteLength(oldest) + 1;
39479
+ }
39480
+ }
39481
+ const temporaryPath = `${this.#path}.tmp`;
39482
+ writeFileSync(temporaryPath, lines.length === 0 ? "" : `${lines.join("\n")}
39483
+ `, {
39484
+ encoding: "utf8",
39485
+ mode: 384
39486
+ });
39487
+ renameSync(temporaryPath, this.#path);
39488
+ };
39489
+ };
39490
+
39094
39491
  // src/native-sessions/codex-history.ts
39095
39492
  import { spawn as spawn5 } from "node:child_process";
39096
39493
  var responseSchema = external_exports.union([
@@ -39677,10 +40074,11 @@ var NativeSessionService = class {
39677
40074
  deletedSessionIds
39678
40075
  };
39679
40076
  }
39680
- if (command.action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession) {
40077
+ const action = command.action === "import-only" ? "import" : command.action === "fork-only" ? "fork" : command.action;
40078
+ if (action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession) {
39681
40079
  throw new AcpExecutionError("This Agent cannot import native sessions", {}, "native_session_unsupported");
39682
40080
  }
39683
- if (command.action === "fork" && !prepared.capabilities.unstableForkSession) {
40081
+ if (action === "fork" && !prepared.capabilities.unstableForkSession) {
39684
40082
  throw new AcpExecutionError(
39685
40083
  "This Agent does not support session forking",
39686
40084
  {},
@@ -39701,7 +40099,8 @@ var NativeSessionService = class {
39701
40099
  sessionId: command.targetSessionId,
39702
40100
  additionalDirectories: target.additionalDirectories
39703
40101
  },
39704
- { kind: command.action, nativeSessionId: target.info.sessionId }
40102
+ { kind: action, nativeSessionId: target.info.sessionId },
40103
+ command.action !== "import-only" && command.action !== "fork-only"
39705
40104
  );
39706
40105
  signal.throwIfAborted();
39707
40106
  const ready = {
@@ -39719,10 +40118,10 @@ var NativeSessionService = class {
39719
40118
  restored: true,
39720
40119
  sessionId: opened.sessionId
39721
40120
  };
39722
- this.record(command, command.action === "fork" ? "native_session_forked" : "native_session_imported");
40121
+ this.record(command, action === "fork" ? "native_session_forked" : "native_session_imported");
39723
40122
  return {
39724
40123
  ...envelope2,
39725
- action: command.action,
40124
+ action,
39726
40125
  ready,
39727
40126
  targetSessionId: command.targetSessionId,
39728
40127
  title: target.info.title ?? "Untitled session",
@@ -40322,13 +40721,15 @@ function addFailureDetails(details, failure2) {
40322
40721
  var RelayConnectionDiagnostics = class {
40323
40722
  #audit;
40324
40723
  #channelId;
40724
+ #localLog;
40325
40725
  #lastClosedEpoch = 0;
40326
40726
  #lastFailedEpoch = 0;
40327
40727
  #relayOrigin;
40328
40728
  #route;
40329
- constructor(audit, channelId, relayUrl) {
40729
+ constructor(audit, channelId, relayUrl, localLog) {
40330
40730
  this.#audit = audit;
40331
40731
  this.#channelId = channelId;
40732
+ this.#localLog = localLog;
40332
40733
  this.#relayOrigin = relayUrl.origin;
40333
40734
  this.#route = describeEnvironmentProxyRoute(relayUrl);
40334
40735
  }
@@ -40415,6 +40816,20 @@ var RelayConnectionDiagnostics = class {
40415
40816
  true
40416
40817
  );
40417
40818
  };
40819
+ daemonDiagnostic = (event, requestId, details, failure2) => {
40820
+ const recordedDetails = { ...details };
40821
+ if (failure2 !== void 0) {
40822
+ addFailureDetails(recordedDetails, failure2);
40823
+ }
40824
+ this.#localLog.record(
40825
+ `Mobius daemon diagnostic ${JSON.stringify({
40826
+ channelId: this.#channelId,
40827
+ event,
40828
+ requestId,
40829
+ ...recordedDetails
40830
+ })}`
40831
+ );
40832
+ };
40418
40833
  #record = (event, commandId, details, warning) => {
40419
40834
  this.#audit.record({
40420
40835
  commandId,
@@ -40423,6 +40838,7 @@ var RelayConnectionDiagnostics = class {
40423
40838
  sessionId: this.#channelId
40424
40839
  });
40425
40840
  const encoded = JSON.stringify({ channelId: this.#channelId, event, ...details });
40841
+ this.#localLog.record(`Mobius relay diagnostic ${encoded}`);
40426
40842
  if (warning) {
40427
40843
  process.stderr.write(`Mobius relay diagnostic ${encoded}
40428
40844
  `);
@@ -40540,7 +40956,7 @@ var RelayConnectionLiveness = class {
40540
40956
  };
40541
40957
 
40542
40958
  // src/relay-connection/session-event-outbox.ts
40543
- import { mkdirSync as mkdirSync3 } from "node:fs";
40959
+ import { mkdirSync as mkdirSync4 } from "node:fs";
40544
40960
  import { dirname as dirname7 } from "node:path";
40545
40961
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
40546
40962
  var DEFAULT_OUTBOX_LIMITS = {
@@ -40607,7 +41023,7 @@ var SessionEventOutbox = class {
40607
41023
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
40608
41024
  validateLimits(limits);
40609
41025
  this.#limits = limits;
40610
- mkdirSync3(dirname7(path2), { recursive: true });
41026
+ mkdirSync4(dirname7(path2), { recursive: true });
40611
41027
  this.#database = new DatabaseSync3(path2);
40612
41028
  this.#database.exec(`
40613
41029
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -43071,6 +43487,11 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43071
43487
  event: "agent_settings_model_unsupported",
43072
43488
  sessionId: `agent-settings:${command2.agentId}`
43073
43489
  });
43490
+ diagnostics.daemonDiagnostic(
43491
+ "agent_settings_model_unsupported",
43492
+ command2.requestId,
43493
+ details
43494
+ );
43074
43495
  process.stderr.write(
43075
43496
  `Mobius daemon diagnostic ${JSON.stringify({ event: "agent_settings_model_unsupported", requestId: command2.requestId, ...details })}
43076
43497
  `
@@ -43101,6 +43522,12 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43101
43522
  event: "agent_settings_discovery_failed",
43102
43523
  sessionId: `agent-settings:${command2.agentId}`
43103
43524
  });
43525
+ diagnostics.daemonDiagnostic(
43526
+ "agent_settings_discovery_failed",
43527
+ command2.requestId,
43528
+ details,
43529
+ failure2
43530
+ );
43104
43531
  if (failure2 instanceof AcpConfigurationValueUnavailableError) {
43105
43532
  process.stderr.write(
43106
43533
  `Mobius daemon diagnostic ${JSON.stringify({ event: "agent_settings_discovery_failed", requestId: command2.requestId, ...details })}
@@ -43178,6 +43605,12 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43178
43605
  event: "agent_catalog_refresh_failed",
43179
43606
  sessionId: "agent-catalog"
43180
43607
  });
43608
+ diagnostics.daemonDiagnostic(
43609
+ "agent_catalog_refresh_failed",
43610
+ command2.requestId,
43611
+ { code: operationErrorCode(failure2) },
43612
+ failure2
43613
+ );
43181
43614
  if (socket.readyState === WebSocket2.OPEN) {
43182
43615
  send(socket, {
43183
43616
  code: operationErrorCode(failure2),
@@ -43262,6 +43695,17 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43262
43695
  event: "native_session_operation_failed",
43263
43696
  details: { code: operationErrorCode(failure2) }
43264
43697
  });
43698
+ diagnostics.daemonDiagnostic(
43699
+ "native_session_operation_failed",
43700
+ command2.requestId,
43701
+ {
43702
+ action: command2.action,
43703
+ agentId: command2.agentId,
43704
+ code: operationErrorCode(failure2),
43705
+ sessionId: command2.sessionId
43706
+ },
43707
+ failure2
43708
+ );
43265
43709
  reportOperationFailure(socket, command2.requestId, command2.sessionId, failure2);
43266
43710
  } finally {
43267
43711
  timeout.cancel();
@@ -43342,6 +43786,16 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43342
43786
  event: "native_session_turn_fork_failed",
43343
43787
  sessionId: command2.sessionId
43344
43788
  });
43789
+ diagnostics.daemonDiagnostic(
43790
+ "native_session_turn_fork_failed",
43791
+ command2.requestId,
43792
+ {
43793
+ agentId: command2.agentId,
43794
+ code: operationErrorCode(failure2),
43795
+ sessionId: command2.sessionId
43796
+ },
43797
+ failure2
43798
+ );
43345
43799
  reportOperationFailure(socket, command2.requestId, command2.sessionId, failure2);
43346
43800
  } finally {
43347
43801
  timeout.cancel();
@@ -43614,7 +44068,12 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43614
44068
  });
43615
44069
  const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
43616
44070
  const installationObserver = new DaemonInstallationObserver();
43617
- const diagnostics = new RelayConnectionDiagnostics(audit, config2.channelId, config2.relayUrl);
44071
+ const diagnostics = new RelayConnectionDiagnostics(
44072
+ audit,
44073
+ config2.channelId,
44074
+ config2.relayUrl,
44075
+ new DaemonDiagnosticLog(stateDirectory)
44076
+ );
43618
44077
  const nativeSessions = new NativeSessionService(config2, directories, sessions, audit);
43619
44078
  const installations = new AgentInstallationManager(
43620
44079
  specifications,