UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

115 lines (114 loc) • 10.8 kB
/** * design/105 — Scheduler 工具壳(CronCreate / CronDelete / CronList + ScheduleWakeup)。模型可调,把未来意图交给注入的 * daemon backend(`env` 实现 {@link SchedulerCapability})。**core 薄壳**:工具只做 ① cron expr 收单判定(引擎唯一的匹配器 `nextCronFireTime`,到点算下一次的也是它) * ② 组装 `intent`(模型面) + `SchedulerContext`(Runner-held,闭包捕获 principal/scope/sessionId) ③ 调 * `env.schedule/cancel/list`。持久化/触发/投回钉住的会话全在 daemon。 * design/136 §2.2(BREAKING 去超集批):`Sleep` 工具已撤除(CC 无此工具;等待抽象=Monitor/后台通知,定时再醒 * =CronCreate delay/at——纯语法糖零缺口)。旧名调用=通用响亮 roster miss(RB-476-A 墓碑已清);daemon 已排的 `label:"sleep"` * delayed intent 照常触发(daemon 只存 prompt+when,零迁移)。 * * [c209-D2] 同名工具消歧(durable 分层激活批 2026-07-16,防后人混淆):**我方 CronCreate = 持久 daemon 形** * (对标上游产品 /schedule 的云端持久语义);**上游同名工具是会话级易失体**({cron: 5字段串, prompt, * recurring: bool, durable: 死字段}——会话结束即消失);壳仓 vendored 的 ScheduleCronTool 是上游原生实现, * 与本工具无关。两形调用在此汇流:上游生态 skill 平移过来的 CC 形调用(`cron` 字符串,`durable` 缺省 false) * 落 **session 生存期**(会话终结随会话 reap,绝不落成永生任务);我方 `schedule` 对象形保持持久语义零回归, * `durable: true` 显式亦持久。session 生存期需要 backend 能力位(supportsSessionLifetime),缺失时诚实拒绝 * 引导 `durable: true`——绝不静默升级语义。 * * 挂载:prepare-task 在 `hasScheduler(executionEnv)` 时调 {@link createSchedulerTools}(需 Runner-held 上下文,故不在 * `createHandsToolkit` —— 与 present_plan/AskUserQuestion 同:这些工具都在 prepare-task 单独挂,那里有 spec.principal)。 */ import type { AgentTool, ExecutionEnv, Result } from "../internal/harness-types.js"; import { SchedulerError, type SchedulerReading, type SchedulerContext, type ScheduledTaskId, type ScheduledTaskSummary } from "../core/scheduler.js"; import { type EngineNotice } from "../core/engine-notice.js"; export declare const SCHEDULE_WAKEUP_TOOL_NAME = "ScheduleWakeup"; /** CronCreate-based autonomous-loop 哨兵(CC `Ldt`)。loop runtime(部署侧)在 fire 时解析回 autonomous-loop 指令。 */ export declare const AUTONOMOUS_LOOP_SENTINEL = "<<autonomous-loop>>"; /** ScheduleWakeup(dynamic-pacing)哨兵(CC `ePe`)——ScheduleWakeup 一律用 `-dynamic` 变体。 */ export declare const AUTONOMOUS_LOOP_DYNAMIC_SENTINEL = "<<autonomous-loop-dynamic>>"; /** wakeup intent 的保留 label:老 backend(list 不回 mode)时 stop 过滤的兜底键;店的迁移据它认出判不清车道的行。 */ export declare const WAKEUP_LABEL = "loop-wakeup"; /** Runner-held 上下文 + run-stop 出口,工具工厂闭包捕获(模型触不到)。 */ export interface SchedulerToolContext { /** 任务的人(`TaskSpec.principal`),原样交给宿主 capability;缺 `isolationScope` 时也是 durable lane 的主人。 */ principal?: string; /** 任务的 isolation scope(`TaskSpec.isolationScope`):在场时是 durable lane 的主人(同一人的另一 scope 看不见这条 job)。 */ isolationScope?: string; /** The session the run belongs to: the owner of the session lane (`session:<sessionId>`). Absent = the run has no session lane — the * readers read the durable lane alone, and the two tools that schedule do not mount. */ sessionId?: string; taskConfig?: unknown; /** The user's zone as the engine judged it ({@link SchedulerContext.timeZone}); rides every context handed to the backend. */ timeZone?: string; /** `ctx.requestStopAfterTurn`(干净结束本 run 的 runner 原语出口)。design/136 §2.2:Sleep 撤除后本槽位 * 保留(human-suspend saga 等共用同一 runner 原语;prepare-task 仍注入)——当前 scheduler 三件不消费。 */ requestStopAfterTurn?: () => void; } /** The two lanes, the closed set a scheduler key starts with. */ export type LaneName = "session" | "durable"; /** The one spelling of a scheduler key: the lane's name, `:`, the owner. */ export declare function laneKeyOf(lane: LaneName, owner: string): string; /** Whether `scope` is a key of `lane`: the lane's name, `:` and at least one more character. */ export declare function isLaneKey(lane: LaneName, scope: unknown): boolean; /** The lanes of one run, each as the context the scheduler backend isolates by. Which lane an entry is on is {@link laneOfIntent}'s answer. */ export interface SchedulerLanes { /** The entries bound to this session — a session-lifetime job, or a session wakeup (it ends with the session only on a backend that vouches for * the session lifetime) — keyed `session:<session id>`. Absent for a run with no session. */ readonly session?: SchedulerContext; /** Every other entry of the run's isolation scope, keyed `durable:<isolation scope>` (else `durable:default`): visible from every session of that scope. */ readonly durable: SchedulerContext; } /** The lanes of the run whose factory context is `ctx`: the session lane keyed by `ctx.sessionId` when it has one, the durable lane by the * isolation scope (else `default`). Derive `ctx` from a verified session / run — see the note above. A lane whose key does not come out * of its lane's form (an empty or non-string session id) is refused. */ export declare function schedulerLanesOf(ctx: SchedulerToolContext): SchedulerLanes; /** The lane an intent is filed on: the session lane for a job that ends with its session (`lifetime: "session"`) or a session wakeup * (`mode: "session-wakeup"`), the durable lane for every other. Read off those two members only, never the label (a label is the * caller's word: CronCreate may write the wakeup's label too). Scheduling picks a lane with it, and the store's move * (`migrateSchedulerStore`) reads a stored row's lane with it. */ export declare function laneOfIntent(intent: { readonly lifetime?: unknown; readonly mode?: unknown; }): LaneName; /** * Every entry of both lanes: the session lane's rows, then the durable lane's rows the first did not already list (a backend that does * not filter by scope answers both lanes with the same rows; one id prints once). A lane that fails fails the whole read with that lane's * own error — a half table would let a reader take "none" for a fact. An environment with no scheduler seam answers `unsupported`, which an * empty list (`ok` with `[]`) is not. A lane without a key is refused (`config.invalid_argument`) before the backend is asked. */ export declare function listScheduled(env: ExecutionEnv, lanes: SchedulerLanes): Promise<Result<ScheduledTaskSummary[], SchedulerError>>; /** * Cancel one entry by id, on the lane that holds it (a run with the durable lane alone asks that lane, with no listing). A bare id no longer * names its lane, so the holder is found by listing the lanes in order until one holds it (both belong to this run, so reading both widens nothing): a backend whose `cancel` answers ok for an id it does not hold would let a * first-lane try swallow the call while the real job on the other lane stays live under a receipt that says it is gone. Only when the * listing is unavailable, or the id is not in the snapshot, does it fall back to trying each lane in turn — and then only a `not_found` * is a reason to ask the next lane. The result is the backend's own: `not_found` for an id neither lane holds, `unsupported` for an * environment with no scheduler seam. A lane without a key is refused (`config.invalid_argument`) before the backend is asked. */ export declare function cancelScheduled(env: ExecutionEnv, lanes: SchedulerLanes, id: ScheduledTaskId): Promise<Result<void, SchedulerError>>; /** CronCreate's intake judge, asked now: {@link cronIntakeRefusal}, the matcher the firing side computes with. Absent a judged * zone UTC stands in — whether an expression ever fires does not depend on the zone, and the instant is not used. */ export declare function cronScheduleError(expr: string, timeZone?: string): string | null; /** `text` when it has at most `limit` units, else its first `limit - 1` units and `…` — a cluster is never cut in the middle, and a cut * text is `limit` units long, the mark one of them (a `limit` of at least 1). Exported for the clipper registry's invariant, not from the root. */ export declare function cutToUnits(text: string, limit: number): string; /** * cron → 人话(CC utils/cron.ts cronToHuman:218-308 类比,收窄到常见形态):"star/N * * * *"→"every N minutes"、 * "M star/N * * *"→"every N hours"、`M H * * *`→"daily at H:MM"、`M H * * D`→"weekly on <day> at H:MM"、 * `M H * * 1-5`→"weekdays at H:MM";其余原样返回(调用方以 `human !== expr` 判断是否可译);收 backend 的 `cron <expr>` 显示串(见 {@link cronExprFromSummary})。 * 只译引擎文法收的表达式({@link isValidCronExpr}):文法拒的串(分钟 61、小时 25、星期 8)原样返回,不给假人话。 */ export declare function cronToHuman(expr: string): string; /** * Tells the operator, once per declared value per notice sink, that the env's scheduler backend offers the seam but does not declare its * store holds lane keys — so {@link createSchedulerTools} mounts nothing on it (`config.scheduler_store_unmoved`). Every other reading: * silence. `scheduler` is the leg's one reading of the declaration ({@link readSchedulerDeclaration}). */ export declare function announceSchedulerStoreUnmoved(scheduler: SchedulerReading, onNotice: ((notice: EngineNotice) => void) | undefined): void; /** * 构建 scheduler 工具(仅当 `env` 暴露 {@link SchedulerCapability}、`supported:true` 且店声明 `scopeKeys: "lane"`;否则返回 `[]`,INERT):有会话 = CronCreate / * CronDelete / CronList / ScheduleWakeup 四只,无会话 = CronDelete / CronList 两只(只读写 durable lane)。`scheduler` = 一条腿对声明的那一次读数 * ({@link readSchedulerDeclaration};缺 = 这里读一次):挂载与工具执行时读的能力位都出自它;CronList / CronDelete 经 {@link listScheduled} / * {@link cancelScheduled},那两只读口每次调用再读一次声明(声明在实例寿命内不变)。 */ export declare function createSchedulerTools(env: ExecutionEnv, ctx: SchedulerToolContext, scheduler?: SchedulerReading): AgentTool[];