Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(scheduler): pause script automation when its owner is archived (#4762)

Chris Zhangb41d90d4e0c3
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
index cb76020b8f..f0c8a33618 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptCapabilityBroker.test.ts
@@ -389,6 +389,18 @@ describe('SchedulerScriptCapabilityBroker', () => {
).rejects.toMatchObject({ code: 'METHOD_NOT_FOUND' });
});
+ it('uses the bound owner for omitted dispatch targets and rejects another target', async () => {
+ sendToSessionMock.mockResolvedValue({ ok: true, targetSessionId: 'owner', agentKind: 'codex', wakeKind: 'queued' });
+ const broker = new SchedulerScriptCapabilityBroker();
+ const context = { schedule: schedule({ targetSessionId: 'owner' }) };
+ await broker.call({ method: 'sessions.dispatch', params: { message: 'update' } }, new Set(['sessions.dispatch']), context);
+ expect(sendToSessionMock).toHaveBeenCalledWith(expect.objectContaining({ targetSessionId: 'owner' }));
+ sendToSessionMock.mockClear();
+ await expect(broker.call({ method: 'sessions.dispatch', params: { target_session_id: 'other', message: 'update' } },
+ new Set(['sessions.dispatch']), context)).rejects.toMatchObject({ code: 'INVALID_ARGS' });
+ expect(sendToSessionMock).not.toHaveBeenCalled();
+ });
+
it('dispatches sessions with host-owned create defaults from the schedule', async () => {
sendToSessionMock.mockResolvedValue({
ok: true,
diff --git a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
index 03fff69169..e16fcc8e73 100644
--- a/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
+++ b/apps/desktop/src/main/scheduler-host/__tests__/scriptRunner.test.ts
@@ -100,6 +100,61 @@ describe('ScriptScheduleRunner', () => {
killProcessTreeMock.mockClear();
});
+ it.each(['archived', 'deleted', 'missing'])('pauses a bound script with a %s owner before any hook or process', async (status) => {
+ const pause = vi.fn(async () => undefined);
+ const db = { select: () => ({ from: () => ({ where: () => ({
+ limit: async () => status === 'missing' ? [] : [{ status }],
+ }) }) }) };
+ const runner = new ScriptScheduleRunner({ broker: { call: vi.fn() }, logger: {},
+ getDb: () => db as never, scheduler: { pause } as never });
+ await expect(runner.fire({ ...schedule(), targetSessionId: 'owner',
+ preRunHook: { command: 'broken-or-idle-hook' } }, {
+ runId: 'run-owner', firedAt: 1, signal: new AbortController().signal,
+ })).resolves.toMatchObject({ skipped: true, resultText: `Script stopped: target session ${status}` });
+ expect(pause).toHaveBeenCalledWith('script-schedule', { exemptRunId: 'run-owner' });
+ expect(executePreRunHookMock).not.toHaveBeenCalled();
+ expect(spawnMock).not.toHaveBeenCalled();
+ });
+
+ it('does not retire a live owner or treat a database outage as a missing owner', async () => {
+ const pause = vi.fn();
+ const limit = vi.fn().mockResolvedValue([{ status: 'active' }]);
+ const db = { select: () => ({ from: () => ({ where: () => ({ limit }) }) }) };
+ executePreRunHookMock.mockResolvedValue({ decision: 'skip', exitCode: 2, durationMs: 1,
+ stdout: '', stderr: '', timedOut: false });
+ const runner = new ScriptScheduleRunner({ broker: { call: vi.fn() }, logger: {},
+ getDb: () => db as never, scheduler: { pause } as never });
+ const input = { ...schedule(), targetSessionId: 'owner', preRunHook: { command: 'idle' } };
+ const ctx = { runId: 'run-owner', firedAt: 1, signal: new AbortController().signal };
+ await expect(runner.fire(input, ctx)).resolves.toMatchObject({ skipped: true });
+ expect(executePreRunHookMock).toHaveBeenCalledOnce();
+ limit.mockRejectedValue(new Error('database unavailable'));
+ await expect(runner.fire(input, ctx)).rejects.toThrow('database unavailable');
+ expect(pause).not.toHaveBeenCalled();
+ });
+
+ it.each(['active', 'archived'])('rechecks durable %s owner after a dispatch NOT_FOUND race', async (status) => {
+ const child = childProcess();
+ spawnMock.mockReturnValue(child);
+ const pause = vi.fn(async () => undefined);
+ const limit = vi.fn().mockResolvedValueOnce([{ status: 'active' }]).mockResolvedValue([{ status }]);
+ const db = { select: () => ({ from: () => ({ where: () => ({ limit }) }) }) };
+ const call = vi.fn().mockRejectedValue(Object.assign(new Error('owner not available'), { code: 'NOT_FOUND' }));
+ const runner = new ScriptScheduleRunner({ broker: { call }, logger: {},
+ getDb: () => db as never, scheduler: { pause } as never });
+ const result = runner.fire({ ...schedule(), targetSessionId: 'owner' }, {
+ runId: 'run-owner', firedAt: 1, signal: new AbortController().signal,
+ });
+ await vi.waitFor(() => expect(spawnMock).toHaveBeenCalled());
+ child.stdout.write(JSON.stringify({ protocol: 'cindy-script/1', type: 'call', id: 'send',
+ method: 'sessions.dispatch', params: { target_session_id: 'owner', message: 'update' } }) + '\n');
+ await vi.waitFor(() => expect(limit).toHaveBeenCalledTimes(2));
+ child.stdout.write(JSON.stringify({ protocol: 'cindy-script/1', type: 'complete', resultText: 'not delivered' }) + '\n');
+ child.emit('close', 0);
+ await result;
+ expect(pause).toHaveBeenCalledTimes(status === 'archived' ? 1 : 0);
+ });
+
it('pre-run hook exit 2 skips without creating a session or spawning the script', async () => {
executePreRunHookMock.mockResolvedValue({
decision: 'skip',
diff --git a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
index 803693ab2f..21eaa08052 100644
--- a/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
+++ b/apps/desktop/src/main/scheduler-host/script-capability-broker.ts
@@ -356,6 +356,11 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
const service = tryGetOrcaCollabService();
if (!service) fail('HOST_NOT_READY', 'session dispatch service is not ready');
const schedule = context.schedule;
+ const requestedTarget = typeof params.target_session_id === 'string'
+ && params.target_session_id.trim() ? params.target_session_id : undefined;
+ if (schedule.targetSessionId && requestedTarget && requestedTarget !== schedule.targetSessionId) {
+ fail('INVALID_ARGS', 'bound scripts can only dispatch to their target session');
+ }
const explicitProviderId = schedule.providerId?.trim() || null;
const dynamicDefaultRoute = !schedule.model?.trim() && schedule.agentKind === 'pi'
? await this.deps.resolveDefaultModelRoute?.(
@@ -368,10 +373,7 @@ export class SchedulerScriptCapabilityBroker implements ScriptCapabilityBroker {
|| defaultModelFor(schedule.agentKind);
if (!model) fail('PRECONDITION_FAILED', 'Pi has no connected model source');
const result = await service.sendToSession({
- targetSessionId:
- typeof params.target_session_id === 'string' && params.target_session_id.trim()
- ? params.target_session_id
- : undefined,
+ targetSessionId: schedule.targetSessionId ?? requestedTarget,
message: requireString(params, 'message'),
title: typeof params.title === 'string' ? params.title : undefined,
useWorktree: false,
diff --git a/apps/desktop/src/main/scheduler-host/script-runner.ts b/apps/desktop/src/main/scheduler-host/script-runner.ts
index a975d4e1d0..6186e0da88 100644
--- a/apps/desktop/src/main/scheduler-host/script-runner.ts
+++ b/apps/desktop/src/main/scheduler-host/script-runner.ts
@@ -163,6 +163,26 @@ export class ScriptScheduleRunner {
}
}
+ private async retireUnavailableOwner(schedule: Schedule, ctx: FireContext): Promise<FireResult | null> {
+ // The owner is a lifecycle binding, not an agent execution mode. Check before
+ // hooks so idle scripts stop too, even when they have no event to dispatch.
+ if (schedule.targetSessionId) {
+ if (!this.deps.getDb || !this.deps.scheduler) {
+ throw new Error('bound script execution requires session storage and scheduler');
+ }
+ const [owner] = await this.deps.getDb()
+ .select({ status: sessions.status }).from(sessions)
+ .where(eq(sessions.id, schedule.targetSessionId)).limit(1);
+ if (!owner || owner.status === 'archived' || owner.status === 'deleted') {
+ await this.deps.scheduler.pause(schedule.id, { exemptRunId: ctx.runId });
+ return { sessionId: '', skipped: true,
+ resultText: `Script stopped: target session ${owner?.status ?? 'missing'}` };
+ }
+ }
+
+ return null;
+ }
+
private async fireInner(schedule: Schedule, ctx: FireContext): Promise<FireResult> {
const config = schedule.scriptConfig;
if (schedule.executionMode !== 'script' || !config?.command.trim()) {
@@ -171,8 +191,13 @@ export class ScriptScheduleRunner {
if (schedule.workspaceKind !== 'project' || !schedule.workingDir?.trim()) {
throw new Error('script execution requires a local project workspace');
}
- if (schedule.useWorktree || schedule.targetSessionId || schedule.persistentSession) {
- throw new Error('script execution does not support worktrees or bound sessions');
+ if (schedule.useWorktree || schedule.persistentSession) {
+ throw new Error('script execution does not support worktrees or persistent sessions');
+ }
+
+ if (schedule.targetSessionId) {
+ const retired = await this.retireUnavailableOwner(schedule, ctx);
+ if (retired) return retired;
}
if (schedule.preRunHook?.command?.trim()) {
@@ -363,7 +388,22 @@ export class ScriptScheduleRunner {
: result;
writeFrame({ type: 'call_result', id: frame.id, ok: true, result: responseResult });
} catch (error) {
- writeFrame({ type: 'call_result', id: frame.id, ok: false, error: safeError(error) });
+ // The owner may be archived after the pre-run check. Only a typed
+ // dispatch rejection for this bound owner retires the schedule; transient
+ // failures and unbound multi-target scripts keep their normal lifecycle.
+ const failure = safeError(error);
+ if (schedule.targetSessionId && frame.method === 'sessions.dispatch'
+ && (!frame.params?.target_session_id || frame.params.target_session_id === schedule.targetSessionId)
+ && ['ARCHIVED', 'DELETED', 'NOT_FOUND'].includes(failure.code)) {
+ try {
+ // Re-read durable state: NOT_FOUND can also mean a temporary runtime
+ // lookup failure, which must not permanently pause a live owner.
+ await this.retireUnavailableOwner(schedule, ctx);
+ } catch (pauseError) {
+ deferredCallFailure = pauseError instanceof Error ? pauseError : new Error(String(pauseError));
+ }
+ }
+ writeFrame({ type: 'call_result', id: frame.id, ok: false, error: failure });
if (completeReceived && !deferredCallFailure) {
deferredCallFailure = error instanceof Error ? error : new Error(safeError(error).message);
}
@@ -479,6 +519,7 @@ export class ScriptScheduleRunner {
runId: ctx.runId,
firedAt: ctx.firedAt,
workingDir: schedule.workingDir,
+ ...(schedule.targetSessionId ? { targetSessionId: schedule.targetSessionId } : {}),
},
});
diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useScheduleForm.validate.test.tsx b/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useScheduleForm.validate.test.tsx
index f3513e9975..aaffa6afbe 100644
--- a/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useScheduleForm.validate.test.tsx
+++ b/apps/desktop/src/renderer/features/scheduler/hooks/__tests__/useScheduleForm.validate.test.tsx
@@ -10,7 +10,7 @@ import { formToProjectConfig } from '../../lib/projectAutomationConfig';
/**
* 回归(codex review #966):script 模式不展示前置检查区块,buildScheduleInput
- * 的 script 分支也会把它清空。若用户在 agent 模式下开了前置检查、命令留空,
+ * 只保留已有的非空检查。若用户在 agent 模式下开了前置检查、命令留空,
* 再切到 script,validate 不该沿用那条校验——否则用户看不到该区块、点不到
* 那个开关,却被挡在保存之外。
*/
diff --git a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts
index 5ca39caaf3..7ec19024bd 100644
--- a/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts
+++ b/apps/desktop/src/renderer/features/scheduler/hooks/useScheduleForm.ts
@@ -419,9 +419,7 @@ export function useScheduleForm(initial: Schedule | null = null): UseScheduleFor
const isHeartbeat = !!tgt;
if (form.executionMode === 'script') {
if (!form.workingDir.trim()) return { key: 'scheduler.editor.validation.selectProject' };
- // 编辑 bound/persistent 任务切到 script 时 targetSessionId 会残留在 form 里
- // (运行会话控件已隐藏,用户无从清理)——不在这里拦:buildScheduleInput 的
- // script 分支会把绑定/worktree/静默字段全部清干净,保存即完成模式转换。
+ // Script bindings survive editing; unavailable owners are paused by the host.
} else if (isHeartbeat) {
if (tgt === '__pending__') return { key: 'scheduler.editor.validation.selectThread' };
} else {
@@ -432,8 +430,7 @@ export function useScheduleForm(initial: Schedule | null = null): UseScheduleFor
return { key: 'scheduler.editor.validation.reasoningInvalid', values: { values: EFFORT_VALUES.join(' / ') } };
}
}
- // script 模式不展示前置检查区块,buildScheduleInput 的 script 分支也会把它清空
- // ——若在 agent 模式下开了前置检查但命令留空,切到 script 后这条校验不该沿用,
+ // script 模式保留已有前置检查;切换时命令留空不创建 hook,
// 否则用户明明看不到该区块也点不到那个开关,却被挡在保存之外。
if (form.executionMode !== 'script' && form.preRunHookEnabled && !form.preRunHookCommand.trim()) {
return { key: 'scheduler.editor.validation.preRunHookCommandRequired' };
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleFormLogic.test.ts b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleFormLogic.test.ts
index e391219136..7f4b708ec0 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleFormLogic.test.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/__tests__/scheduleFormLogic.test.ts
@@ -295,7 +295,7 @@ describe('canSubmitSessionBinding', () => {
})).toBe(false);
});
- it('allows script mode to clear an unavailable stale binding', () => {
+ it('allows script edits while the host handles unavailable lifecycle owners', () => {
expect(canSubmitSessionBinding('script', 'bound', undefined)).toBe(true);
expect(
canSubmitSessionBinding('script', 'bound', { sessionId: 'session-1', state: 'deleted' }),
@@ -884,3 +884,17 @@ describe('scheduleToUserCreateInput', () => {
expect(original.agentKind).toBe('codex');
});
});
+
+
+describe('script lifecycle serialization', () => {
+ it('preserves owner and installed gate while keeping script cwd', () => {
+ const input = buildScheduleInput(makeForm({ executionMode: 'script',
+ targetSessionId: 'owner', workingDir: '/watcher', scriptCommand: 'node run.mjs',
+ preRunHookEnabled: true, preRunHookCommand: 'node /watcher/gate.mjs',
+ }));
+ expect(input.targetSessionId).toBe('owner');
+ expect(input.workingDir).toBe('/watcher');
+ expect(input.preRunHook?.command).toBe('node /watcher/gate.mjs');
+ expect(buildScheduleInput(makeForm({ executionMode: 'script', targetSessionId: '__pending__' })).targetSessionId).toBeUndefined();
+ });
+});
diff --git a/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts b/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
index b64e8e37e3..fe9b53c741 100644
--- a/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
+++ b/apps/desktop/src/renderer/features/scheduler/lib/scheduleFormLogic.ts
@@ -167,8 +167,8 @@ export type RunMode = 'fresh' | 'persistent' | 'bound';
* Agent-mode bound schedules may only be persisted after the selected session
* has resolved as available and active. Archived sessions remain openable, so
* their reference state is still `available`, but the runner cannot use them as
- * ordinary heartbeat targets. Script mode intentionally clears targetSessionId,
- * so a stale binding must not block that mode conversion.
+ * ordinary heartbeat targets. Script bindings are lifecycle owners: editing them remains allowed,
+ * and the runner pauses unavailable owners before executing hooks or scripts.
*/
export function canSubmitSessionBinding(
executionMode: ScheduleFormState['executionMode'],
@@ -536,7 +536,7 @@ export function buildScheduleInput(form: ScheduleFormState): CreateScheduleInput
useWorktree: !isScript && form.workspaceKind === 'project' && form.useWorktree,
persistentSession: !isScript && form.persistentSession,
silentWhenIdle: !isScript && form.silentWhenIdle,
- targetSessionId: !isScript ? (form.targetSessionId.trim() || undefined) : undefined,
+ targetSessionId: hasRealBinding(form) ? form.targetSessionId.trim() : undefined,
preRunHook: buildPreRunHook(form),
notify: {
desktop: form.notifyDesktop,
@@ -549,9 +549,7 @@ export function buildScheduleInput(form: ScheduleFormState): CreateScheduleInput
base.workspaceKind = 'project';
base.workingDir = form.workingDir.trim();
base.useWorktree = false;
- // script 模式不叠前置检查(任务本体就是脚本,UI 也不展示该区块);保留 key,
- // 编辑保存时按 hasKey + undefined = 写 NULL 契约把历史 hook 清列。
- base.preRunHook = undefined;
+ // Preserve installed script gates when editing; hidden controls must not erase them.
return base;
}
diff --git a/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts b/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
index 793e100747..c480bdc357 100644
--- a/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
+++ b/packages/lizi-mcps/src/__tests__/cindy_schedulerMcpServer.test.ts
@@ -630,11 +630,10 @@ describe('cindy_scheduler MCP server (in-process smoke)', () => {
await h.cleanup();
});
- it('call_tool(schedule_create, script + bound-session/worktree combos) returns INVALID_PARAMS', async () => {
+ it('call_tool(schedule_create, script + persistent-session/worktree combos) returns INVALID_PARAMS', async () => {
for (const extra of [
{ persistentSession: true },
{ useWorktree: true },
- { bindToCurrentSession: true },
]) {
const result = await h.client.callTool({
name: 'call_tool',
@@ -714,10 +713,8 @@ describe('cindy_scheduler MCP server (in-process smoke)', () => {
await h.cleanup();
});
- it('call_tool(schedule_update, targetSessionId=null) unbinds so a bound schedule can switch to script mode (codex review 966)', async () => {
- // 已绑定会话的任务:schema 只收 string 或缺省时,JSON 调用方拼不出"解绑"的
- // 合法 patch(缺省 = 不修改),也就永远切不成 script 模式——null 必须被翻译
- // 成 key 在但值 undefined 的引擎语义(同 preRunHook 约定)。
+ it('call_tool(schedule_update, targetSessionId=null) preserves a binding when switching to script, and explicitly unbinds with null', async () => {
+ // Omitted target preserves the lifecycle owner; explicit null clears it.
const created = await h.client.callTool({
name: 'call_tool',
arguments: {
@@ -730,7 +727,7 @@ describe('cindy_scheduler MCP server (in-process smoke)', () => {
expect((createdEnv.data as Schedule).targetSessionId).toBe('sess-bound-1');
const id = (createdEnv.data as Schedule).id;
- // 不解绑直接切 script → 引擎合并态校验拦下(绑定与 script 互斥)
+ // 切到 script 保留生命周期绑定;只有显式 null 才解绑。
const stillBound = await h.client.callTool({
name: 'call_tool',
arguments: {
@@ -743,7 +740,7 @@ describe('cindy_scheduler MCP server (in-process smoke)', () => {
},
});
const stillBoundEnv = parseToolResult(stillBound as { content: unknown[]; isError?: boolean }).envelope;
- expect(stillBoundEnv).toMatchObject({ ok: false, code: 'INVALID_PARAMS' });
+ expect(stillBoundEnv).toMatchObject({ ok: true, data: { executionMode: 'script', targetSessionId: 'sess-bound-1' } });
// targetSessionId: null 解绑 + 切 script,一个 patch 完成
const unboundToScript = await h.client.callTool({
@@ -1066,6 +1063,16 @@ describe('schedule_create — bindToCurrentSession', () => {
expect(created.input).toBeUndefined();
});
+ it('script binding uses caller identity and retains its own working directory', async () => {
+ const { created, registry } = setup('sess-current');
+ const env = await callCreate(registry, { executionMode: 'script',
+ scriptConfig: { command: 'node watcher.mjs', capabilities: ['sessions.dispatch'] },
+ workingDir: '/watcher', bindToCurrentSession: true, targetSessionId: 'stale',
+ });
+ expect(env.ok).toBe(true);
+ expect(created.input).toMatchObject({ targetSessionId: 'sess-current', workingDir: '/watcher' });
+ });
+
it('不设 bindToCurrentSession → 沿用 agent 传的 targetSessionId(向后兼容)', async () => {
const { created, registry } = setup('sess-current');
const env = await callCreate(registry, { targetSessionId: 'sess-explicit' });
@@ -1619,6 +1626,17 @@ describe('schedule_set_pre_run_hook — 统一安装通道', () => {
expect((data.test as Record<string, unknown>).decision).toBe('skip');
});
+ it('bound script hooks are installed in script cwd rather than owner cwd', async () => {
+ const { registry, installCalls } = setup({
+ scheduleRow: { id: 'sch-1', name: 'watcher', executionMode: 'script',
+ workingDir: '/watcher', targetSessionId: 'owner' },
+ resolveSessionWorkDir: async () => '/owner',
+ });
+ const env = await callTool(registry, { scheduleId: 'sch-1', script: 'process.exit(2)' });
+ expect(env.ok).toBe(true);
+ expect(installCalls[0]).toMatchObject({ workingDir: '/watcher' });
+ });
+
it('绑定会话任务 → 优先用 resolveSessionWorkDir 解析的会话目录落盘(schedule.workingDir 过期不用)', async () => {
const { registry, installCalls } = setup({
scheduleRow: {
diff --git a/packages/lizi-mcps/src/scheduler/create.ts b/packages/lizi-mcps/src/scheduler/create.ts
index 6c8cd62569..d06548572c 100644
--- a/packages/lizi-mcps/src/scheduler/create.ts
+++ b/packages/lizi-mcps/src/scheduler/create.ts
@@ -42,7 +42,7 @@ export function registerScheduleCreateTool(
'(7) 用户说"静默运行 / 没事别打扰我 / 只记录不用每次提醒"之类 → silentWhenIdle=true;如果用户定义了提醒条件,把条件保留在 prompt 里(如 CI 失败/新评论时提醒),runner 只会注入很短的主动上报协议;' +
'(8) 轮询型任务("有新 PR 才 review / CI 挂了才处理")优先配 preRunHook 前置检查(exit 0=放行、exit 2=跳过本轮不烧 token;报错/超时 fail-closed 阻止本轮并记录失败)。**脚本一律经 schedule_set_pre_run_hook 创建/修改**(落盘路径、协议、自测由宿主代码统一保证),不要自己写脚本文件再手填 preRunHook.command——先调它拿 command 再来创建,或创建后传 scheduleId 让它直接挂载;' +
'(9) 既有工作流程中的自动跟进,沿用该流程明确的频率、执行引擎、静默与通知默认值;用户在线也不需要为这些默认值另行确认。用户主动新建独立任务时,若关键实体或会实质改变目标的参数缺失,先询问,不盲猜;用户已明确说明或已有流程定义的参数不重复问。' +
- '(10) **仅运行脚本模式(零 token)**:executionMode="script" 时不启动 agent,宿主直接执行 scriptConfig.command(cwd=workingDir,必填本地项目目录);脚本经 stdout/stdin 的 cindy-script/1 JSONL 协议回调宿主受限能力,能力按 scriptConfig.capabilities 白名单授予(默认全拒)。script 模式不需要 prompt(可省),且不支持 useWorktree / targetSessionId / bindToCurrentSession / persistentSession。与 preRunHook 的分工:preRunHook 只是"要不要跑"的闸门,script 模式是"任务本体就是脚本"。',
+ '(10) **仅运行脚本模式(零 token)**:executionMode="script" 时不启动 agent,宿主直接执行 scriptConfig.command(cwd=workingDir,必填本地项目目录);脚本经 stdout/stdin 的 cindy-script/1 JSONL 协议回调宿主受限能力,能力按 scriptConfig.capabilities 白名单授予(默认全拒)。script 模式不需要 prompt(可省),不支持 useWorktree / persistentSession。单任务跟进应传 bindToCurrentSession=true 或 targetSessionId:它是脚本的生命周期绑定及唯一投递目标,目标归档、删除或不存在时自动暂停,恢复任务不会自动恢复调度。未绑定脚本保留独立任务语义。与 preRunHook 的分工:preRunHook 只是"要不要跑"的闸门,script 模式是"任务本体就是脚本"。',
inputShape: {
name: z.string().min(1).describe('展示名(GUI / 通知里出现)'),
prompt: z
@@ -177,9 +177,9 @@ export function registerScheduleCreateTool(
if (!(input.workingDir ?? '').trim()) {
throw new Error('invalid request: executionMode="script" 需要 workingDir(本地项目绝对路径)');
}
- if (input.useWorktree || input.targetSessionId || bindToCurrentSession || input.persistentSession) {
+ if (input.useWorktree || input.persistentSession) {
throw new Error(
- 'invalid request: script 模式不支持 useWorktree / targetSessionId / bindToCurrentSession / persistentSession',
+ 'invalid request: script 模式不支持 useWorktree / persistentSession',
);
}
input = { ...input, prompt: input.prompt ?? '', workspaceKind: 'project' };
diff --git a/packages/lizi-mcps/src/scheduler/setPreRunHook.ts b/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
index bd744d571f..f8f282f596 100644
--- a/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
+++ b/packages/lizi-mcps/src/scheduler/setPreRunHook.ts
@@ -94,11 +94,12 @@ export function registerScheduleSetPreRunHookTool(
if (scheduleId) {
const schedule = await scheduler.get(scheduleId);
if (!schedule) throw new Error(`Schedule not found: ${scheduleId}`);
+ // Script uses its own cwd; agent heartbeat inherits its bound session cwd.
// 目录优先级:显式入参 > 绑定会话的 meta.workDir > schedule.workingDir。
// 绑定会话(heartbeat)任务的 schedule.workingDir 通常为空(或"project
// 任务改绑会话"后过期),不解析会话目录会把脚本落进 fallbackDir、自测
// cwd 也与生产运行不一致。解析失败回落旧行为。
- if (!workingDir && schedule.targetSessionId && hookScript.resolveSessionWorkDir) {
+ if (!workingDir && schedule.executionMode !== 'script' && schedule.targetSessionId && hookScript.resolveSessionWorkDir) {
const sessionDir = await hookScript
.resolveSessionWorkDir(schedule.targetSessionId)
.catch(() => undefined);
diff --git a/packages/lizi-mcps/src/scheduler/update.ts b/packages/lizi-mcps/src/scheduler/update.ts
index f506f8779b..862650e934 100644
--- a/packages/lizi-mcps/src/scheduler/update.ts
+++ b/packages/lizi-mcps/src/scheduler/update.ts
@@ -66,7 +66,7 @@ export function registerScheduleUpdateTool(
.min(1)
.nullable()
.optional()
- .describe('显式绑定到某条已存 session。跟进**当前对话**请改用 bindToCurrentSession,不要自己查 / 抄 session id。传 null = 解绑(清除会话绑定,比如把已绑定任务切成 script 模式前必须先解绑);省略 = 不修改。'),
+ .describe('显式绑定到某条已存 session。跟进**当前对话**请改用 bindToCurrentSession,不要自己查 / 抄 session id。传 null = 解绑;省略 = 不修改。script 模式同样可绑定,绑定为生命周期归属及唯一投递目标,归档或删除后停止。'),
bindToCurrentSession: z
.boolean()
.optional()
@@ -79,7 +79,7 @@ export function registerScheduleUpdateTool(
executionMode: z
.enum(EXECUTION_MODE)
.optional()
- .describe('执行方式:agent / script(仅运行脚本,零 token),语义见 schedule_create 同名字段。切到 script 时任务须已有(或本次 patch 同时带)scriptConfig,且 workingDir 是本地项目目录、未绑会话未开 worktree,否则报 INVALID_PARAMS'),
+ .describe('执行方式:agent / script(仅运行脚本,零 token),语义见 schedule_create 同名字段。切到 script 时任务须已有(或本次 patch 同时带)scriptConfig,且 workingDir 是本地项目目录、未开 worktree 或 persistentSession,否则报 INVALID_PARAMS'),
scriptConfig: z
.object({
command: z.string().min(1),
diff --git a/packages/maker-scheduler/src/__tests__/pre-run-hook-update.test.ts b/packages/maker-scheduler/src/__tests__/pre-run-hook-update.test.ts
index b124b9f72f..db775efe41 100644
--- a/packages/maker-scheduler/src/__tests__/pre-run-hook-update.test.ts
+++ b/packages/maker-scheduler/src/__tests__/pre-run-hook-update.test.ts
@@ -128,3 +128,41 @@ describe('stabilizePreRunHookForCreate', () => {
expect(result.preRunHook?.command).toBe('node scripts/check.mjs@/project-b');
});
});
+
+
+describe('script lifecycle bindings keep hook cwd independent', () => {
+ it.each([undefined, 'agent'] as const)(
+ 'resolves retained relative hooks in the new script project when switching from %s',
+ async (executionMode) => {
+ const existing = schedule({ executionMode, targetSessionId: 'owner' });
+ const resolveSessionWorkDir = vi.fn(async () => '/owner-project');
+ // MCP may omit the hook; the desktop editor resubmits its unchanged value.
+ for (const hookPatch of [{}, { preRunHook: existing.preRunHook }]) {
+ const result = await stabilizePreRunHookForUpdate(existing, {
+ executionMode: 'script', workingDir: '/script-project', ...hookPatch,
+ }, {
+ resolveSessionWorkDir,
+ stabilizeCommand: async ({ command, workingDir }) => `${command}@${workingDir}`,
+ });
+ expect(result.preRunHook).toEqual({
+ command: 'node scripts/check.mjs@/script-project', timeoutMs: 5_000,
+ });
+ }
+ expect(resolveSessionWorkDir).not.toHaveBeenCalled();
+ },
+ );
+
+ it('resolves create and update hooks in the script project', async () => {
+ const deps = { resolveSessionWorkDir: vi.fn(async () => '/owner'),
+ stabilizeCommand: vi.fn(async ({ command, workingDir }) => `${command}@${workingDir}`) };
+ const bound = schedule({ executionMode: 'script', targetSessionId: 'owner' });
+ const created = await stabilizePreRunHookForCreate(bound, deps);
+ expect(created.preRunHook?.command).toBe('node scripts/check.mjs@/project-a');
+ const unchanged = await stabilizePreRunHookForUpdate(bound, { workingDir: '/project-b' }, deps);
+ expect(unchanged.preRunHook?.command).toBe('node scripts/check.mjs@/project-a');
+ const changed = await stabilizePreRunHookForUpdate(bound, { workingDir: '/project-b',
+ preRunHook: { command: 'node new.mjs' } }, deps);
+ expect(changed.preRunHook?.command).toBe('node new.mjs@/project-b');
+ expect(deps.resolveSessionWorkDir).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/maker-scheduler/src/__tests__/scheduler.test.ts b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
index 5af1470310..9960331617 100644
--- a/packages/maker-scheduler/src/__tests__/scheduler.test.ts
+++ b/packages/maker-scheduler/src/__tests__/scheduler.test.ts
@@ -515,12 +515,16 @@ describe('Scheduler', () => {
});
await expect(h.scheduler.update(script.id, { useWorktree: true })).rejects.toThrow(
- 'does not support worktrees or bound sessions',
+ 'does not support worktrees or persistent sessions',
);
await expect(h.scheduler.update(script.id, { silentWhenIdle: true })).rejects.toThrow(
'does not support silentWhenIdle',
);
+ const bound = await h.scheduler.update(script.id, { targetSessionId: 'owner-session' });
+ expect(bound.targetSessionId).toBe('owner-session');
+ expect(bound.executionMode).toBe('script');
+
// 堵 update 逃逸:script 任务(prompt 合法为空)只切 executionMode='agent'
// 不带 prompt → 会落库空提示词的 agent 任务,必须拒;带 prompt 一起切才放行。
await expect(
diff --git a/packages/maker-scheduler/src/engine/scheduler.ts b/packages/maker-scheduler/src/engine/scheduler.ts
index c5b2d1df2f..b4da6f31af 100644
--- a/packages/maker-scheduler/src/engine/scheduler.ts
+++ b/packages/maker-scheduler/src/engine/scheduler.ts
@@ -80,8 +80,8 @@ function validateScheduleExecutionShape(
if (schedule.workspaceKind !== 'project' || !schedule.workingDir?.trim()) {
throw new Error('script execution requires a local project workspace');
}
- if (schedule.useWorktree || schedule.targetSessionId || schedule.persistentSession) {
- throw new Error('script execution does not support worktrees or bound sessions');
+ if (schedule.useWorktree || schedule.persistentSession) {
+ throw new Error('script execution does not support worktrees or persistent sessions');
}
// silentWhenIdle 的静默协议依赖 agent 在会话里调 silence 工具,script 任务无
// agent、该语义整体不适用;显式传入按不支持字段拒绝(UI 提交层恒为 false)。
diff --git a/packages/maker-scheduler/src/pre-run-hook-update.ts b/packages/maker-scheduler/src/pre-run-hook-update.ts
index 9c54b08540..2a77eca5ab 100644
--- a/packages/maker-scheduler/src/pre-run-hook-update.ts
+++ b/packages/maker-scheduler/src/pre-run-hook-update.ts
@@ -38,7 +38,7 @@ export async function stabilizePreRunHookForCreate(
): Promise<CreateScheduleInput> {
if (!input.preRunHook?.command?.trim()) return input;
const workingDir = await resolveEffectiveWorkingDir(
- input.targetSessionId,
+ input.executionMode === 'script' ? undefined : input.targetSessionId,
input.workingDir,
deps.resolveSessionWorkDir,
);
@@ -55,7 +55,9 @@ export async function stabilizePreRunHookForCreate(
*
* An unchanged relative command belongs to the pre-update workdir, so it is
* resolved there before a session/workdir rebind. A newly supplied command is
- * resolved against the post-update workdir instead.
+ * resolved against the post-update workdir instead. Switching from agent to
+ * script also resolves relative hooks in the new script project: the owner
+ * binding no longer supplies the execution directory in that mode.
*/
export async function stabilizePreRunHookForUpdate(
existing: Schedule,
@@ -76,14 +78,15 @@ export async function stabilizePreRunHookForUpdate(
: existing.targetSessionId;
const nextWorkingDir = hasOwn(patch, 'workingDir') ? patch.workingDir : existing.workingDir;
const commandChanged = patchHasHook && nextHook.command !== existing.preRunHook?.command;
- const workingDir = commandChanged
+ const switchingToScript = existing.executionMode !== 'script' && patch.executionMode === 'script';
+ const workingDir = commandChanged || switchingToScript
? await resolveEffectiveWorkingDir(
- nextTargetSessionId,
+ (patch.executionMode ?? existing.executionMode) === 'script' ? undefined : nextTargetSessionId,
nextWorkingDir,
deps.resolveSessionWorkDir,
)
: await resolveEffectiveWorkingDir(
- existing.targetSessionId,
+ existing.executionMode === 'script' ? undefined : existing.targetSessionId,
existing.workingDir,
deps.resolveSessionWorkDir,
);
diff --git a/packages/maker-scheduler/src/types.ts b/packages/maker-scheduler/src/types.ts
index bde624a42a..f75505476b 100644
--- a/packages/maker-scheduler/src/types.ts
+++ b/packages/maker-scheduler/src/types.ts
@@ -241,6 +241,7 @@ export interface Schedule {
workspaceKind: ScheduleWorkspaceKind;
workingDir?: string;
useWorktree: boolean;
+ /** Script mode: lifecycle owner and sole dispatch target; no agent turn is started by the runner. */
targetSessionId?: string;
/**
* 持续会话模式:true → runner 在第一次 fire 成功创建 session 后自动把 sessionId
diff --git a/packages/maker-shared/src/__tests__/scheduleForm.test.ts b/packages/maker-shared/src/__tests__/scheduleForm.test.ts
index 8f1d38f16b..565acfac60 100644
--- a/packages/maker-shared/src/__tests__/scheduleForm.test.ts
+++ b/packages/maker-shared/src/__tests__/scheduleForm.test.ts
@@ -327,7 +327,7 @@ describe('mobile schedule form model', () => {
});
it('pins agent-only fields back to script-safe values when serializing a script draft (codex review 966 second pass)', () => {
- // 表单残留或误操作把 draft 拨到 script 非法组合(worktree/绑定/持续会话/
+ // 表单残留或误操作把 draft 拨到 script 非法组合(worktree/持续会话/
// dialogue 工作区/静默)时,序列化层必须钉回合法值——否则引擎合并态校验
// 直接拒绝整个 patch,一个可见控件就能让保存失败。
const draft = {
@@ -347,7 +347,7 @@ describe('mobile schedule form model', () => {
persistentSession: false,
silentWhenIdle: false,
});
- expect(input.targetSessionId).toBeUndefined();
+ expect(input.targetSessionId).toBe('sess-oops');
});
it('still requires a prompt for a regular agent-mode schedule', () => {
diff --git a/packages/maker-shared/src/scheduleForm.ts b/packages/maker-shared/src/scheduleForm.ts
index 112c891a34..4a200b35b8 100644
--- a/packages/maker-shared/src/scheduleForm.ts
+++ b/packages/maker-shared/src/scheduleForm.ts
@@ -414,18 +414,15 @@ export function buildMobileScheduleInput(draft: MobileScheduleDraft): RemoteSche
},
};
if (draft.executionMode === 'script') {
- // 仅运行脚本任务:引擎合并态校验对 script 模式拒绝 worktree/绑定/持续会话/
- // silentWhenIdle 与非 project 工作区——表单残留或误操作的这些 agent-only
- // 字段一律钉回 script 合法值,否则一个可见控件就能让整个保存失败(codex
- // review 发现)。model/effort/fastMode 不带(= 不修改),targetSessionId 为
- // undefined 时 JSON 序列化自然丢 key(= 不修改)。
+ // Script schedules retain their lifecycle owner when edited from mobile.
+ // They still run in their own project cwd without starting an agent turn.
return {
...input,
workspaceKind: 'project',
workingDir: draft.workingDir.trim(),
useWorktree: false,
persistentSession: false,
- targetSessionId: undefined,
+ targetSessionId: targetSessionId || undefined,
silentWhenIdle: false,
};
}