@agent-dock/cli 0.3.10 → 0.3.11

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
@@ -945,11 +945,11 @@ var init_sdk = __esm({
945
945
 
946
946
  // src/abortable.ts
947
947
  function abortable(operation, signal) {
948
- return new Promise((resolve13, reject2) => {
948
+ return new Promise((resolve14, reject2) => {
949
949
  const abort = () => reject2(signal.reason);
950
950
  if (signal.aborted) abort();
951
951
  else signal.addEventListener("abort", abort, { once: true });
952
- operation.then(resolve13, reject2).finally(() => signal.removeEventListener("abort", abort));
952
+ operation.then(resolve14, reject2).finally(() => signal.removeEventListener("abort", abort));
953
953
  });
954
954
  }
955
955
  var init_abortable = __esm({
@@ -960,7 +960,7 @@ var init_abortable = __esm({
960
960
 
961
961
  // src/daemon/time.ts
962
962
  function sleep(ms) {
963
- return new Promise((resolve13) => setTimeout(resolve13, ms));
963
+ return new Promise((resolve14) => setTimeout(resolve14, ms));
964
964
  }
965
965
  var init_time = __esm({
966
966
  "src/daemon/time.ts"() {
@@ -3158,7 +3158,7 @@ ${prompt}`;
3158
3158
  if (result.messages.length) return result;
3159
3159
  const remaining = deadline - Date.now();
3160
3160
  if (remaining <= 0) return { ...result, timedOut: true };
3161
- await new Promise((resolve13) => setTimeout(resolve13, Math.min(this.pollIntervalMs, remaining)));
3161
+ await new Promise((resolve14) => setTimeout(resolve14, Math.min(this.pollIntervalMs, remaining)));
3162
3162
  }
3163
3163
  }
3164
3164
  /**
@@ -4129,8 +4129,8 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
4129
4129
  try {
4130
4130
  const names = await Promise.race([
4131
4131
  pending,
4132
- new Promise((resolve13) => {
4133
- timer = setTimeout(() => resolve13(void 0), chatNamesTimeoutMs);
4132
+ new Promise((resolve14) => {
4133
+ timer = setTimeout(() => resolve14(void 0), chatNamesTimeoutMs);
4134
4134
  })
4135
4135
  ]);
4136
4136
  if (names) {
@@ -4302,7 +4302,7 @@ ${truncate(entry.data.message ?? "Agent \u6267\u884C\u672A\u5B8C\u5168\u6210\u52
4302
4302
  }
4303
4303
  if (attempt < 3) {
4304
4304
  const delay = isLarkMessageRateLimit(error) ? larkRateLimitBackoffMs(attempt) : attempt * 300;
4305
- await new Promise((resolve13) => setTimeout(resolve13, delay));
4305
+ await new Promise((resolve14) => setTimeout(resolve14, delay));
4306
4306
  }
4307
4307
  }
4308
4308
  }
@@ -4861,7 +4861,7 @@ ${error instanceof Error ? error.message : String(error)}`;
4861
4861
  this.log.warn({ error, messageId: pending.input.messageId, attempt, attempts }, "\u66F4\u65B0\u98DE\u4E66\u670D\u52A1\u5361\u7247\u5931\u8D25");
4862
4862
  if (attempt < attempts) {
4863
4863
  const retryDelay = isLarkMessageRateLimit(error) ? Math.max(0, cardRateLimitedUntil - Date.now()) : attempt * 300;
4864
- await new Promise((resolve13) => setTimeout(resolve13, retryDelay));
4864
+ await new Promise((resolve14) => setTimeout(resolve14, retryDelay));
4865
4865
  }
4866
4866
  }
4867
4867
  }
@@ -4982,7 +4982,7 @@ ${error instanceof Error ? error.message : String(error)}`;
4982
4982
  if (attempt < maxQuietReplyAttempts) {
4983
4983
  const delay = isLarkMessageRateLimit(error) ? larkRateLimitBackoffMs(attempt) : attempt * 500;
4984
4984
  this.log.warn({ error, attempt, chatId: event.chatId, messageId: event.messageId }, "\u53D1\u9001\u9759\u9ED8\u7EC8\u6001\u56DE\u590D\u5931\u8D25\uFF0C\u51C6\u5907\u91CD\u8BD5");
4985
- await new Promise((resolve13) => setTimeout(resolve13, delay));
4985
+ await new Promise((resolve14) => setTimeout(resolve14, delay));
4986
4986
  }
4987
4987
  }
4988
4988
  }
@@ -5660,13 +5660,13 @@ __export(session_cli_exports, {
5660
5660
  streamSessionShow: () => streamSessionShow
5661
5661
  });
5662
5662
  import { existsSync as existsSync9 } from "node:fs";
5663
- import { join as join20, resolve as resolve9 } from "node:path";
5663
+ import { join as join20, resolve as resolve10 } from "node:path";
5664
5664
  function resolveDatabasePath(explicit, cwd = process.cwd()) {
5665
- if (explicit) return resolve9(cwd, explicit);
5666
- if (process.env.AGENTDOCK_DATABASE_URL) return resolve9(cwd, process.env.AGENTDOCK_DATABASE_URL);
5665
+ if (explicit) return resolve10(cwd, explicit);
5666
+ if (process.env.AGENTDOCK_DATABASE_URL) return resolve10(cwd, process.env.AGENTDOCK_DATABASE_URL);
5667
5667
  const daemonDir = resolveDaemonDir(cwd);
5668
5668
  const recorded = readDaemonStatus(daemonDir)?.database;
5669
- return recorded ? resolve9(daemonDir, recorded) : join20(daemonDir, "..", "agentdock.db");
5669
+ return recorded ? resolve10(daemonDir, recorded) : join20(daemonDir, "..", "agentdock.db");
5670
5670
  }
5671
5671
  function sessionPeerIds(sessions2, sourceId2) {
5672
5672
  const source2 = sessions2.find((session) => session.id === sourceId2);
@@ -5925,9 +5925,15 @@ import { Command } from "commander";
5925
5925
  var collect = (value, previous = []) => [...previous, value];
5926
5926
  var addCardOptions = (command) => command.option("--state <state>", "Card state: queued, running, completed, failed, or interrupted", "completed").option("--read-only", "Render the card without action buttons").option("--agent-name <name>", "Agent name shown in the card title").option("--task-name <name>", "Card subtitle / task name", "AgentDock").option("--task-id <id>", "Task identifier shown in the footer").option("--elapsed-seconds <seconds>", "Elapsed time shown in the footer", "0").option("--app-id <id>", "Lark app ID; defaults to LARK_APP_ID").option("--app-secret <secret>", "Lark app secret; defaults to LARK_APP_SECRET").option("--base-url <url>", "Lark OpenAPI base URL; defaults to LARK_OPEN_API_BASE_URL");
5927
5927
  var addServerOptions = (command) => command.option("--host <host>", "Advanced: bind a specific host or interface").option("--local-only", "Only accept connections from this computer (127.0.0.1)").option("--port <port>", "Bind port (default: 4310)").option("--cwd <directory>", "Default Agent working directory").option("--database <file>", "SQLite database path").option("--idle-timeout-ms <ms>", "Release idle Agent drivers (default: 21600000)").option("--cleanup-interval-ms <ms>", "Idle cleanup interval (default: 300000)").option("--lark-app-id <id>", "Lark app ID used by /api/lark; defaults to LARK_APP_ID").option("--lark-app-secret <secret>", "Lark app secret used by /api/lark; defaults to LARK_APP_SECRET").option("--lark-receive-id <id>", "Default Lark recipient used by /api/lark").option("--lark-chat-id <id>", "Default Lark group chat ID used by /api/lark").option("--lark-receive-id-type <type>", "Default Lark recipient ID type").option("--lark-agent-name <name>", "Default Lark card agent name").option("--lark-base-url <url>", "Lark OpenAPI base URL").option("--no-lark-listen", "Disable Lark message listening for this process without changing saved configuration");
5928
- var serverOptionsFrom = (options, command) => ({ ...command.optsWithGlobals(), ...options });
5928
+ var serverOptionsFrom = (options, command) => {
5929
+ const merged = { ...command.optsWithGlobals() };
5930
+ for (const [key, value] of Object.entries(options)) {
5931
+ if (command.getOptionValueSource(key) !== "default") merged[key] = value;
5932
+ }
5933
+ return merged;
5934
+ };
5929
5935
  function createCliProgram(version, handlers = {}) {
5930
- const program = new Command().name("agent-dock").description("Run the AgentDock local session server").version(version, "-V, --version", "Show the installed version");
5936
+ const program = new Command().name("agent-dock").description("Run the AgentDock local session server").version(version, "-V, --version", "Show the installed version").enablePositionalOptions();
5931
5937
  addServerOptions(program).showHelpAfterError();
5932
5938
  program.action((options) => handlers.serve?.(options));
5933
5939
  const lark = program.command("lark").description("Send AgentDock cards, or send/read/listen to Lark messages");
@@ -6033,11 +6039,12 @@ Notes:
6033
6039
  watch.command("resume").description("\u6062\u590D watch").argument("<watch-id>").option("--json", "\u8F93\u51FA JSON").action((id, options) => handlers.watchResume?.(id, options));
6034
6040
  watch.command("run").description("\u7ACB\u5373\u6267\u884C\u4E00\u6B21").argument("<watch-id>").option("--json", "\u8F93\u51FA JSON").action((id, options) => handlers.watchRun?.(id, options));
6035
6041
  watch.command("remove").description("\u5220\u9664 watch").argument("<watch-id>").option("--json", "\u8F93\u51FA JSON").action((id, options) => handlers.watchRemove?.(id, options));
6036
- program.command("notify").description("\u8BA9\u4E3B\u4F1A\u8BDD\u4E3B\u52A8\u901A\u77E5\u7528\u6237\uFF1B\u514D\u6253\u6270\u9ED8\u8BA4\u5173\u95ED").argument("<text>", "\u901A\u77E5\u5185\u5BB9").option("--ask", "\u9700\u8981\u7528\u6237\u62CD\u677F").option("--urgent", "\u7ED5\u8FC7\u514D\u6253\u6270").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((text3, options) => handlers.notify?.(text3, options));
6042
+ program.command("notify").description("\u8BA9\u4E3B\u4F1A\u8BDD\u4E3B\u52A8\u901A\u77E5\u7528\u6237").argument("<text>", "\u901A\u77E5\u5185\u5BB9").option("--ask", "\u9700\u8981\u7528\u6237\u62CD\u677F").option("--urgent", "\u7D27\u6025\u901A\u77E5\uFF1A\u7CFB\u7EDF\u8F6E\u6B21\u91CC\u4E5F\u653E\u884C").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((text3, options) => handlers.notify?.(text3, options));
6037
6043
  const main2 = program.command("main").description("\u67E5\u770B\u6216\u6307\u5B9A\u4E3B\u4F1A\u8BDD");
6038
6044
  main2.command("show").description("\u67E5\u770B\u5F53\u524D\u4E3B\u4F1A\u8BDD").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.mainGet?.(options));
6039
6045
  main2.command("set").description("\u628A\u73B0\u6709\u4F1A\u8BDD\u8BBE\u4E3A\u4E3B\u4F1A\u8BDD\uFF1B\u4E0D\u4F20 session-id \u65F6\u65B0\u5EFA").argument("[session-id]", "\u73B0\u6709\u4F1A\u8BDD ID").option("--agent <id>", "\u65B0\u5EFA\u65F6\u4F7F\u7528\u7684 Agent").option("--cwd <dir>", "\u65B0\u5EFA\u65F6\u7684\u5DE5\u4F5C\u76EE\u5F55").option("--model <model>", "\u65B0\u5EFA\u65F6\u7684\u6A21\u578B").option("--reasoning-effort <effort>", "\u65B0\u5EFA\u65F6\u7684 reasoning effort").option("--name <name>", "\u5C0F\u732B\u7684\u540D\u5B57\uFF08\u4E3B\u4F1A\u8BDD\u5728\u754C\u9762\u4E0A\u7684\u5F62\u8C61\uFF09\uFF0C\u9ED8\u8BA4\u300C\u56E2\u5B50\u300D").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((sessionId, options) => handlers.mainSet?.(sessionId, options));
6040
6046
  main2.command("clear").description("\u6E05\u9664\u4E3B\u4F1A\u8BDD\u8BBE\u7F6E").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.mainClear?.(options));
6047
+ main2.command("restore").description("\u6062\u590D\u88AB\u8BEF\u5F52\u6863\u7684\u5F53\u524D\u4E3B\u4F1A\u8BDD\uFF08\u89E3\u9664\u5F52\u6863\u5E76\u91CD\u65B0\u542F\u52A8\uFF09").argument("[session-id]").option("--json", "\u8F93\u51FA JSON").action((sessionId, options) => handlers.mainRestore?.(sessionId, options));
6041
6048
  const handoff = main2.command("handoff").description("\u4EA4\u63A5\u4EEA\u5F0F\uFF1A\u8001\u732B\u9000\u4F11\u3001\u65B0\u732B\u63A5\u73ED\u3002\u4E0D\u5E26 --yes \u53EA\u63D0\u8BAE\uFF1B--yes \u7531\u7528\u6237\u672C\u4EBA\u786E\u8BA4\u5E76\u6267\u884C\uFF08\u5931\u8D25\u81EA\u52A8\u56DE\u6EDA\uFF09").option("--yes", "\u786E\u8BA4\u5E76\u7ACB\u523B\u6267\u884C\u4EEA\u5F0F\uFF08\u53EA\u63A5\u53D7\u7528\u6237\u672C\u4EBA\uFF1BAgent \u53EA\u80FD\u63D0\u8BAE\uFF09").option("--name <name>", "\u65B0\u732B\u7684\u540D\u5B57\uFF1B\u9ED8\u8BA4\u6CBF\u7528").option("--reason <text>", "\u4EA4\u63A5\u539F\u56E0").option("--wait <seconds>", "--yes \u65F6\u6700\u591A\u7B49\u591A\u4E45\uFF0C\u9ED8\u8BA4 180").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.mainHandoff?.(options));
6042
6049
  handoff.command("show").description("\u4EA4\u63A5\u8FDB\u5EA6\u3001\u4FBF\u7B7E\u4EA4\u63A5\u660E\u7EC6\uFF1B\u4E0D\u4F20 id \u770B\u6700\u8FD1\u4E00\u6B21").argument("[handoff-id]").option("--json", "\u8F93\u51FA JSON").action((id, _options, command) => handlers.mainHandoffShow?.(id, command.optsWithGlobals()));
6043
6050
  handoff.command("cancel").description("\u5A49\u62D2\u4EA4\u63A5\u63D0\u8BAE\uFF08\u300C\u518D\u966A\u6211\u4E00\u9635\u300D\uFF09").argument("[handoff-id]").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((id, _options, command) => handlers.mainHandoffCancel?.(id, command.optsWithGlobals()));
@@ -6051,9 +6058,6 @@ Notes:
6051
6058
  notes.command("list").description("\u5217\u51FA\u5899\u4E0A\u7684\u4FBF\u7B7E\uFF1B--archived \u770B\u5F52\u6863\u533A").option("--archived", "\u770B\u5F52\u6863\u533A\uFF08\u6309\u6279\u6B21\uFF09").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.notesList?.(options));
6052
6059
  notes.command("archive").description("\u628A\u5DF2\u5173\u95ED\u7684\u4FBF\u7B7E\u6298\u53E0\u8FDB\u5F52\u6863\u533A").option("--task <task-id>", "\u6307\u5B9A\u4FBF\u7B7E\uFF0C\u53EF\u91CD\u590D", collect, []).option("--closed-before-hours <hours>", "\u6298\u53E0\u5173\u95ED\u8D85\u8FC7\u8FD9\u4E48\u4E45\u7684\u4FBF\u7B7E").option("--reason <text>", "\u539F\u56E0").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.notesArchive?.(options));
6053
6060
  notes.command("unarchive").description("\u4ECE\u5F52\u6863\u533A\u53D6\u51FA\u4FBF\u7B7E").option("--batch <batch-id>", "\u53D6\u51FA\u4E00\u6574\u6279").option("--task <task-id>", "\u53D6\u51FA\u5355\u5F20\uFF0C\u53EF\u91CD\u590D", collect, []).option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.notesUnarchive?.(options));
6054
- const settings = program.command("settings").description("\u4E3B\u4F1A\u8BDD\u8BBE\u7F6E");
6055
- settings.command("show").description("\u67E5\u770B\u8BBE\u7F6E").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.settingsGet?.(options));
6056
- settings.command("quiet-hours").description("\u8BBE\u7F6E\u514D\u6253\u6270\u65F6\u6BB5\uFF08\u9ED8\u8BA4\u5173\u95ED\uFF09").option("--enabled", "\u5F00\u542F\u514D\u6253\u6270").option("--off", "\u5173\u95ED\u514D\u6253\u6270").option("--start <HH:MM>", "\u5F00\u59CB\u65F6\u95F4").option("--end <HH:MM>", "\u7ED3\u675F\u65F6\u95F4").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.settingsQuietHours?.(options));
6057
6061
  const draft = program.command("draft").description("\u5BF9\u5916\u56DE\u590D\u8349\u7A3F\uFF1A\u786E\u8BA4\u540E\u624D\u53D1\u9001");
6058
6062
  draft.command("create").description("\u521B\u5EFA\u8349\u7A3F").requiredOption("--channel <channel>", "github_comment / lark_reply").option("--target <target>", "\u5982 github:owner/repo#12\uFF1Blark_reply \u53EF\u6539\u7528 --chat").option("--body-file <file>", "\u6B63\u6587\u6587\u4EF6\uFF1B- \u8868\u793A stdin").option("--chat <chat>", "lark_reply \u76EE\u6807\u7FA4\u540D\u6216 chat_id").option("--reply-to <target>", "lark_reply \u56DE\u590D\u76EE\u6807\uFF1Aom_* / \u6570\u5B57 rootId / \u5173\u952E\u5B57").option("--in-thread", "lark_reply \u5728\u8BDD\u9898\u5185\u56DE\u590D").option("--at <user>", "lark_reply \u8981 @ \u7684\u59D3\u540D\u3001ou_* open_id \u6216\u6570\u5B57 userId\uFF0C\u53EF\u91CD\u590D", collect, []).option("--task <task-id>", "\u5173\u8054\u4E8B\u9879").option("--from <session-id>", "\u6765\u6E90\u4F1A\u8BDD\uFF1B\u9ED8\u8BA4 $agentdock_session_id").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.draftCreate?.(options));
6059
6063
  draft.command("list").description("\u5217\u51FA\u8349\u7A3F").option("--json", "\u8F93\u51FA JSON").action((options) => handlers.draftList?.(options));
@@ -6129,9 +6133,9 @@ Changes take effect immediately; no restart needed.`);
6129
6133
  autostart.command(action).description(description).option("--json", "Output raw JSON").action((options) => handlers.autostart?.(action, options));
6130
6134
  }
6131
6135
  const addProcessCommands = (parent) => {
6132
- parent.command("start").description("Start the AgentDock server in the background").action((options, command) => handlers.daemonStart?.(serverOptionsFrom(options, command)));
6136
+ addServerOptions(parent.command("start").description("Start the AgentDock server in the background")).action((options, command) => handlers.daemonStart?.(serverOptionsFrom(options, command)));
6133
6137
  parent.command("stop").description("Stop the background AgentDock server").action(() => handlers.daemonStop?.());
6134
- parent.command("restart").description("Restart the background AgentDock server").action((options, command) => handlers.daemonRestart?.(serverOptionsFrom(options, command)));
6138
+ addServerOptions(parent.command("restart").description("Restart the background AgentDock server")).action((options, command) => handlers.daemonRestart?.(serverOptionsFrom(options, command)));
6135
6139
  parent.command("status").description("Show whether the background AgentDock server is running").option("--json", "Output raw status as JSON").action((options) => handlers.daemonStatus?.(options));
6136
6140
  };
6137
6141
  addProcessCommands(program);
@@ -6307,8 +6311,8 @@ var KeepAwakeService = class {
6307
6311
  const child = (this.options.spawn ?? spawn2)(this.caffeinatePath, this.args(), { stdio: "ignore" });
6308
6312
  this.child = child;
6309
6313
  try {
6310
- await new Promise((resolve13, reject2) => {
6311
- child.once("spawn", resolve13);
6314
+ await new Promise((resolve14, reject2) => {
6315
+ child.once("spawn", resolve14);
6312
6316
  child.once("error", reject2);
6313
6317
  });
6314
6318
  } catch (error) {
@@ -6368,7 +6372,7 @@ var PROCESS_HELPER_TIMEOUT_MS = 8e3;
6368
6372
  var PROCESS_HELPER_MAX_BUFFER_BYTES = 33554432;
6369
6373
  async function runTimedExecFile(command, args, options = {}) {
6370
6374
  const timeoutMs = Math.max(1, Math.round(options.timeoutMs ?? 8e3));
6371
- return await new Promise((resolve13, reject2) => {
6375
+ return await new Promise((resolve14, reject2) => {
6372
6376
  let settled = false;
6373
6377
  let timer;
6374
6378
  const child = execFile2(command, [...args], {
@@ -6385,7 +6389,7 @@ async function runTimedExecFile(command, args, options = {}) {
6385
6389
  reject2(error);
6386
6390
  return;
6387
6391
  }
6388
- resolve13(stdout);
6392
+ resolve14(stdout);
6389
6393
  });
6390
6394
  timer = setTimeout(() => {
6391
6395
  if (settled) return;
@@ -6419,10 +6423,10 @@ function isoNow() {
6419
6423
  return (/* @__PURE__ */ new Date()).toISOString();
6420
6424
  }
6421
6425
  function waitForSpawn(child) {
6422
- return new Promise((resolve13, reject2) => {
6426
+ return new Promise((resolve14, reject2) => {
6423
6427
  const onSpawn = () => {
6424
6428
  child.off("error", onError);
6425
- resolve13();
6429
+ resolve14();
6426
6430
  };
6427
6431
  const onError = (error) => {
6428
6432
  child.off("spawn", onSpawn);
@@ -6441,7 +6445,7 @@ function requireAgentStdio(child) {
6441
6445
  }
6442
6446
  function waitForChildExit(child, timeoutMs) {
6443
6447
  if (!isChildProcessRunning(child)) return Promise.resolve(true);
6444
- return new Promise((resolve13) => {
6448
+ return new Promise((resolve14) => {
6445
6449
  let settled = false;
6446
6450
  const timer = setTimeout(() => {
6447
6451
  finish(false);
@@ -6452,7 +6456,7 @@ function waitForChildExit(child, timeoutMs) {
6452
6456
  child.off("close", onExitLike);
6453
6457
  child.off("exit", onExitLike);
6454
6458
  clearTimeout(timer);
6455
- resolve13(value);
6459
+ resolve14(value);
6456
6460
  };
6457
6461
  const onExitLike = () => {
6458
6462
  finish(true);
@@ -8903,7 +8907,7 @@ async function withTimeout(promise, timeoutMs) {
8903
8907
  }
8904
8908
  }
8905
8909
  async function withInterrupt(run2, onInterrupt) {
8906
- return await new Promise((resolve13, reject2) => {
8910
+ return await new Promise((resolve14, reject2) => {
8907
8911
  let settled = false;
8908
8912
  const finish = (cb) => {
8909
8913
  if (settled) return;
@@ -8928,7 +8932,7 @@ async function withInterrupt(run2, onInterrupt) {
8928
8932
  process.once("SIGINT", onSigint);
8929
8933
  process.once("SIGTERM", onSigterm);
8930
8934
  process.once("SIGHUP", onSighup);
8931
- run2().then((result) => finish(() => resolve13(result)), (error) => finish(() => reject2(error)));
8935
+ run2().then((result) => finish(() => resolve14(result)), (error) => finish(() => reject2(error)));
8932
8936
  });
8933
8937
  }
8934
8938
  function preferCodexPermissionRefusal(request, agentName) {
@@ -9004,8 +9008,8 @@ async function askPermission(options) {
9004
9008
  const signal = options.signal ? AbortSignal.any([options.signal, questionController.signal]) : questionController.signal;
9005
9009
  let onClose = () => {
9006
9010
  };
9007
- const closed = new Promise((resolve13) => {
9008
- onClose = () => resolve13(void 0);
9011
+ const closed = new Promise((resolve14) => {
9012
+ onClose = () => resolve14(void 0);
9009
9013
  rl.once("close", onClose);
9010
9014
  });
9011
9015
  try {
@@ -9833,8 +9837,8 @@ function captureCommandProbeOutput(child, timeoutMs, retire) {
9833
9837
  let disposed = false;
9834
9838
  let timer;
9835
9839
  let resolveResult;
9836
- const result = new Promise((resolve13) => {
9837
- resolveResult = resolve13;
9840
+ const result = new Promise((resolve14) => {
9841
+ resolveResult = resolve14;
9838
9842
  });
9839
9843
  const finish = (value) => {
9840
9844
  if (settled) return;
@@ -10253,8 +10257,8 @@ function canPromptForPermission() {
10253
10257
  return process.stdin.isTTY && process.stderr.isTTY;
10254
10258
  }
10255
10259
  function waitMs2(ms) {
10256
- return new Promise((resolve13) => {
10257
- setTimeout(resolve13, Math.max(0, ms));
10260
+ return new Promise((resolve14) => {
10261
+ setTimeout(resolve14, Math.max(0, ms));
10258
10262
  });
10259
10263
  }
10260
10264
  function onStreamError() {
@@ -10313,8 +10317,8 @@ var TerminalManager = class {
10313
10317
  const { proc, spawnCommand } = await spawnTerminalProcess(params, this.cwd, authority);
10314
10318
  let resolveExit = () => {
10315
10319
  };
10316
- const exitPromise = new Promise((resolve13) => {
10317
- resolveExit = resolve13;
10320
+ const exitPromise = new Promise((resolve14) => {
10321
+ resolveExit = resolve14;
10318
10322
  });
10319
10323
  const terminal = {
10320
10324
  process: proc,
@@ -10747,8 +10751,8 @@ function elicitationRequestScopeId(request) {
10747
10751
  }
10748
10752
  async function raceWithAbort(signal, pending) {
10749
10753
  let onAbort;
10750
- const aborted = new Promise((resolve13) => {
10751
- onAbort = () => resolve13(void 0);
10754
+ const aborted = new Promise((resolve14) => {
10755
+ onAbort = () => resolve14(void 0);
10752
10756
  if (signal.aborted) onAbort();
10753
10757
  else signal.addEventListener("abort", onAbort, { once: true });
10754
10758
  });
@@ -11211,8 +11215,8 @@ var AcpClient = class {
11211
11215
  async admitSpawnedProcess(child, observe, admit) {
11212
11216
  let releaseExitNotification = () => {
11213
11217
  };
11214
- observe(new Promise((resolve13) => {
11215
- releaseExitNotification = resolve13;
11218
+ observe(new Promise((resolve14) => {
11219
+ releaseExitNotification = resolve14;
11216
11220
  }));
11217
11221
  try {
11218
11222
  await admit();
@@ -11592,8 +11596,8 @@ var AcpClient = class {
11592
11596
  const activePromise = active.promise;
11593
11597
  if (!activePromise) return;
11594
11598
  let timer;
11595
- const timeoutPromise = new Promise((resolve13) => {
11596
- timer = setTimeout(resolve13, waitMs3);
11599
+ const timeoutPromise = new Promise((resolve14) => {
11600
+ timer = setTimeout(resolve14, waitMs3);
11597
11601
  });
11598
11602
  try {
11599
11603
  return await Promise.race([activePromise.then((response) => response, () => void 0), timeoutPromise]);
@@ -12113,7 +12117,7 @@ var AcpClient = class {
12113
12117
  return error;
12114
12118
  }
12115
12119
  async runConnectionRequest(run2, authority, mapRequestError) {
12116
- return await new Promise((resolve13, reject2) => {
12120
+ return await new Promise((resolve14, reject2) => {
12117
12121
  const rejectRequestError = (error) => {
12118
12122
  try {
12119
12123
  reject2(mapRequestError ? mapRequestError(error) : error);
@@ -12145,7 +12149,7 @@ var AcpClient = class {
12145
12149
  value: await run2()
12146
12150
  };
12147
12151
  }).then((outcome) => {
12148
- if (outcome.started) finish(() => resolve13(outcome.value));
12152
+ if (outcome.started) finish(() => resolve14(outcome.value));
12149
12153
  }, (error) => finish(() => rejectRequestError(error)));
12150
12154
  });
12151
12155
  }
@@ -12250,8 +12254,8 @@ var AcpClient = class {
12250
12254
  await this.sessionUpdateChain;
12251
12255
  if (this.processedSessionUpdates === this.observedSessionUpdates) return;
12252
12256
  }
12253
- await new Promise((resolve13) => {
12254
- setTimeout(resolve13, DRAIN_POLL_INTERVAL_MS);
12257
+ await new Promise((resolve14) => {
12258
+ setTimeout(resolve14, DRAIN_POLL_INTERVAL_MS);
12255
12259
  });
12256
12260
  }
12257
12261
  throw new Error(`Timed out waiting for session replay drain after ${normalizedTimeoutMs}ms`);
@@ -14501,14 +14505,14 @@ function commandRecord(value) {
14501
14505
  return value;
14502
14506
  }
14503
14507
  function createDeferred() {
14504
- let resolve13;
14508
+ let resolve14;
14505
14509
  let reject2;
14506
14510
  return {
14507
14511
  promise: new Promise((res, rej) => {
14508
- resolve13 = res;
14512
+ resolve14 = res;
14509
14513
  reject2 = rej;
14510
14514
  }),
14511
- resolve: resolve13,
14515
+ resolve: resolve14,
14512
14516
  reject: reject2
14513
14517
  };
14514
14518
  }
@@ -15086,8 +15090,8 @@ var AcpRuntimeManager = class {
15086
15090
  async serializeManagerOperation(locks, key, run2) {
15087
15091
  const previous = locks.get(key) ?? Promise.resolve();
15088
15092
  let release;
15089
- const gate = new Promise((resolve13) => {
15090
- release = resolve13;
15093
+ const gate = new Promise((resolve14) => {
15094
+ release = resolve14;
15091
15095
  });
15092
15096
  const tail2 = previous.then(() => gate);
15093
15097
  locks.set(key, tail2);
@@ -16311,7 +16315,7 @@ try {
16311
16315
  }
16312
16316
  `;
16313
16317
  function testRegexWithTimeout(pattern, input, timeoutMs = 1e3) {
16314
- return new Promise((resolve13, reject2) => {
16318
+ return new Promise((resolve14, reject2) => {
16315
16319
  const worker = new Worker(workerSource, { eval: true, workerData: { pattern, input } });
16316
16320
  let settled = false;
16317
16321
  const finish = (callback) => {
@@ -16323,7 +16327,7 @@ function testRegexWithTimeout(pattern, input, timeoutMs = 1e3) {
16323
16327
  callback();
16324
16328
  };
16325
16329
  const timer = setTimeout(() => finish(() => reject2(new RegexMatchTimeoutError(timeoutMs))), timeoutMs);
16326
- worker.once("message", (result) => finish(() => result.error ? reject2(new Error(`\u6B63\u5219\u5339\u914D\u5931\u8D25\uFF1A${result.error}`)) : resolve13(result.matched === true)));
16330
+ worker.once("message", (result) => finish(() => result.error ? reject2(new Error(`\u6B63\u5219\u5339\u914D\u5931\u8D25\uFF1A${result.error}`)) : resolve14(result.matched === true)));
16327
16331
  worker.once("error", (error) => finish(() => reject2(error)));
16328
16332
  worker.once("exit", (code) => {
16329
16333
  if (code !== 0) finish(() => reject2(new Error(`\u6B63\u5219\u5339\u914D\u9694\u79BB\u4EFB\u52A1\u5F02\u5E38\u9000\u51FA\uFF1A${code}`)));
@@ -16571,10 +16575,10 @@ async function terminateExternalChild(child, graceMs = 5e3) {
16571
16575
  } catch {
16572
16576
  }
16573
16577
  if (child.exitCode !== null || child.signalCode !== null) return;
16574
- await new Promise((resolve13) => {
16578
+ await new Promise((resolve14) => {
16575
16579
  const done = () => {
16576
16580
  clearTimeout(timer);
16577
- resolve13();
16581
+ resolve14();
16578
16582
  };
16579
16583
  const timer = setTimeout(() => {
16580
16584
  if (child.exitCode === null) child.kill("SIGKILL");
@@ -16779,7 +16783,7 @@ var AcpxAdapter = class {
16779
16783
  if (this.permissionMode === "deny-all") return { outcome: "reject_once" };
16780
16784
  if (this.permissionMode === "approve-reads" && /read|search|fetch/i.test(String(request.inferredKind ?? ""))) return { outcome: "allow_once" };
16781
16785
  this.options.onEvent({ type: "permission_request", data: { id, toolCallId: raw.toolCall?.toolCallId, title: raw.toolCall?.title ?? "Permission required", options: raw.options ?? [], status: "pending" } });
16782
- return new Promise((resolve13) => this.pendingPermissions.set(id, resolve13));
16786
+ return new Promise((resolve14) => this.pendingPermissions.set(id, resolve14));
16783
16787
  }
16784
16788
  });
16785
16789
  }
@@ -16990,7 +16994,7 @@ var AcpxAdapter = class {
16990
16994
  await this.start();
16991
16995
  }
16992
16996
  async stop(options = {}) {
16993
- for (const resolve13 of this.pendingPermissions.values()) resolve13({ outcome: "reject_once" });
16997
+ for (const resolve14 of this.pendingPermissions.values()) resolve14({ outcome: "reject_once" });
16994
16998
  this.pendingPermissions.clear();
16995
16999
  const turn = this.turn;
16996
17000
  if (turn) {
@@ -17006,10 +17010,10 @@ var AcpxAdapter = class {
17006
17010
  if (options.discardSession) await this.resetPersistentState();
17007
17011
  }
17008
17012
  async resolvePermission(id, approved) {
17009
- const resolve13 = this.pendingPermissions.get(id);
17010
- if (!resolve13) return false;
17013
+ const resolve14 = this.pendingPermissions.get(id);
17014
+ if (!resolve14) return false;
17011
17015
  this.pendingPermissions.delete(id);
17012
- resolve13({ outcome: approved ? "allow_once" : "reject_once" });
17016
+ resolve14({ outcome: approved ? "allow_once" : "reject_once" });
17013
17017
  return true;
17014
17018
  }
17015
17019
  async setModel(model) {
@@ -17878,7 +17882,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
17878
17882
  return await driver.start();
17879
17883
  } catch (error) {
17880
17884
  if (!this.resumeOptions(session) || attempt >= 4 || !mentionsActiveWriter(error)) throw error;
17881
- await new Promise((resolve13) => setTimeout(resolve13, 1500));
17885
+ await new Promise((resolve14) => setTimeout(resolve14, 1500));
17882
17886
  }
17883
17887
  }
17884
17888
  }
@@ -17981,7 +17985,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
17981
17985
  this.activeTurns.delete(id);
17982
17986
  this.activeTasks.delete(id);
17983
17987
  this.touch(id);
17984
- for (const resolve13 of this.turnWaiters.get(id) ?? []) resolve13();
17988
+ for (const resolve14 of this.turnWaiters.get(id) ?? []) resolve14();
17985
17989
  this.turnWaiters.delete(id);
17986
17990
  if (!hardInterrupted) this.scheduleQueue(id);
17987
17991
  }
@@ -18039,9 +18043,9 @@ var AgentDockRuntime = class _AgentDockRuntime {
18039
18043
  }
18040
18044
  let timer;
18041
18045
  try {
18042
- return await new Promise((resolve13) => {
18043
- timer = setTimeout(() => resolve13(true), timeoutMs);
18044
- void turn.then(() => resolve13(false));
18046
+ return await new Promise((resolve14) => {
18047
+ timer = setTimeout(() => resolve14(true), timeoutMs);
18048
+ void turn.then(() => resolve14(false));
18045
18049
  });
18046
18050
  } finally {
18047
18051
  if (timer) clearTimeout(timer);
@@ -18262,9 +18266,9 @@ var AgentDockRuntime = class _AgentDockRuntime {
18262
18266
  }
18263
18267
  waitForTurn(id) {
18264
18268
  if (!this.activeTurns.has(id)) return Promise.resolve();
18265
- return new Promise((resolve13) => {
18269
+ return new Promise((resolve14) => {
18266
18270
  const waiters = this.turnWaiters.get(id) ?? /* @__PURE__ */ new Set();
18267
- waiters.add(resolve13);
18271
+ waiters.add(resolve14);
18268
18272
  this.turnWaiters.set(id, waiters);
18269
18273
  });
18270
18274
  }
@@ -18380,7 +18384,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
18380
18384
  this.queuedAgentPrompts.delete(sessionId);
18381
18385
  this.queuedRiskPolicies.delete(sessionId);
18382
18386
  this.queueRuns.delete(sessionId);
18383
- for (const resolve13 of this.turnWaiters.get(sessionId) ?? []) resolve13();
18387
+ for (const resolve14 of this.turnWaiters.get(sessionId) ?? []) resolve14();
18384
18388
  this.turnWaiters.delete(sessionId);
18385
18389
  for (const key of this.permissions.keys()) if (key.startsWith(`${sessionId}:`)) this.permissions.delete(key);
18386
18390
  }
@@ -18429,7 +18433,7 @@ var AgentDockRuntime = class _AgentDockRuntime {
18429
18433
  this.driverEventChains.clear();
18430
18434
  this.driverEventErrors.clear();
18431
18435
  this.openToolCalls.clear();
18432
- for (const waiters of this.turnWaiters.values()) for (const resolve13 of waiters) resolve13();
18436
+ for (const waiters of this.turnWaiters.values()) for (const resolve14 of waiters) resolve14();
18433
18437
  this.turnWaiters.clear();
18434
18438
  this.queues.clear();
18435
18439
  this.queuedAgentPrompts.clear();
@@ -20989,7 +20993,7 @@ printf 'codex=%s\\n' "$(command -v codex 2>/dev/null)"
20989
20993
  printf 'home=%s\\n' "$HOME"
20990
20994
  `;
20991
20995
  function runSsh(host, script, timeoutMs) {
20992
- return new Promise((resolve13) => {
20996
+ return new Promise((resolve14) => {
20993
20997
  let stdout = "";
20994
20998
  let stderr = "";
20995
20999
  let settled = false;
@@ -20999,12 +21003,12 @@ function runSsh(host, script, timeoutMs) {
20999
21003
  if (settled) return;
21000
21004
  settled = true;
21001
21005
  clearTimeout(timer);
21002
- resolve13(result);
21006
+ resolve14(result);
21003
21007
  };
21004
21008
  try {
21005
21009
  child = spawn8("ssh", [...sshArgs(host), `sh -c ${shellQuote3(script)}`], { stdio: ["ignore", "pipe", "pipe"] });
21006
21010
  } catch (error) {
21007
- resolve13({ code: null, stdout, stderr, timedOut: false, error: error instanceof Error ? error.message : String(error) });
21011
+ resolve14({ code: null, stdout, stderr, timedOut: false, error: error instanceof Error ? error.message : String(error) });
21008
21012
  return;
21009
21013
  }
21010
21014
  const timer = setTimeout(() => {
@@ -21101,7 +21105,7 @@ function normalizeCodexUsage(result, checkedAt = Date.now()) {
21101
21105
  return { status: "available", plan: bucket.planType ?? void 0, windows, checkedAt };
21102
21106
  }
21103
21107
  function readFromCodex() {
21104
- return new Promise((resolve13) => {
21108
+ return new Promise((resolve14) => {
21105
21109
  let settled = false;
21106
21110
  let buffer = "";
21107
21111
  let child;
@@ -21110,7 +21114,7 @@ function readFromCodex() {
21110
21114
  settled = true;
21111
21115
  clearTimeout(timer);
21112
21116
  child?.kill();
21113
- resolve13(usage);
21117
+ resolve14(usage);
21114
21118
  };
21115
21119
  const unavailable = (reason) => ({ status: "unavailable", reason, windows: [], checkedAt: Date.now() });
21116
21120
  const timer = setTimeout(() => done(unavailable("Codex \u989D\u5EA6\u67E5\u8BE2\u8D85\u65F6")), 8e3);
@@ -21821,29 +21825,12 @@ function registerLifecycleRoutes(app, assistant) {
21821
21825
 
21822
21826
  // src/assistant/routes.ts
21823
21827
  var bad2 = (message) => new RuntimeError("INVALID_ASSISTANT_INPUT", message, 400);
21824
- var emojiSegmenter = typeof Intl !== "undefined" && "Segmenter" in Intl ? new Intl.Segmenter("zh", { granularity: "grapheme" }) : void 0;
21825
- function normalizeSilentEmoji(value) {
21826
- if (value === null || value === void 0) return "";
21827
- if (typeof value !== "string") throw bad2("\u9759\u9ED8\u89E6\u53D1\u8868\u60C5\u5FC5\u987B\u662F\u5355\u4E2A emoji");
21828
- const text3 = value.trim();
21829
- if (!text3) return "";
21830
- const graphemes = emojiSegmenter ? [...emojiSegmenter.segment(text3)].map((part) => part.segment) : Array.from(text3);
21831
- const emojiLike = new RegExp("\\p{Extended_Pictographic}", "u").test(text3) || /^[\u{1F1E6}-\u{1F1FF}]{2}$/u.test(text3) || /\u20E3/u.test(text3);
21832
- if (graphemes.length !== 1 || !emojiLike) throw bad2("\u9759\u9ED8\u89E6\u53D1\u8868\u60C5\u5FC5\u987B\u662F\u5355\u4E2A emoji");
21833
- return text3;
21834
- }
21835
21828
  function assertMain(assistant, from) {
21836
21829
  const main2 = assistant.mainSessionId;
21837
21830
  if (!main2) throw bad2("\u8FD8\u6CA1\u6709\u6307\u5B9A\u4E3B\u4F1A\u8BDD");
21838
21831
  if (from && from !== main2) throw new RuntimeError("FORBIDDEN", "\u53EA\u6709\u4E3B\u4F1A\u8BDD\u80FD\u6267\u884C\u8FD9\u4E2A\u64CD\u4F5C", 403);
21839
21832
  return main2;
21840
21833
  }
21841
- function assertSettingsCaller(assistant, from) {
21842
- if (!from) return;
21843
- const main2 = assistant.mainSessionId;
21844
- if (!main2) throw bad2("\u8FD8\u6CA1\u6709\u6307\u5B9A\u4E3B\u4F1A\u8BDD");
21845
- if (from !== main2) throw new RuntimeError("FORBIDDEN", "\u53EA\u6709\u4E3B\u4F1A\u8BDD\u80FD\u6267\u884C\u8FD9\u4E2A\u64CD\u4F5C", 403);
21846
- }
21847
21834
  function registerAssistantRoutes(app, assistant) {
21848
21835
  app.get("/api/assistant/main", async () => ({
21849
21836
  sessionId: assistant.mainSessionId ?? null,
@@ -21871,6 +21858,10 @@ function registerAssistantRoutes(app, assistant) {
21871
21858
  }
21872
21859
  throw bad2("sessionId \u6216 agentId \u5FC5\u586B");
21873
21860
  });
21861
+ app.post("/api/assistant/main/restore", async (request) => {
21862
+ const sessionId = request.body?.sessionId?.trim() || void 0;
21863
+ return assistant.restoreMainSession(sessionId);
21864
+ });
21874
21865
  app.put("/api/assistant/companion", async (request) => {
21875
21866
  assertMain(assistant, request.body?.from);
21876
21867
  if (!request.body?.name?.trim()) throw bad2("name \u5FC5\u586B");
@@ -21883,31 +21874,10 @@ function registerAssistantRoutes(app, assistant) {
21883
21874
  await assistant.clearMainSession();
21884
21875
  return { ok: true };
21885
21876
  });
21886
- app.get("/api/assistant/settings", async () => ({
21887
- mainSessionId: assistant.mainSessionId ?? null,
21888
- quietHours: assistant.getQuietHours(),
21889
- silentEmoji: assistant.getSilentEmoji()
21890
- }));
21891
- app.put("/api/assistant/settings", async (request) => {
21892
- assertSettingsCaller(assistant, request.body?.from);
21893
- const body = request.body ?? {};
21894
- const hasQuietHours = body.quietHours !== void 0;
21895
- const hasSilentEmoji = Object.hasOwn(body, "silentEmoji");
21896
- if (!hasQuietHours && !hasSilentEmoji) throw bad2("quietHours \u6216 silentEmoji \u81F3\u5C11\u586B\u4E00\u4E2A");
21897
- const quietHours = hasQuietHours ? assistant.setQuietHours({
21898
- enabled: body.quietHours?.enabled === true,
21899
- start: body.quietHours?.start ?? "23:00",
21900
- end: body.quietHours?.end ?? "08:00"
21901
- }) : assistant.getQuietHours();
21902
- const silentEmoji = hasSilentEmoji ? assistant.setSilentEmoji(normalizeSilentEmoji(body.silentEmoji)) : assistant.getSilentEmoji();
21903
- return { quietHours, silentEmoji };
21904
- });
21905
21877
  app.get("/api/assistant/state", async () => ({
21906
21878
  mainSessionId: assistant.mainSessionId ?? null,
21907
21879
  mainSession: await assistant.getMainSession() ?? null,
21908
21880
  companion: await assistant.getCompanion() ?? null,
21909
- quietHours: assistant.getQuietHours(),
21910
- silentEmoji: assistant.getSilentEmoji(),
21911
21881
  tasks: assistant.listTasks(),
21912
21882
  watches: assistant.listWatches(),
21913
21883
  drafts: assistant.listDrafts(),
@@ -21943,7 +21913,13 @@ function registerAssistantRoutes(app, assistant) {
21943
21913
  app.post("/api/assistant/tasks/:id/start", async (request) => {
21944
21914
  assertMain(assistant, request.body?.from);
21945
21915
  await assistant.lifecycle.assertNoSystemRound(request.body?.from, "\u8BA9\u8BA1\u5212\u5361\u5F00\u5DE5");
21946
- return { task: await assistant.startPlannedTask(request.params.id) };
21916
+ const body = request.body ?? {};
21917
+ return { task: await assistant.startPlannedTask(request.params.id, {
21918
+ ...body.agentId?.trim() ? { agentId: body.agentId.trim() } : {},
21919
+ ...body.cwd?.trim() ? { cwd: body.cwd.trim() } : {},
21920
+ ...body.model?.trim() ? { model: body.model.trim() } : {},
21921
+ ...body.reasoningEffort?.trim() ? { reasoningEffort: body.reasoningEffort.trim() } : {}
21922
+ }) };
21947
21923
  });
21948
21924
  app.post("/api/assistant/tasks/:id/review", async (request) => {
21949
21925
  assertMain(assistant, request.body?.from);
@@ -23906,7 +23882,7 @@ async function buildApp(runtime, options = {}) {
23906
23882
  } catch (error) {
23907
23883
  const detail = describeAcpError(error);
23908
23884
  if (attempt < 3 && /active writer/i.test(detail)) {
23909
- await new Promise((resolve13) => setTimeout(resolve13, 1200));
23885
+ await new Promise((resolve14) => setTimeout(resolve14, 1200));
23910
23886
  continue;
23911
23887
  }
23912
23888
  throw error;
@@ -23962,7 +23938,10 @@ async function buildApp(runtime, options = {}) {
23962
23938
  return result ?? { ok: true };
23963
23939
  });
23964
23940
  }
23965
- app.post("/api/sessions/:id/archive", async (request) => runtime.archive(request.params.id));
23941
+ app.post("/api/sessions/:id/archive", async (request) => {
23942
+ await options.assistant?.assertSessionArchivable(request.params.id);
23943
+ return runtime.archive(request.params.id);
23944
+ });
23966
23945
  app.post("/api/sessions/:id/permissions/:permissionId", async (request) => runtime.resolvePermission(request.params.id, request.params.permissionId, request.body.approved));
23967
23946
  app.get("/api/sessions/:id/events", async (request, reply) => {
23968
23947
  if (request.query.limit !== void 0) {
@@ -23988,7 +23967,7 @@ async function buildApp(runtime, options = {}) {
23988
23967
  return await loadExternalSessionTranscript(effective, session.sourceId, session.cwd, { timeoutMs: 6e4 });
23989
23968
  } catch (error) {
23990
23969
  if (attempt < 3 && /active writer/i.test(describeAcpError(error))) {
23991
- await new Promise((resolve13) => setTimeout(resolve13, 1200));
23970
+ await new Promise((resolve14) => setTimeout(resolve14, 1200));
23992
23971
  continue;
23993
23972
  }
23994
23973
  throw error;
@@ -24168,11 +24147,11 @@ event: ${event.type}
24168
24147
  data: ${JSON.stringify(event)}
24169
24148
 
24170
24149
  `);
24171
- const drain = () => new Promise((resolve13) => {
24150
+ const drain = () => new Promise((resolve14) => {
24172
24151
  const finish = () => {
24173
24152
  reply.raw.off("drain", finish);
24174
24153
  reply.raw.off("close", finish);
24175
- resolve13();
24154
+ resolve14();
24176
24155
  };
24177
24156
  reply.raw.once("drain", finish);
24178
24157
  reply.raw.once("close", finish);
@@ -25793,7 +25772,7 @@ var LarkProtocolClient = class {
25793
25772
  }
25794
25773
  async connectOnce() {
25795
25774
  const url = await this.buildWsUrl();
25796
- return new Promise((resolve13, reject2) => {
25775
+ return new Promise((resolve14, reject2) => {
25797
25776
  const ws = new WebSocket(url, {
25798
25777
  headers: { "user-agent": USER_AGENT2 },
25799
25778
  handshakeTimeout: 15e3
@@ -25821,7 +25800,7 @@ var LarkProtocolClient = class {
25821
25800
  this.clearHeartbeat();
25822
25801
  });
25823
25802
  this.startHeartbeat(ws);
25824
- resolve13(ws);
25803
+ resolve14(ws);
25825
25804
  });
25826
25805
  ws.once("error", (error) => fail(error));
25827
25806
  ws.once("close", () => fail(new Error("WebSocket closed before open")));
@@ -25829,14 +25808,14 @@ var LarkProtocolClient = class {
25829
25808
  }
25830
25809
  waitForClose(ws) {
25831
25810
  if (ws.readyState === WebSocket.CLOSED) return Promise.resolve();
25832
- return new Promise((resolve13) => {
25833
- ws.once("close", () => resolve13());
25811
+ return new Promise((resolve14) => {
25812
+ ws.once("close", () => resolve14());
25834
25813
  });
25835
25814
  }
25836
25815
  async sleep(ms) {
25837
25816
  const deadline = Date.now() + ms;
25838
25817
  while (this.running && Date.now() < deadline) {
25839
- await new Promise((resolve13) => setTimeout(resolve13, Math.min(250, deadline - Date.now())));
25818
+ await new Promise((resolve14) => setTimeout(resolve14, Math.min(250, deadline - Date.now())));
25840
25819
  }
25841
25820
  }
25842
25821
  startHeartbeat(ws) {
@@ -27165,8 +27144,8 @@ var LarkAvatarService = class {
27165
27144
  let sentAny = false;
27166
27145
  const buffered = [];
27167
27146
  let resolveDone;
27168
- const done = new Promise((resolve13) => {
27169
- resolveDone = resolve13;
27147
+ const done = new Promise((resolve14) => {
27148
+ resolveDone = resolve14;
27170
27149
  });
27171
27150
  const flush = () => {
27172
27151
  if (flushTimer) {
@@ -27250,12 +27229,12 @@ var LarkAvatarService = class {
27250
27229
  const pending = buffered.splice(0);
27251
27230
  for (const event of pending) handle(event);
27252
27231
  const timeoutMs = input.timeoutMs ?? 0;
27253
- const timeoutPromise = timeoutMs > 0 ? new Promise((resolve13) => {
27232
+ const timeoutPromise = timeoutMs > 0 ? new Promise((resolve14) => {
27254
27233
  timeout = setTimeout(() => {
27255
27234
  terminal = "timeout";
27256
27235
  settled = true;
27257
27236
  flush();
27258
- resolve13();
27237
+ resolve14();
27259
27238
  }, timeoutMs);
27260
27239
  timeout.unref?.();
27261
27240
  }) : void 0;
@@ -27734,7 +27713,7 @@ ${signature}` : body;
27734
27713
  throw new RuntimeError("NO_MAIN_SESSION", "\u8FD8\u6CA1\u6709\u4E3B\u4F1A\u8BDD\uFF0C\u65E0\u6CD5\u53D1\u9001\u8868\u60C5\u89E6\u53D1\u8F6E\u6B21", 409);
27735
27714
  }
27736
27715
  const task = await this.mainSession.dispatch({
27737
- // origin=emoji 与网页端「静默触发表情」一致:不新增用户气泡、不打扰。
27716
+ // origin=emoji:时间线不新增用户气泡,也不打扰用户。
27738
27717
  prompt: `\u98DE\u4E66\u8868\u60C5\u89E6\u53D1\uFF08${input.emoji}\uFF09\uFF1A${reactionSummary(input.message, 80)}`,
27739
27718
  agentPrompt,
27740
27719
  origin: "emoji",
@@ -27954,7 +27933,7 @@ ${signature}` : body;
27954
27933
  if (activeTurns.length) {
27955
27934
  await Promise.race([
27956
27935
  Promise.allSettled(activeTurns),
27957
- new Promise((resolve13) => setTimeout(resolve13, 5e3))
27936
+ new Promise((resolve14) => setTimeout(resolve14, 5e3))
27958
27937
  ]);
27959
27938
  }
27960
27939
  if (this.ownsStore) this.store.close();
@@ -28422,6 +28401,7 @@ var ASSISTANT_SCHEMA = `
28422
28401
  created_at TEXT NOT NULL, sent_at TEXT
28423
28402
  );
28424
28403
  CREATE INDEX IF NOT EXISTS assistant_drafts_state ON assistant_drafts(state, created_at);
28404
+ -- \u9759\u9ED8\u65F6\u6BB5\u5DF2\u4E0B\u7EBF\uFF1A\u5386\u53F2 state='pending' \u7684\u901A\u77E5\u884C\u539F\u6837\u4FDD\u7559\uFF0C\u4E0D\u518D\u8BFB\u53D6\u6216\u8865\u53D1\u3002
28425
28405
  CREATE TABLE IF NOT EXISTS assistant_notifications (
28426
28406
  id TEXT PRIMARY KEY, text TEXT NOT NULL, ask INTEGER NOT NULL DEFAULT 0,
28427
28407
  urgent INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL,
@@ -28789,12 +28769,6 @@ var AssistantStore = class {
28789
28769
  this.sqlite.prepare("INSERT INTO assistant_notifications (id, text, ask, urgent, state, created_at, sent_at) VALUES (?, ?, ?, ?, ?, ?, ?)").run(id, text3, ask ? 1 : 0, urgent ? 1 : 0, state, now(), state === "sent" ? now() : null);
28790
28770
  return id;
28791
28771
  }
28792
- listPendingNotifications() {
28793
- return this.sqlite.prepare("SELECT id, text, ask, urgent, created_at FROM assistant_notifications WHERE state = 'pending' ORDER BY created_at").all().map((row) => ({ id: row.id, text: row.text, ask: row.ask === 1, urgent: row.urgent === 1, createdAt: row.created_at }));
28794
- }
28795
- markNotificationSent(id) {
28796
- this.sqlite.prepare("UPDATE assistant_notifications SET state = 'sent', sent_at = ? WHERE id = ?").run(now(), id);
28797
- }
28798
28772
  // ---- 归档区:已关闭便签折叠进批次,只读、可取出 ----
28799
28773
  /** 只折叠已关闭且还没归档的;返回真正折叠了的 id(重复调用幂等)。 */
28800
28774
  archiveTasks(taskIds, batchId, at) {
@@ -29593,7 +29567,7 @@ function renderHandoffBriefing(pkg) {
29593
29567
  if (pkg.recentTurns.length) {
29594
29568
  lines.push("", "\u3010\u524D\u4EFB\u6700\u8FD1\u51E0\u8F6E\u5BF9\u8BDD\uFF08\u8282\u9009\uFF09\u3011");
29595
29569
  for (const turn of pkg.recentTurns) {
29596
- lines.push(`- ${turn.origin === "injected" ? "\u7763\u529E" : turn.origin === "emoji" ? "\u9759\u9ED8\u8F6E\u6B21" : "\u7528\u6237"}\uFF1A${turn.prompt}`);
29570
+ lines.push(`- ${turn.origin === "injected" ? "\u7763\u529E" : turn.origin === "emoji" ? "\u8868\u60C5\u89E6\u53D1\u8F6E\u6B21" : "\u7528\u6237"}\uFF1A${turn.prompt}`);
29597
29571
  if (turn.reply) lines.push(` ${p.name}\uFF1A${turn.reply}`);
29598
29572
  }
29599
29573
  }
@@ -30601,6 +30575,45 @@ function withContext(percent2) {
30601
30575
  return percent2 === void 0 ? {} : { contextPercent: percent2 };
30602
30576
  }
30603
30577
 
30578
+ // src/assistant/cwd.ts
30579
+ init_src2();
30580
+ import { accessSync, constants as constants3, statSync as statSync4 } from "node:fs";
30581
+ import { homedir as homedir14 } from "node:os";
30582
+ import { isAbsolute as isAbsolute6, resolve as resolve9 } from "node:path";
30583
+ function expandHomePath(value) {
30584
+ const trimmed = value.trim();
30585
+ if (trimmed === "~") return homedir14();
30586
+ if (trimmed.startsWith("~/") || trimmed.startsWith("~\\")) return resolve9(homedir14(), trimmed.slice(2));
30587
+ return trimmed;
30588
+ }
30589
+ function resolveCwdArgument(value, base = process.cwd()) {
30590
+ return resolve9(base, expandHomePath(value));
30591
+ }
30592
+ function validateCwd(value) {
30593
+ const trimmed = value?.trim();
30594
+ if (!trimmed) return void 0;
30595
+ const expanded = expandHomePath(trimmed);
30596
+ if (!isAbsolute6(expanded)) {
30597
+ throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u5FC5\u987B\u662F\u7EDD\u5BF9\u8DEF\u5F84\uFF1A${trimmed}`, 400);
30598
+ }
30599
+ const absolute = resolve9(expanded);
30600
+ let stats;
30601
+ try {
30602
+ stats = statSync4(absolute);
30603
+ } catch {
30604
+ throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${absolute}`, 400);
30605
+ }
30606
+ if (!stats.isDirectory()) {
30607
+ throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6\u5939\uFF1A${absolute}`, 400);
30608
+ }
30609
+ try {
30610
+ accessSync(absolute, constants3.R_OK | constants3.X_OK);
30611
+ } catch {
30612
+ throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u53EF\u8BBF\u95EE\uFF08\u9700\u8981\u8BFB\u548C\u6267\u884C\u6743\u9650\uFF09\uFF1A${absolute}`, 400);
30613
+ }
30614
+ return absolute;
30615
+ }
30616
+
30604
30617
  // src/assistant/service.ts
30605
30618
  var execFileAsync5 = promisify7(execFile7);
30606
30619
  var defaultPostGithubComment = async (input) => {
@@ -30612,13 +30625,10 @@ var defaultPostGithubComment = async (input) => {
30612
30625
  ], { timeout: 3e4 });
30613
30626
  };
30614
30627
  var MAIN_SESSION_KEY = "assistant.main";
30615
- var QUIET_HOURS_KEY = "assistant.quietHours";
30616
- var SILENT_EMOJI_KEY = "assistant.silentEmoji";
30617
30628
  var COMPANION_KEY = "assistant.companion";
30618
30629
  var DEFAULT_COMPANION_NAME = "\u5C0FA\u540C\u5B66";
30619
30630
  var MAX_COMPANION_NAME = 16;
30620
30631
  var SNAPSHOT_HASH_KEY = "assistant.snapshot.hashes";
30621
- var DEFAULT_QUIET_HOURS = { enabled: false, start: "23:00", end: "08:00" };
30622
30632
  var SIGNAL_THROTTLE_MS = {
30623
30633
  review: 10 * 6e4,
30624
30634
  needs_you: 2 * 6e4,
@@ -30691,9 +30701,20 @@ var AssistantService = class {
30691
30701
  }
30692
30702
  async initialize() {
30693
30703
  this.mainSessionIdValue = (await this.repos.config.get(MAIN_SESSION_KEY))?.trim() || void 0;
30704
+ this.warnLegacySettings();
30694
30705
  await this.refreshMainSystemPrompt();
30695
30706
  await this.lifecycle.initialize();
30696
30707
  }
30708
+ /**
30709
+ * 静默时段/静默触发表情已下线。旧库里的设置行保留原样,启动时只提示一次,
30710
+ * 不参与解析,也不能因为旧字段让 daemon 起不来。
30711
+ */
30712
+ warnLegacySettings() {
30713
+ const legacy = ["assistant.quietHours", "assistant.silentEmoji", "assistant.silentTriggerEmoji"].filter((key) => this.store.getSetting(key) !== void 0);
30714
+ if (legacy.length) {
30715
+ this.log.warn(`\u68C0\u6D4B\u5230\u5DF2\u4E0B\u7EBF\u7684\u8BBE\u7F6E ${legacy.join("\u3001")}\uFF0C\u5DF2\u5FFD\u7565\uFF1B\u65E7\u503C\u4FDD\u7559\u4F46\u4E0D\u518D\u751F\u6548\u3002`);
30716
+ }
30717
+ }
30697
30718
  /**
30698
30719
  * 主会话提示词是产品行为的一部分,升级后必须让已有主会话也拿到新版本。
30699
30720
  * 只改 assistant-main 会话,用户自己选的普通会话不动;daemon 重启后首次
@@ -30740,6 +30761,62 @@ var AssistantService = class {
30740
30761
  async listSessions() {
30741
30762
  return this.repos.sessions.list();
30742
30763
  }
30764
+ /**
30765
+ * 归档前的硬拦。当前主会话在岗时不能直接归档:归档只会停掉 driver 并写 archivedAt,
30766
+ * 不会清掉主会话指针,之后既不能继续对话,也不能发起交接(交接会拒绝已归档的前任)。
30767
+ * 已退休/已解除的主会话、以及普通会话照常允许。
30768
+ */
30769
+ async assertSessionArchivable(sessionId) {
30770
+ if (sessionId !== this.mainSessionIdValue) return;
30771
+ const session = await this.repos.sessions.get(sessionId);
30772
+ if (!session || session.archivedAt) return;
30773
+ const cat = this.store.findCatBySession(sessionId, ["active", "retired", "released", "aborted"]);
30774
+ if (cat && cat.state !== "active") return;
30775
+ throw new RuntimeError(
30776
+ "MAIN_SESSION_NEEDS_HANDOFF",
30777
+ "\u8FD9\u662F\u5F53\u524D\u4E3B\u4F1A\u8BDD\uFF0C\u4E0D\u80FD\u76F4\u63A5\u5F52\u6863\uFF1A\u5F52\u6863\u540E\u65E0\u6CD5\u7EE7\u7EED\u5BF9\u8BDD\uFF0C\u4E5F\u65E0\u6CD5\u518D\u53D1\u8D77\u4EA4\u63A5\u3002\u8BF7\u5148\u70B9\u300C\u9000\u4F11\u5E76\u4EA4\u63A5\u300D\uFF0C\u4EA4\u63A5\u5B8C\u6210\u540E\u65E7\u4E3B\u4F1A\u8BDD\u4F1A\u81EA\u52A8\u5F52\u6863\uFF1B\u5982\u679C\u53EA\u662F\u60F3\u505C\u4E0B\uFF0C\u53EF\u4EE5\u5728\u8BBE\u7F6E\u91CC\u300C\u8BA9\u5B83\u4F11\u606F\u300D\u3002",
30778
+ 409
30779
+ );
30780
+ }
30781
+ /**
30782
+ * 历史修复:旧版本允许直接归档主会话,结果主会话指针还指着只读会话,页面只剩
30783
+ * 「已永久归档」而没有任何恢复入口。这里解除当前主会话的归档并重新拉起 driver;
30784
+ * 只允许恢复当前主会话,已接班的前任保持只读,避免把血缘弄乱。
30785
+ */
30786
+ async restoreMainSession(sessionId) {
30787
+ const target = sessionId?.trim() || this.mainSessionIdValue;
30788
+ if (!target) throw new RuntimeError("NO_MAIN_SESSION", "\u8FD8\u6CA1\u6709\u6307\u5B9A\u4E3B\u4F1A\u8BDD\uFF0C\u6CA1\u6709\u53EF\u6062\u590D\u7684\u4F1A\u8BDD", 400);
30789
+ if (target !== this.mainSessionIdValue) {
30790
+ throw new RuntimeError("MAIN_SESSION_RESTORE_UNAVAILABLE", "\u53EA\u6709\u5F53\u524D\u4E3B\u4F1A\u8BDD\u53EF\u4EE5\u6062\u590D\uFF1B\u5DF2\u7ECF\u4EA4\u63A5\u9000\u4F11\u7684\u524D\u4EFB\u4FDD\u6301\u53EA\u8BFB\u3002", 409);
30791
+ }
30792
+ this.lifecycle.assertIdle();
30793
+ const open = this.store.openHandoff();
30794
+ if (open && open.fromSessionId === target && isHandoffExecuting(open.state)) {
30795
+ throw new RuntimeError("HANDOFF_IN_PROGRESS", "\u8FD9\u4E2A\u4E3B\u4F1A\u8BDD\u6B63\u5728\u6267\u884C\u4EA4\u63A5\uFF0C\u7B49\u5B83\u7ED3\u675F\u518D\u6062\u590D", 409);
30796
+ }
30797
+ const session = await this.repos.sessions.get(target);
30798
+ if (!session) throw new RuntimeError("SESSION_NOT_FOUND", `\u4F1A\u8BDD\u4E0D\u5B58\u5728\uFF1A${target}`, 404);
30799
+ let changed = false;
30800
+ if (session.archivedAt) {
30801
+ session.archivedAt = null;
30802
+ session.state = "stopped";
30803
+ session.updatedAt = now();
30804
+ await this.repos.sessions.save(session);
30805
+ changed = true;
30806
+ }
30807
+ if (session.state === "stopped" || session.state === "failed") {
30808
+ try {
30809
+ await this.runtime.restart(target);
30810
+ } catch (error) {
30811
+ throw new RuntimeError("MAIN_SESSION_RESTORE_FAILED", `\u5DF2\u89E3\u9664\u5F52\u6863\uFF0C\u4F46\u4E3B\u4F1A\u8BDD\u6CA1\u80FD\u91CD\u65B0\u542F\u52A8\uFF1A${error instanceof Error ? error.message : String(error)}\u3002\u4FEE\u597D Agent \u540E\u53EF\u518D\u70B9\u4E00\u6B21\u6062\u590D\u3002`, 503);
30812
+ }
30813
+ changed = true;
30814
+ }
30815
+ this.snapshotFull = true;
30816
+ await this.refreshMainSystemPrompt();
30817
+ await this.lifecycle.ensureCat();
30818
+ return { session: await this.repos.sessions.get(target) ?? session, restored: changed };
30819
+ }
30743
30820
  /**
30744
30821
  * `lineage: false` 只给交接仪式用:仪式自己写血缘(新猫 generation+1),
30745
30822
  * 其余入口(`main set`、认领)换主会话时按「新认领」处理,旧猫标 released。
@@ -30811,38 +30888,6 @@ var AssistantService = class {
30811
30888
  this.lifecycle.renameActiveCat(normalized2);
30812
30889
  return profile;
30813
30890
  }
30814
- getQuietHours() {
30815
- const raw = this.store.getSetting(QUIET_HOURS_KEY);
30816
- if (!raw) return { ...DEFAULT_QUIET_HOURS };
30817
- try {
30818
- const parsed = JSON.parse(raw);
30819
- return {
30820
- enabled: parsed.enabled === true,
30821
- start: typeof parsed.start === "string" ? parsed.start : DEFAULT_QUIET_HOURS.start,
30822
- end: typeof parsed.end === "string" ? parsed.end : DEFAULT_QUIET_HOURS.end
30823
- };
30824
- } catch {
30825
- return { ...DEFAULT_QUIET_HOURS };
30826
- }
30827
- }
30828
- setQuietHours(input) {
30829
- const normalized2 = {
30830
- enabled: input.enabled === true,
30831
- start: normalizeClock(input.start, DEFAULT_QUIET_HOURS.start),
30832
- end: normalizeClock(input.end, DEFAULT_QUIET_HOURS.end)
30833
- };
30834
- this.store.setSetting(QUIET_HOURS_KEY, JSON.stringify(normalized2));
30835
- return normalized2;
30836
- }
30837
- /** 静默触发表情;空串表示关闭。只存一个已规范化的 emoji,校验在 HTTP 入口完成。 */
30838
- getSilentEmoji() {
30839
- return (this.store.getSetting(SILENT_EMOJI_KEY) ?? "").trim();
30840
- }
30841
- setSilentEmoji(value) {
30842
- const normalized2 = value.trim();
30843
- this.store.setSetting(SILENT_EMOJI_KEY, normalized2);
30844
- return normalized2;
30845
- }
30846
30891
  /**
30847
30892
  * 主会话每一轮开头的状态快照。只对主会话生效;没有变化时整块省略。
30848
30893
  * 快照是「事实」,督办信号是「提醒」:即使信号漏了,主会话下一轮也能看到状态。
@@ -31010,7 +31055,6 @@ ${prompt}` : prompt;
31010
31055
  }
31011
31056
  }
31012
31057
  await this.scanWatches();
31013
- await this.flushPendingNotifications();
31014
31058
  await this.lifecycle.scan().catch((error) => this.log.warn(`\u751F\u547D\u5468\u671F\u626B\u63CF\u5931\u8D25\uFF1A${error instanceof Error ? error.message : String(error)}`));
31015
31059
  }
31016
31060
  // ---- 事项 ----
@@ -31026,7 +31070,8 @@ ${prompt}` : prompt;
31026
31070
  async startTask(input) {
31027
31071
  const mainId = this.requireMain();
31028
31072
  const main2 = await this.repos.sessions.get(mainId);
31029
- const { agentId, cwd, model, reasoningEffort } = this.resolveTaskConfig(main2, input);
31073
+ const explicitCwd = validateCwd(input.cwd);
31074
+ const { agentId, cwd, model, reasoningEffort } = this.resolveTaskConfig(main2, { ...input, cwd: explicitCwd });
31030
31075
  const session = await this.runtime.start({
31031
31076
  agentId,
31032
31077
  ...cwd ? { cwd } : {},
@@ -31059,6 +31104,7 @@ ${prompt}` : prompt;
31059
31104
  }
31060
31105
  planTask(input) {
31061
31106
  this.requireMain();
31107
+ const cwd = validateCwd(input.cwd);
31062
31108
  return this.store.createTask({
31063
31109
  title: input.title,
31064
31110
  ...input.notes ? { notes: input.notes } : {},
@@ -31066,20 +31112,26 @@ ${prompt}` : prompt;
31066
31112
  ...input.expectMinutes === void 0 ? {} : { expectMinutes: input.expectMinutes },
31067
31113
  state: "review",
31068
31114
  ...input.agentId ? { agentId: input.agentId } : {},
31069
- ...input.cwd ? { cwd: input.cwd } : {},
31115
+ ...cwd ? { cwd } : {},
31070
31116
  ...input.model ? { model: input.model } : {},
31071
31117
  ...input.reasoningEffort ? { reasoningEffort: input.reasoningEffort } : {},
31072
31118
  plan: true
31073
31119
  });
31074
31120
  }
31075
- async startPlannedTask(id) {
31121
+ async startPlannedTask(id, overrides = {}) {
31076
31122
  const task = this.store.getTask(id);
31077
31123
  if (!task) throw new Error(`\u4E8B\u9879\u4E0D\u5B58\u5728\uFF1A${id}`);
31078
31124
  if (!task.plan) throw new Error("\u8FD9\u4E2A\u4E8B\u9879\u4E0D\u662F\u8BA1\u5212\u5361");
31079
31125
  if (task.state === "closed") throw new Error("\u4E8B\u9879\u5DF2\u5173\u95ED");
31080
31126
  const mainId = this.requireMain();
31081
31127
  const main2 = await this.repos.sessions.get(mainId);
31082
- const { agentId, cwd, model, reasoningEffort } = this.resolveTaskConfig(main2, task);
31128
+ const explicitCwd = validateCwd(overrides.cwd ?? task.cwd);
31129
+ const { agentId, cwd, model, reasoningEffort } = this.resolveTaskConfig(main2, {
31130
+ agentId: overrides.agentId ?? task.agentId,
31131
+ cwd: explicitCwd,
31132
+ model: overrides.model ?? task.model,
31133
+ reasoningEffort: overrides.reasoningEffort ?? task.reasoningEffort
31134
+ });
31083
31135
  const session = await this.runtime.start({
31084
31136
  agentId,
31085
31137
  ...cwd ? { cwd } : {},
@@ -31181,7 +31233,7 @@ ${prompt}` : prompt;
31181
31233
  let session = task.sessionId ? await this.repos.sessions.get(task.sessionId) : void 0;
31182
31234
  if (!session || session.archivedAt) {
31183
31235
  const main2 = await this.repos.sessions.get(mainId);
31184
- const { agentId, cwd, model, reasoningEffort } = this.resolveTaskConfig(main2, task);
31236
+ const { agentId, cwd, model, reasoningEffort } = this.resolveTaskConfig(main2, { ...task, cwd: validateCwd(task.cwd) });
31185
31237
  session = await this.runtime.start({
31186
31238
  agentId,
31187
31239
  ...cwd ? { cwd } : {},
@@ -31406,14 +31458,9 @@ ${message}`, mode);
31406
31458
  async notify(input) {
31407
31459
  const text3 = input.text.trim();
31408
31460
  if (!text3) throw new Error("\u901A\u77E5\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A");
31409
- const quiet = this.getQuietHours();
31410
- if (quiet.enabled && !input.urgent && isInQuietHours(quiet)) {
31411
- const id2 = this.store.addNotification(text3, input.ask === true, false, "pending");
31412
- return { id: id2, delayed: true, quietHours: quiet };
31413
- }
31414
31461
  const sent = await this.sendNotification(text3, input.ask === true);
31415
31462
  const id = this.store.addNotification(text3, input.ask === true, input.urgent === true, sent ? "sent" : "failed");
31416
- return { id, delayed: false, sent };
31463
+ return { id, sent };
31417
31464
  }
31418
31465
  async sendNotification(text3, ask) {
31419
31466
  if (!this.notifyChannel) return false;
@@ -31424,14 +31471,6 @@ ${message}`, mode);
31424
31471
  return false;
31425
31472
  }
31426
31473
  }
31427
- async flushPendingNotifications() {
31428
- const quiet = this.getQuietHours();
31429
- if (quiet.enabled && isInQuietHours(quiet)) return;
31430
- for (const pending of this.store.listPendingNotifications()) {
31431
- const sent = await this.sendNotification(pending.text, pending.ask);
31432
- if (sent) this.store.markNotificationSent(pending.id);
31433
- }
31434
- }
31435
31474
  requireMain() {
31436
31475
  if (!this.mainSessionIdValue) throw new Error("\u8FD8\u6CA1\u6709\u6307\u5B9A\u4E3B\u4F1A\u8BDD\u3002\u5148\u5728\u8BBE\u7F6E\u91CC\u9009\u62E9\u6216\u65B0\u5EFA\u4E00\u4E2A\u4E3B\u4F1A\u8BDD\u3002");
31437
31476
  return this.mainSessionIdValue;
@@ -31470,7 +31509,7 @@ function buildMainSystemPrompt() {
31470
31509
  '- \u53D6\u6D88\uFF1A`agent-dock task cancel <\u4EFB\u52A1ID> --reason "..."`\uFF1B\u53EA\u5728\u4E8B\u9879\u786E\u5B9E\u4E0D\u8BE5\u7EE7\u7EED\u65F6\u7528\u3002',
31471
31510
  '- \u4FA7\u8FB9\u4F1A\u8BDD\uFF1A`agent-dock session show <\u4F1A\u8BDDID>` \u8BFB\u5B9E\u9645\u8F93\u51FA\uFF1B`agent-dock session send <\u4F1A\u8BDDID> "\u8865\u5145\u8981\u6C42" --mode queue` \u8FFD\u52A0\u8981\u6C42\uFF0C\u7D27\u6025\u65F6 `--mode interrupt`\u3002',
31472
31511
  '- \u76D1\u63A7\uFF1A`agent-dock watch add --name "CI \u7EFF\u4E86" --command "..." --every 5m`\uFF1B\u811A\u672C exit 0 \u8868\u793A\u6761\u4EF6\u6EE1\u8DB3\uFF0C\u9002\u5408\u7B49\u5916\u90E8\u72B6\u6001\uFF0C\u4E0D\u9002\u5408\u4EE3\u66FF\u4E00\u6B21\u6027\u6392\u67E5\u3002',
31473
- '- \u901A\u77E5\uFF1A`agent-dock notify "..." --ask` \u8BA9\u7528\u6237\u62CD\u677F\uFF1B\u7D27\u6025\u4E14\u9700\u8981\u7ED5\u8FC7\u514D\u6253\u6270\u65F6\u52A0 `--urgent`\u3002',
31512
+ '- \u901A\u77E5\uFF1A`agent-dock notify "..." --ask` \u8BA9\u7528\u6237\u62CD\u677F\uFF1B\u7D27\u6025\u901A\u77E5\u52A0 `--urgent`\uFF08\u7CFB\u7EDF\u8F6E\u6B21\u91CC\u4E5F\u653E\u884C\uFF09\u3002',
31474
31513
  '- \u8349\u7A3F\uFF1A`agent-dock draft create --channel github_comment|lark_reply --target "..." --body-file <\u6587\u4EF6>` \u5148\u5199\u8349\u7A3F\uFF0C\u7528\u6237\u786E\u8BA4\u540E\u7528 `agent-dock draft send <\u8349\u7A3FID>` \u53D1\u9001\u3002',
31475
31514
  "- \u72B6\u6001\uFF1A`agent-dock status --json` \u53EA\u7528\u4E8E\u56DE\u7B54 daemon \u662F\u5426\u5728\u8FD0\u884C\uFF1B\u4E0D\u8981\u628A\u5B83\u5F53\u4F5C\u4EFB\u52A1\u8FDB\u5EA6\u67E5\u8BE2\u6216\u6D3E\u6D3B\u524D\u7684\u8C03\u7814\u3002",
31476
31515
  "- \u4EE5\u4E0A\u53C2\u6570\u4E0D\u786E\u5B9A\u65F6\u7528 `agent-dock task|session|watch|notify|draft|status -h` \u67E5\uFF0C\u4E0D\u8981\u731C\u3002",
@@ -31609,26 +31648,6 @@ function normalizeCompanionName(value) {
31609
31648
  const normalized2 = [...value.replace(/\s+/g, " ").trim()].slice(0, MAX_COMPANION_NAME).join("").trim();
31610
31649
  return normalized2 || void 0;
31611
31650
  }
31612
- function normalizeClock(value, fallback) {
31613
- const match = value.trim().match(/^(\d{1,2}):(\d{2})$/);
31614
- if (!match) return fallback;
31615
- const hour = Number(match[1]);
31616
- const minute = Number(match[2]);
31617
- if (hour < 0 || hour > 23 || minute < 0 || minute > 59) return fallback;
31618
- return `${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")}`;
31619
- }
31620
- function isInQuietHours(quiet) {
31621
- const current = /* @__PURE__ */ new Date();
31622
- const minutes = current.getHours() * 60 + current.getMinutes();
31623
- const start = clockMinutes(quiet.start);
31624
- const end = clockMinutes(quiet.end);
31625
- if (start === end) return false;
31626
- return start < end ? minutes >= start && minutes < end : minutes >= start || minutes < end;
31627
- }
31628
- function clockMinutes(value) {
31629
- const [hour, minute] = value.split(":").map(Number);
31630
- return (hour ?? 0) * 60 + (minute ?? 0);
31631
- }
31632
31651
  function stallMinutes(expectMinutes) {
31633
31652
  return Math.max(STALL_DEFAULT_MINUTES, Math.round((expectMinutes ?? 0) * 1.5));
31634
31653
  }
@@ -31664,7 +31683,7 @@ function parseGithubTarget(value) {
31664
31683
  }
31665
31684
  async function runWatchCommand(watch) {
31666
31685
  const shell = resolveLoginShell();
31667
- return await new Promise((resolve13) => {
31686
+ return await new Promise((resolve14) => {
31668
31687
  const child = spawn11(shell.file, [...shell.args, "-c", watch.command], {
31669
31688
  cwd: watch.cwd ?? process.cwd(),
31670
31689
  env: { ...process.env, agentdock_watch_id: watch.id, agentdock_session_id: watch.ownerSessionId },
@@ -31697,7 +31716,7 @@ async function runWatchCommand(watch) {
31697
31716
  if (settled) return;
31698
31717
  settled = true;
31699
31718
  clearTimeout(timer);
31700
- resolve13({ exitCode, output: output3.trim() });
31719
+ resolve14({ exitCode, output: output3.trim() });
31701
31720
  };
31702
31721
  child.on("error", (error) => {
31703
31722
  append(Buffer.from(String(error)));
@@ -32263,8 +32282,8 @@ async function runLarkMessageListen(options, deps = {}) {
32263
32282
  let writeChain = Promise.resolve();
32264
32283
  let resolveDone;
32265
32284
  let rejectDone;
32266
- const done = new Promise((resolve13, reject2) => {
32267
- resolveDone = resolve13;
32285
+ const done = new Promise((resolve14, reject2) => {
32286
+ resolveDone = resolve14;
32268
32287
  rejectDone = reject2;
32269
32288
  });
32270
32289
  const cleanup = () => {
@@ -32466,11 +32485,11 @@ function acpxPassThroughArgs(argv) {
32466
32485
  return argv[2] === "acpx" ? argv.slice(3) : void 0;
32467
32486
  }
32468
32487
  function runAcpx(args, spawnProcess = spawn12) {
32469
- return new Promise((resolve13, reject2) => {
32488
+ return new Promise((resolve14, reject2) => {
32470
32489
  const options = { stdio: "inherit", env: process.env };
32471
32490
  const child = spawnProcess("acpx", [...args], options);
32472
32491
  child.once("error", reject2);
32473
- child.once("exit", (code, signal) => resolve13(code ?? (signal ? 1 : 0)));
32492
+ child.once("exit", (code, signal) => resolve14(code ?? (signal ? 1 : 0)));
32474
32493
  });
32475
32494
  }
32476
32495
 
@@ -32607,7 +32626,7 @@ init_agent_tools();
32607
32626
  init_daemon();
32608
32627
  init_time();
32609
32628
  import { readFileSync as readFileSync11 } from "node:fs";
32610
- import { resolve as resolve10 } from "node:path";
32629
+ import { resolve as resolve11 } from "node:path";
32611
32630
  var STARTUP_LOG_MAX_BYTES = 16 * 1024;
32612
32631
  var READY_TIMEOUT_MS = 15e3;
32613
32632
  var RESTART_HOST_ENV = "AGENTDOCK_DAEMON_RESTART_HOST";
@@ -32636,8 +32655,8 @@ function markDaemonReady(dir, patch = {}) {
32636
32655
  async function daemonStart(options, handlers, env = process.env) {
32637
32656
  const invocationCwd = process.cwd();
32638
32657
  const dir = isDaemonChild(env) ? defaultDaemonDir(invocationCwd) : resolveDaemonDir(invocationCwd, env.HOME);
32639
- const cwd = isDaemonChild(env) ? invocationCwd : resolve10(dir, "../..");
32640
- const database = resolve10(cwd, options.database ?? ".agentdock/agentdock.db");
32658
+ const cwd = isDaemonChild(env) ? invocationCwd : resolve11(dir, "../..");
32659
+ const database = resolve11(cwd, options.database ?? ".agentdock/agentdock.db");
32641
32660
  if (isDaemonChild(env)) {
32642
32661
  const meta = childMeta(env);
32643
32662
  writePidFile(dir, process.pid);
@@ -32877,11 +32896,11 @@ init_session_cli();
32877
32896
  import { spawnSync as spawnSync3 } from "node:child_process";
32878
32897
  import { chmodSync as chmodSync3, existsSync as existsSync11, mkdirSync as mkdirSync6, readFileSync as readFileSync12, rmSync as rmSync4, writeFileSync as writeFileSync5 } from "node:fs";
32879
32898
  import { createServer } from "node:net";
32880
- import { delimiter, dirname as dirname12, join as join21, resolve as resolve11 } from "node:path";
32899
+ import { delimiter, dirname as dirname12, join as join21, resolve as resolve12 } from "node:path";
32881
32900
  init_daemon();
32882
32901
  var SANDBOX_FILE = "sandbox.json";
32883
32902
  function findRepoRoot(start = process.cwd()) {
32884
- let dir = resolve11(start);
32903
+ let dir = resolve12(start);
32885
32904
  for (; ; ) {
32886
32905
  if (existsSync11(join21(dir, "apps", "server", "package.json")) && existsSync11(join21(dir, "pnpm-workspace.yaml"))) return dir;
32887
32906
  const parent = dirname12(dir);
@@ -33000,7 +33019,7 @@ async function readLineFromStdin() {
33000
33019
  return Buffer.concat(chunks).toString("utf8").split(/\r?\n/)[0] ?? "";
33001
33020
  }
33002
33021
  function promptHidden(question) {
33003
- return new Promise((resolve13, reject2) => {
33022
+ return new Promise((resolve14, reject2) => {
33004
33023
  const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
33005
33024
  const output3 = rl;
33006
33025
  let prompted = false;
@@ -33018,7 +33037,7 @@ function promptHidden(question) {
33018
33037
  rl.question(question, (answer) => {
33019
33038
  rl.close();
33020
33039
  process.stdout.write("\n");
33021
- resolve13(answer);
33040
+ resolve14(answer);
33022
33041
  });
33023
33042
  });
33024
33043
  }
@@ -33251,8 +33270,15 @@ function parseCheck(value) {
33251
33270
  return { criterion, met: status === "met", ...evidence ? { evidence } : {} };
33252
33271
  }
33253
33272
  async function runTaskStart(taskId, options) {
33273
+ const cwd = options.cwd ? resolveCwdArgument(options.cwd) : void 0;
33254
33274
  if (taskId) {
33255
- const result2 = await callDaemon(daemon(), `/api/assistant/tasks/${encodeURIComponent(taskId)}/start`, "POST", { ...fromFields(options.from) });
33275
+ const result2 = await callDaemon(daemon(), `/api/assistant/tasks/${encodeURIComponent(taskId)}/start`, "POST", {
33276
+ ...options.agent ? { agentId: options.agent } : {},
33277
+ ...cwd ? { cwd } : {},
33278
+ ...options.model ? { model: options.model } : {},
33279
+ ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
33280
+ ...fromFields(options.from)
33281
+ });
33256
33282
  return print(result2, options.json);
33257
33283
  }
33258
33284
  const title = options.title?.trim();
@@ -33266,7 +33292,7 @@ async function runTaskStart(taskId, options) {
33266
33292
  doneWhen,
33267
33293
  ...options.expectMinutes ? { expectMinutes: Number(options.expectMinutes) } : {},
33268
33294
  ...options.agent ? { agentId: options.agent } : {},
33269
- ...options.cwd ? { cwd: options.cwd } : {},
33295
+ ...cwd ? { cwd } : {},
33270
33296
  ...options.model ? { model: options.model } : {},
33271
33297
  ...options.reasoningEffort ? { reasoningEffort: options.reasoningEffort } : {},
33272
33298
  plan: options.plan === true,
@@ -33385,17 +33411,9 @@ async function runMainSet(sessionId, options) {
33385
33411
  async function runMainClear(options) {
33386
33412
  return print(await callDaemon(daemon(), "/api/assistant/main", "DELETE", { ...fromFields(options.from) }), options.json);
33387
33413
  }
33388
- async function runSettingsGet(options) {
33389
- return print(await callDaemon(daemon(), "/api/assistant/settings", "GET"), options.json);
33390
- }
33391
- async function runSettingsQuietHours(options) {
33392
- const current = await callDaemon(daemon(), "/api/assistant/settings", "GET");
33393
- const quiet = {
33394
- enabled: options.off === true ? false : options.enabled === true,
33395
- start: options.start ?? current.quietHours.start,
33396
- end: options.end ?? current.quietHours.end
33397
- };
33398
- return print(await callDaemon(daemon(), "/api/assistant/settings", "PUT", { quietHours: quiet, ...fromFields(options.from) }), options.json);
33414
+ async function runMainRestore(sessionId, options) {
33415
+ const body = sessionId?.trim() ? { sessionId: sessionId.trim() } : {};
33416
+ return print(await callDaemon(daemon(), "/api/assistant/main/restore", "POST", body), options.json);
33399
33417
  }
33400
33418
  async function runDraftCreate(options) {
33401
33419
  const channel = options.channel;
@@ -33597,7 +33615,7 @@ async function waitForHandoff(id, options) {
33597
33615
  if (Date.now() - started > limit) {
33598
33616
  throw new Error(`\u4EA4\u63A5 ${id} \u8FD8\u5728\u8FDB\u884C\uFF08${handoffStateLabel[handoff.state] ?? text2(handoff.state)}\uFF09\u3002\u7A0D\u540E\u7528 agent-dock main handoff show ${id} \u67E5\u770B\uFF1B\u5931\u8D25\u4F1A\u81EA\u52A8\u56DE\u6EDA\u3002`);
33599
33617
  }
33600
- await new Promise((resolve13) => setTimeout(resolve13, 1e3));
33618
+ await new Promise((resolve14) => setTimeout(resolve14, 1e3));
33601
33619
  }
33602
33620
  }
33603
33621
  async function runMainHandoff(options) {
@@ -33735,7 +33753,7 @@ init_src();
33735
33753
  init_daemon();
33736
33754
  init_session_cli();
33737
33755
  import { readFileSync as readFileSync14 } from "node:fs";
33738
- import { resolve as resolve12 } from "node:path";
33756
+ import { resolve as resolve13 } from "node:path";
33739
33757
 
33740
33758
  // src/sources-router/daemon-call.ts
33741
33759
  init_session_cli();
@@ -34485,7 +34503,7 @@ function runRouterDryRun(fixture, options) {
34485
34503
  return output2({ sourceId: sourceId2, ...result, persisted: false, createdCase: false, createdSession: false, sentAction: false }, options.json);
34486
34504
  }
34487
34505
  function readFixture(fixture) {
34488
- return fixture ? readFileSync14(resolve12(fixture), "utf8") : readFileSync14(0, "utf8");
34506
+ return fixture ? readFileSync14(resolve13(fixture), "utf8") : readFileSync14(0, "utf8");
34489
34507
  }
34490
34508
  function parseFixture(raw) {
34491
34509
  try {
@@ -34554,9 +34572,9 @@ async function restartWithInstalledCli(entrypoint) {
34554
34572
  if (!existsSync12(entrypoint)) throw new Error(`Updated AgentDock entrypoint was not found: ${entrypoint}. The service was not restarted.`);
34555
34573
  const previousPid = daemonStatus().pid;
34556
34574
  const child = spawn13(process.execPath, [entrypoint, "daemon", "restart"], { stdio: "inherit", env: process.env });
34557
- await new Promise((resolve13, reject2) => {
34575
+ await new Promise((resolve14, reject2) => {
34558
34576
  child.once("error", reject2);
34559
- child.once("exit", (code) => code === 0 ? resolve13() : reject2(new Error(`AgentDock restart exited with code ${code ?? "unknown"}.`)));
34577
+ child.once("exit", (code) => code === 0 ? resolve14() : reject2(new Error(`AgentDock restart exited with code ${code ?? "unknown"}.`)));
34560
34578
  });
34561
34579
  const deadline = Date.now() + 15e3;
34562
34580
  while (Date.now() < deadline) {
@@ -34848,6 +34866,9 @@ ${status.plistPath}` : "\u5F00\u673A\u81EA\u542F\uFF1A\u672A\u5F00\u542F"}
34848
34866
  mainClear: async (options) => {
34849
34867
  process.stdout.write(await runMainClear(options));
34850
34868
  },
34869
+ mainRestore: async (sessionId, options) => {
34870
+ process.stdout.write(await runMainRestore(sessionId, options));
34871
+ },
34851
34872
  mainHandoff: async (options) => {
34852
34873
  process.stdout.write(await runMainHandoff(options));
34853
34874
  },
@@ -34881,12 +34902,6 @@ ${status.plistPath}` : "\u5F00\u673A\u81EA\u542F\uFF1A\u672A\u5F00\u542F"}
34881
34902
  notesUnarchive: async (options) => {
34882
34903
  process.stdout.write(await runNotesUnarchive(options));
34883
34904
  },
34884
- settingsGet: async (options) => {
34885
- process.stdout.write(await runSettingsGet(options));
34886
- },
34887
- settingsQuietHours: async (options) => {
34888
- process.stdout.write(await runSettingsQuietHours(options));
34889
- },
34890
34905
  draftCreate: async (options) => {
34891
34906
  process.stdout.write(await runDraftCreate(options));
34892
34907
  },