Skip to content

Commit 055a2a9

Browse files
authored
fix(core): fail schedule creation when a code check throws and pause invalid checks immediately (#60349)
1 parent 8609cc5 commit 055a2a9

6 files changed

Lines changed: 75 additions & 14 deletions

File tree

‎packages/core/src/plugin/command/schedule.txt‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ Request: $ARGUMENTS
44

55
Use the schedule tools in the `opencode` namespace. They only see this session's schedules.
66

7-
- To schedule something, call `schedule_create`. Choose `when` (`{ in: "20 minutes" }`, `{ at: "2026-10-27T09:00" }`, `{ every: "1 hour" }` or `{ cron: "0 9 * * 1-5" }`, optional with `until` which defaults to every 30s). Add `until` (wake once then stop, 24h default timeout) or `if` (gate each recurring slot with no model call) using either `{ run: "..." }` for a shell check or `{ code: "..." }` for a Code Mode JavaScript check calling `tools.<path>(...)` statically and returning a boolean or `{ wake, state?, message? }`. To stop a repeating schedule, add `ends`: `{ after: "8 hours" }`, `{ at: "..." }` or `{ times: 3 }`. Write `prompt` as the instruction you will receive when it wakes, with enough context to act on it without this conversation.
7+
- To schedule something, call `schedule_create`. Choose `when` (`{ in: "20 minutes" }`, `{ at: "2026-10-27T09:00" }`, `{ every: "1 hour" }` or `{ cron: "0 9 * * 1-5" }`, optional with `until` which defaults to every 30s). Add `until` (wake once then stop, 24h default timeout; matches immediately if already true) or `if` (gate each recurring slot with no model call; baselines `state` at creation without waking) using either `{ run: "..." }` for a shell check or `{ code: "..." }` for a Code Mode JavaScript check calling `tools.<path>(...)` statically (no `fetch`, 30s / 20 calls / 32 KB caps) and returning a boolean or `{ wake, state?, message? }`. Code checks run once at creation with `state = null` and fail `schedule_create` if they throw. To stop a repeating schedule, add `ends`: `{ after: "8 hours" }`, `{ at: "..." }` or `{ times: 3 }`. Write `prompt` as the instruction you will receive when it wakes, with enough context to act on it without this conversation.
88
- To pause, resume or delete one, find its id with `schedule_list`, then call `schedule_pause`, `schedule_resume` or `schedule_delete`.
99
- If the request is empty, call `schedule_list` and show this session's schedules: name, when, status and next run.
1010

‎packages/core/src/schedule.ts‎

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -294,7 +294,7 @@ const layer = Layer.effect(
294294

295295
if (!outcome.ok) {
296296
const strikes = row.failures + 1
297-
if (strikes < MAX_CHECK_FAILURES) {
297+
if (!outcome.invalid && strikes < MAX_CHECK_FAILURES) {
298298
yield* update(row, {
299299
failures: strikes,
300300
last_outcome: "failed",
@@ -304,13 +304,16 @@ const layer = Layer.effect(
304304
return
305305
}
306306
const run = row.run_count + 1
307+
const note = outcome.invalid
308+
? `[Schedule paused after invalid check: ${outcome.error}]`
309+
: `[Schedule paused after ${strikes} failed checks: ${outcome.error}]`
307310
const id = yield* admitWake(
308311
row,
309312
session.id,
310313
run,
311314
due,
312315
late,
313-
`${row.action.prompt}\n\n[Schedule paused after ${strikes} failed checks: ${outcome.error}]`,
316+
`${row.action.prompt}\n\n${note}`,
314317
{ error: outcome.error, failures: strikes },
315318
)
316319
yield* db
@@ -636,7 +639,7 @@ const layer = Layer.effect(
636639
check === undefined
637640
? { matched: false as const, state: null as Schema.Json, checks: 0 }
638641
: yield* Effect.gen(function* () {
639-
yield* ScheduleCheck.authorize(session, input.name, check).pipe(
642+
yield* ScheduleCheck.authorize(session, input.name, when, check).pipe(
640643
instances.provide(session),
641644
Effect.mapError((error) => (typeof error === "string" ? new InvalidError({ reason: error }) : error)),
642645
Effect.catchTag("FileSystem.DirectoryNotFoundError", () =>
@@ -647,7 +650,7 @@ const layer = Layer.effect(
647650
)
648651
const shouldSeed =
649652
check.mode === "until" ||
650-
(check.condition.type === "code" && when.type === "every") ||
653+
check.condition.type === "code" ||
651654
(check.condition.type === "shell" && check.condition.changes === true)
652655
if (!shouldSeed) return { matched: false as const, state: null as Schema.Json, checks: 0 }
653656
const init = yield* ScheduleCheck.evaluate(session, check, null, {
@@ -663,7 +666,8 @@ const layer = Layer.effect(
663666
),
664667
)
665668
if (!init.ok) {
666-
if (init.invalid) return yield* new InvalidError({ reason: init.error })
669+
// A code check that throws or fails at creation is broken (e.g. wrong MCP response field); fail right away.
670+
if (init.invalid || check.condition.type === "code") return yield* new InvalidError({ reason: init.error })
667671
return { matched: false as const, state: null as Schema.Json, checks: 0 }
668672
}
669673
if (check.mode === "until" && init.wake)

‎packages/core/src/schedule/check.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -117,15 +117,16 @@ export function describe(condition: ScheduleSchema.Condition): string {
117117
export const authorize = Effect.fnUntraced(function* (
118118
session: SessionSchema.Info,
119119
name: string | undefined,
120+
when: ScheduleSchema.When,
120121
check: ScheduleSchema.StoredCheck,
121122
) {
122123
const plugins = yield* Plugin.Service
123124
yield* plugins.awaitActivation
124125
switch (check.condition.type) {
125126
case "shell":
126-
return yield* authorizeShell(session, name, check.mode, check.condition)
127+
return yield* authorizeShell(session, name, when, check.mode, check.condition)
127128
case "code":
128-
return yield* authorizeCode(session, name, check.mode, check.condition)
129+
return yield* authorizeCode(session, name, when, check.mode, check.condition)
129130
}
130131
})
131132

@@ -182,6 +183,7 @@ const resolveCodeTools = Effect.fnUntraced(function* (paths: ReadonlyArray<strin
182183
const authorizeCode = Effect.fnUntraced(function* (
183184
session: SessionSchema.Info,
184185
name: string | undefined,
186+
when: ScheduleSchema.When,
185187
mode: ScheduleSchema.CheckMode,
186188
condition: ScheduleSchema.CodeCondition,
187189
) {
@@ -206,7 +208,7 @@ const authorizeCode = Effect.fnUntraced(function* (
206208
yield* permission.assert({
207209
action: "execute",
208210
resources: ["*"],
209-
metadata: { schedule: name, mode, code: condition.code, tools: [] },
211+
metadata: { schedule: name, mode, when, unattended: true, code: condition.code, tools: [] },
210212
sessionID: session.id,
211213
agent: agent.id,
212214
})
@@ -233,7 +235,7 @@ const authorizeCode = Effect.fnUntraced(function* (
233235
action,
234236
resources: ["*"],
235237
// No `save`: "always" would save a project-wide allow, while scheduled ticks run via Unattended.
236-
metadata: { schedule: name, mode, code: condition.code, tools: [...paths] },
238+
metadata: { schedule: name, mode, when, unattended: true, code: condition.code, tools: [...paths] },
237239
sessionID: session.id,
238240
agent: agent.id,
239241
}),
@@ -388,13 +390,16 @@ const assertShellPermissions = Effect.fnUntraced(function* (
388390
const authorizeShell = Effect.fnUntraced(function* (
389391
session: SessionSchema.Info,
390392
name: string | undefined,
393+
when: ScheduleSchema.When,
391394
mode: ScheduleSchema.CheckMode,
392395
condition: ScheduleSchema.ShellCondition,
393396
) {
394397
const scanned = yield* scanShell(condition.run)
395398
yield* assertShellPermissions(session, scanned, {
396399
schedule: name,
397400
mode,
401+
when,
402+
unattended: true,
398403
run: condition.run,
399404
})
400405
})

‎packages/core/test/schedule.test.ts‎

Lines changed: 48 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1358,7 +1358,13 @@ describe("Schedule", () => {
13581358
expect(asked).toHaveLength(1)
13591359
expect(asked[0]).toMatchObject({
13601360
action: "slack_read_thread",
1361-
metadata: { schedule: "thread", mode: "if", tools: ["slack.read_thread"] },
1361+
metadata: {
1362+
schedule: "thread",
1363+
mode: "if",
1364+
when: { type: "every", every: "1 minute" },
1365+
unattended: true,
1366+
tools: ["slack.read_thread"],
1367+
},
13621368
})
13631369
expect(asked[0]?.save).toBeUndefined()
13641370

@@ -1419,5 +1425,46 @@ describe("Schedule", () => {
14191425
expect(yield* bad("return true")).toMatchObject({ _tag: "Permission.BlockedError" })
14201426
}),
14211427
)
1428+
1429+
it.effect("fails schedule_create when a t=0 code run throws, and pauses on strike 1 when a later tick returns an invalid shape", () =>
1430+
Effect.gen(function* () {
1431+
const schedules = yield* setup()
1432+
const thrown = yield* Effect.flip(
1433+
schedules.create({
1434+
sessionID,
1435+
when: { type: "cron", cron: "0 9 * * *" },
1436+
if: {
1437+
type: "code",
1438+
code: `const t = await tools.slack.read_thread({}); return t.nonexistent.length > 0`,
1439+
},
1440+
action: { type: "prompt", prompt: "Morning check." },
1441+
}),
1442+
)
1443+
expect(thrown).toMatchObject({ _tag: "Schedule.InvalidError" })
1444+
1445+
// First run (state === null) returns valid { wake: false, state: { ok: true } };
1446+
// first scheduled tick (state !== null) returns an invalid string, pausing immediately on strike 1.
1447+
const schedule = yield* schedules.create({
1448+
sessionID,
1449+
when: { type: "every", every: "1 minute" },
1450+
if: {
1451+
type: "code",
1452+
code: `if (state === null) return { wake: false, state: { ok: true } }; return "not-a-check-result"`,
1453+
},
1454+
action: { type: "prompt", prompt: "Watch." },
1455+
})
1456+
yield* TestClock.adjust("1 minute")
1457+
yield* schedules.tick
1458+
expect(yield* schedules.get(schedule.id)).toMatchObject({
1459+
status: "paused",
1460+
lastOutcome: "failed",
1461+
runCount: 1,
1462+
})
1463+
const { db } = yield* Database.Service
1464+
expect(yield* SessionInbox.find(db, messageID(schedule, 1))).toMatchObject({
1465+
payload: { text: expect.stringContaining("[Schedule paused after invalid check:") },
1466+
})
1467+
}),
1468+
)
14221469
})
14231470
})

‎packages/protocol/openapi.json‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎packages/schema/src/schedule.ts‎

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -188,8 +188,13 @@ export const ShellConditionInput = Schema.Struct({
188188

189189
export const CodeConditionInput = Schema.Struct({
190190
code: Schema.String.check(Schema.isMinLength(1)).annotate({
191-
description:
192-
"Code Mode JavaScript program. Static tools.<path>(...) calls are authorized at creation; gets state, now and runs, and returns a boolean or { wake, state?, message? }.",
191+
description: [
192+
"Code Mode JavaScript check (no fetch; 30s, 20 tool calls, 32 KB output cap).",
193+
'Call tools statically as tools.<ns>.<tool>(...) or tools["ns-name"].tool(...); each is authorized once at creation to run unattended.',
194+
"Runs once at creation with state = null (if baselines state without waking; until matches immediately if true), with globals state, now (epoch ms) and runs.",
195+
"Return a boolean or { wake, state?, message? } (message is appended to prompt on wake), e.g.:",
196+
'const t = await tools.slack.read_thread({ id }); return { wake: state !== null && t.count > state.count, state: { count: t.count }, message: "New reply" }',
197+
].join(" "),
193198
}),
194199
}).annotate({ identifier: "Schedule.CodeConditionInput" })
195200

0 commit comments

Comments
 (0)