@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/index.js CHANGED
@@ -20988,6 +20988,26 @@ var nativeSessionTurnForkCommandSchema = external_exports.strictObject({
20988
20988
  messageOccurrence: external_exports.number().int().positive(),
20989
20989
  title: external_exports.string().max(500)
20990
20990
  }).readonly();
20991
+ var nativeSessionRequestSchema = external_exports.discriminatedUnion("action", [
20992
+ external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
20993
+ external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
20994
+ external_exports.strictObject({
20995
+ ...identity,
20996
+ action: external_exports.literal("list"),
20997
+ cursor: identifier.nullable()
20998
+ }).readonly(),
20999
+ external_exports.strictObject({
21000
+ ...identity,
21001
+ action: external_exports.enum(["import", "fork"]),
21002
+ entryId: identifier,
21003
+ targetSessionId: identifier
21004
+ }).readonly(),
21005
+ external_exports.strictObject({
21006
+ ...identity,
21007
+ action: external_exports.literal("delete"),
21008
+ entryId: identifier
21009
+ }).readonly()
21010
+ ]);
20991
21011
  var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
20992
21012
  external_exports.strictObject({ ...identity, action: external_exports.literal("preview"), entryId: identifier }).readonly(),
20993
21013
  external_exports.strictObject({ ...identity, action: external_exports.literal("find"), nativeSessionId: identifier }).readonly(),
@@ -21002,6 +21022,12 @@ var nativeSessionCommandSchema = external_exports.discriminatedUnion("action", [
21002
21022
  entryId: identifier,
21003
21023
  targetSessionId: identifier
21004
21024
  }).readonly(),
21025
+ external_exports.strictObject({
21026
+ ...identity,
21027
+ action: external_exports.enum(["import-only", "fork-only"]),
21028
+ entryId: identifier,
21029
+ targetSessionId: identifier
21030
+ }).readonly(),
21005
21031
  external_exports.strictObject({
21006
21032
  ...identity,
21007
21033
  action: external_exports.literal("delete"),
@@ -31159,6 +31185,15 @@ var MAX_PRE_SESSION_UPDATES = 100;
31159
31185
  var MAX_PRE_SESSION_UPDATE_BYTES = 1024 * 1024;
31160
31186
  var SESSION_CONTROL_COMMAND_ID = "session-control";
31161
31187
  var SESSION_CONTROL_TIMEOUT_MILLISECONDS = 3e4;
31188
+ function nativeHistoryNotRetained() {
31189
+ return {
31190
+ cause: {
31191
+ code: "native_history_not_retained",
31192
+ message: "Native message history is not retained in the cloud for this Session."
31193
+ },
31194
+ status: "unavailable"
31195
+ };
31196
+ }
31162
31197
  var NullAcpSessionObserver = class {
31163
31198
  onCommands = () => Promise.resolve();
31164
31199
  onConfig = () => Promise.resolve();
@@ -33824,7 +33859,7 @@ var AcpSessionManager = class {
33824
33859
  this.#endSessionUse(options.sessionId);
33825
33860
  }
33826
33861
  };
33827
- openNativeSession = async (options, origin) => {
33862
+ openNativeSession = async (options, origin, loadHistory) => {
33828
33863
  const key = `${options.agent.id}:${origin.nativeSessionId}`;
33829
33864
  if (this.#nativeOperations.has(key)) {
33830
33865
  throw new AcpExecutionError("The native session is being managed", {}, "session_busy");
@@ -33854,7 +33889,7 @@ var AcpSessionManager = class {
33854
33889
  }
33855
33890
  this.#nativeOperations.add(key);
33856
33891
  try {
33857
- const history = await runtime.loadHistory(options.signal);
33892
+ const history = loadHistory ? await runtime.loadHistory(options.signal) : nativeHistoryNotRetained();
33858
33893
  return {
33859
33894
  prepared: runtime.prepared(),
33860
33895
  sessionId: existing.sessionId,
@@ -33885,7 +33920,7 @@ var AcpSessionManager = class {
33885
33920
  const openedKey = `${options.agent.id}:${runtime.nativeSessionId()}`;
33886
33921
  this.#nativeOperations.add(openedKey);
33887
33922
  try {
33888
- const history = await runtime.loadHistory(options.signal);
33923
+ const history = loadHistory ? await runtime.loadHistory(options.signal) : nativeHistoryNotRetained();
33889
33924
  return {
33890
33925
  sessionId: options.sessionId,
33891
33926
  prepared: runtime.prepared(),
@@ -34809,8 +34844,31 @@ var mcpElicitationParamsSchema = external_exports.object({
34809
34844
  url: external_exports.string().optional()
34810
34845
  });
34811
34846
  var threadStartResponseSchema = external_exports.object({
34847
+ approvalPolicy: external_exports.unknown().optional(),
34848
+ approvalsReviewer: external_exports.unknown().optional(),
34849
+ model: boundedText(256).nullish(),
34850
+ reasoningEffort: boundedText(256).nullish(),
34851
+ sandbox: external_exports.unknown().optional(),
34852
+ serviceTier: boundedText(256).nullish(),
34812
34853
  thread: external_exports.object({ id: boundedText(256) })
34813
34854
  });
34855
+ var reasoningEffortOptionSchema = external_exports.object({
34856
+ description: boundedText(4096).nullish(),
34857
+ reasoningEffort: boundedText(256)
34858
+ });
34859
+ var modelSchema = external_exports.object({
34860
+ additionalSpeedTiers: external_exports.array(boundedText(256)).max(100).nullish(),
34861
+ defaultReasoningEffort: boundedText(256).nullish(),
34862
+ description: boundedText(4096).nullish(),
34863
+ displayName: boundedText(256).nullish(),
34864
+ id: boundedText(256),
34865
+ isDefault: external_exports.boolean().nullish(),
34866
+ supportedReasoningEfforts: external_exports.array(reasoningEffortOptionSchema).max(100).nullish()
34867
+ });
34868
+ var modelListResponseSchema = external_exports.object({
34869
+ data: external_exports.array(modelSchema).max(1e3),
34870
+ nextCursor: boundedText(1024).nullish()
34871
+ });
34814
34872
 
34815
34873
  // src/acp/codex/app-server-client.ts
34816
34874
  var INITIALIZE_TIMEOUT_MILLISECONDS = 3e4;
@@ -35150,6 +35208,56 @@ function agentMessageMeta(phase) {
35150
35208
  var APPROVAL_REASON_CHARACTER_LIMIT = 500;
35151
35209
  var APPROVAL_TIMEOUT_MILLISECONDS = 36e5;
35152
35210
  var CODEX_AGENT_VERSION = "0.154.0";
35211
+ var MODEL_SETTING_ID = "model";
35212
+ var REASONING_EFFORT_SETTING_ID = "reasoning_effort";
35213
+ var MODE_SETTING_ID = "mode";
35214
+ var FAST_MODE_SETTING_ID = "fast-mode";
35215
+ var MODEL_CATALOG_LIMIT = 1e3;
35216
+ var FAST_TIER = "fast";
35217
+ var SERVICE_TIER_FAST = "priority";
35218
+ var WORKSPACE_WRITE_POLICY = Object.freeze({
35219
+ excludeSlashTmp: false,
35220
+ excludeTmpdirEnvVar: false,
35221
+ networkAccess: false,
35222
+ type: "workspaceWrite",
35223
+ writableRoots: []
35224
+ });
35225
+ var READ_ONLY_MODE = Object.freeze({
35226
+ approvalPolicy: "on-request",
35227
+ approvalsReviewer: "user",
35228
+ description: "Always ask to edit external files and use the internet",
35229
+ id: "read-only",
35230
+ name: "Ask for approval",
35231
+ sandboxPolicy: WORKSPACE_WRITE_POLICY
35232
+ });
35233
+ var AGENT_MODE = Object.freeze({
35234
+ approvalPolicy: "on-request",
35235
+ approvalsReviewer: "auto_review",
35236
+ description: "Only ask for actions detected as potentially unsafe",
35237
+ id: "agent",
35238
+ name: "Approve for me",
35239
+ sandboxPolicy: WORKSPACE_WRITE_POLICY
35240
+ });
35241
+ var FULL_ACCESS_MODE = Object.freeze({
35242
+ approvalPolicy: "never",
35243
+ approvalsReviewer: "user",
35244
+ description: "Unrestricted access to the internet and any file on your computer",
35245
+ id: "agent-full-access",
35246
+ name: "Full access",
35247
+ sandboxPolicy: { type: "dangerFullAccess" }
35248
+ });
35249
+ var AGENT_MODES = Object.freeze([READ_ONLY_MODE, AGENT_MODE, FULL_ACCESS_MODE]);
35250
+ var DEFAULT_MODE = AGENT_MODE;
35251
+ function initialMode(environment) {
35252
+ const requested = environment["INITIAL_AGENT_MODE"];
35253
+ if (requested === void 0) {
35254
+ return DEFAULT_MODE.id;
35255
+ }
35256
+ return AGENT_MODES.some((mode) => mode.id === requested) ? requested : DEFAULT_MODE.id;
35257
+ }
35258
+ function capitalize(value) {
35259
+ return value.length === 0 ? value : value.charAt(0).toUpperCase() + value.slice(1);
35260
+ }
35153
35261
  var APPROVAL_OPTIONS = Object.freeze([
35154
35262
  { kind: "allow_once", name: "Allow once", optionId: "accept" },
35155
35263
  { kind: "allow_always", name: "Allow for this session", optionId: "acceptForSession" },
@@ -35187,6 +35295,84 @@ function promptInput(prompt) {
35187
35295
  }
35188
35296
  return input2;
35189
35297
  }
35298
+ function modelValues(models) {
35299
+ return models.map((model) => ({
35300
+ description: model.description ?? "",
35301
+ name: model.displayName ?? model.id,
35302
+ value: model.id
35303
+ }));
35304
+ }
35305
+ function effortValues(model) {
35306
+ return (model?.supportedReasoningEfforts ?? []).map((option) => ({
35307
+ description: option.description ?? "",
35308
+ name: capitalize(option.reasoningEffort),
35309
+ value: option.reasoningEffort
35310
+ }));
35311
+ }
35312
+ function modelSetting(models, currentValue) {
35313
+ const values = modelValues(models);
35314
+ const current = currentValue.length > 0 ? currentValue : models.find((model) => model.isDefault === true)?.id ?? values[0]?.value ?? "";
35315
+ if (current.length === 0) {
35316
+ return null;
35317
+ }
35318
+ const options = values.some((value) => value.value === current) ? values : [{ description: "", name: current, value: current }, ...values];
35319
+ return {
35320
+ category: "model",
35321
+ currentValue: current,
35322
+ description: "Model Codex uses for the session",
35323
+ id: MODEL_SETTING_ID,
35324
+ name: "Model",
35325
+ options,
35326
+ type: "select"
35327
+ };
35328
+ }
35329
+ function modeSetting(currentValue) {
35330
+ return {
35331
+ category: "mode",
35332
+ currentValue,
35333
+ description: "Approval and sandboxing preset for the session",
35334
+ id: MODE_SETTING_ID,
35335
+ name: "Mode",
35336
+ options: AGENT_MODES.map((mode) => ({
35337
+ description: mode.description,
35338
+ name: mode.name,
35339
+ value: mode.id
35340
+ })),
35341
+ type: "select"
35342
+ };
35343
+ }
35344
+ function fastModeSetting(model, enabled) {
35345
+ if (model?.additionalSpeedTiers?.includes(FAST_TIER) !== true) {
35346
+ return null;
35347
+ }
35348
+ return {
35349
+ category: "model_config",
35350
+ currentValue: enabled,
35351
+ description: "1.5x speed, increased usage",
35352
+ id: FAST_MODE_SETTING_ID,
35353
+ name: "Fast mode",
35354
+ type: "boolean"
35355
+ };
35356
+ }
35357
+ function effortSetting(model, currentValue) {
35358
+ const values = effortValues(model);
35359
+ if (values.length === 0) {
35360
+ return null;
35361
+ }
35362
+ const current = values.some((value) => value.value === currentValue) ? currentValue : values[0]?.value ?? "";
35363
+ if (current.length === 0) {
35364
+ return null;
35365
+ }
35366
+ return {
35367
+ category: "thought_level",
35368
+ currentValue: current,
35369
+ description: "How much reasoning effort the model should use",
35370
+ id: REASONING_EFFORT_SETTING_ID,
35371
+ name: "Reasoning effort",
35372
+ options: values,
35373
+ type: "select"
35374
+ };
35375
+ }
35190
35376
  function userInputSchema(questions) {
35191
35377
  const properties = {};
35192
35378
  const required2 = [];
@@ -35211,10 +35397,21 @@ var CodexAcpAgent = class {
35211
35397
  #app;
35212
35398
  #appServer;
35213
35399
  #connection = null;
35400
+ #models = [];
35214
35401
  #nativeSessionId = "";
35402
+ // Whether the current turn must carry a policy at all. Until the user picks a mode, Codex's own
35403
+ // configuration decides, so `turn/start` omits the fields and inherits what the host set up.
35404
+ #policySelected = false;
35405
+ #selection;
35215
35406
  #turn = null;
35216
35407
  #updateTail = Promise.resolve();
35217
35408
  constructor(options) {
35409
+ this.#selection = {
35410
+ effort: "",
35411
+ fastMode: false,
35412
+ mode: initialMode(options.environment),
35413
+ model: ""
35414
+ };
35218
35415
  this.#appServer = new CodexAppServerClient({
35219
35416
  command: options.command,
35220
35417
  cwd: options.cwd,
@@ -35248,7 +35445,18 @@ var CodexAcpAgent = class {
35248
35445
  )
35249
35446
  );
35250
35447
  this.#nativeSessionId = created.thread.id;
35251
- return { sessionId: created.thread.id };
35448
+ this.#selection = {
35449
+ ...this.#selection,
35450
+ effort: created.reasoningEffort ?? "",
35451
+ model: created.model ?? ""
35452
+ };
35453
+ return { configOptions: this.#configOptions(), sessionId: created.thread.id };
35454
+ }).onRequest(methods4.agent.session.setConfigOption, async (context) => {
35455
+ this.#applySelection(context.params.configId, context.params.value);
35456
+ return { configOptions: this.#configOptions() };
35457
+ }).onRequest(methods4.agent.session.setMode, async (context) => {
35458
+ this.#applySelection(MODE_SETTING_ID, context.params.modeId);
35459
+ return {};
35252
35460
  }).onRequest(methods4.agent.session.prompt, async (context) => {
35253
35461
  return await this.#runTurn(promptInput(context.params.prompt), context.signal);
35254
35462
  }).onRequest(methods4.agent.session.close, async () => {
@@ -35259,9 +35467,10 @@ var CodexAcpAgent = class {
35259
35467
  }
35260
35468
  /** The ACP agent app Mobius connects its own ACP client to, in-process. */
35261
35469
  app = () => this.#app;
35262
- /** Starts the app-server and performs its handshake. */
35470
+ /** Starts the app-server, performs its handshake, and reads the model catalog Codex offers. */
35263
35471
  initialize = async (signal) => {
35264
35472
  await this.#appServer.initialize(signal);
35473
+ await this.#loadModels(signal);
35265
35474
  };
35266
35475
  /**
35267
35476
  * Releases the app-server and every process it started. Mirrors the adapter path's teardown so a
@@ -35273,6 +35482,129 @@ var CodexAcpAgent = class {
35273
35482
  this.#appServer.detach();
35274
35483
  await stopProcessTree(child, captured);
35275
35484
  };
35485
+ /**
35486
+ * Reads the model catalog once per app-server. A failure leaves the catalog empty, which costs
35487
+ * the Run settings panel its model selector; it must not cost the conversation itself, so the
35488
+ * turn lifecycle continues without settings rather than failing initialization.
35489
+ */
35490
+ #loadModels = async (signal) => {
35491
+ const models = [];
35492
+ let cursor = null;
35493
+ try {
35494
+ do {
35495
+ const decoded = modelListResponseSchema.parse(
35496
+ await this.#appServer.request(
35497
+ "model/list",
35498
+ { cursor, limit: null },
35499
+ AbortSignal.any([signal, AbortSignal.timeout(APPROVAL_TIMEOUT_MILLISECONDS)])
35500
+ )
35501
+ );
35502
+ models.push(...decoded.data);
35503
+ cursor = decoded.nextCursor ?? null;
35504
+ } while (cursor !== null && models.length < MODEL_CATALOG_LIMIT);
35505
+ } catch (error62) {
35506
+ signal.throwIfAborted();
35507
+ process.stderr.write(`[codex-acp] model catalog unavailable: ${String(error62)}
35508
+ `);
35509
+ }
35510
+ this.#models = Object.freeze(models.slice(0, MODEL_CATALOG_LIMIT));
35511
+ };
35512
+ #model = (id) => this.#models.find((model) => model.id === id);
35513
+ /** The ACP settings Mobius discovers and renders in Run settings. */
35514
+ #configOptions = () => {
35515
+ const options = [];
35516
+ const model = modelSetting(this.#models, this.#selection.model);
35517
+ if (model !== null) {
35518
+ options.push(model);
35519
+ }
35520
+ const effort = effortSetting(this.#model(this.#selection.model), this.#selection.effort);
35521
+ if (effort !== null) {
35522
+ options.push(effort);
35523
+ }
35524
+ const fastMode = fastModeSetting(this.#model(this.#selection.model), this.#selection.fastMode);
35525
+ if (fastMode !== null) {
35526
+ options.push(fastMode);
35527
+ }
35528
+ options.push(modeSetting(this.#selection.mode));
35529
+ return options;
35530
+ };
35531
+ /**
35532
+ * Applies one `session/set_config_option`. Switching models re-resolves the effort the way Codex
35533
+ * does — the current effort when the new model supports it, otherwise the model's own default —
35534
+ * so the reply never advertises an effort the selected model cannot run.
35535
+ */
35536
+ #applySelection = (configId, value) => {
35537
+ if (configId === FAST_MODE_SETTING_ID) {
35538
+ if (typeof value !== "boolean") {
35539
+ throw new AcpExecutionError(
35540
+ "The requested Codex setting is invalid",
35541
+ {},
35542
+ "invalid_session_configuration"
35543
+ );
35544
+ }
35545
+ if (value && this.#model(this.#selection.model)?.additionalSpeedTiers?.includes(FAST_TIER) !== true) {
35546
+ throw new AcpExecutionError(
35547
+ "The selected Codex model has no fast mode",
35548
+ {},
35549
+ "invalid_session_configuration"
35550
+ );
35551
+ }
35552
+ this.#selection = { ...this.#selection, fastMode: value };
35553
+ return;
35554
+ }
35555
+ if (typeof value !== "string") {
35556
+ throw new AcpExecutionError("The requested Codex setting is invalid", {}, "invalid_session_configuration");
35557
+ }
35558
+ if (configId === MODE_SETTING_ID) {
35559
+ if (!AGENT_MODES.some((mode) => mode.id === value)) {
35560
+ throw new AcpExecutionError(
35561
+ "The requested Codex mode is unavailable",
35562
+ {},
35563
+ "invalid_session_configuration"
35564
+ );
35565
+ }
35566
+ this.#selection = { ...this.#selection, mode: value };
35567
+ this.#policySelected = true;
35568
+ return;
35569
+ }
35570
+ if (configId === MODEL_SETTING_ID) {
35571
+ if (value === this.#selection.model) {
35572
+ return;
35573
+ }
35574
+ const model = this.#model(value);
35575
+ if (model === void 0) {
35576
+ throw new AcpExecutionError(
35577
+ "The requested Codex model is unavailable",
35578
+ {},
35579
+ "invalid_session_configuration"
35580
+ );
35581
+ }
35582
+ const supported = (model.supportedReasoningEfforts ?? []).map((option) => option.reasoningEffort);
35583
+ const effort = supported.includes(this.#selection.effort) ? this.#selection.effort : model.defaultReasoningEffort ?? supported[0] ?? "";
35584
+ this.#selection = {
35585
+ ...this.#selection,
35586
+ effort,
35587
+ fastMode: this.#selection.fastMode && model.additionalSpeedTiers?.includes(FAST_TIER) === true,
35588
+ model: value
35589
+ };
35590
+ return;
35591
+ }
35592
+ if (configId === REASONING_EFFORT_SETTING_ID) {
35593
+ const supported = (this.#model(this.#selection.model)?.supportedReasoningEfforts ?? []).map(
35594
+ (option) => option.reasoningEffort
35595
+ );
35596
+ if (!supported.includes(value)) {
35597
+ throw new AcpExecutionError(
35598
+ "The requested Codex reasoning effort is unavailable",
35599
+ {},
35600
+ "invalid_session_configuration"
35601
+ );
35602
+ }
35603
+ this.#selection = { ...this.#selection, effort: value };
35604
+ return;
35605
+ }
35606
+ throw new AcpExecutionError("The requested Codex setting is unavailable", {}, "invalid_session_configuration");
35607
+ };
35276
35608
  #emit = async (update) => {
35277
35609
  const connection = this.#connection;
35278
35610
  if (connection === null || this.#nativeSessionId.length === 0) {
@@ -35478,10 +35810,27 @@ var CodexAcpAgent = class {
35478
35810
  const turn = { completion, turn: { id: "" } };
35479
35811
  this.#turn = turn;
35480
35812
  try {
35813
+ const selection = this.#selection;
35814
+ const mode = AGENT_MODES.find((candidate) => candidate.id === selection.mode) ?? DEFAULT_MODE;
35815
+ const supportsFast = this.#model(selection.model)?.additionalSpeedTiers?.includes(FAST_TIER) === true;
35481
35816
  const started = turnSchema.parse(
35482
35817
  (await this.#appServer.request(
35483
35818
  "turn/start",
35484
- { input: input2, threadId: this.#nativeSessionId },
35819
+ {
35820
+ // Until a mode is chosen, `config.toml` decides the sandbox and approval
35821
+ // policy, and those fields stay off the turn so the host's own setup is
35822
+ // inherited rather than overridden.
35823
+ ...this.#policySelected ? {
35824
+ approvalPolicy: mode.approvalPolicy,
35825
+ approvalsReviewer: mode.approvalsReviewer,
35826
+ sandboxPolicy: mode.sandboxPolicy
35827
+ } : {},
35828
+ ...selection.effort.length === 0 ? {} : { effort: selection.effort },
35829
+ input: input2,
35830
+ ...selection.model.length === 0 ? {} : { model: selection.model },
35831
+ ...selection.fastMode && supportsFast ? { serviceTier: SERVICE_TIER_FAST } : {},
35832
+ threadId: this.#nativeSessionId
35833
+ },
35485
35834
  signal
35486
35835
  )).turn
35487
35836
  );
@@ -39030,6 +39379,54 @@ var WorkspaceDirectoryService = class {
39030
39379
  };
39031
39380
  };
39032
39381
 
39382
+ // src/daemon-diagnostic-log.ts
39383
+ import { appendFileSync, mkdirSync as mkdirSync3, readFileSync as readFileSync2, renameSync, statSync as statSync3, writeFileSync } from "node:fs";
39384
+ import { join as join17 } from "node:path";
39385
+ var MAXIMUM_DAEMON_LOG_BYTES = 1 * 1024 * 1024;
39386
+ var DaemonDiagnosticLog = class {
39387
+ #directory;
39388
+ #path;
39389
+ #maximumBytes;
39390
+ constructor(stateDirectory, maximumBytes = MAXIMUM_DAEMON_LOG_BYTES) {
39391
+ this.#directory = join17(stateDirectory, "logs");
39392
+ this.#path = join17(this.#directory, "daemon.log");
39393
+ this.#maximumBytes = maximumBytes;
39394
+ }
39395
+ record = (diagnostic) => {
39396
+ const encoded = `${diagnostic.replace(/[\r\n]+/gu, " ").trim()}
39397
+ `;
39398
+ const encodedBytes = Buffer.byteLength(encoded);
39399
+ mkdirSync3(this.#directory, { mode: 448, recursive: true });
39400
+ let existingBytes = 0;
39401
+ try {
39402
+ existingBytes = statSync3(this.#path).size;
39403
+ } catch (cause) {
39404
+ if (!(cause instanceof Error && Reflect.get(cause, "code") === "ENOENT")) {
39405
+ throw cause;
39406
+ }
39407
+ }
39408
+ if (existingBytes + encodedBytes <= this.#maximumBytes) {
39409
+ appendFileSync(this.#path, encoded, { encoding: "utf8", mode: 384 });
39410
+ return;
39411
+ }
39412
+ const lines = `${existingBytes === 0 ? "" : readFileSync2(this.#path, "utf8")}${encoded}`.split("\n").filter((line) => line.length > 0);
39413
+ let totalBytes = lines.reduce((total, line) => total + Buffer.byteLength(line) + 1, 0);
39414
+ while (totalBytes > this.#maximumBytes && lines.length > 0) {
39415
+ const oldest = lines.shift();
39416
+ if (oldest !== void 0) {
39417
+ totalBytes -= Buffer.byteLength(oldest) + 1;
39418
+ }
39419
+ }
39420
+ const temporaryPath = `${this.#path}.tmp`;
39421
+ writeFileSync(temporaryPath, lines.length === 0 ? "" : `${lines.join("\n")}
39422
+ `, {
39423
+ encoding: "utf8",
39424
+ mode: 384
39425
+ });
39426
+ renameSync(temporaryPath, this.#path);
39427
+ };
39428
+ };
39429
+
39033
39430
  // src/native-sessions/codex-history.ts
39034
39431
  import { spawn as spawn5 } from "node:child_process";
39035
39432
  var responseSchema = external_exports.union([
@@ -39616,10 +40013,11 @@ var NativeSessionService = class {
39616
40013
  deletedSessionIds
39617
40014
  };
39618
40015
  }
39619
- if (command.action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession) {
40016
+ const action = command.action === "import-only" ? "import" : command.action === "fork-only" ? "fork" : command.action;
40017
+ if (action === "import" && !prepared.capabilities.loadSession && !prepared.capabilities.resumeSession) {
39620
40018
  throw new AcpExecutionError("This Agent cannot import native sessions", {}, "native_session_unsupported");
39621
40019
  }
39622
- if (command.action === "fork" && !prepared.capabilities.unstableForkSession) {
40020
+ if (action === "fork" && !prepared.capabilities.unstableForkSession) {
39623
40021
  throw new AcpExecutionError(
39624
40022
  "This Agent does not support session forking",
39625
40023
  {},
@@ -39640,7 +40038,8 @@ var NativeSessionService = class {
39640
40038
  sessionId: command.targetSessionId,
39641
40039
  additionalDirectories: target.additionalDirectories
39642
40040
  },
39643
- { kind: command.action, nativeSessionId: target.info.sessionId }
40041
+ { kind: action, nativeSessionId: target.info.sessionId },
40042
+ command.action !== "import-only" && command.action !== "fork-only"
39644
40043
  );
39645
40044
  signal.throwIfAborted();
39646
40045
  const ready = {
@@ -39658,10 +40057,10 @@ var NativeSessionService = class {
39658
40057
  restored: true,
39659
40058
  sessionId: opened.sessionId
39660
40059
  };
39661
- this.record(command, command.action === "fork" ? "native_session_forked" : "native_session_imported");
40060
+ this.record(command, action === "fork" ? "native_session_forked" : "native_session_imported");
39662
40061
  return {
39663
40062
  ...envelope2,
39664
- action: command.action,
40063
+ action,
39665
40064
  ready,
39666
40065
  targetSessionId: command.targetSessionId,
39667
40066
  title: target.info.title ?? "Untitled session",
@@ -40241,13 +40640,15 @@ function addFailureDetails(details, failure2) {
40241
40640
  var RelayConnectionDiagnostics = class {
40242
40641
  #audit;
40243
40642
  #channelId;
40643
+ #localLog;
40244
40644
  #lastClosedEpoch = 0;
40245
40645
  #lastFailedEpoch = 0;
40246
40646
  #relayOrigin;
40247
40647
  #route;
40248
- constructor(audit, channelId, relayUrl) {
40648
+ constructor(audit, channelId, relayUrl, localLog) {
40249
40649
  this.#audit = audit;
40250
40650
  this.#channelId = channelId;
40651
+ this.#localLog = localLog;
40251
40652
  this.#relayOrigin = relayUrl.origin;
40252
40653
  this.#route = describeEnvironmentProxyRoute(relayUrl);
40253
40654
  }
@@ -40334,6 +40735,20 @@ var RelayConnectionDiagnostics = class {
40334
40735
  true
40335
40736
  );
40336
40737
  };
40738
+ daemonDiagnostic = (event, requestId, details, failure2) => {
40739
+ const recordedDetails = { ...details };
40740
+ if (failure2 !== void 0) {
40741
+ addFailureDetails(recordedDetails, failure2);
40742
+ }
40743
+ this.#localLog.record(
40744
+ `Mobius daemon diagnostic ${JSON.stringify({
40745
+ channelId: this.#channelId,
40746
+ event,
40747
+ requestId,
40748
+ ...recordedDetails
40749
+ })}`
40750
+ );
40751
+ };
40337
40752
  #record = (event, commandId, details, warning) => {
40338
40753
  this.#audit.record({
40339
40754
  commandId,
@@ -40342,6 +40757,7 @@ var RelayConnectionDiagnostics = class {
40342
40757
  sessionId: this.#channelId
40343
40758
  });
40344
40759
  const encoded = JSON.stringify({ channelId: this.#channelId, event, ...details });
40760
+ this.#localLog.record(`Mobius relay diagnostic ${encoded}`);
40345
40761
  if (warning) {
40346
40762
  process.stderr.write(`Mobius relay diagnostic ${encoded}
40347
40763
  `);
@@ -40459,7 +40875,7 @@ var RelayConnectionLiveness = class {
40459
40875
  };
40460
40876
 
40461
40877
  // src/relay-connection/session-event-outbox.ts
40462
- import { mkdirSync as mkdirSync3 } from "node:fs";
40878
+ import { mkdirSync as mkdirSync4 } from "node:fs";
40463
40879
  import { dirname as dirname7 } from "node:path";
40464
40880
  import { DatabaseSync as DatabaseSync3 } from "node:sqlite";
40465
40881
  var DEFAULT_OUTBOX_LIMITS = {
@@ -40526,7 +40942,7 @@ var SessionEventOutbox = class {
40526
40942
  constructor(path2, limits = DEFAULT_OUTBOX_LIMITS) {
40527
40943
  validateLimits(limits);
40528
40944
  this.#limits = limits;
40529
- mkdirSync3(dirname7(path2), { recursive: true });
40945
+ mkdirSync4(dirname7(path2), { recursive: true });
40530
40946
  this.#database = new DatabaseSync3(path2);
40531
40947
  this.#database.exec(`
40532
40948
  CREATE TABLE IF NOT EXISTS relay_session_event_outbox (
@@ -42990,6 +43406,11 @@ async function runRelayConnection(config2, directories, audit, sessions, install
42990
43406
  event: "agent_settings_model_unsupported",
42991
43407
  sessionId: `agent-settings:${command2.agentId}`
42992
43408
  });
43409
+ diagnostics.daemonDiagnostic(
43410
+ "agent_settings_model_unsupported",
43411
+ command2.requestId,
43412
+ details
43413
+ );
42993
43414
  process.stderr.write(
42994
43415
  `Mobius daemon diagnostic ${JSON.stringify({ event: "agent_settings_model_unsupported", requestId: command2.requestId, ...details })}
42995
43416
  `
@@ -43020,6 +43441,12 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43020
43441
  event: "agent_settings_discovery_failed",
43021
43442
  sessionId: `agent-settings:${command2.agentId}`
43022
43443
  });
43444
+ diagnostics.daemonDiagnostic(
43445
+ "agent_settings_discovery_failed",
43446
+ command2.requestId,
43447
+ details,
43448
+ failure2
43449
+ );
43023
43450
  if (failure2 instanceof AcpConfigurationValueUnavailableError) {
43024
43451
  process.stderr.write(
43025
43452
  `Mobius daemon diagnostic ${JSON.stringify({ event: "agent_settings_discovery_failed", requestId: command2.requestId, ...details })}
@@ -43097,6 +43524,12 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43097
43524
  event: "agent_catalog_refresh_failed",
43098
43525
  sessionId: "agent-catalog"
43099
43526
  });
43527
+ diagnostics.daemonDiagnostic(
43528
+ "agent_catalog_refresh_failed",
43529
+ command2.requestId,
43530
+ { code: operationErrorCode(failure2) },
43531
+ failure2
43532
+ );
43100
43533
  if (socket.readyState === WebSocket2.OPEN) {
43101
43534
  send(socket, {
43102
43535
  code: operationErrorCode(failure2),
@@ -43181,6 +43614,17 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43181
43614
  event: "native_session_operation_failed",
43182
43615
  details: { code: operationErrorCode(failure2) }
43183
43616
  });
43617
+ diagnostics.daemonDiagnostic(
43618
+ "native_session_operation_failed",
43619
+ command2.requestId,
43620
+ {
43621
+ action: command2.action,
43622
+ agentId: command2.agentId,
43623
+ code: operationErrorCode(failure2),
43624
+ sessionId: command2.sessionId
43625
+ },
43626
+ failure2
43627
+ );
43184
43628
  reportOperationFailure(socket, command2.requestId, command2.sessionId, failure2);
43185
43629
  } finally {
43186
43630
  timeout.cancel();
@@ -43261,6 +43705,16 @@ async function runRelayConnection(config2, directories, audit, sessions, install
43261
43705
  event: "native_session_turn_fork_failed",
43262
43706
  sessionId: command2.sessionId
43263
43707
  });
43708
+ diagnostics.daemonDiagnostic(
43709
+ "native_session_turn_fork_failed",
43710
+ command2.requestId,
43711
+ {
43712
+ agentId: command2.agentId,
43713
+ code: operationErrorCode(failure2),
43714
+ sessionId: command2.sessionId
43715
+ },
43716
+ failure2
43717
+ );
43264
43718
  reportOperationFailure(socket, command2.requestId, command2.sessionId, failure2);
43265
43719
  } finally {
43266
43720
  timeout.cancel();
@@ -43533,7 +43987,12 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43533
43987
  });
43534
43988
  const directories = new WorkspaceDirectoryService(config2.bindingId, config2.defaultWorkspace);
43535
43989
  const installationObserver = new DaemonInstallationObserver();
43536
- const diagnostics = new RelayConnectionDiagnostics(audit, config2.channelId, config2.relayUrl);
43990
+ const diagnostics = new RelayConnectionDiagnostics(
43991
+ audit,
43992
+ config2.channelId,
43993
+ config2.relayUrl,
43994
+ new DaemonDiagnosticLog(stateDirectory)
43995
+ );
43537
43996
  const nativeSessions = new NativeSessionService(config2, directories, sessions, audit);
43538
43997
  const installations = new AgentInstallationManager(
43539
43998
  specifications,
@@ -43666,7 +44125,7 @@ async function runDaemon(config2, audit, signal, timer = systemDaemonTimer, opti
43666
44125
 
43667
44126
  // src/runtime.ts
43668
44127
  import { mkdir as mkdir6, realpath as realpath10, stat as stat9 } from "node:fs/promises";
43669
- import { dirname as dirname8, join as join17, resolve as resolve7 } from "node:path";
44128
+ import { dirname as dirname8, join as join18, resolve as resolve7 } from "node:path";
43670
44129
  var IDENTIFIER_PATTERN7 = /^[a-zA-Z0-9][a-zA-Z0-9._:-]{0,127}$/;
43671
44130
  var RUNTIME_CREDENTIAL_PATTERN2 = /^[a-zA-Z0-9_-]{32,256}$/;
43672
44131
  var MobiusRuntimeConfigurationError = class extends Error {
@@ -43723,7 +44182,7 @@ function loadMobiusRuntimeConnection(environment = process.env) {
43723
44182
  throw new MobiusRuntimeConfigurationError("MOBIUS_CHANNEL_ID is invalid");
43724
44183
  }
43725
44184
  return Object.freeze({
43726
- auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join17(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
44185
+ auditDatabasePath: environment["MOBIUS_AUDIT_DATABASE"]?.trim() || join18(readStateDirectory(environment), "audit", `${channelId}.sqlite`),
43727
44186
  channelId,
43728
44187
  defaultWorkspace: loadDefaultWorkspace(environment),
43729
44188
  relayUrl: requiredEnvironmentValue(environment, "MOBIUS_RELAY_URL"),