@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/dist/index.js
ADDED
|
@@ -0,0 +1,826 @@
|
|
|
1
|
+
import { isDeepStrictEqual, promisify } from "node:util";
|
|
2
|
+
import { defineTool } from "@deepseek-ai/dsh-tools";
|
|
3
|
+
import { execFile } from "node:child_process";
|
|
4
|
+
import { existsSync } from "node:fs";
|
|
5
|
+
import { mkdtempDisposable, readFile, writeFile } from "node:fs/promises";
|
|
6
|
+
import os from "node:os";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { fileURLToPath } from "node:url";
|
|
9
|
+
import { z } from "zod";
|
|
10
|
+
// \0@oxc-project+runtime@0.159.0/helpers/esm/usingCtx.js
|
|
11
|
+
function _usingCtx() {
|
|
12
|
+
var r = "function" == typeof SuppressedError ? SuppressedError : function(r, e) {
|
|
13
|
+
var n = Error();
|
|
14
|
+
return n.name = "SuppressedError", n.error = r, n.suppressed = e, n;
|
|
15
|
+
}, e = {}, n = [];
|
|
16
|
+
function using(r, e) {
|
|
17
|
+
if (null != e) {
|
|
18
|
+
if (Object(e) !== e) throw new TypeError("using declarations can only be used with objects, functions, null, or undefined.");
|
|
19
|
+
if (r) var o = e[Symbol.asyncDispose || Symbol["for"]("Symbol.asyncDispose")];
|
|
20
|
+
if (void 0 === o && (o = e[Symbol.dispose || Symbol["for"]("Symbol.dispose")], r)) var t = o;
|
|
21
|
+
if ("function" != typeof o) throw new TypeError("Object is not disposable.");
|
|
22
|
+
t && (o = function o() {
|
|
23
|
+
try {
|
|
24
|
+
t.call(e);
|
|
25
|
+
} catch (r) {
|
|
26
|
+
return Promise.reject(r);
|
|
27
|
+
}
|
|
28
|
+
}), n.push({
|
|
29
|
+
v: e,
|
|
30
|
+
d: o,
|
|
31
|
+
a: r
|
|
32
|
+
});
|
|
33
|
+
} else r && n.push({
|
|
34
|
+
d: e,
|
|
35
|
+
a: r
|
|
36
|
+
});
|
|
37
|
+
return e;
|
|
38
|
+
}
|
|
39
|
+
return {
|
|
40
|
+
e,
|
|
41
|
+
u: using.bind(null, !1),
|
|
42
|
+
a: using.bind(null, !0),
|
|
43
|
+
d: function d() {
|
|
44
|
+
var o, t = this.e, s = 0;
|
|
45
|
+
function next() {
|
|
46
|
+
for (; o = n.pop();) try {
|
|
47
|
+
if (!o.a && 1 === s) return s = 0, n.push(o), Promise.resolve().then(next);
|
|
48
|
+
if (o.d) {
|
|
49
|
+
var r = o.d.call(o.v);
|
|
50
|
+
if (o.a) return s |= 2, Promise.resolve(r).then(next, err);
|
|
51
|
+
} else s |= 1;
|
|
52
|
+
} catch (r) {
|
|
53
|
+
return err(r);
|
|
54
|
+
}
|
|
55
|
+
if (1 === s) return t !== e ? Promise.reject(t) : Promise.resolve();
|
|
56
|
+
if (t !== e) throw t;
|
|
57
|
+
}
|
|
58
|
+
function err(n) {
|
|
59
|
+
return t = t !== e ? new r(n, t) : n, next();
|
|
60
|
+
}
|
|
61
|
+
return next();
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
// src/executor.ts
|
|
66
|
+
const execFileAsync = promisify(execFile);
|
|
67
|
+
function resolveRunnerCliPath() {
|
|
68
|
+
const direct = fileURLToPath(new URL("./runner-cli.ts", import.meta.url));
|
|
69
|
+
if (existsSync(direct)) return direct;
|
|
70
|
+
const fromDist = fileURLToPath(new URL("../src/runner-cli.ts", import.meta.url));
|
|
71
|
+
if (existsSync(fromDist)) return fromDist;
|
|
72
|
+
return direct;
|
|
73
|
+
}
|
|
74
|
+
const RUNNER_CLI_PATH = resolveRunnerCliPath();
|
|
75
|
+
async function readRunnerOutput(outputPath) {
|
|
76
|
+
try {
|
|
77
|
+
const rawOutput = await readFile(outputPath, "utf8");
|
|
78
|
+
return JSON.parse(rawOutput);
|
|
79
|
+
} catch (err) {
|
|
80
|
+
if (typeof err === "object" && err !== null && "code" in err && err.code === "ENOENT") return null;
|
|
81
|
+
throw err;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
async function executeScript(scriptPath, ctx, timeoutMs = 3e4, cwd = process.cwd(), signal) {
|
|
85
|
+
try {
|
|
86
|
+
var _usingCtx$1 = _usingCtx();
|
|
87
|
+
const tmp = _usingCtx$1.a(await mkdtempDisposable(path.join(os.tmpdir(), "dsh-script-")));
|
|
88
|
+
const inputPath = path.join(tmp.path, "input.json");
|
|
89
|
+
const outputPath = path.join(tmp.path, "output.json");
|
|
90
|
+
await writeFile(inputPath, JSON.stringify(ctx), "utf8");
|
|
91
|
+
try {
|
|
92
|
+
await execFileAsync(process.execPath, [
|
|
93
|
+
RUNNER_CLI_PATH,
|
|
94
|
+
scriptPath,
|
|
95
|
+
inputPath,
|
|
96
|
+
outputPath
|
|
97
|
+
], {
|
|
98
|
+
signal,
|
|
99
|
+
timeout: timeoutMs,
|
|
100
|
+
cwd,
|
|
101
|
+
env: { ...process.env }
|
|
102
|
+
});
|
|
103
|
+
const data = await readRunnerOutput(outputPath);
|
|
104
|
+
if (!data || !data.success) throw new Error(data?.error ?? "Runner failed to produce output");
|
|
105
|
+
return data.result;
|
|
106
|
+
} catch (error) {
|
|
107
|
+
const fallbackOutput = await readRunnerOutput(outputPath).catch(() => null);
|
|
108
|
+
if (fallbackOutput && !fallbackOutput.success && fallbackOutput.error) {
|
|
109
|
+
const err = new Error(fallbackOutput.error, { cause: error });
|
|
110
|
+
if (fallbackOutput.stack) err.stack = fallbackOutput.stack;
|
|
111
|
+
throw err;
|
|
112
|
+
}
|
|
113
|
+
if (error instanceof Error) {
|
|
114
|
+
if ("killed" in error && error.killed) throw new Error(`Script execution timed out after ${timeoutMs}ms: ${scriptPath}`, { cause: error });
|
|
115
|
+
throw error;
|
|
116
|
+
}
|
|
117
|
+
throw new Error(String(error), { cause: error });
|
|
118
|
+
}
|
|
119
|
+
} catch (_) {
|
|
120
|
+
_usingCtx$1.e = _;
|
|
121
|
+
} finally {
|
|
122
|
+
await _usingCtx$1.d();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// src/skill.ts
|
|
126
|
+
const SCHEDULE_SCRIPT_SKILL_NAME = "schedule-script";
|
|
127
|
+
const SCHEDULE_SCRIPT_SKILL_DESCRIPTION = "Schedule recurring TypeScript background scripts without consuming LLM tokens.";
|
|
128
|
+
const SCHEDULE_SCRIPT_SKILL_CONTENT = `
|
|
129
|
+
# Schedule Script Skill
|
|
130
|
+
|
|
131
|
+
Run TypeScript scripts periodically in the background using DSH Automation Tasks.
|
|
132
|
+
Iterations execute in isolated Node 26 subprocesses and consume 0 LLM tokens during silent monitoring.
|
|
133
|
+
|
|
134
|
+
## Script Contract
|
|
135
|
+
|
|
136
|
+
Scripts are standalone files with **zero imports**. Define your script-specific \`State\` interface, with the runner contract inlined directly on \`main\`:
|
|
137
|
+
|
|
138
|
+
\`\`\`ts
|
|
139
|
+
// 1. Define your custom State shape (mandatory initial state passed when scheduled)
|
|
140
|
+
interface State {
|
|
141
|
+
target: string;
|
|
142
|
+
count: number;
|
|
143
|
+
lastChecked?: string;
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// 2. Export main with the inlined runner contract
|
|
147
|
+
export async function main(ctx: {
|
|
148
|
+
state: State; // Preserved state (mandatory, seeded when scheduled)
|
|
149
|
+
sessionId: string; // Active DSH session ID
|
|
150
|
+
}): Promise<{
|
|
151
|
+
state: State; // REQUIRED: state preserved for next run
|
|
152
|
+
prompt?: string; // OPTIONAL: awakens agent in chat with this prompt
|
|
153
|
+
error?: string; // OPTIONAL: recoverable warning shown in UI row
|
|
154
|
+
stop?: boolean; // OPTIONAL: stops recurrence when true
|
|
155
|
+
}> {
|
|
156
|
+
const count = ctx.state.count + 1;
|
|
157
|
+
|
|
158
|
+
// Case 1: Silent poll (0 LLM tokens, updates status pill quietly)
|
|
159
|
+
if (count < 3) {
|
|
160
|
+
return {
|
|
161
|
+
state: { ...ctx.state, count, lastChecked: new Date().toISOString() },
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
// Case 2: Recoverable warning (surfaces in UI row, keeps schedule active)
|
|
166
|
+
if (count === 3) {
|
|
167
|
+
return {
|
|
168
|
+
state: { ...ctx.state, count, lastChecked: new Date().toISOString() },
|
|
169
|
+
error: "Temporary network timeout while checking endpoint (will retry)",
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
// Case 3: Prompt (awakens agent in chat to reason and take action)
|
|
174
|
+
return {
|
|
175
|
+
state: { ...ctx.state, count, lastChecked: new Date().toISOString() },
|
|
176
|
+
prompt: \`Polled run #\${count}: found 3 tasks ready for processing.\`,
|
|
177
|
+
stop: true, // auto-stops further recurrence
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
\`\`\`
|
|
181
|
+
|
|
182
|
+
### Summary of Inlined Return Fields
|
|
183
|
+
| Field | Type | Behavior |
|
|
184
|
+
| :--- | :--- | :--- |
|
|
185
|
+
| \`state\` | \`State\` (required) | Preserved and passed back into \`ctx.state\` on the next run. |
|
|
186
|
+
| \`prompt\` | \`string\` (optional) | Replaces automation prompt with this text and **awakens the agent** to respond. |
|
|
187
|
+
| \`error\` | \`string\` (optional) | Marks run with a recoverable warning in the UI row; **keeps schedule running** without LLM call. |
|
|
188
|
+
| \`stop\` | \`boolean\` (optional) | If \`true\`, cleanly stops further recurrence. |
|
|
189
|
+
|
|
190
|
+
### Critical vs Recoverable Errors
|
|
191
|
+
- **Recoverable Errors**: Handled in your script and returned via \`error: "..."\`. Surfaced in the UI status row without stopping the schedule or invoking the LLM.
|
|
192
|
+
- **Critical Errors**: Uncaught exceptions, syntax errors, or execution timeouts automatically halt recurrence, mark the schedule as stopped, and surface the error in the UI.
|
|
193
|
+
|
|
194
|
+
## Tool Activation Notice
|
|
195
|
+
|
|
196
|
+
The tools \`test_schedule_script\` and \`schedule_script\` are conditionally activated by loading this skill. Tool admissions are resolved at turn boundaries, which means **these tools are only visible to the agent on the NEXT turn**. They cannot be called within the same turn that invokes the skill.
|
|
197
|
+
|
|
198
|
+
## Mandatory Two-Step Workflow
|
|
199
|
+
|
|
200
|
+
Scheduling scripts is strictly a **two-step conversational process**.
|
|
201
|
+
|
|
202
|
+
### Step 1: Prepare Script & Propose Parameters (Turn 1)
|
|
203
|
+
|
|
204
|
+
1. Write or update the standalone TypeScript script in the workspace (e.g. \`.agents/scripts/<name>.ts\`).
|
|
205
|
+
2. Do **NOT** attempt to call \`test_schedule_script\` or \`schedule_script\` in this turn (they are not admitted yet).
|
|
206
|
+
3. Present the proposed schedule parameters to the user and request confirmation. End the turn immediately.
|
|
207
|
+
|
|
208
|
+
#### Example Output to the User:
|
|
209
|
+
\`\`\`markdown
|
|
210
|
+
I have created the background poller script at \`.agents/scripts/poller.ts\`.
|
|
211
|
+
|
|
212
|
+
**Proposed Schedule:**
|
|
213
|
+
- **Script Path:** \`.agents/scripts/poller.ts\`
|
|
214
|
+
- **Title:** Check Endpoint Health
|
|
215
|
+
- **Interval:** 60s
|
|
216
|
+
- **Initial State:** \`{ "target": "https://api.example.com/health", "count": 0 }\`
|
|
217
|
+
|
|
218
|
+
Please confirm to proceed with testing and scheduling this task.
|
|
219
|
+
\`\`\`
|
|
220
|
+
|
|
221
|
+
### Step 2: Test & Schedule Upon Confirmation (Turn 2)
|
|
222
|
+
|
|
223
|
+
Once the user confirms in the next turn, \`test_schedule_script\` and \`schedule_script\` are admitted and ready to use:
|
|
224
|
+
|
|
225
|
+
1. **Test the script**: Execute \`test_schedule_script\` with the script path and initial state:
|
|
226
|
+
\`\`\`json
|
|
227
|
+
{
|
|
228
|
+
"script_path": ".agents/scripts/poller.ts",
|
|
229
|
+
"state": { "target": "https://api.example.com/health", "count": 0 }
|
|
230
|
+
}
|
|
231
|
+
\`\`\`
|
|
232
|
+
Verify \`success: true\`. Fix any syntax or runtime errors before proceeding.
|
|
233
|
+
|
|
234
|
+
2. **Schedule the script**: Only after \`test_schedule_script\` succeeds, call \`schedule_script\`:
|
|
235
|
+
\`\`\`json
|
|
236
|
+
{
|
|
237
|
+
"script_path": ".agents/scripts/poller.ts",
|
|
238
|
+
"title": "Check Endpoint Health",
|
|
239
|
+
"interval_seconds": 60,
|
|
240
|
+
"state": { "target": "https://api.example.com/health", "count": 0 }
|
|
241
|
+
}
|
|
242
|
+
\`\`\`
|
|
243
|
+
`.trim();
|
|
244
|
+
// src/types.ts
|
|
245
|
+
const SCHEDULE_SCRIPT_KIND = "dsh-schedule-script";
|
|
246
|
+
const SCHEDULE_SCRIPT_EVENT_NAME = "dsh-schedule-script";
|
|
247
|
+
const scriptExecutionStatusSchema = z.enum([
|
|
248
|
+
"idle",
|
|
249
|
+
"running",
|
|
250
|
+
"warning",
|
|
251
|
+
"error",
|
|
252
|
+
"stopped"
|
|
253
|
+
]);
|
|
254
|
+
const scheduleSystemStatusSchema = z.enum([
|
|
255
|
+
"active",
|
|
256
|
+
"paused",
|
|
257
|
+
"ended",
|
|
258
|
+
"deleted"
|
|
259
|
+
]);
|
|
260
|
+
const scheduleScriptSummarySchema = z.object({
|
|
261
|
+
scriptStatus: scriptExecutionStatusSchema,
|
|
262
|
+
skillInvoked: z.boolean().optional(),
|
|
263
|
+
scheduleId: z.string().optional(),
|
|
264
|
+
cleanupPending: z.boolean().optional(),
|
|
265
|
+
cleanupError: z.string().optional(),
|
|
266
|
+
scriptPath: z.string().optional(),
|
|
267
|
+
totalRuns: z.number(),
|
|
268
|
+
lastRunAt: z.number().optional(),
|
|
269
|
+
lastDurationMs: z.number().optional(),
|
|
270
|
+
state: z.unknown().optional(),
|
|
271
|
+
lastPrompt: z.object({
|
|
272
|
+
message: z.string(),
|
|
273
|
+
timestamp: z.number()
|
|
274
|
+
}).optional(),
|
|
275
|
+
lastError: z.object({
|
|
276
|
+
message: z.string(),
|
|
277
|
+
timestamp: z.number(),
|
|
278
|
+
fatal: z.boolean().default(false)
|
|
279
|
+
}).optional()
|
|
280
|
+
});
|
|
281
|
+
// src/fold.ts
|
|
282
|
+
function initialScheduleScriptSummary() {
|
|
283
|
+
return {
|
|
284
|
+
scriptStatus: "idle",
|
|
285
|
+
skillInvoked: false,
|
|
286
|
+
totalRuns: 0
|
|
287
|
+
};
|
|
288
|
+
}
|
|
289
|
+
function foldScheduleScriptEvent(state, event) {
|
|
290
|
+
if (event.type === "tool/call") {
|
|
291
|
+
if (event.data.name === "skill") try {
|
|
292
|
+
const raw = event.data.arguments ?? event.data.args;
|
|
293
|
+
const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
|
|
294
|
+
if (parsed && typeof parsed === "object" && parsed.name === "schedule-script") {
|
|
295
|
+
if (state.skillInvoked) return state;
|
|
296
|
+
return {
|
|
297
|
+
...state,
|
|
298
|
+
skillInvoked: true
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
} catch {}
|
|
302
|
+
return state;
|
|
303
|
+
}
|
|
304
|
+
if (event.type !== "command/run") return state;
|
|
305
|
+
if (event.data.name !== "dsh-schedule-script" || typeof event.data.args !== "string") return state;
|
|
306
|
+
try {
|
|
307
|
+
const payload = JSON.parse(event.data.args);
|
|
308
|
+
if (payload.action === "skill") return {
|
|
309
|
+
...state,
|
|
310
|
+
skillInvoked: true
|
|
311
|
+
};
|
|
312
|
+
if (payload.action === "start") {
|
|
313
|
+
const { lastError: _, scheduleId: _id, cleanupPending: _pending, cleanupError: _cleanup, ...rest } = state;
|
|
314
|
+
return {
|
|
315
|
+
...rest,
|
|
316
|
+
scriptStatus: "idle",
|
|
317
|
+
scriptPath: payload.scriptPath,
|
|
318
|
+
state: payload.state
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
if (payload.action === "iteration") {
|
|
322
|
+
const { lastError: _, ...rest } = state;
|
|
323
|
+
const next = {
|
|
324
|
+
...rest,
|
|
325
|
+
scriptStatus: payload.error ? "warning" : "idle",
|
|
326
|
+
scriptPath: payload.scriptPath,
|
|
327
|
+
totalRuns: state.totalRuns + 1,
|
|
328
|
+
lastRunAt: payload.timestamp,
|
|
329
|
+
lastDurationMs: payload.durationMs
|
|
330
|
+
};
|
|
331
|
+
if (payload.scheduleId !== void 0) next.scheduleId = payload.scheduleId;
|
|
332
|
+
if (payload.state !== void 0) next.state = payload.state;
|
|
333
|
+
if (payload.prompt) next.lastPrompt = {
|
|
334
|
+
message: payload.prompt,
|
|
335
|
+
timestamp: payload.timestamp
|
|
336
|
+
};
|
|
337
|
+
if (payload.error) next.lastError = {
|
|
338
|
+
message: payload.error,
|
|
339
|
+
timestamp: payload.timestamp,
|
|
340
|
+
fatal: false
|
|
341
|
+
};
|
|
342
|
+
return next;
|
|
343
|
+
}
|
|
344
|
+
if (payload.action === "error") return {
|
|
345
|
+
...state,
|
|
346
|
+
scriptStatus: payload.fatal === false ? "warning" : "error",
|
|
347
|
+
...payload.scheduleId !== void 0 ? { scheduleId: payload.scheduleId } : {},
|
|
348
|
+
scriptPath: payload.scriptPath,
|
|
349
|
+
lastError: {
|
|
350
|
+
message: payload.error,
|
|
351
|
+
timestamp: payload.timestamp,
|
|
352
|
+
fatal: payload.fatal !== false
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
if (payload.action === "stop") return {
|
|
356
|
+
...state,
|
|
357
|
+
scriptStatus: state.scriptStatus === "error" ? "error" : "stopped",
|
|
358
|
+
cleanupPending: true,
|
|
359
|
+
...payload.scheduleId !== void 0 ? { scheduleId: payload.scheduleId } : {}
|
|
360
|
+
};
|
|
361
|
+
if (payload.action === "cleanup") {
|
|
362
|
+
const { cleanupError: _, ...rest } = state;
|
|
363
|
+
return {
|
|
364
|
+
...rest,
|
|
365
|
+
cleanupPending: payload.error !== void 0,
|
|
366
|
+
...payload.error !== void 0 ? { cleanupError: payload.error } : {}
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
} catch {}
|
|
370
|
+
return state;
|
|
371
|
+
}
|
|
372
|
+
function toScheduleScriptRecord(summary) {
|
|
373
|
+
return summary.skillInvoked || summary.totalRuns > 0 || summary.scriptPath !== void 0 ? summary : null;
|
|
374
|
+
}
|
|
375
|
+
// src/parser.ts
|
|
376
|
+
function formatScriptPrompt(payload) {
|
|
377
|
+
return JSON.stringify({
|
|
378
|
+
kind: SCHEDULE_SCRIPT_KIND,
|
|
379
|
+
scriptPath: payload.scriptPath,
|
|
380
|
+
state: payload.state,
|
|
381
|
+
...payload.timeoutMs ? { timeoutMs: payload.timeoutMs } : {}
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
function parseScriptPrompt(promptText) {
|
|
385
|
+
if (!promptText) return null;
|
|
386
|
+
try {
|
|
387
|
+
const parsed = JSON.parse(promptText.trim());
|
|
388
|
+
if (parsed && typeof parsed === "object" && parsed.kind === "dsh-schedule-script" && typeof parsed.scriptPath === "string" && "state" in parsed && parsed.state !== void 0) {
|
|
389
|
+
const timeoutMs = typeof parsed.timeoutMs === "number" && Number.isFinite(parsed.timeoutMs) && parsed.timeoutMs > 0 ? parsed.timeoutMs : void 0;
|
|
390
|
+
return {
|
|
391
|
+
kind: SCHEDULE_SCRIPT_KIND,
|
|
392
|
+
scriptPath: parsed.scriptPath,
|
|
393
|
+
state: parsed.state,
|
|
394
|
+
...timeoutMs ? { timeoutMs } : {}
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
} catch {}
|
|
398
|
+
return null;
|
|
399
|
+
}
|
|
400
|
+
function parseReminderBatch(messageText) {
|
|
401
|
+
const line = messageText.split("\n").find((l) => l.startsWith("reminders_json:"));
|
|
402
|
+
if (!line) return null;
|
|
403
|
+
const jsonText = line.slice(15).trim();
|
|
404
|
+
let rawItems;
|
|
405
|
+
try {
|
|
406
|
+
rawItems = JSON.parse(jsonText);
|
|
407
|
+
} catch {
|
|
408
|
+
return null;
|
|
409
|
+
}
|
|
410
|
+
if (!Array.isArray(rawItems)) return null;
|
|
411
|
+
const scripts = [];
|
|
412
|
+
const remainingReminders = [];
|
|
413
|
+
for (const item of rawItems) {
|
|
414
|
+
if (!item || typeof item !== "object" || typeof item.reminder_prompt !== "string" || typeof item.schedule_id !== "string") continue;
|
|
415
|
+
const reminder = item;
|
|
416
|
+
const scriptPayload = parseScriptPrompt(reminder.reminder_prompt);
|
|
417
|
+
if (scriptPayload) scripts.push({
|
|
418
|
+
scheduleId: reminder.schedule_id,
|
|
419
|
+
reminder,
|
|
420
|
+
payload: scriptPayload
|
|
421
|
+
});
|
|
422
|
+
else remainingReminders.push(reminder);
|
|
423
|
+
}
|
|
424
|
+
if (scripts.length === 0) return null;
|
|
425
|
+
return {
|
|
426
|
+
scripts,
|
|
427
|
+
remainingReminders
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
function formatRemainingBatch(remainingReminders, originalText) {
|
|
431
|
+
const lineIdx = originalText.indexOf("reminders_json:");
|
|
432
|
+
if (lineIdx === -1) return originalText;
|
|
433
|
+
const lineEnd = originalText.indexOf("\n", lineIdx);
|
|
434
|
+
const prefix = originalText.slice(0, lineIdx);
|
|
435
|
+
const suffix = lineEnd === -1 ? "" : originalText.slice(lineEnd);
|
|
436
|
+
return `${prefix}reminders_json: ${JSON.stringify(remainingReminders)}${suffix}`;
|
|
437
|
+
}
|
|
438
|
+
function formatWakingPrompt(scriptPrompts, remainingBatchText) {
|
|
439
|
+
const parts = scriptPrompts.filter(Boolean);
|
|
440
|
+
if (remainingBatchText?.trim()) parts.push(remainingBatchText);
|
|
441
|
+
return parts.join("\n\n");
|
|
442
|
+
}
|
|
443
|
+
// src/index.ts
|
|
444
|
+
const name = "dsh-schedule-script";
|
|
445
|
+
const inject = [
|
|
446
|
+
"commands",
|
|
447
|
+
"sessionProjections",
|
|
448
|
+
"tools",
|
|
449
|
+
"skills",
|
|
450
|
+
"schedule"
|
|
451
|
+
];
|
|
452
|
+
async function apply(ctx) {
|
|
453
|
+
const projectionHandle = await ctx.sessionProjections.register({
|
|
454
|
+
key: "dshScheduleScript",
|
|
455
|
+
stateSchema: scheduleScriptSummarySchema,
|
|
456
|
+
init: () => initialScheduleScriptSummary(),
|
|
457
|
+
apply: (state, event) => foldScheduleScriptEvent(state, event),
|
|
458
|
+
wire: {
|
|
459
|
+
viewSchema: scheduleScriptSummarySchema.nullable(),
|
|
460
|
+
view: toScheduleScriptRecord
|
|
461
|
+
},
|
|
462
|
+
stateVersion: 1
|
|
463
|
+
});
|
|
464
|
+
ctx.effect(() => () => projectionHandle.dispose());
|
|
465
|
+
function isScheduleScriptActive(session) {
|
|
466
|
+
const summary = projectionHandle.stateOf(session);
|
|
467
|
+
return Boolean(summary.skillInvoked) || summary.totalRuns > 0 || summary.scriptPath !== void 0;
|
|
468
|
+
}
|
|
469
|
+
function appendScriptEvent(session, payload, idSuffix) {
|
|
470
|
+
const commandId = `schedule-script-${idSuffix}`;
|
|
471
|
+
session.append("command/run", {
|
|
472
|
+
commandId,
|
|
473
|
+
name: SCHEDULE_SCRIPT_EVENT_NAME,
|
|
474
|
+
args: JSON.stringify(payload),
|
|
475
|
+
source: { kind: "user" }
|
|
476
|
+
});
|
|
477
|
+
session.append("command/done", {
|
|
478
|
+
commandId,
|
|
479
|
+
kind: payload.action === "error" && payload.fatal !== false ? "error" : "success"
|
|
480
|
+
});
|
|
481
|
+
}
|
|
482
|
+
ctx.effect(() => {
|
|
483
|
+
const unregister = ctx.skills.register({
|
|
484
|
+
name: SCHEDULE_SCRIPT_SKILL_NAME,
|
|
485
|
+
description: SCHEDULE_SCRIPT_SKILL_DESCRIPTION,
|
|
486
|
+
source: "runtime",
|
|
487
|
+
content: SCHEDULE_SCRIPT_SKILL_CONTENT
|
|
488
|
+
});
|
|
489
|
+
return () => unregister();
|
|
490
|
+
});
|
|
491
|
+
ctx.on("tools/post-execute", async (exec, result, next) => {
|
|
492
|
+
const decision = await next();
|
|
493
|
+
if (exec.name === "skill" && exec.agent?.session && !result.isError) try {
|
|
494
|
+
if ((typeof exec.arguments === "string" ? JSON.parse(exec.arguments) : exec.arguments)?.name === "schedule-script") appendScriptEvent(exec.agent.session, {
|
|
495
|
+
action: "skill",
|
|
496
|
+
timestamp: Date.now()
|
|
497
|
+
}, `skill-${Date.now()}`);
|
|
498
|
+
} catch {}
|
|
499
|
+
return decision;
|
|
500
|
+
});
|
|
501
|
+
ctx.effect(() => {
|
|
502
|
+
return () => projectionHandle.dispose();
|
|
503
|
+
});
|
|
504
|
+
async function activeScriptTasks(sessionId) {
|
|
505
|
+
const tasks = /* @__PURE__ */ new Map();
|
|
506
|
+
let offset = 0;
|
|
507
|
+
let total;
|
|
508
|
+
do {
|
|
509
|
+
const page = await ctx.schedule.list({
|
|
510
|
+
active: true,
|
|
511
|
+
offset
|
|
512
|
+
});
|
|
513
|
+
for (const item of page.items) if (item.target !== void 0 && item.target.kind === "session" && item.target.sessionId === sessionId && item.prompt !== void 0) {
|
|
514
|
+
const payload = parseScriptPrompt(item.prompt);
|
|
515
|
+
if (payload !== null) tasks.set(item.id, payload);
|
|
516
|
+
}
|
|
517
|
+
offset = page.offset + page.limit;
|
|
518
|
+
total = page.total;
|
|
519
|
+
} while (offset < total);
|
|
520
|
+
return tasks;
|
|
521
|
+
}
|
|
522
|
+
function verifyBatch(batch, tasks) {
|
|
523
|
+
const remaining = [...batch.remainingReminders];
|
|
524
|
+
const jobs = /* @__PURE__ */ new Map();
|
|
525
|
+
for (const job of batch.scripts) {
|
|
526
|
+
const payload = tasks.get(job.scheduleId);
|
|
527
|
+
if (payload === void 0 || !isDeepStrictEqual(payload, job.payload)) remaining.push(job.reminder);
|
|
528
|
+
else jobs.set(job.scheduleId, payload);
|
|
529
|
+
}
|
|
530
|
+
return {
|
|
531
|
+
jobs,
|
|
532
|
+
remaining
|
|
533
|
+
};
|
|
534
|
+
}
|
|
535
|
+
async function deleteTerminalSchedule(session, scheduleId) {
|
|
536
|
+
let error;
|
|
537
|
+
try {
|
|
538
|
+
await ctx.schedule.edit({
|
|
539
|
+
id: scheduleId,
|
|
540
|
+
action: "delete"
|
|
541
|
+
});
|
|
542
|
+
} catch (failure) {
|
|
543
|
+
error = `Failed to delete schedule ${scheduleId}: ${failure instanceof Error ? failure.message : String(failure)}`;
|
|
544
|
+
}
|
|
545
|
+
appendScriptEvent(session, {
|
|
546
|
+
action: "cleanup",
|
|
547
|
+
timestamp: Date.now(),
|
|
548
|
+
...error !== void 0 ? { error } : {}
|
|
549
|
+
}, `cleanup-${Date.now()}`);
|
|
550
|
+
}
|
|
551
|
+
async function runVerifiedJob(session, scheduleId, payload, signal) {
|
|
552
|
+
const summary = projectionHandle.stateOf(session);
|
|
553
|
+
const ownsState = summary.scheduleId === void 0 ? summary.scriptPath === payload.scriptPath : summary.scheduleId === scheduleId;
|
|
554
|
+
if (ownsState && (summary.scriptStatus === "stopped" || summary.scriptStatus === "error")) {
|
|
555
|
+
await deleteTerminalSchedule(session, scheduleId);
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
const iteration = summary.totalRuns + 1;
|
|
559
|
+
const startTime = Date.now();
|
|
560
|
+
let prompt;
|
|
561
|
+
let stopReason;
|
|
562
|
+
try {
|
|
563
|
+
const result = await executeScript(payload.scriptPath, {
|
|
564
|
+
state: ownsState && summary.state !== void 0 ? summary.state : payload.state,
|
|
565
|
+
sessionId: session.id
|
|
566
|
+
}, payload.timeoutMs === void 0 ? 3e4 : payload.timeoutMs, session.header.cwd, signal);
|
|
567
|
+
appendScriptEvent(session, {
|
|
568
|
+
action: "iteration",
|
|
569
|
+
scheduleId,
|
|
570
|
+
scriptPath: payload.scriptPath,
|
|
571
|
+
iteration,
|
|
572
|
+
state: result.state,
|
|
573
|
+
durationMs: Date.now() - startTime,
|
|
574
|
+
timestamp: startTime,
|
|
575
|
+
prompt: result.prompt,
|
|
576
|
+
error: result.error
|
|
577
|
+
}, `run-${iteration}`);
|
|
578
|
+
if (result.prompt) prompt = `[Scheduled Task: ${payload.scriptPath}]\n${result.prompt}`;
|
|
579
|
+
if (result.stop) stopReason = "script_completed";
|
|
580
|
+
} catch (error) {
|
|
581
|
+
signal.throwIfAborted();
|
|
582
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
583
|
+
appendScriptEvent(session, {
|
|
584
|
+
action: "error",
|
|
585
|
+
scheduleId,
|
|
586
|
+
scriptPath: payload.scriptPath,
|
|
587
|
+
iteration,
|
|
588
|
+
error: message,
|
|
589
|
+
timestamp: Date.now(),
|
|
590
|
+
fatal: true
|
|
591
|
+
}, `err-${iteration}`);
|
|
592
|
+
stopReason = `critical_error: ${message}`;
|
|
593
|
+
}
|
|
594
|
+
if (stopReason !== void 0) {
|
|
595
|
+
appendScriptEvent(session, {
|
|
596
|
+
action: "stop",
|
|
597
|
+
scheduleId,
|
|
598
|
+
reason: stopReason,
|
|
599
|
+
timestamp: Date.now()
|
|
600
|
+
}, `stop-${iteration}`);
|
|
601
|
+
await deleteTerminalSchedule(session, scheduleId);
|
|
602
|
+
}
|
|
603
|
+
return prompt;
|
|
604
|
+
}
|
|
605
|
+
ctx.on("agent/pre-step", async ({ agent, messages, signal }, next) => {
|
|
606
|
+
const targetIndex = messages.findIndex((m) => m.content.length > 0 && m.content[0].type === "text" && m.content[0].text.startsWith("[SCHEDULE REMINDER BATCH]"));
|
|
607
|
+
if (targetIndex === -1) return next();
|
|
608
|
+
const first = messages[targetIndex].content[0];
|
|
609
|
+
if (first.type !== "text") return next();
|
|
610
|
+
const batch = parseReminderBatch(first.text);
|
|
611
|
+
if (batch === null) return next();
|
|
612
|
+
const tasks = await activeScriptTasks(agent.session.id);
|
|
613
|
+
const { jobs, remaining } = verifyBatch(batch, tasks);
|
|
614
|
+
if (jobs.size === 0) return next();
|
|
615
|
+
const prompts = [];
|
|
616
|
+
if (tasks.size > 1) prompts.push("Multiple active script schedules target this session. Pause or delete all but one before scripts can run.");
|
|
617
|
+
else for (const [scheduleId, payload] of jobs) {
|
|
618
|
+
const prompt = await runVerifiedJob(agent.session, scheduleId, payload, signal);
|
|
619
|
+
if (prompt !== void 0) prompts.push(prompt);
|
|
620
|
+
}
|
|
621
|
+
const text = formatWakingPrompt(prompts, remaining.length > 0 ? formatRemainingBatch(remaining, first.text) : void 0);
|
|
622
|
+
if (text) {
|
|
623
|
+
messages[targetIndex] = {
|
|
624
|
+
...messages[targetIndex],
|
|
625
|
+
content: [{
|
|
626
|
+
type: "text",
|
|
627
|
+
text
|
|
628
|
+
}, ...messages[targetIndex].content.slice(1)]
|
|
629
|
+
};
|
|
630
|
+
return next();
|
|
631
|
+
}
|
|
632
|
+
if (messages.length > 1) {
|
|
633
|
+
messages.splice(targetIndex, 1);
|
|
634
|
+
return next();
|
|
635
|
+
}
|
|
636
|
+
return { kind: "reject" };
|
|
637
|
+
});
|
|
638
|
+
ctx.tools.register(defineTool({
|
|
639
|
+
name: "test_schedule_script",
|
|
640
|
+
description: "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.",
|
|
641
|
+
parameters: {
|
|
642
|
+
script_path: {
|
|
643
|
+
type: "string",
|
|
644
|
+
required: true,
|
|
645
|
+
description: "Path to the TypeScript script to test (e.g. .agents/scripts/sync.ts)"
|
|
646
|
+
},
|
|
647
|
+
state: {
|
|
648
|
+
type: "object",
|
|
649
|
+
required: true,
|
|
650
|
+
additionalProperties: true,
|
|
651
|
+
description: "Initial state to test with (mandatory)"
|
|
652
|
+
},
|
|
653
|
+
timeout_ms: {
|
|
654
|
+
type: "number",
|
|
655
|
+
default: 3e4,
|
|
656
|
+
description: "Execution timeout in milliseconds (default: 30000)"
|
|
657
|
+
}
|
|
658
|
+
},
|
|
659
|
+
output: {
|
|
660
|
+
schema: {
|
|
661
|
+
type: "object",
|
|
662
|
+
properties: {
|
|
663
|
+
success: {
|
|
664
|
+
type: "boolean",
|
|
665
|
+
required: true
|
|
666
|
+
},
|
|
667
|
+
message: {
|
|
668
|
+
type: "string",
|
|
669
|
+
required: true
|
|
670
|
+
},
|
|
671
|
+
state: { type: "json" },
|
|
672
|
+
prompt: { type: "string" },
|
|
673
|
+
error: { type: "string" },
|
|
674
|
+
stop: { type: "boolean" },
|
|
675
|
+
duration_ms: { type: "number" }
|
|
676
|
+
},
|
|
677
|
+
additionalProperties: false
|
|
678
|
+
},
|
|
679
|
+
render(_args, val) {
|
|
680
|
+
return [{
|
|
681
|
+
type: "text",
|
|
682
|
+
text: val.message
|
|
683
|
+
}];
|
|
684
|
+
}
|
|
685
|
+
},
|
|
686
|
+
async execute(args, exec) {
|
|
687
|
+
const agent = exec.agent;
|
|
688
|
+
if (!agent) return {
|
|
689
|
+
success: false,
|
|
690
|
+
message: "No active agent session"
|
|
691
|
+
};
|
|
692
|
+
const testState = args.state;
|
|
693
|
+
const timeoutMs = args.timeout_ms ?? 3e4;
|
|
694
|
+
const startTime = Date.now();
|
|
695
|
+
try {
|
|
696
|
+
const result = await executeScript(args.script_path, {
|
|
697
|
+
state: testState,
|
|
698
|
+
sessionId: agent.session.id
|
|
699
|
+
}, timeoutMs, agent.session.header.cwd);
|
|
700
|
+
const durationMs = Date.now() - startTime;
|
|
701
|
+
let summaryMsg = `Test execution succeeded in ${durationMs}ms.`;
|
|
702
|
+
if (result.prompt) summaryMsg += ` Prompt emitted: "${result.prompt}".`;
|
|
703
|
+
else summaryMsg += " Silent poll (no prompt emitted).";
|
|
704
|
+
if (result.error) summaryMsg += ` Recoverable warning: "${result.error}".`;
|
|
705
|
+
if (result.stop) summaryMsg += " Script requested stop.";
|
|
706
|
+
const payload = {
|
|
707
|
+
success: true,
|
|
708
|
+
message: summaryMsg,
|
|
709
|
+
duration_ms: durationMs
|
|
710
|
+
};
|
|
711
|
+
if (result.state !== void 0) payload.state = result.state ?? null;
|
|
712
|
+
if (result.prompt !== void 0) payload.prompt = result.prompt;
|
|
713
|
+
if (result.error !== void 0) payload.error = result.error;
|
|
714
|
+
if (result.stop !== void 0) payload.stop = result.stop;
|
|
715
|
+
return payload;
|
|
716
|
+
} catch (err) {
|
|
717
|
+
const durationMs = Date.now() - startTime;
|
|
718
|
+
const errorMsg = err instanceof Error ? err.message : String(err);
|
|
719
|
+
return {
|
|
720
|
+
success: false,
|
|
721
|
+
message: `Test execution failed (${durationMs}ms): ${errorMsg}`,
|
|
722
|
+
error: errorMsg,
|
|
723
|
+
duration_ms: durationMs
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
}), { when: ({ agent }) => isScheduleScriptActive(agent.session) });
|
|
728
|
+
const creatingSessions = /* @__PURE__ */ new Set();
|
|
729
|
+
ctx.tools.register(defineTool({
|
|
730
|
+
name: "schedule_script",
|
|
731
|
+
description: "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.",
|
|
732
|
+
parameters: {
|
|
733
|
+
script_path: {
|
|
734
|
+
type: "string",
|
|
735
|
+
required: true,
|
|
736
|
+
description: "Absolute or relative path to the TypeScript script (e.g. .agents/scripts/sync.ts)"
|
|
737
|
+
},
|
|
738
|
+
title: {
|
|
739
|
+
type: "string",
|
|
740
|
+
required: true,
|
|
741
|
+
description: "Concise human-readable name for the schedule in the user's language (e.g. 'Sync database every 5m')"
|
|
742
|
+
},
|
|
743
|
+
interval_seconds: {
|
|
744
|
+
type: "number",
|
|
745
|
+
default: 60,
|
|
746
|
+
description: "Recurrence interval in seconds (minimum 60)"
|
|
747
|
+
},
|
|
748
|
+
state: {
|
|
749
|
+
type: "object",
|
|
750
|
+
required: true,
|
|
751
|
+
additionalProperties: true,
|
|
752
|
+
description: "Initial state to pass to the script's main({ state }) (mandatory)"
|
|
753
|
+
}
|
|
754
|
+
},
|
|
755
|
+
output: {
|
|
756
|
+
schema: {
|
|
757
|
+
type: "object",
|
|
758
|
+
properties: {
|
|
759
|
+
success: {
|
|
760
|
+
type: "boolean",
|
|
761
|
+
required: true
|
|
762
|
+
},
|
|
763
|
+
message: {
|
|
764
|
+
type: "string",
|
|
765
|
+
required: true
|
|
766
|
+
}
|
|
767
|
+
},
|
|
768
|
+
additionalProperties: false
|
|
769
|
+
},
|
|
770
|
+
render(_args, val) {
|
|
771
|
+
return [{
|
|
772
|
+
type: "text",
|
|
773
|
+
text: val.message
|
|
774
|
+
}];
|
|
775
|
+
}
|
|
776
|
+
},
|
|
777
|
+
async execute(args, exec) {
|
|
778
|
+
const agent = exec.agent;
|
|
779
|
+
if (!agent) return {
|
|
780
|
+
success: false,
|
|
781
|
+
message: "No active agent session"
|
|
782
|
+
};
|
|
783
|
+
if (creatingSessions.has(agent.session.id)) return {
|
|
784
|
+
success: false,
|
|
785
|
+
message: "A script schedule is already being created for this session."
|
|
786
|
+
};
|
|
787
|
+
creatingSessions.add(agent.session.id);
|
|
788
|
+
try {
|
|
789
|
+
if ((await activeScriptTasks(agent.session.id)).size > 0) return {
|
|
790
|
+
success: false,
|
|
791
|
+
message: "This session already has an active script schedule. Pause or delete it before scheduling another."
|
|
792
|
+
};
|
|
793
|
+
const interval = Math.max(60, Number(args.interval_seconds) || 60);
|
|
794
|
+
const promptText = formatScriptPrompt({
|
|
795
|
+
scriptPath: args.script_path,
|
|
796
|
+
state: args.state
|
|
797
|
+
});
|
|
798
|
+
await ctx.schedule.create({
|
|
799
|
+
title: args.title,
|
|
800
|
+
prompt: promptText,
|
|
801
|
+
timing: {
|
|
802
|
+
kind: "every",
|
|
803
|
+
every_seconds: interval
|
|
804
|
+
},
|
|
805
|
+
target: {
|
|
806
|
+
kind: "session",
|
|
807
|
+
sessionId: agent.session.id
|
|
808
|
+
}
|
|
809
|
+
});
|
|
810
|
+
appendScriptEvent(agent.session, {
|
|
811
|
+
action: "start",
|
|
812
|
+
scriptPath: args.script_path,
|
|
813
|
+
state: args.state,
|
|
814
|
+
timestamp: Date.now()
|
|
815
|
+
}, `start-${Date.now()}`);
|
|
816
|
+
return {
|
|
817
|
+
success: true,
|
|
818
|
+
message: `Scheduled background script '${args.script_path}' every ${interval}s via Automation tasks (Title: ${args.title})`
|
|
819
|
+
};
|
|
820
|
+
} finally {
|
|
821
|
+
creatingSessions.delete(agent.session.id);
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
}), { when: ({ agent }) => isScheduleScriptActive(agent.session) });
|
|
825
|
+
}
|
|
826
|
+
export { SCHEDULE_SCRIPT_EVENT_NAME, SCHEDULE_SCRIPT_KIND, SCHEDULE_SCRIPT_SKILL_CONTENT, SCHEDULE_SCRIPT_SKILL_DESCRIPTION, SCHEDULE_SCRIPT_SKILL_NAME, apply, executeScript, foldScheduleScriptEvent, formatScriptPrompt, initialScheduleScriptSummary, inject, name, scheduleScriptSummarySchema, scheduleSystemStatusSchema, scriptExecutionStatusSchema, toScheduleScriptRecord };
|