@agent-dock/cli 0.3.18 → 0.3.20

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
@@ -1189,7 +1189,13 @@ function pickFinalAssistantText(entries) {
1189
1189
  const text3 = index >= 0 ? folded[index]?.data?.text : void 0;
1190
1190
  return typeof text3 === "string" ? text3 : "";
1191
1191
  }
1192
- var isTerminalToolStatus, isPendingToolStatus, isAssistantText, isToolEntry, toolCallIdOf, toolStatusOf, isCarriedOverToolCall, agentWarningPrefix, isAgentWarningText, agentStreamErrorPrefix, agentStreamErrorSuffix, isAgentStreamErrorText, antigravityAuthErrorPattern;
1192
+ function isDeferredAsyncWaitText(text3) {
1193
+ const trimmed = text3?.trim();
1194
+ if (!trimmed || trimmed.length > DEFERRED_WAIT_MAX_CHARS) return false;
1195
+ if (DEFERRED_WAIT_DISPATCH_RE.test(trimmed)) return false;
1196
+ return DEFERRED_WAIT_PATTERNS.some((pattern) => pattern.test(trimmed));
1197
+ }
1198
+ var isTerminalToolStatus, isPendingToolStatus, isAssistantText, isToolEntry, toolCallIdOf, toolStatusOf, isCarriedOverToolCall, agentWarningPrefix, isAgentWarningText, agentStreamErrorPrefix, agentStreamErrorSuffix, isAgentStreamErrorText, antigravityAuthErrorPattern, DEFERRED_WAIT_MAX_CHARS, DEFERRED_WAIT_DISPATCH_RE, DEFERRED_WAIT_PATTERNS, ACPX_DEFERRED_WAIT_CORRECTION_PROMPT;
1193
1199
  var init_turn_outcome = __esm({
1194
1200
  "../../packages/shared/src/turn-outcome.ts"() {
1195
1201
  "use strict";
@@ -1206,6 +1212,15 @@ var init_turn_outcome = __esm({
1206
1212
  agentStreamErrorSuffix = /(?:\r?\n){1,2}Error:\s*(?:RetriableError|T):[^\n]*\s*$/i;
1207
1213
  isAgentStreamErrorText = (text3) => agentStreamErrorPrefix.test(text3);
1208
1214
  antigravityAuthErrorPattern = "^\\s*(?:\u26A0\\s*)?UNAUTHENTICATED\\s*\\(code\\s+401\\)";
1215
+ DEFERRED_WAIT_MAX_CHARS = 600;
1216
+ DEFERRED_WAIT_DISPATCH_RE = /(?:已派活|atask_[a-z0-9-]+)/i;
1217
+ DEFERRED_WAIT_PATTERNS = [
1218
+ /(?:正在|仍在|已在|目前在|后台正在|当前正在).{0,35}(?:后台|运行|执行|构建|编译|测试|跑|等待|进行中|发布|触发).{0,45}(?:完成后|结束后|跑完后|一完成|稍后|随后|会自动|我会立刻|我会再|再继续|再汇报|再通知|再进入|再验收)/,
1219
+ /(?:等|等待).{0,25}(?:完成|结束|跑完|返回|结果|构建|测试|发布|流水线|通知).{0,25}(?:后|之后|再|我会|立刻|自动|继续|汇报|推进|唤醒)/,
1220
+ /\b(?:running|executing|building|testing|waiting)\b.{0,45}\b(?:in the background|for (?:it|the build|the test|the tests|the task|the command|ci|workflow|run|completion) to (?:finish|complete))\b/i,
1221
+ /\b(?:i['’]?ll|will)\s+(?:wake up|resume|continue|report|follow up|let you know|proceed)\b.{0,35}\b(?:when|once|as soon as)\b.{0,30}\b(?:finish|finishes|complete|completes|done|ready)\b/i
1222
+ ];
1223
+ ACPX_DEFERRED_WAIT_CORRECTION_PROMPT = "[AgentDock \u5F3A\u7EA6\u675F] ACPX \u6309\u8F6E\u6B21\u6536\u53E3\uFF0C\u672C\u8F6E\u7ED3\u675F\u540E\u4E0D\u4F1A\u628A\u5185\u7F6E\u540E\u53F0\u4EFB\u52A1\uFF08background task\uFF09\u3001\u5185\u7F6E subAgent \u6216\u5B9A\u65F6\u5668\u7684\u5B8C\u6210\u4E8B\u4EF6\u5F02\u6B65\u63A8\u56DE\u5524\u9192\u4F60\u2014\u2014\u4F60\u521A\u624D\u7ED3\u675F\u672C\u8F6E\u4F1A\u8BA9\u7528\u6237\u4E00\u76F4\u5E72\u7B49\u3002\u8BF7\u7ACB\u523B\u68C0\u67E5\u672A\u5B8C\u6210\u7684\u540E\u53F0\u4EFB\u52A1\u72B6\u6001\uFF0C\u5E76\u5728\u672C\u8F6E\u5DE5\u5177\u8C03\u7528\u5185\u540C\u6B65\u7B49\u5230\u6700\u7EC8\u7ED3\u679C\u518D\u7ED9\u51FA\u5B8C\u6574\u7B54\u590D\uFF1B\u4E25\u7981\u518D\u6B21\u63D0\u524D\u7ED3\u675F\u672C\u8F6E\u7B49\u5F85\u901A\u77E5\u3002";
1209
1224
  }
1210
1225
  });
1211
1226
 
@@ -1316,7 +1331,10 @@ function validateHighRiskPattern(pattern) {
1316
1331
  if (!safeRegex(pattern)) return { valid: false, error: "\u6B63\u5219\u8868\u8FBE\u5F0F\u53EF\u80FD\u9020\u6210\u707E\u96BE\u6027\u56DE\u6EAF\uFF0C\u8BF7\u79FB\u9664\u5D4C\u5957\u91CF\u8BCD\u6216\u62C6\u5206\u590D\u6742\u8868\u8FBE\u5F0F" };
1317
1332
  return { valid: true };
1318
1333
  }
1319
- var highRiskPatternMaxLength, protocols, permissionModes, agentConfigSchema, RuntimeError, now, makeId, defaultLarkTraceLimit;
1334
+ function isMainSessionScheduleTarget(sessionId) {
1335
+ return sessionId === SCHEDULE_MAIN_SESSION_ID;
1336
+ }
1337
+ var highRiskPatternMaxLength, protocols, permissionModes, agentConfigSchema, RuntimeError, SCHEDULE_MAIN_SESSION_ID, now, makeId, defaultLarkTraceLimit;
1320
1338
  var init_src2 = __esm({
1321
1339
  "../../packages/shared/src/index.ts"() {
1322
1340
  init_turn_outcome();
@@ -1359,6 +1377,7 @@ var init_src2 = __esm({
1359
1377
  code;
1360
1378
  statusCode;
1361
1379
  };
1380
+ SCHEDULE_MAIN_SESSION_ID = "main";
1362
1381
  now = () => (/* @__PURE__ */ new Date()).toISOString();
1363
1382
  makeId = (prefix) => `${prefix}_${crypto.randomUUID()}`;
1364
1383
  defaultLarkTraceLimit = 50;
@@ -6845,8 +6864,9 @@ Notes:
6845
6864
  dev.command("env").description("Print sandbox URL, database and paths as JSON (for scripts and browser checks)").option("--repo <dir>", "agent-dock source repo").action((options) => handlers.devEnv?.(options));
6846
6865
  dev.command("down").description("Stop the sandbox and delete its data").option("--keep-data", "Stop but keep the sandbox database for inspection").option("--repo <dir>", "agent-dock source repo").action((options) => handlers.devDown?.(options));
6847
6866
  const schedule = program.command("schedule").description("Register and manage AgentDock scheduled prompts (persisted by the daemon, survive restarts)");
6848
- schedule.command("add").description("Register a scheduled prompt; defaults to the current session (agentdock_session_id)").argument("<prompt>", "Prompt delivered to the session when the schedule fires").option("--cron <expr>", 'Recurring 5-field cron expression, e.g. "0 9 * * 1-5"').option("--every <interval>", "Fixed interval from now, e.g. 45m, 2h, 1h30m, 1d (not limited to divisors of 60 like cron)").option("--at <time>", 'One-shot trigger time, e.g. "2026-10-14 18:00" (local) or ISO 8601').option("--tz <timezone>", "IANA timezone for --cron, defaults to the machine timezone").option("--name <name>", "Short label shown in lists").option("--delivery <mode>", "new_session (default: fresh session each run) or append (continue in the bound session)").option("--session <session-id>", "Bind to this session instead of the current one (current session or its linked main/side sessions only)").option("--from <session-id>", "Source session ID (defaults to agentdock_session_id)").option("--json", "Output the created schedule as JSON").action((prompt, options) => handlers.scheduleAdd?.(prompt, options));
6849
- schedule.command("list").description("List schedules of the current session (all schedules outside a session)").option("--all", "List schedules of every session").option("--session <session-id>", "List schedules bound to this session").option("--json", "Output raw schedule rows as JSON").action((options) => handlers.scheduleList?.(options));
6867
+ schedule.command("add").alias("create").description("Register a scheduled prompt; defaults to the current session (agentdock_session_id)").argument("<prompt>", "Prompt delivered to the session when the schedule fires").option("--cron <expr>", 'Recurring 5-field cron expression, e.g. "0 9 * * 1-5"').option("--every <interval>", "Fixed interval from now, e.g. 45m, 2h, 1h30m, 1d (not limited to divisors of 60 like cron)").option("--at <time>", 'One-shot trigger time, e.g. "2026-10-14 18:00" (local) or ISO 8601').option("--tz <timezone>", "IANA timezone for --cron, defaults to the machine timezone").option("--name <name>", "Short label shown in lists").option("--delivery <mode>", "new_session (default: fresh session each run) or append (continue in the bound session)").option("--session <session-id>", 'Bind to this session (use "main" to dynamically follow the active main session)').option("--main", "Dynamically follow the active main session (shorthand for --session main; survives handoff)").option("--from <session-id>", "Source session ID (defaults to agentdock_session_id)").option("--json", "Output the created schedule as JSON").action((prompt, options) => handlers.scheduleAdd?.(prompt, options));
6868
+ schedule.command("update").description("Update an existing schedule (prompt, timing, delivery, or target session)").argument("<schedule-id>", "Schedule ID (sch_*)").option("--prompt <prompt>", "Updated prompt text").option("--name <name>", "Updated short label").option("--cron <expr>", "Switch to a 5-field cron expression").option("--every <interval>", "Switch to a fixed interval, e.g. 45m, 2h, 1d").option("--at <time>", "Switch to a one-shot trigger time").option("--tz <timezone>", "IANA timezone for --cron").option("--delivery <mode>", "new_session or append").option("--session <session-id>", 'Rebind to this session (use "main" to dynamically follow the active main session)').option("--main", "Dynamically follow the active main session (shorthand for --session main)").option("--from <session-id>", "Source session ID (defaults to agentdock_session_id)").option("--json", "Output the updated schedule as JSON").action((id, options) => handlers.scheduleUpdate?.(id, options));
6869
+ schedule.command("list").description("List schedules of the current session (all schedules outside a session)").option("--all", "List schedules of every session").option("--session <session-id>", 'List schedules bound to this session (use "main" for main-following schedules)').option("--main", "List schedules dynamically following the active main session").option("--json", "Output raw schedule rows as JSON").action((options) => handlers.scheduleList?.(options));
6850
6870
  schedule.command("show").description("Show one schedule with its recent runs").argument("<schedule-id>", "Schedule ID (sch_*)").option("--json", "Output raw schedule and runs as JSON").action((id, options) => handlers.scheduleShow?.(id, options));
6851
6871
  for (const [name, description, handler] of [
6852
6872
  ["pause", "Pause a schedule", "schedulePause"],
@@ -6866,6 +6886,8 @@ Examples:
6866
6886
  $ agent-dock schedule add "\u68C0\u67E5\u53D1\u5E03\u72B6\u6001" --every 45m # also 2h, 1h30m, 1d
6867
6887
  $ agent-dock schedule add "\u63D0\u9192\u6211\u5F00\u4F1A" --at "2026-10-14 18:00" # local time; --tz for another zone
6868
6888
  $ agent-dock schedule add "\u7EE7\u7EED\u8DDF\u8FDB" --every 1h --delivery append
6889
+ $ agent-dock schedule add "\u6BCF\u65E5\u5DE1\u68C0" --cron "0 9 * * *" --delivery append --main # follow active main session across handoffs
6890
+ $ agent-dock schedule update sch_xxx --main --delivery append
6869
6891
  $ agent-dock schedule list
6870
6892
  $ agent-dock schedule show|pause|resume|run|remove SCHEDULE_ID
6871
6893
 
@@ -18016,10 +18038,18 @@ var AcpxAdapter = class {
18016
18038
 
18017
18039
  // ../../packages/transports/src/index.ts
18018
18040
  import { spawn as spawn5, spawnSync } from "node:child_process";
18041
+ import { accessSync as accessSync2, constants as constants3, statSync as statSync4 } from "node:fs";
18019
18042
  import readline2 from "node:readline";
18020
18043
  import * as pty from "node-pty";
18021
18044
  function commandExists(command) {
18022
- if (command.includes("/") || command.includes("\\")) return spawnSync("test", ["-x", command]).status === 0;
18045
+ if (command.includes("/") || command.includes("\\")) {
18046
+ try {
18047
+ accessSync2(command, constants3.X_OK);
18048
+ return statSync4(command).isFile();
18049
+ } catch {
18050
+ return false;
18051
+ }
18052
+ }
18023
18053
  return spawnSync(process.platform === "win32" ? "where" : "which", [command], { stdio: "ignore" }).status === 0;
18024
18054
  }
18025
18055
  function probeAgent(agent, acpxCommand = "acpx") {
@@ -19048,6 +19078,11 @@ var AgentDockRuntime = class _AgentDockRuntime {
19048
19078
  if (riskPolicy) await this.applyRiskPolicy(session, driver, riskPolicy);
19049
19079
  outcome = await this.executeTurnAndResolve(id, session, task, driver, resolvedAgentPrompt, retryAfterSequence);
19050
19080
  }
19081
+ if (outcome.status === "completed" && session.source !== "assistant-main" && !this.interruptedTurns.has(id) && isDeferredAsyncWaitText(outcome.finalText)) {
19082
+ const retryAfterSequence = this.sequences.get(id);
19083
+ await this.emit(id, "status", { state: "acpx_sync_guard", reason: "deferred_async_wait" });
19084
+ outcome = await this.executeTurnAndResolve(id, session, task, driver, ACPX_DEFERRED_WAIT_CORRECTION_PROMPT, retryAfterSequence);
19085
+ }
19051
19086
  task.finalText = outcome.finalText;
19052
19087
  session.lastMessageAt = now();
19053
19088
  if (outcome.status === "interrupted") {
@@ -19658,7 +19693,7 @@ import { fileURLToPath as fileURLToPath5 } from "node:url";
19658
19693
  init_src2();
19659
19694
  init_daemon();
19660
19695
  import { spawn as spawn7 } from "node:child_process";
19661
- import { closeSync, mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync5, rmSync as rmSync2, statSync as statSync4, writeFileSync as writeFileSync3 } from "node:fs";
19696
+ import { closeSync, mkdirSync as mkdirSync4, openSync as openSync2, readFileSync as readFileSync5, rmSync as rmSync2, statSync as statSync5, writeFileSync as writeFileSync3 } from "node:fs";
19662
19697
  import { homedir as homedir5 } from "node:os";
19663
19698
  import { dirname as dirname7, join as join8 } from "node:path";
19664
19699
 
@@ -19859,7 +19894,7 @@ var SelfUpdateService = class {
19859
19894
  */
19860
19895
  lockHeld() {
19861
19896
  try {
19862
- if (this.now() - statSync4(this.lockFile).mtimeMs > UPDATE_LOCK_MAX_AGE_MS) return false;
19897
+ if (this.now() - statSync5(this.lockFile).mtimeMs > UPDATE_LOCK_MAX_AGE_MS) return false;
19863
19898
  return pidAlive(Number(readFileSync5(this.lockFile, "utf8").trim()));
19864
19899
  } catch {
19865
19900
  return false;
@@ -19963,7 +19998,7 @@ init_listener();
19963
19998
  // src/lark/security-hooks.ts
19964
19999
  init_service();
19965
20000
  import { access as access2, mkdir as mkdir3, readFile as readFile4, writeFile as writeFile3 } from "node:fs/promises";
19966
- import { constants as constants3 } from "node:fs";
20001
+ import { constants as constants4 } from "node:fs";
19967
20002
  import { dirname as dirname8, join as join10 } from "node:path";
19968
20003
  var guardVersion = "agentdock-high-risk-guard-v2";
19969
20004
  var quote = (value) => `'${value.replaceAll("'", "'\\''")}'`;
@@ -20087,7 +20122,7 @@ async function larkHookStatus(agentId, workspace) {
20087
20122
  const { hooksPath } = paths(adapter, workspace);
20088
20123
  let writable = true;
20089
20124
  try {
20090
- await access2(workspace, constants3.W_OK);
20125
+ await access2(workspace, constants4.W_OK);
20091
20126
  } catch {
20092
20127
  writable = false;
20093
20128
  }
@@ -23102,15 +23137,14 @@ function registerShareLinkRoutes(app, service, runtime) {
23102
23137
  // src/schedules/routes.ts
23103
23138
  function registerScheduleRoutes(app, schedules2) {
23104
23139
  app.get("/api/schedules", async (request) => {
23105
- const all = await schedules2.list();
23106
- const sessionId = request.query?.sessionId?.trim();
23107
- return sessionId ? all.filter((item) => item.sessionId === sessionId) : all;
23140
+ return schedules2.list(request.query?.sessionId?.trim() || void 0);
23108
23141
  });
23109
23142
  app.post("/api/schedules", async (request, reply) => {
23110
23143
  const body = request.body ?? {};
23111
23144
  const created = await schedules2.create({
23112
23145
  prompt: body.prompt ?? "",
23113
23146
  ...body.sessionId !== void 0 ? { sessionId: body.sessionId } : {},
23147
+ ...body.followMain !== void 0 ? { followMain: Boolean(body.followMain) } : {},
23114
23148
  ...body.template !== void 0 ? { template: body.template } : {},
23115
23149
  ...body.name !== void 0 ? { name: body.name } : {},
23116
23150
  ...body.delivery !== void 0 ? { delivery: body.delivery } : {},
@@ -23129,6 +23163,7 @@ function registerScheduleRoutes(app, schedules2) {
23129
23163
  ...body.prompt !== void 0 ? { prompt: body.prompt } : {},
23130
23164
  ...body.delivery !== void 0 ? { delivery: body.delivery } : {},
23131
23165
  ...body.sessionId !== void 0 ? { sessionId: body.sessionId } : {},
23166
+ ...body.followMain !== void 0 ? { followMain: Boolean(body.followMain) } : {},
23132
23167
  ...body.template !== void 0 ? { template: body.template } : {},
23133
23168
  ...body.cron !== void 0 ? { cron: body.cron } : {},
23134
23169
  ...body.runAt !== void 0 ? { runAt: body.runAt } : {},
@@ -25067,7 +25102,7 @@ init_side_chat_config();
25067
25102
 
25068
25103
  // src/json-compression.ts
25069
25104
  import { promisify as promisify6 } from "node:util";
25070
- import { brotliCompress, constants as constants4, gzip } from "node:zlib";
25105
+ import { brotliCompress, constants as constants5, gzip } from "node:zlib";
25071
25106
  var brotli = promisify6(brotliCompress);
25072
25107
  var gzipAsync = promisify6(gzip);
25073
25108
  var JSON_COMPRESSION_THRESHOLD = 32 * 1024;
@@ -25093,7 +25128,7 @@ function registerJsonCompression(app, threshold = JSON_COMPRESSION_THRESHOLD) {
25093
25128
  if (size < threshold) return payload;
25094
25129
  const encoding = pickJsonEncoding(request.headers["accept-encoding"]);
25095
25130
  if (!encoding) return payload;
25096
- const body = encoding === "br" ? await brotli(payload, { params: { [constants4.BROTLI_PARAM_MODE]: constants4.BROTLI_MODE_TEXT, [constants4.BROTLI_PARAM_QUALITY]: 4, [constants4.BROTLI_PARAM_SIZE_HINT]: size } }) : await gzipAsync(payload, { level: 6 });
25131
+ const body = encoding === "br" ? await brotli(payload, { params: { [constants5.BROTLI_PARAM_MODE]: constants5.BROTLI_MODE_TEXT, [constants5.BROTLI_PARAM_QUALITY]: 4, [constants5.BROTLI_PARAM_SIZE_HINT]: size } }) : await gzipAsync(payload, { level: 6 });
25097
25132
  reply.header("content-encoding", encoding);
25098
25133
  const vary = String(reply.getHeader("vary") ?? "");
25099
25134
  if (!/(^|,)\s*accept-encoding\s*(,|$)/i.test(vary)) reply.header("vary", vary ? `${vary}, Accept-Encoding` : "Accept-Encoding");
@@ -29581,8 +29616,8 @@ ${signature}` : body;
29581
29616
  // src/initial-system-prompt.ts
29582
29617
  function buildRuntimeGuidance(sessionId) {
29583
29618
  return `[AgentDock]
29584
- \u4F60\u8FD0\u884C\u5728 AgentDock \u6258\u7BA1\u7684\u4F1A\u8BDD\u4E2D\uFF0C\u5F53\u524D\u4F1A\u8BDD ID\uFF1A${sessionId}\u3002
29585
- - \u672C\u8F6E\u7ED3\u675F\u3001\u88AB\u4E2D\u65AD\u6216\u8D85\u65F6\u540E\uFF0CClaude \u5185\u7F6E subAgent \u548C\u540E\u53F0\u8FDB\u7A0B\uFF08&\u3001nohup\u3001tmux \u7B49\uFF09\u53EF\u80FD\u88AB\u4E00\u5E76\u7EC8\u6B62\uFF1A\u957F\u4EFB\u52A1\u5728\u5DE5\u5177\u8C03\u7528\u5185\u540C\u6B65\u7B49\u5230\u7ED3\u679C\uFF0C\u4E0D\u8981\u6D3E\u7ED9\u5185\u7F6E subAgent\uFF0C\u4E5F\u4E0D\u8981\u300C\u5148\u542F\u52A8\u3001\u7A0D\u540E\u518D\u770B\u300D\uFF1BAgentDock \u4FA7\u8FB9\u4F1A\u8BDD\u7528 \`agent-dock task start\`\uFF0C\u4E0D\u53D7\u6B64\u9650\u3002
29619
+ \u4F60\u8FD0\u884C\u5728 AgentDock\uFF08ACPX\uFF09\u6258\u7BA1\u7684\u4F1A\u8BDD\u4E2D\uFF0C\u5F53\u524D\u4F1A\u8BDD ID\uFF1A${sessionId}\u3002
29620
+ - \u3010\u786C\u7EA6\u675F \xB7 \u9AD8\u4E8E\u5185\u7F6E\u5F02\u6B65\u63D0\u793A\u3011ACPX \u6309\u8F6E\u6B21\u6536\u53E3\uFF1A\u672C\u8F6E\u4E00\u65E6\u7ED3\u675F\uFF08end_turn\uFF09\uFF0C\u4EFB\u4F55\u5185\u7F6E\u540E\u53F0\u4EFB\u52A1\uFF08background task\uFF09\u3001\u5185\u7F6E subAgent\u3001\u5185\u7F6E timer/schedule\u3001swarm \u6216\u540E\u53F0\u8FDB\u7A0B\uFF08&\u3001nohup\u3001tmux \u7B49\uFF09\u7684\u5B8C\u6210\u4E8B\u4EF6\u90FD\u4E0D\u4F1A\u5F02\u6B65\u63A8\u56DE\u5524\u9192\u4F60\uFF0C\u4E14\u540E\u53F0\u8FDB\u7A0B\u53EF\u80FD\u88AB\u7EC8\u6B62\u3002\u51E1\u662F\u9700\u8981\u62FF\u5230\u7ED3\u679C\u7684\u547D\u4EE4/\u6784\u5EFA/\u6D4B\u8BD5/CI\uFF0C\u5FC5\u987B\u5728\u672C\u8F6E\u5DE5\u5177\u8C03\u7528\u5185\u540C\u6B65\u7B49\u5230\u7ED3\u679C\uFF0C\u4E25\u7981\u7ED3\u675F\u672C\u8F6E\u5E76\u627F\u8BFA\u300C\u540E\u53F0\u8DD1\u5B8C\u540E\u518D\u6C47\u62A5\u300D\uFF1B\u4E0D\u8981\u6D3E\u7ED9\u5185\u7F6E subAgent\uFF08\u8DE8\u4F1A\u8BDD\u6D3E\u6D3B\u7EDF\u4E00\u7528 \`agent-dock task start\`\uFF09\u3002
29586
29621
  - \u5B9A\u65F6 / \u5468\u671F\u6267\u884C / \u300CX \u70B9\u63D0\u9192\u6211\u300D\u7528 \`agent-dock schedule\`\uFF0C\u4E0D\u8981\u7528 CronCreate\u3001ScheduleWakeup\u3001/loop\u3001crontab \u6216 sleep \u8F6E\u8BE2\u3002
29587
29622
  - \u4E0E\u4E3B\u4F1A\u8BDD / \u4FA7\u8FB9\u4F1A\u8BDD\u901A\u4FE1\u7528 \`agent-dock session\`\uFF0C\u4E0D\u8981\u7528 Claude \u7684 ListAgents / SendMessage\u3002
29588
29623
  - \u7528\u5230\u4EE5\u4E0A\u80FD\u529B\u524D\uFF0C\u5148\u8FD0\u884C \`agent-dock schedule -h\` \u6216 \`agent-dock session -h\` \u8BFB\u7528\u6CD5\u3002`;
@@ -29709,8 +29744,23 @@ var ScheduleService = class {
29709
29744
  this.timer = void 0;
29710
29745
  await this.ticking;
29711
29746
  }
29712
- list() {
29713
- return this.schedules.list();
29747
+ async resolveMainSessionId() {
29748
+ const id = (await this.options.resolveMainSessionId?.())?.trim();
29749
+ return id || void 0;
29750
+ }
29751
+ /**
29752
+ * 列出定时任务;指定 sessionId 时只看该会话的任务:
29753
+ * - sessionId='main':只看跟随当前主会话的任务;
29754
+ * - sessionId 恰好是当前活跃主会话 ID:同时包含直接绑在该会话上的和跟随主会话的任务。
29755
+ */
29756
+ async list(sessionId) {
29757
+ const all = await this.schedules.list();
29758
+ const target = sessionId?.trim();
29759
+ if (!target) return all;
29760
+ if (isMainSessionScheduleTarget(target)) return all.filter((item) => isMainSessionScheduleTarget(item.sessionId));
29761
+ const mainId = await this.resolveMainSessionId();
29762
+ const includeMain = Boolean(mainId && mainId === target);
29763
+ return all.filter((item) => item.sessionId === target || includeMain && isMainSessionScheduleTarget(item.sessionId));
29714
29764
  }
29715
29765
  async get(id) {
29716
29766
  const schedule = await this.schedules.get(id);
@@ -29721,22 +29771,45 @@ var ScheduleService = class {
29721
29771
  await this.get(id);
29722
29772
  return this.schedules.listRuns(id, limit);
29723
29773
  }
29724
- /** 最近执行(跨任务);给 sessionId 时只看绑在这个会话上的任务。 */
29774
+ /** 最近执行(跨任务);给 sessionId 时只看绑在这个会话上的任务(主会话同时含跟随主会话的任务)。 */
29725
29775
  async recentRuns(limit = 50, sessionId) {
29726
29776
  if (!sessionId) return this.schedules.listRecentRuns(limit);
29727
- const ids = (await this.schedules.list()).filter((item) => item.sessionId === sessionId).map((item) => item.id);
29777
+ const ids = (await this.list(sessionId)).map((item) => item.id);
29728
29778
  return this.schedules.listRecentRuns(limit, ids);
29729
29779
  }
29780
+ /**
29781
+ * 主会话交接换代时,把旧主会话上存量写死 sessionId 的 append 定时任务平滑迁移为跟随当前主会话,
29782
+ * 避免旧主会话归档后存量任务在下次触发时被误停用。
29783
+ */
29784
+ async migrateSessionAppendSchedulesToMain(fromSessionId) {
29785
+ const all = await this.schedules.list();
29786
+ const targets = all.filter((item) => item.delivery === "append" && item.sessionId === fromSessionId);
29787
+ if (!targets.length) return 0;
29788
+ const stamp2 = this.clock().toISOString();
29789
+ for (const item of targets) {
29790
+ await this.schedules.save({ ...item, sessionId: SCHEDULE_MAIN_SESSION_ID, updatedAt: stamp2 });
29791
+ }
29792
+ this.options.log?.info(`\u4E3B\u4F1A\u8BDD\u4EA4\u63A5\uFF1A\u5DF2\u5C06 ${targets.length} \u6761\u7ED1\u5B9A\u65E7\u4E3B\u4F1A\u8BDD ${fromSessionId} \u7684\u8FFD\u52A0\u578B\u5B9A\u65F6\u4EFB\u52A1\u8FC1\u79FB\u4E3A\u8DDF\u968F\u5F53\u524D\u4E3B\u4F1A\u8BDD`);
29793
+ return targets.length;
29794
+ }
29730
29795
  async create(input) {
29731
29796
  const prompt = input.prompt?.trim();
29732
29797
  if (!prompt) throw new RuntimeError("INVALID_SCHEDULE", "\u5B9A\u65F6\u4EFB\u52A1\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A", 400);
29733
29798
  const delivery = input.delivery ?? "new_session";
29734
29799
  if (delivery !== "append" && delivery !== "new_session") throw new RuntimeError("INVALID_SCHEDULE", `\u672A\u77E5\u7684\u6295\u9012\u65B9\u5F0F\uFF1A${String(delivery)}`, 400);
29735
- const sessionId = input.sessionId?.trim();
29800
+ const followMain = input.followMain === true || isMainSessionScheduleTarget(input.sessionId?.trim());
29801
+ const sessionId = followMain ? SCHEDULE_MAIN_SESSION_ID : input.sessionId?.trim();
29736
29802
  if (!sessionId && delivery === "append") throw new RuntimeError("INVALID_SCHEDULE", "\u8FFD\u52A0\u5230\u4F1A\u8BDD\u5FC5\u987B\u6307\u5B9A\u4F1A\u8BDD", 400);
29737
- const session = sessionId ? await this.sessions.get(sessionId) : void 0;
29738
- if (sessionId && !session) throw new RuntimeError("SESSION_NOT_FOUND", `\u4F1A\u8BDD\u4E0D\u5B58\u5728\uFF1A${sessionId}`, 404);
29739
- if (session?.archivedAt) throw new RuntimeError("SESSION_ARCHIVED", `\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF1A${sessionId}`, 409);
29803
+ let session;
29804
+ if (followMain) {
29805
+ const mainId = await this.resolveMainSessionId();
29806
+ const main2 = mainId ? await this.sessions.get(mainId) : void 0;
29807
+ if (main2 && !main2.archivedAt) session = main2;
29808
+ } else if (sessionId) {
29809
+ session = await this.sessions.get(sessionId);
29810
+ if (!session) throw new RuntimeError("SESSION_NOT_FOUND", `\u4F1A\u8BDD\u4E0D\u5B58\u5728\uFF1A${sessionId}`, 404);
29811
+ if (session.archivedAt) throw new RuntimeError("SESSION_ARCHIVED", `\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF1A${sessionId}`, 409);
29812
+ }
29740
29813
  const template = delivery === "new_session" ? normalizeTemplate(input.template) ?? (session ? templateFrom(session) : void 0) : void 0;
29741
29814
  if (delivery === "new_session" && !template) throw new RuntimeError("INVALID_SCHEDULE", "\u6BCF\u6B21\u65B0\u5F00\u4F1A\u8BDD\u9700\u8981\u6307\u5B9A Agent \u548C\u5DE5\u4F5C\u76EE\u5F55\uFF0C\u6216\u7ED1\u5B9A\u4E00\u4E2A\u4F1A\u8BDD", 400);
29742
29815
  const timezone = input.timezone?.trim() || localTimezone();
@@ -29750,7 +29823,7 @@ var ScheduleService = class {
29750
29823
  const schedule = {
29751
29824
  id: scheduleId(),
29752
29825
  name: input.name?.trim() || prompt.replace(/\s+/g, " ").slice(0, 40),
29753
- sessionId: session?.id ?? null,
29826
+ sessionId: followMain ? SCHEDULE_MAIN_SESSION_ID : session?.id ?? null,
29754
29827
  delivery,
29755
29828
  sessionTemplate: template ? JSON.stringify(template) : null,
29756
29829
  cron,
@@ -29777,12 +29850,30 @@ var ScheduleService = class {
29777
29850
  if (!prompt) throw new RuntimeError("INVALID_SCHEDULE", "\u5B9A\u65F6\u4EFB\u52A1\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A", 400);
29778
29851
  const delivery = input.delivery ?? current.delivery;
29779
29852
  if (delivery !== "append" && delivery !== "new_session") throw new RuntimeError("INVALID_SCHEDULE", `\u672A\u77E5\u7684\u6295\u9012\u65B9\u5F0F\uFF1A${String(delivery)}`, 400);
29780
- const sessionId = input.sessionId !== void 0 ? input.sessionId?.trim() || null : current.sessionId ?? null;
29853
+ let sessionId;
29854
+ if (input.followMain === true) {
29855
+ sessionId = SCHEDULE_MAIN_SESSION_ID;
29856
+ } else if (input.sessionId !== void 0) {
29857
+ const trimmed = input.sessionId?.trim() || null;
29858
+ sessionId = isMainSessionScheduleTarget(trimmed) ? SCHEDULE_MAIN_SESSION_ID : trimmed;
29859
+ } else if (input.followMain === false && isMainSessionScheduleTarget(current.sessionId)) {
29860
+ sessionId = null;
29861
+ } else {
29862
+ sessionId = current.sessionId ?? null;
29863
+ }
29781
29864
  if (delivery === "append" && !sessionId) throw new RuntimeError("INVALID_SCHEDULE", "\u8FFD\u52A0\u5230\u4F1A\u8BDD\u5FC5\u987B\u6307\u5B9A\u4F1A\u8BDD", 400);
29782
- const session = sessionId ? await this.sessions.get(sessionId) : void 0;
29783
- if (sessionId && sessionId !== current.sessionId) {
29784
- if (!session) throw new RuntimeError("SESSION_NOT_FOUND", `\u4F1A\u8BDD\u4E0D\u5B58\u5728\uFF1A${sessionId}`, 404);
29785
- if (session.archivedAt) throw new RuntimeError("SESSION_ARCHIVED", `\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF1A${sessionId}`, 409);
29865
+ const followMain = isMainSessionScheduleTarget(sessionId);
29866
+ let session;
29867
+ if (followMain) {
29868
+ const mainId = await this.resolveMainSessionId();
29869
+ const main2 = mainId ? await this.sessions.get(mainId) : void 0;
29870
+ if (main2 && !main2.archivedAt) session = main2;
29871
+ } else if (sessionId) {
29872
+ session = await this.sessions.get(sessionId);
29873
+ if (sessionId !== current.sessionId) {
29874
+ if (!session) throw new RuntimeError("SESSION_NOT_FOUND", `\u4F1A\u8BDD\u4E0D\u5B58\u5728\uFF1A${sessionId}`, 404);
29875
+ if (session.archivedAt) throw new RuntimeError("SESSION_ARCHIVED", `\u4F1A\u8BDD\u5DF2\u5F52\u6863\uFF1A${sessionId}`, 409);
29876
+ }
29786
29877
  }
29787
29878
  let template;
29788
29879
  if (delivery === "new_session") {
@@ -29904,10 +29995,20 @@ var ScheduleService = class {
29904
29995
  return finished;
29905
29996
  }
29906
29997
  async attempt(schedule) {
29907
- const source2 = schedule.sessionId ? await this.runtime.getSession(schedule.sessionId) : void 0;
29908
- if (schedule.sessionId && (!source2 || source2.archivedAt)) {
29909
- await this.disable(schedule.id, "\u6765\u6E90\u4F1A\u8BDD\u4E0D\u5B58\u5728\u6216\u5DF2\u5F52\u6863");
29910
- return { status: "failed", reason: "\u6765\u6E90\u4F1A\u8BDD\u4E0D\u5B58\u5728\u6216\u5DF2\u5F52\u6863\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u5DF2\u505C\u7528", sessionId: schedule.sessionId, taskId: null };
29998
+ const followMain = isMainSessionScheduleTarget(schedule.sessionId);
29999
+ let source2;
30000
+ if (followMain) {
30001
+ const mainId = await this.resolveMainSessionId();
30002
+ source2 = mainId ? await this.runtime.getSession(mainId) : void 0;
30003
+ if (!source2 || source2.archivedAt) {
30004
+ return { status: "skipped", reason: "\u5F53\u524D\u6CA1\u6709\u6D3B\u8DC3\u7684\u4E3B\u4F1A\u8BDD\uFF0C\u672C\u6B21\u8DF3\u8FC7", sessionId: null, taskId: null };
30005
+ }
30006
+ } else if (schedule.sessionId) {
30007
+ source2 = await this.runtime.getSession(schedule.sessionId);
30008
+ if (!source2 || source2.archivedAt) {
30009
+ await this.disable(schedule.id, "\u6765\u6E90\u4F1A\u8BDD\u4E0D\u5B58\u5728\u6216\u5DF2\u5F52\u6863");
30010
+ return { status: "failed", reason: "\u6765\u6E90\u4F1A\u8BDD\u4E0D\u5B58\u5728\u6216\u5DF2\u5F52\u6863\uFF0C\u5B9A\u65F6\u4EFB\u52A1\u5DF2\u505C\u7528", sessionId: schedule.sessionId, taskId: null };
30011
+ }
29911
30012
  }
29912
30013
  const previous = await this.unfinishedPrevious(schedule);
29913
30014
  if (previous) return { status: "skipped", reason: `\u4E0A\u4E00\u6B21\u89E6\u53D1\u7684\u4EFB\u52A1\u8FD8\u672A\u7ED3\u675F\uFF08${previous}\uFF09`, sessionId: null, taskId: null };
@@ -29918,22 +30019,25 @@ var ScheduleService = class {
29918
30019
  const task2 = await this.runtime.dispatch(source2.id, prompt);
29919
30020
  return { status: "delivered", reason: null, sessionId: source2.id, taskId: task2.id };
29920
30021
  }
30022
+ const parentSessionId = source2?.id ?? null;
29921
30023
  const template = parseTemplate(schedule);
29922
30024
  const created = await this.runtime.start({
29923
30025
  agentId: template.agentId,
29924
30026
  cwd: template.cwd,
29925
30027
  ...template.model ? { model: template.model } : {},
29926
30028
  ...template.reasoningEffort ? { reasoningEffort: template.reasoningEffort } : {},
29927
- systemPrompt: buildScheduleSessionSeed(schedule),
29928
- ...schedule.sessionId ? { source: scheduleSessionSource, sourceId: schedule.sessionId } : {}
30029
+ systemPrompt: buildScheduleSessionSeed({ ...schedule, sessionId: parentSessionId }),
30030
+ ...parentSessionId ? { source: scheduleSessionSource, sourceId: parentSessionId } : {}
29929
30031
  });
29930
30032
  const task = await this.runtime.dispatch(created.id, prompt);
29931
30033
  return { status: "delivered", reason: null, sessionId: created.id, taskId: task.id };
29932
30034
  }
29933
- /** 上一条已投递的任务若仍在排队/执行,返回它的状态。 */
30035
+ /** 上一条已投递的任务若仍在排队/执行,返回它的状态。已归档会话(如换代后的前任主会话)上的旧任务不再阻塞新触发。 */
29934
30036
  async unfinishedPrevious(schedule) {
29935
30037
  const last = (await this.schedules.listRuns(schedule.id, 10)).find((run2) => run2.status === "delivered" && run2.sessionId && run2.taskId);
29936
30038
  if (!last) return void 0;
30039
+ const lastSession = await this.runtime.getSession(last.sessionId);
30040
+ if (lastSession?.archivedAt) return void 0;
29937
30041
  const task = (await this.runtime.getTasks(last.sessionId)).find((item) => item.id === last.taskId);
29938
30042
  return task && unfinishedTaskStatuses.has(task.status) ? task.status : void 0;
29939
30043
  }
@@ -32180,6 +32284,11 @@ var AssistantLifecycle = class {
32180
32284
  retired.peakAgeScore = collected.cat.peakAgeScore;
32181
32285
  }
32182
32286
  this.store.saveCat(retired);
32287
+ try {
32288
+ await this.host.onMainSessionHandoff?.(fromSession.id, session.id);
32289
+ } catch (error) {
32290
+ this.log.warn(`\u4E3B\u4F1A\u8BDD\u4EA4\u63A5\u8FC1\u79FB\u5B9A\u65F6\u4EFB\u52A1\u5931\u8D25\uFF1A${errorMessage2(error)}`);
32291
+ }
32183
32292
  await this.runtime.archive(fromSession.id);
32184
32293
  committed = true;
32185
32294
  this.markStep(id, "retiring", `\u65E7\u4E3B\u4F1A\u8BDD ${fromSession.id} \u5DF2\u5F52\u6863\uFF08\u53EA\u8BFB\uFF0C\u8BB0\u5F55\u5168\u90E8\u4FDD\u7559\uFF09`);
@@ -32364,7 +32473,7 @@ function withContext(percent2) {
32364
32473
 
32365
32474
  // src/assistant/cwd.ts
32366
32475
  init_src2();
32367
- import { accessSync as accessSync2, constants as constants5, statSync as statSync5 } from "node:fs";
32476
+ import { accessSync as accessSync3, constants as constants6, statSync as statSync6 } from "node:fs";
32368
32477
  import { homedir as homedir16 } from "node:os";
32369
32478
  import { isAbsolute as isAbsolute8, resolve as resolve11 } from "node:path";
32370
32479
  function expandHomePath(value) {
@@ -32386,7 +32495,7 @@ function validateCwd(value) {
32386
32495
  const absolute = resolve11(expanded);
32387
32496
  let stats;
32388
32497
  try {
32389
- stats = statSync5(absolute);
32498
+ stats = statSync6(absolute);
32390
32499
  } catch {
32391
32500
  throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u5B58\u5728\uFF1A${absolute}`, 400);
32392
32501
  }
@@ -32394,7 +32503,7 @@ function validateCwd(value) {
32394
32503
  throw new RuntimeError("INVALID_TASK_CWD", `\u5DE5\u4F5C\u76EE\u5F55\u4E0D\u662F\u6587\u4EF6\u5939\uFF1A${absolute}`, 400);
32395
32504
  }
32396
32505
  try {
32397
- accessSync2(absolute, constants5.R_OK | constants5.X_OK);
32506
+ accessSync3(absolute, constants6.R_OK | constants6.X_OK);
32398
32507
  } catch {
32399
32508
  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);
32400
32509
  }
@@ -32508,7 +32617,8 @@ var AssistantService = class {
32508
32617
  nameSession: (sessionId, title) => this.nameSession(sessionId, title),
32509
32618
  mainSystemPrompt: () => buildMainSystemPrompt(),
32510
32619
  normalizeName: normalizeCompanionName,
32511
- agentCatalog: (agentId) => this.handoffAgentCatalog(agentId)
32620
+ agentCatalog: (agentId) => this.handoffAgentCatalog(agentId),
32621
+ ...options.onMainSessionHandoff ? { onMainSessionHandoff: options.onMainSessionHandoff } : {}
32512
32622
  }
32513
32623
  });
32514
32624
  }
@@ -33767,7 +33877,9 @@ async function startLocalServer(options = {}) {
33767
33877
  const sideChatConfig = new SideChatConfigService({ config: repos.config, listAgents: () => runtime.listAgents() });
33768
33878
  const packageJson2 = JSON.parse(readFileSync9(new URL("../package.json", import.meta.url), "utf8"));
33769
33879
  const selfUpdate = options.cliEntrypoint ? new SelfUpdateService({ currentVersion: packageJson2.version, packageName: packageJson2.name, cliEntrypoint: options.cliEntrypoint, env }) : void 0;
33770
- schedules2 = new ScheduleService(repos.schedules, repos.sessions, runtime);
33880
+ schedules2 = new ScheduleService(repos.schedules, repos.sessions, runtime, {
33881
+ resolveMainSessionId: () => assistant?.mainSessionId
33882
+ });
33771
33883
  assistant = new AssistantService({
33772
33884
  databaseUrl: config.databaseUrl,
33773
33885
  runtime,
@@ -33778,6 +33890,9 @@ async function startLocalServer(options = {}) {
33778
33890
  sendLarkReply: (input) => {
33779
33891
  if (!larkAvatar) throw new Error("\u98DE\u4E66\u66FF\u8EAB\u5C1A\u672A\u521D\u59CB\u5316");
33780
33892
  return larkAvatar.sendMessage(input);
33893
+ },
33894
+ onMainSessionHandoff: async (fromSessionId) => {
33895
+ await schedules2?.migrateSessionAppendSchedulesToMain(fromSessionId);
33781
33896
  }
33782
33897
  });
33783
33898
  await assistant.initialize();
@@ -34900,16 +35015,27 @@ function sandboxEnv(sandbox, base = process.env) {
34900
35015
  AGENTDOCK_ALLOW_REACTION_TEST: "true",
34901
35016
  agentdock_database: sandbox.database
34902
35017
  };
34903
- env.PATH = [shimDir(sandbox), base.PATH].filter(Boolean).join(delimiter2);
35018
+ const pathKey = process.platform === "win32" ? Object.keys(base).find((key) => key.toUpperCase() === "PATH") ?? "PATH" : "PATH";
35019
+ env[pathKey] = [shimDir(sandbox), base[pathKey]].filter(Boolean).join(delimiter2);
34904
35020
  for (const key of ["agentdock_session_id", "agentdock_group_tools_url", "agentdock_group_tools_token"]) delete env[key];
34905
35021
  for (const key of [DAEMON_ENV_FLAG, DAEMON_CWD_ENV, DAEMON_STARTED_AT_ENV, DAEMON_DIR_ENV]) delete env[key];
34906
35022
  return env;
34907
35023
  }
34908
35024
  var shellQuote5 = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
34909
35025
  function writeCliShim(sandbox, node = process.execPath) {
34910
- if (process.platform === "win32") return;
34911
35026
  const dir = shimDir(sandbox);
34912
35027
  mkdirSync6(dir, { recursive: true });
35028
+ if (process.platform === "win32") {
35029
+ const quote2 = (path5) => `"${path5.replace(/%/g, "%%")}"`;
35030
+ writeFileSync5(
35031
+ join23(dir, "agent-dock.cmd"),
35032
+ `@echo off\r
35033
+ setlocal DisableDelayedExpansion\r
35034
+ ${quote2(node)} ${quote2(sandbox.entrypoint)} %*\r
35035
+ `
35036
+ );
35037
+ return;
35038
+ }
34913
35039
  const file = join23(dir, "agent-dock");
34914
35040
  writeFileSync5(file, `#!/bin/sh
34915
35041
  exec ${shellQuote5(node)} ${shellQuote5(sandbox.entrypoint)} "$@"
@@ -35038,6 +35164,8 @@ function runPasswordStatus(path5 = webPasswordPath()) {
35038
35164
  }
35039
35165
 
35040
35166
  // src/schedule-cli.ts
35167
+ init_src2();
35168
+ init_src();
35041
35169
  init_session_cli();
35042
35170
  var deliveryLabel = { new_session: "\u6BCF\u6B21\u65B0\u5F00\u4F1A\u8BDD", append: "\u8FFD\u52A0\u5230\u4F1A\u8BDD" };
35043
35171
  function localTime(iso, timezone) {
@@ -35045,6 +35173,7 @@ function localTime(iso, timezone) {
35045
35173
  return new Date(iso).toLocaleString("zh-CN", { hour12: false, ...timezone ? { timeZone: timezone } : {} });
35046
35174
  }
35047
35175
  function scheduleWhere(item) {
35176
+ if (isMainSessionScheduleTarget(item.sessionId)) return "\u8DDF\u968F\u5F53\u524D\u4E3B\u4F1A\u8BDD\uFF08\u6362\u4EE3\u81EA\u52A8\u8DDF\u968F\uFF09";
35048
35177
  if (item.sessionId) return `\u4F1A\u8BDD ${item.sessionId}`;
35049
35178
  try {
35050
35179
  const template = JSON.parse(item.sessionTemplate ?? "");
@@ -35063,19 +35192,53 @@ function scheduleLine(item) {
35063
35192
  function runLine(run2) {
35064
35193
  return `${localTime(run2.fireAt)} ${run2.status}${run2.reason ? `\uFF08${run2.reason}\uFF09` : ""}${run2.sessionId ? ` session=${run2.sessionId}` : ""}${run2.taskId ? ` task=${run2.taskId}` : ""}`;
35065
35194
  }
35195
+ function resolveMainOption(options) {
35196
+ const raw = options.session?.trim();
35197
+ if (options.main && raw && !isMainSessionScheduleTarget(raw)) {
35198
+ throw new Error("--main \u4E0D\u80FD\u4E0E --session \u540C\u65F6\u6307\u5B9A\u4E0D\u540C\u7684\u4F1A\u8BDD\u3002");
35199
+ }
35200
+ if (options.main || isMainSessionScheduleTarget(raw)) {
35201
+ return { session: SCHEDULE_MAIN_SESSION_ID, followMain: true };
35202
+ }
35203
+ return { ...raw ? { session: raw } : {}, followMain: false };
35204
+ }
35205
+ async function assertMainPeerIfApplicable(database, fromId) {
35206
+ const repos = createRepositories(database);
35207
+ let mainId;
35208
+ try {
35209
+ mainId = (await repos.config.get("assistant.main"))?.trim() || void 0;
35210
+ } finally {
35211
+ repos.close();
35212
+ }
35213
+ if (mainId && mainId !== fromId) {
35214
+ await assertPeerTarget(database, mainId, fromId, true);
35215
+ }
35216
+ }
35066
35217
  async function runScheduleAdd(prompt, options = {}) {
35067
35218
  const text3 = prompt.trim();
35068
35219
  if (!text3) throw new Error("\u5B9A\u65F6\u4EFB\u52A1\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A\u3002");
35069
35220
  if ([options.cron, options.at, options.every].filter(Boolean).length !== 1) throw new Error("\u5FC5\u987B\u4E14\u53EA\u80FD\u6307\u5B9A --cron\u3001--every\u3001--at \u4E2D\u7684\u4E00\u4E2A\u3002");
35070
35221
  if (options.delivery && options.delivery !== "new_session" && options.delivery !== "append") throw new Error("--delivery \u53EA\u80FD\u662F new_session \u6216 append\u3002");
35222
+ const { session: explicitSession, followMain } = resolveMainOption(options);
35071
35223
  const state = requireDaemon(options.daemonDir);
35072
- const fromId = sourceSessionId(options.from);
35073
- const sessionId = options.session?.trim() || fromId;
35074
- if (sessionId !== fromId) await assertPeerTarget(state.database, sessionId, fromId, true);
35224
+ let fromId;
35225
+ let sessionId;
35226
+ if (followMain) {
35227
+ try {
35228
+ fromId = sourceSessionId(options.from);
35229
+ } catch {
35230
+ }
35231
+ if (fromId) await assertMainPeerIfApplicable(state.database, fromId);
35232
+ sessionId = SCHEDULE_MAIN_SESSION_ID;
35233
+ } else {
35234
+ fromId = sourceSessionId(options.from);
35235
+ sessionId = explicitSession || fromId;
35236
+ if (sessionId !== fromId) await assertPeerTarget(state.database, sessionId, fromId, true);
35237
+ }
35075
35238
  const created = await callDaemon(state, "/api/schedules", "POST", {
35076
35239
  sessionId,
35077
35240
  prompt: text3,
35078
- createdBySessionId: fromId,
35241
+ ...fromId ? { createdBySessionId: fromId } : {},
35079
35242
  ...options.cron ? { cron: options.cron } : {},
35080
35243
  ...options.every ? { intervalMinutes: parseEvery(options.every) } : {},
35081
35244
  ...options.at ? { runAt: parseAt(options.at) } : {},
@@ -35088,6 +35251,59 @@ async function runScheduleAdd(prompt, options = {}) {
35088
35251
  ${scheduleLine(created)}
35089
35252
  `;
35090
35253
  }
35254
+ async function runScheduleUpdate(id, options = {}) {
35255
+ const timingCount = [options.cron, options.at, options.every].filter(Boolean).length;
35256
+ if (timingCount > 1) throw new Error("--cron\u3001--every\u3001--at \u6700\u591A\u53EA\u80FD\u6307\u5B9A\u4E00\u4E2A\u3002");
35257
+ if (options.delivery && options.delivery !== "new_session" && options.delivery !== "append") throw new Error("--delivery \u53EA\u80FD\u662F new_session \u6216 append\u3002");
35258
+ const { session: explicitSession, followMain } = resolveMainOption(options);
35259
+ const state = requireDaemon(options.daemonDir);
35260
+ if (followMain) {
35261
+ let fromId;
35262
+ try {
35263
+ fromId = sourceSessionId(options.from);
35264
+ } catch {
35265
+ }
35266
+ if (fromId) await assertMainPeerIfApplicable(state.database, fromId);
35267
+ } else if (explicitSession) {
35268
+ let fromId;
35269
+ try {
35270
+ fromId = sourceSessionId(options.from);
35271
+ } catch {
35272
+ }
35273
+ if (fromId && explicitSession !== fromId) await assertPeerTarget(state.database, explicitSession, fromId, true);
35274
+ }
35275
+ const body = {};
35276
+ if (options.prompt !== void 0) {
35277
+ const text3 = options.prompt.trim();
35278
+ if (!text3) throw new Error("\u5B9A\u65F6\u4EFB\u52A1\u5185\u5BB9\u4E0D\u80FD\u4E3A\u7A7A\u3002");
35279
+ body.prompt = text3;
35280
+ }
35281
+ if (options.name !== void 0) body.name = options.name;
35282
+ if (options.delivery !== void 0) body.delivery = options.delivery;
35283
+ if (explicitSession !== void 0) body.sessionId = explicitSession;
35284
+ if (options.tz !== void 0) body.timezone = options.tz;
35285
+ if (options.cron !== void 0) {
35286
+ body.cron = options.cron;
35287
+ body.intervalMinutes = null;
35288
+ body.runAt = null;
35289
+ }
35290
+ if (options.every !== void 0) {
35291
+ body.intervalMinutes = parseEvery(options.every);
35292
+ body.cron = null;
35293
+ body.runAt = null;
35294
+ }
35295
+ if (options.at !== void 0) {
35296
+ body.runAt = parseAt(options.at);
35297
+ body.cron = null;
35298
+ body.intervalMinutes = null;
35299
+ }
35300
+ if (!Object.keys(body).length) throw new Error("\u8BF7\u81F3\u5C11\u6307\u5B9A\u4E00\u4E2A\u8981\u66F4\u65B0\u7684\u5B57\u6BB5\uFF08\u5982 --prompt\u3001--name\u3001--cron\u3001--every\u3001--at\u3001--delivery\u3001--session\u3001--main\uFF09\u3002");
35301
+ const updated = await callDaemon(state, `/api/schedules/${encodeURIComponent(id)}`, "PATCH", body);
35302
+ if (options.json) return JSON.stringify(updated, null, 2) + "\n";
35303
+ return `\u5DF2\u66F4\u65B0\u5B9A\u65F6\u4EFB\u52A1\uFF1A
35304
+ ${scheduleLine(updated)}
35305
+ `;
35306
+ }
35091
35307
  function parseEvery(value) {
35092
35308
  const text3 = value.trim().toLowerCase();
35093
35309
  if (/^\d+$/.test(text3)) return Number(text3);
@@ -35113,7 +35329,8 @@ function parseAt(value) {
35113
35329
  }
35114
35330
  async function runScheduleList(options = {}) {
35115
35331
  const state = requireDaemon(options.daemonDir);
35116
- let sessionId = options.session?.trim();
35332
+ const { session: explicitSession } = resolveMainOption(options);
35333
+ let sessionId = explicitSession;
35117
35334
  if (!options.all && !sessionId) {
35118
35335
  try {
35119
35336
  sessionId = sourceSessionId();
@@ -35122,8 +35339,11 @@ async function runScheduleList(options = {}) {
35122
35339
  }
35123
35340
  const items = await callDaemon(state, `/api/schedules${sessionId ? `?sessionId=${encodeURIComponent(sessionId)}` : ""}`, "GET");
35124
35341
  if (options.json) return JSON.stringify(items, null, 2) + "\n";
35125
- if (!items.length) return sessionId ? `\u4F1A\u8BDD ${sessionId} \u6CA1\u6709\u5B9A\u65F6\u4EFB\u52A1\u3002\u7528 --all \u67E5\u770B\u5168\u90E8\u3002
35342
+ if (!items.length) {
35343
+ if (isMainSessionScheduleTarget(sessionId)) return "\u6CA1\u6709\u8DDF\u968F\u5F53\u524D\u4E3B\u4F1A\u8BDD\u7684\u5B9A\u65F6\u4EFB\u52A1\u3002\u7528 --all \u67E5\u770B\u5168\u90E8\u3002\n";
35344
+ return sessionId ? `\u4F1A\u8BDD ${sessionId} \u6CA1\u6709\u5B9A\u65F6\u4EFB\u52A1\u3002\u7528 --all \u67E5\u770B\u5168\u90E8\u3002
35126
35345
  ` : "\u6CA1\u6709\u5B9A\u65F6\u4EFB\u52A1\u3002\n";
35346
+ }
35127
35347
  return items.map(scheduleLine).join("\n\n") + "\n";
35128
35348
  }
35129
35349
  async function runScheduleShow(id, options = {}) {
@@ -36840,6 +37060,9 @@ ${status.plistPath}` : "\u5F00\u673A\u81EA\u542F\uFF1A\u672A\u5F00\u542F"}
36840
37060
  scheduleAdd: async (prompt, options) => {
36841
37061
  process.stdout.write(await runScheduleAdd(prompt, options));
36842
37062
  },
37063
+ scheduleUpdate: async (id, options) => {
37064
+ process.stdout.write(await runScheduleUpdate(id, options));
37065
+ },
36843
37066
  scheduleList: async (options) => {
36844
37067
  process.stdout.write(await runScheduleList(options));
36845
37068
  },