@lukstei/dsh-schedule-script 0.0.0-stage → 0.2.2-rc.5.3
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/LICENSE +21 -0
- package/README.md +203 -2
- package/cordis.patch.yml +4 -0
- package/dist/client.js +848 -0
- package/dist/index.js +826 -0
- package/package.json +103 -3
- package/src/client.tsx +717 -0
- package/src/executor.ts +101 -0
- package/src/fold.ts +154 -0
- package/src/index.ts +616 -0
- package/src/parser.ts +138 -0
- package/src/runner-cli.ts +81 -0
- package/src/skill.ts +120 -0
- package/src/styles.ts +333 -0
- package/src/types.ts +132 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,616 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
2
|
+
import type { Context } from "@deepseek-ai/cordis";
|
|
3
|
+
import type { Agent } from "@deepseek-ai/dsh-agent";
|
|
4
|
+
import type { CommandId } from "@deepseek-ai/dsh-commands";
|
|
5
|
+
import type { Session } from "@deepseek-ai/dsh-session";
|
|
6
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
7
|
+
import { executeScript } from "./executor.ts";
|
|
8
|
+
import {
|
|
9
|
+
foldScheduleScriptEvent,
|
|
10
|
+
initialScheduleScriptSummary,
|
|
11
|
+
toScheduleScriptRecord,
|
|
12
|
+
} from "./fold.ts";
|
|
13
|
+
import {
|
|
14
|
+
formatRemainingBatch,
|
|
15
|
+
formatScriptPrompt,
|
|
16
|
+
formatWakingPrompt,
|
|
17
|
+
parseReminderBatch,
|
|
18
|
+
parseScriptPrompt,
|
|
19
|
+
} from "./parser.ts";
|
|
20
|
+
import {
|
|
21
|
+
SCHEDULE_SCRIPT_SKILL_CONTENT,
|
|
22
|
+
SCHEDULE_SCRIPT_SKILL_DESCRIPTION,
|
|
23
|
+
SCHEDULE_SCRIPT_SKILL_NAME,
|
|
24
|
+
} from "./skill.ts";
|
|
25
|
+
import {
|
|
26
|
+
SCHEDULE_SCRIPT_EVENT_NAME,
|
|
27
|
+
type ScheduleScriptEventPayload,
|
|
28
|
+
type ScheduleScriptPromptPayload,
|
|
29
|
+
scheduleScriptSummarySchema,
|
|
30
|
+
} from "./types.ts";
|
|
31
|
+
|
|
32
|
+
export * from "./executor.ts";
|
|
33
|
+
export * from "./fold.ts";
|
|
34
|
+
export { formatScriptPrompt } from "./parser.ts";
|
|
35
|
+
export * from "./skill.ts";
|
|
36
|
+
export * from "./types.ts";
|
|
37
|
+
|
|
38
|
+
export interface ScheduleCatalogEntry {
|
|
39
|
+
readonly id: string;
|
|
40
|
+
readonly title?: string;
|
|
41
|
+
readonly prompt?: string;
|
|
42
|
+
readonly status?: "active" | "paused" | "ended";
|
|
43
|
+
readonly target?: {
|
|
44
|
+
readonly kind: string;
|
|
45
|
+
readonly sessionId?: string;
|
|
46
|
+
};
|
|
47
|
+
readonly involvedSessionIds?: readonly string[];
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface ScheduleListRequest {
|
|
51
|
+
readonly active?: boolean;
|
|
52
|
+
readonly limit?: number;
|
|
53
|
+
readonly offset?: number;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface ScheduleListResult {
|
|
57
|
+
readonly items: readonly ScheduleCatalogEntry[];
|
|
58
|
+
readonly shown: number;
|
|
59
|
+
readonly total: number;
|
|
60
|
+
readonly limit: number;
|
|
61
|
+
readonly offset: number;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface ScheduleCreateRequest {
|
|
65
|
+
readonly title: string;
|
|
66
|
+
readonly prompt: string;
|
|
67
|
+
readonly timing: { readonly kind: "every"; readonly every_seconds: number };
|
|
68
|
+
readonly target: { readonly kind: "session"; readonly sessionId: string };
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export interface ScheduleEditRequest {
|
|
72
|
+
readonly id: string;
|
|
73
|
+
readonly action: "delete" | "update";
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export interface ScheduleService {
|
|
77
|
+
create: (req: ScheduleCreateRequest) => Promise<unknown>;
|
|
78
|
+
list: (req?: ScheduleListRequest) => Promise<ScheduleListResult>;
|
|
79
|
+
edit: (req: ScheduleEditRequest) => Promise<unknown>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
declare module "@deepseek-ai/cordis" {
|
|
83
|
+
interface Context {
|
|
84
|
+
skills: {
|
|
85
|
+
register: (spec: {
|
|
86
|
+
name: string;
|
|
87
|
+
description: string;
|
|
88
|
+
source: string;
|
|
89
|
+
content: string;
|
|
90
|
+
}) => () => void;
|
|
91
|
+
};
|
|
92
|
+
schedule: ScheduleService;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export const name = "dsh-schedule-script";
|
|
97
|
+
export const inject = [
|
|
98
|
+
"commands",
|
|
99
|
+
"sessionProjections",
|
|
100
|
+
"tools",
|
|
101
|
+
"skills",
|
|
102
|
+
"schedule",
|
|
103
|
+
] as const;
|
|
104
|
+
|
|
105
|
+
export async function apply(ctx: Context): Promise<void> {
|
|
106
|
+
const projectionHandle = await ctx.sessionProjections.register({
|
|
107
|
+
key: "dshScheduleScript",
|
|
108
|
+
stateSchema: scheduleScriptSummarySchema,
|
|
109
|
+
init: () => initialScheduleScriptSummary(),
|
|
110
|
+
apply: (state, event) => foldScheduleScriptEvent(state, event),
|
|
111
|
+
wire: {
|
|
112
|
+
viewSchema: scheduleScriptSummarySchema.nullable(),
|
|
113
|
+
view: toScheduleScriptRecord,
|
|
114
|
+
},
|
|
115
|
+
stateVersion: 1,
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
ctx.effect(() => () => projectionHandle.dispose());
|
|
119
|
+
|
|
120
|
+
function isScheduleScriptActive(session: Session): boolean {
|
|
121
|
+
const summary = projectionHandle.stateOf(session);
|
|
122
|
+
return (
|
|
123
|
+
Boolean(summary.skillInvoked) ||
|
|
124
|
+
summary.totalRuns > 0 ||
|
|
125
|
+
summary.scriptPath !== undefined
|
|
126
|
+
);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function appendScriptEvent(
|
|
130
|
+
session: Session,
|
|
131
|
+
payload: ScheduleScriptEventPayload,
|
|
132
|
+
idSuffix: string,
|
|
133
|
+
): void {
|
|
134
|
+
const commandId = `schedule-script-${idSuffix}` as CommandId;
|
|
135
|
+
session.append("command/run", {
|
|
136
|
+
commandId,
|
|
137
|
+
name: SCHEDULE_SCRIPT_EVENT_NAME,
|
|
138
|
+
args: JSON.stringify(payload),
|
|
139
|
+
source: { kind: "user" },
|
|
140
|
+
});
|
|
141
|
+
session.append("command/done", {
|
|
142
|
+
commandId,
|
|
143
|
+
kind:
|
|
144
|
+
payload.action === "error" && payload.fatal !== false
|
|
145
|
+
? "error"
|
|
146
|
+
: "success",
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// Register embedded skill directly via injected skills service
|
|
151
|
+
ctx.effect(() => {
|
|
152
|
+
const unregister = ctx.skills.register({
|
|
153
|
+
name: SCHEDULE_SCRIPT_SKILL_NAME,
|
|
154
|
+
description: SCHEDULE_SCRIPT_SKILL_DESCRIPTION,
|
|
155
|
+
source: "runtime",
|
|
156
|
+
content: SCHEDULE_SCRIPT_SKILL_CONTENT,
|
|
157
|
+
});
|
|
158
|
+
return () => unregister();
|
|
159
|
+
});
|
|
160
|
+
|
|
161
|
+
ctx.on("tools/post-execute", async (exec, result, next) => {
|
|
162
|
+
const decision = await next();
|
|
163
|
+
if (exec.name === "skill" && exec.agent?.session && !result.isError) {
|
|
164
|
+
try {
|
|
165
|
+
const args =
|
|
166
|
+
typeof exec.arguments === "string"
|
|
167
|
+
? JSON.parse(exec.arguments)
|
|
168
|
+
: exec.arguments;
|
|
169
|
+
if (args?.name === SCHEDULE_SCRIPT_SKILL_NAME) {
|
|
170
|
+
appendScriptEvent(
|
|
171
|
+
exec.agent.session,
|
|
172
|
+
{
|
|
173
|
+
action: "skill",
|
|
174
|
+
timestamp: Date.now(),
|
|
175
|
+
},
|
|
176
|
+
`skill-${Date.now()}`,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
} catch {
|
|
180
|
+
// ignore malformed arguments
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return decision;
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
ctx.effect(() => {
|
|
187
|
+
return () => projectionHandle.dispose();
|
|
188
|
+
});
|
|
189
|
+
|
|
190
|
+
async function activeScriptTasks(sessionId: string) {
|
|
191
|
+
const tasks = new Map<string, ScheduleScriptPromptPayload>();
|
|
192
|
+
let offset = 0;
|
|
193
|
+
let total: number;
|
|
194
|
+
do {
|
|
195
|
+
const page = await ctx.schedule.list({ active: true, offset });
|
|
196
|
+
for (const item of page.items) {
|
|
197
|
+
if (
|
|
198
|
+
item.target !== undefined &&
|
|
199
|
+
item.target.kind === "session" &&
|
|
200
|
+
item.target.sessionId === sessionId &&
|
|
201
|
+
item.prompt !== undefined
|
|
202
|
+
) {
|
|
203
|
+
const payload = parseScriptPrompt(item.prompt);
|
|
204
|
+
if (payload !== null) tasks.set(item.id, payload);
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
offset = page.offset + page.limit;
|
|
208
|
+
total = page.total;
|
|
209
|
+
} while (offset < total);
|
|
210
|
+
return tasks;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function verifyBatch(
|
|
214
|
+
batch: NonNullable<ReturnType<typeof parseReminderBatch>>,
|
|
215
|
+
tasks: Map<string, ScheduleScriptPromptPayload>,
|
|
216
|
+
) {
|
|
217
|
+
const remaining = [...batch.remainingReminders];
|
|
218
|
+
const jobs = new Map<string, ScheduleScriptPromptPayload>();
|
|
219
|
+
for (const job of batch.scripts) {
|
|
220
|
+
const payload = tasks.get(job.scheduleId);
|
|
221
|
+
if (payload === undefined || !isDeepStrictEqual(payload, job.payload)) {
|
|
222
|
+
remaining.push(job.reminder);
|
|
223
|
+
} else {
|
|
224
|
+
jobs.set(job.scheduleId, payload);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
return { jobs, remaining };
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
async function deleteTerminalSchedule(session: Session, scheduleId: string) {
|
|
231
|
+
let error: string | undefined;
|
|
232
|
+
try {
|
|
233
|
+
await ctx.schedule.edit({ id: scheduleId, action: "delete" });
|
|
234
|
+
} catch (failure: unknown) {
|
|
235
|
+
error = `Failed to delete schedule ${scheduleId}: ${failure instanceof Error ? failure.message : String(failure)}`;
|
|
236
|
+
}
|
|
237
|
+
appendScriptEvent(
|
|
238
|
+
session,
|
|
239
|
+
{
|
|
240
|
+
action: "cleanup",
|
|
241
|
+
timestamp: Date.now(),
|
|
242
|
+
...(error !== undefined ? { error } : {}),
|
|
243
|
+
},
|
|
244
|
+
`cleanup-${Date.now()}`,
|
|
245
|
+
);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function runVerifiedJob(
|
|
249
|
+
session: Session,
|
|
250
|
+
scheduleId: string,
|
|
251
|
+
payload: ScheduleScriptPromptPayload,
|
|
252
|
+
signal: AbortSignal,
|
|
253
|
+
): Promise<string | undefined> {
|
|
254
|
+
const summary = projectionHandle.stateOf(session);
|
|
255
|
+
const ownsState =
|
|
256
|
+
summary.scheduleId === undefined
|
|
257
|
+
? summary.scriptPath === payload.scriptPath
|
|
258
|
+
: summary.scheduleId === scheduleId;
|
|
259
|
+
if (
|
|
260
|
+
ownsState &&
|
|
261
|
+
(summary.scriptStatus === "stopped" || summary.scriptStatus === "error")
|
|
262
|
+
) {
|
|
263
|
+
await deleteTerminalSchedule(session, scheduleId);
|
|
264
|
+
return;
|
|
265
|
+
}
|
|
266
|
+
const iteration = summary.totalRuns + 1;
|
|
267
|
+
const startTime = Date.now();
|
|
268
|
+
let prompt: string | undefined;
|
|
269
|
+
let stopReason: string | undefined;
|
|
270
|
+
try {
|
|
271
|
+
const result = await executeScript(
|
|
272
|
+
payload.scriptPath,
|
|
273
|
+
{
|
|
274
|
+
state:
|
|
275
|
+
ownsState && summary.state !== undefined
|
|
276
|
+
? summary.state
|
|
277
|
+
: payload.state,
|
|
278
|
+
sessionId: session.id,
|
|
279
|
+
},
|
|
280
|
+
payload.timeoutMs === undefined ? 30000 : payload.timeoutMs,
|
|
281
|
+
session.header.cwd,
|
|
282
|
+
signal,
|
|
283
|
+
);
|
|
284
|
+
appendScriptEvent(
|
|
285
|
+
session,
|
|
286
|
+
{
|
|
287
|
+
action: "iteration",
|
|
288
|
+
scheduleId,
|
|
289
|
+
scriptPath: payload.scriptPath,
|
|
290
|
+
iteration,
|
|
291
|
+
state: result.state,
|
|
292
|
+
durationMs: Date.now() - startTime,
|
|
293
|
+
timestamp: startTime,
|
|
294
|
+
prompt: result.prompt,
|
|
295
|
+
error: result.error,
|
|
296
|
+
},
|
|
297
|
+
`run-${iteration}`,
|
|
298
|
+
);
|
|
299
|
+
if (result.prompt)
|
|
300
|
+
prompt = `[Scheduled Task: ${payload.scriptPath}]\n${result.prompt}`;
|
|
301
|
+
if (result.stop) stopReason = "script_completed";
|
|
302
|
+
} catch (error: unknown) {
|
|
303
|
+
signal.throwIfAborted();
|
|
304
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
305
|
+
appendScriptEvent(
|
|
306
|
+
session,
|
|
307
|
+
{
|
|
308
|
+
action: "error",
|
|
309
|
+
scheduleId,
|
|
310
|
+
scriptPath: payload.scriptPath,
|
|
311
|
+
iteration,
|
|
312
|
+
error: message,
|
|
313
|
+
timestamp: Date.now(),
|
|
314
|
+
fatal: true,
|
|
315
|
+
},
|
|
316
|
+
`err-${iteration}`,
|
|
317
|
+
);
|
|
318
|
+
stopReason = `critical_error: ${message}`;
|
|
319
|
+
}
|
|
320
|
+
if (stopReason !== undefined) {
|
|
321
|
+
appendScriptEvent(
|
|
322
|
+
session,
|
|
323
|
+
{
|
|
324
|
+
action: "stop",
|
|
325
|
+
scheduleId,
|
|
326
|
+
reason: stopReason,
|
|
327
|
+
timestamp: Date.now(),
|
|
328
|
+
},
|
|
329
|
+
`stop-${iteration}`,
|
|
330
|
+
);
|
|
331
|
+
await deleteTerminalSchedule(session, scheduleId);
|
|
332
|
+
}
|
|
333
|
+
return prompt;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
ctx.on("agent/pre-step", async ({ agent, messages, signal }, next) => {
|
|
337
|
+
const targetIndex = messages.findIndex(
|
|
338
|
+
(m) =>
|
|
339
|
+
m.content.length > 0 &&
|
|
340
|
+
m.content[0].type === "text" &&
|
|
341
|
+
m.content[0].text.startsWith("[SCHEDULE REMINDER BATCH]"),
|
|
342
|
+
);
|
|
343
|
+
if (targetIndex === -1) return next();
|
|
344
|
+
const first = messages[targetIndex].content[0];
|
|
345
|
+
if (first.type !== "text") return next();
|
|
346
|
+
const batch = parseReminderBatch(first.text);
|
|
347
|
+
if (batch === null) return next();
|
|
348
|
+
const tasks = await activeScriptTasks(agent.session.id);
|
|
349
|
+
const { jobs, remaining } = verifyBatch(batch, tasks);
|
|
350
|
+
if (jobs.size === 0) return next();
|
|
351
|
+
const prompts: string[] = [];
|
|
352
|
+
if (tasks.size > 1) {
|
|
353
|
+
prompts.push(
|
|
354
|
+
"Multiple active script schedules target this session. Pause or delete all but one before scripts can run.",
|
|
355
|
+
);
|
|
356
|
+
} else {
|
|
357
|
+
for (const [scheduleId, payload] of jobs) {
|
|
358
|
+
const prompt = await runVerifiedJob(
|
|
359
|
+
agent.session,
|
|
360
|
+
scheduleId,
|
|
361
|
+
payload,
|
|
362
|
+
signal,
|
|
363
|
+
);
|
|
364
|
+
if (prompt !== undefined) prompts.push(prompt);
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
const remainingText =
|
|
368
|
+
remaining.length > 0
|
|
369
|
+
? formatRemainingBatch(remaining, first.text)
|
|
370
|
+
: undefined;
|
|
371
|
+
const text = formatWakingPrompt(prompts, remainingText);
|
|
372
|
+
if (text) {
|
|
373
|
+
messages[targetIndex] = {
|
|
374
|
+
...messages[targetIndex],
|
|
375
|
+
content: [
|
|
376
|
+
{ type: "text", text },
|
|
377
|
+
...messages[targetIndex].content.slice(1),
|
|
378
|
+
],
|
|
379
|
+
};
|
|
380
|
+
return next();
|
|
381
|
+
}
|
|
382
|
+
if (messages.length > 1) {
|
|
383
|
+
messages.splice(targetIndex, 1);
|
|
384
|
+
return next();
|
|
385
|
+
}
|
|
386
|
+
return { kind: "reject" };
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
ctx.tools.register(
|
|
390
|
+
defineTool({
|
|
391
|
+
name: "test_schedule_script",
|
|
392
|
+
description:
|
|
393
|
+
"Test-run a background script once in an isolated subprocess exactly as the scheduler would invoke it. ALWAYS test your script with this tool before calling schedule_script.",
|
|
394
|
+
parameters: {
|
|
395
|
+
script_path: {
|
|
396
|
+
type: "string",
|
|
397
|
+
required: true,
|
|
398
|
+
description:
|
|
399
|
+
"Path to the TypeScript script to test (e.g. .agents/scripts/sync.ts)",
|
|
400
|
+
},
|
|
401
|
+
state: {
|
|
402
|
+
type: "object",
|
|
403
|
+
required: true,
|
|
404
|
+
additionalProperties: true,
|
|
405
|
+
description: "Initial state to test with (mandatory)",
|
|
406
|
+
},
|
|
407
|
+
timeout_ms: {
|
|
408
|
+
type: "number",
|
|
409
|
+
default: 30000,
|
|
410
|
+
description: "Execution timeout in milliseconds (default: 30000)",
|
|
411
|
+
},
|
|
412
|
+
},
|
|
413
|
+
output: {
|
|
414
|
+
schema: {
|
|
415
|
+
type: "object",
|
|
416
|
+
properties: {
|
|
417
|
+
success: { type: "boolean", required: true },
|
|
418
|
+
message: { type: "string", required: true },
|
|
419
|
+
state: { type: "json" },
|
|
420
|
+
prompt: { type: "string" },
|
|
421
|
+
error: { type: "string" },
|
|
422
|
+
stop: { type: "boolean" },
|
|
423
|
+
duration_ms: { type: "number" },
|
|
424
|
+
},
|
|
425
|
+
additionalProperties: false,
|
|
426
|
+
},
|
|
427
|
+
render(_args, val) {
|
|
428
|
+
return [{ type: "text", text: val.message }];
|
|
429
|
+
},
|
|
430
|
+
},
|
|
431
|
+
async execute(args, exec) {
|
|
432
|
+
const agent = exec.agent;
|
|
433
|
+
if (!agent) {
|
|
434
|
+
return { success: false, message: "No active agent session" };
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
const testState = args.state;
|
|
438
|
+
const timeoutMs = args.timeout_ms ?? 30000;
|
|
439
|
+
const startTime = Date.now();
|
|
440
|
+
|
|
441
|
+
try {
|
|
442
|
+
const result = await executeScript(
|
|
443
|
+
args.script_path,
|
|
444
|
+
{
|
|
445
|
+
state: testState,
|
|
446
|
+
sessionId: agent.session.id,
|
|
447
|
+
},
|
|
448
|
+
timeoutMs,
|
|
449
|
+
agent.session.header.cwd,
|
|
450
|
+
);
|
|
451
|
+
|
|
452
|
+
const durationMs = Date.now() - startTime;
|
|
453
|
+
let summaryMsg = `Test execution succeeded in ${durationMs}ms.`;
|
|
454
|
+
if (result.prompt) {
|
|
455
|
+
summaryMsg += ` Prompt emitted: "${result.prompt}".`;
|
|
456
|
+
} else {
|
|
457
|
+
summaryMsg += " Silent poll (no prompt emitted).";
|
|
458
|
+
}
|
|
459
|
+
if (result.error) {
|
|
460
|
+
summaryMsg += ` Recoverable warning: "${result.error}".`;
|
|
461
|
+
}
|
|
462
|
+
if (result.stop) {
|
|
463
|
+
summaryMsg += " Script requested stop.";
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const payload: {
|
|
467
|
+
success: boolean;
|
|
468
|
+
message: string;
|
|
469
|
+
state?: Parameters<typeof JSON.stringify>[0];
|
|
470
|
+
prompt?: string;
|
|
471
|
+
error?: string;
|
|
472
|
+
stop?: boolean;
|
|
473
|
+
duration_ms: number;
|
|
474
|
+
} = {
|
|
475
|
+
success: true,
|
|
476
|
+
message: summaryMsg,
|
|
477
|
+
duration_ms: durationMs,
|
|
478
|
+
};
|
|
479
|
+
if (result.state !== undefined) {
|
|
480
|
+
payload.state = (result.state ?? null) as Parameters<
|
|
481
|
+
typeof JSON.stringify
|
|
482
|
+
>[0];
|
|
483
|
+
}
|
|
484
|
+
if (result.prompt !== undefined) {
|
|
485
|
+
payload.prompt = result.prompt;
|
|
486
|
+
}
|
|
487
|
+
if (result.error !== undefined) {
|
|
488
|
+
payload.error = result.error;
|
|
489
|
+
}
|
|
490
|
+
if (result.stop !== undefined) {
|
|
491
|
+
payload.stop = result.stop;
|
|
492
|
+
}
|
|
493
|
+
return payload;
|
|
494
|
+
} catch (err: unknown) {
|
|
495
|
+
const durationMs = Date.now() - startTime;
|
|
496
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
497
|
+
return {
|
|
498
|
+
success: false,
|
|
499
|
+
message: `Test execution failed (${durationMs}ms): ${errorMsg}`,
|
|
500
|
+
error: errorMsg,
|
|
501
|
+
duration_ms: durationMs,
|
|
502
|
+
};
|
|
503
|
+
}
|
|
504
|
+
},
|
|
505
|
+
}),
|
|
506
|
+
{
|
|
507
|
+
when: ({ agent }: { agent: Agent }) =>
|
|
508
|
+
isScheduleScriptActive(agent.session),
|
|
509
|
+
},
|
|
510
|
+
);
|
|
511
|
+
|
|
512
|
+
const creatingSessions = new Set<string>();
|
|
513
|
+
ctx.tools.register(
|
|
514
|
+
defineTool({
|
|
515
|
+
name: "schedule_script",
|
|
516
|
+
description:
|
|
517
|
+
"Schedule a TypeScript script to run periodically in the background. It executes in an isolated Node subprocess and consumes 0 LLM tokens on silent iterations.",
|
|
518
|
+
parameters: {
|
|
519
|
+
script_path: {
|
|
520
|
+
type: "string",
|
|
521
|
+
required: true,
|
|
522
|
+
description:
|
|
523
|
+
"Absolute or relative path to the TypeScript script (e.g. .agents/scripts/sync.ts)",
|
|
524
|
+
},
|
|
525
|
+
title: {
|
|
526
|
+
type: "string",
|
|
527
|
+
required: true,
|
|
528
|
+
description:
|
|
529
|
+
"Concise human-readable name for the schedule in the user's language (e.g. 'Sync database every 5m')",
|
|
530
|
+
},
|
|
531
|
+
interval_seconds: {
|
|
532
|
+
type: "number",
|
|
533
|
+
default: 60,
|
|
534
|
+
description: "Recurrence interval in seconds (minimum 60)",
|
|
535
|
+
},
|
|
536
|
+
state: {
|
|
537
|
+
type: "object",
|
|
538
|
+
required: true,
|
|
539
|
+
additionalProperties: true,
|
|
540
|
+
description:
|
|
541
|
+
"Initial state to pass to the script's main({ state }) (mandatory)",
|
|
542
|
+
},
|
|
543
|
+
},
|
|
544
|
+
output: {
|
|
545
|
+
schema: {
|
|
546
|
+
type: "object",
|
|
547
|
+
properties: {
|
|
548
|
+
success: { type: "boolean", required: true },
|
|
549
|
+
message: { type: "string", required: true },
|
|
550
|
+
},
|
|
551
|
+
additionalProperties: false,
|
|
552
|
+
},
|
|
553
|
+
render(_args, val) {
|
|
554
|
+
return [{ type: "text", text: val.message }];
|
|
555
|
+
},
|
|
556
|
+
},
|
|
557
|
+
async execute(args, exec) {
|
|
558
|
+
const agent = exec.agent;
|
|
559
|
+
if (!agent) {
|
|
560
|
+
return { success: false, message: "No active agent session" };
|
|
561
|
+
}
|
|
562
|
+
if (creatingSessions.has(agent.session.id))
|
|
563
|
+
return {
|
|
564
|
+
success: false,
|
|
565
|
+
message:
|
|
566
|
+
"A script schedule is already being created for this session.",
|
|
567
|
+
};
|
|
568
|
+
creatingSessions.add(agent.session.id);
|
|
569
|
+
try {
|
|
570
|
+
const existing = await activeScriptTasks(agent.session.id);
|
|
571
|
+
if (existing.size > 0) {
|
|
572
|
+
return {
|
|
573
|
+
success: false,
|
|
574
|
+
message:
|
|
575
|
+
"This session already has an active script schedule. Pause or delete it before scheduling another.",
|
|
576
|
+
};
|
|
577
|
+
}
|
|
578
|
+
const interval = Math.max(60, Number(args.interval_seconds) || 60);
|
|
579
|
+
const promptText = formatScriptPrompt({
|
|
580
|
+
scriptPath: args.script_path,
|
|
581
|
+
state: args.state,
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
await ctx.schedule.create({
|
|
585
|
+
title: args.title,
|
|
586
|
+
prompt: promptText,
|
|
587
|
+
timing: { kind: "every", every_seconds: interval },
|
|
588
|
+
target: { kind: "session", sessionId: agent.session.id },
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
appendScriptEvent(
|
|
592
|
+
agent.session,
|
|
593
|
+
{
|
|
594
|
+
action: "start",
|
|
595
|
+
scriptPath: args.script_path,
|
|
596
|
+
state: args.state,
|
|
597
|
+
timestamp: Date.now(),
|
|
598
|
+
},
|
|
599
|
+
`start-${Date.now()}`,
|
|
600
|
+
);
|
|
601
|
+
|
|
602
|
+
return {
|
|
603
|
+
success: true,
|
|
604
|
+
message: `Scheduled background script '${args.script_path}' every ${interval}s via Automation tasks (Title: ${args.title})`,
|
|
605
|
+
};
|
|
606
|
+
} finally {
|
|
607
|
+
creatingSessions.delete(agent.session.id);
|
|
608
|
+
}
|
|
609
|
+
},
|
|
610
|
+
}),
|
|
611
|
+
{
|
|
612
|
+
when: ({ agent }: { agent: Agent }) =>
|
|
613
|
+
isScheduleScriptActive(agent.session),
|
|
614
|
+
},
|
|
615
|
+
);
|
|
616
|
+
}
|