@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.
@@ -0,0 +1,101 @@
1
+ import { execFile } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { mkdtempDisposable, readFile, writeFile } from "node:fs/promises";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { promisify } from "node:util";
8
+ import type { ScriptContext, ScriptResult } from "./types.ts";
9
+
10
+ const execFileAsync = promisify(execFile);
11
+
12
+ function resolveRunnerCliPath(): string {
13
+ const direct = fileURLToPath(new URL("./runner-cli.ts", import.meta.url));
14
+ if (existsSync(direct)) return direct;
15
+ const fromDist = fileURLToPath(
16
+ new URL("../src/runner-cli.ts", import.meta.url),
17
+ );
18
+ if (existsSync(fromDist)) return fromDist;
19
+ return direct;
20
+ }
21
+
22
+ const RUNNER_CLI_PATH = resolveRunnerCliPath();
23
+
24
+ async function readRunnerOutput(
25
+ outputPath: string,
26
+ ): Promise<
27
+ | { success: true; result: ScriptResult }
28
+ | { success: false; error: string; stack?: string }
29
+ | null
30
+ > {
31
+ try {
32
+ const rawOutput = await readFile(outputPath, "utf8");
33
+ return JSON.parse(rawOutput);
34
+ } catch (err: unknown) {
35
+ if (
36
+ typeof err === "object" &&
37
+ err !== null &&
38
+ "code" in err &&
39
+ (err as NodeJS.ErrnoException).code === "ENOENT"
40
+ ) {
41
+ return null;
42
+ }
43
+ throw err;
44
+ }
45
+ }
46
+
47
+ export async function executeScript(
48
+ scriptPath: string,
49
+ ctx: ScriptContext,
50
+ timeoutMs = 30000,
51
+ cwd = process.cwd(),
52
+ signal?: AbortSignal,
53
+ ): Promise<ScriptResult> {
54
+ await using tmp = await mkdtempDisposable(
55
+ path.join(os.tmpdir(), "dsh-script-"),
56
+ );
57
+ const inputPath = path.join(tmp.path, "input.json");
58
+ const outputPath = path.join(tmp.path, "output.json");
59
+
60
+ await writeFile(inputPath, JSON.stringify(ctx), "utf8");
61
+
62
+ try {
63
+ await execFileAsync(
64
+ process.execPath,
65
+ [RUNNER_CLI_PATH, scriptPath, inputPath, outputPath],
66
+ {
67
+ signal,
68
+ timeout: timeoutMs,
69
+ cwd,
70
+ env: { ...process.env },
71
+ },
72
+ );
73
+
74
+ const data = await readRunnerOutput(outputPath);
75
+ if (!data || !data.success) {
76
+ throw new Error(data?.error ?? "Runner failed to produce output");
77
+ }
78
+
79
+ return data.result;
80
+ } catch (error: unknown) {
81
+ const fallbackOutput = await readRunnerOutput(outputPath).catch(() => null);
82
+ if (fallbackOutput && !fallbackOutput.success && fallbackOutput.error) {
83
+ const err = new Error(fallbackOutput.error, { cause: error });
84
+ if (fallbackOutput.stack) {
85
+ err.stack = fallbackOutput.stack;
86
+ }
87
+ throw err;
88
+ }
89
+
90
+ if (error instanceof Error) {
91
+ if ("killed" in error && (error as { killed?: boolean }).killed) {
92
+ throw new Error(
93
+ `Script execution timed out after ${timeoutMs}ms: ${scriptPath}`,
94
+ { cause: error },
95
+ );
96
+ }
97
+ throw error;
98
+ }
99
+ throw new Error(String(error), { cause: error });
100
+ }
101
+ }
package/src/fold.ts ADDED
@@ -0,0 +1,154 @@
1
+ import type { SessionEvent } from "@deepseek-ai/dsh-session";
2
+ import { SCHEDULE_SCRIPT_SKILL_NAME } from "./skill.ts";
3
+ import {
4
+ SCHEDULE_SCRIPT_EVENT_NAME,
5
+ type ScheduleScriptEventPayload,
6
+ type ScheduleScriptSummary,
7
+ } from "./types.ts";
8
+
9
+ export function initialScheduleScriptSummary(): ScheduleScriptSummary {
10
+ return {
11
+ scriptStatus: "idle",
12
+ skillInvoked: false,
13
+ totalRuns: 0,
14
+ };
15
+ }
16
+
17
+ export function foldScheduleScriptEvent(
18
+ state: ScheduleScriptSummary,
19
+ event: SessionEvent,
20
+ ): ScheduleScriptSummary {
21
+ if (event.type === "tool/call") {
22
+ if (event.data.name === "skill") {
23
+ try {
24
+ const raw =
25
+ (event.data as { arguments?: unknown; args?: unknown }).arguments ??
26
+ (event.data as { arguments?: unknown; args?: unknown }).args;
27
+ const parsed = typeof raw === "string" ? JSON.parse(raw) : raw;
28
+ if (
29
+ parsed &&
30
+ typeof parsed === "object" &&
31
+ (parsed as { name?: string }).name === SCHEDULE_SCRIPT_SKILL_NAME
32
+ ) {
33
+ if (state.skillInvoked) return state;
34
+ return {
35
+ ...state,
36
+ skillInvoked: true,
37
+ };
38
+ }
39
+ } catch {
40
+ // ignore malformed arguments
41
+ }
42
+ }
43
+ return state;
44
+ }
45
+ if (event.type !== "command/run") return state;
46
+ if (
47
+ event.data.name !== SCHEDULE_SCRIPT_EVENT_NAME ||
48
+ typeof event.data.args !== "string"
49
+ ) {
50
+ return state;
51
+ }
52
+
53
+ try {
54
+ const payload = JSON.parse(event.data.args) as ScheduleScriptEventPayload;
55
+ if (payload.action === "skill") {
56
+ return {
57
+ ...state,
58
+ skillInvoked: true,
59
+ };
60
+ }
61
+ if (payload.action === "start") {
62
+ const {
63
+ lastError: _,
64
+ scheduleId: _id,
65
+ cleanupPending: _pending,
66
+ cleanupError: _cleanup,
67
+ ...rest
68
+ } = state;
69
+ return {
70
+ ...rest,
71
+ scriptStatus: "idle",
72
+ scriptPath: payload.scriptPath,
73
+ state: payload.state,
74
+ };
75
+ }
76
+ if (payload.action === "iteration") {
77
+ const { lastError: _, ...rest } = state;
78
+ const next: ScheduleScriptSummary = {
79
+ ...rest,
80
+ scriptStatus: payload.error ? "warning" : "idle",
81
+ scriptPath: payload.scriptPath,
82
+ totalRuns: state.totalRuns + 1,
83
+ lastRunAt: payload.timestamp,
84
+ lastDurationMs: payload.durationMs,
85
+ };
86
+ if (payload.scheduleId !== undefined)
87
+ next.scheduleId = payload.scheduleId;
88
+ if (payload.state !== undefined) {
89
+ next.state = payload.state;
90
+ }
91
+ if (payload.prompt) {
92
+ next.lastPrompt = {
93
+ message: payload.prompt,
94
+ timestamp: payload.timestamp,
95
+ };
96
+ }
97
+ if (payload.error) {
98
+ next.lastError = {
99
+ message: payload.error,
100
+ timestamp: payload.timestamp,
101
+ fatal: false,
102
+ };
103
+ }
104
+ return next;
105
+ }
106
+ if (payload.action === "error") {
107
+ return {
108
+ ...state,
109
+ scriptStatus: payload.fatal === false ? "warning" : "error",
110
+ ...(payload.scheduleId !== undefined
111
+ ? { scheduleId: payload.scheduleId }
112
+ : {}),
113
+ scriptPath: payload.scriptPath,
114
+ lastError: {
115
+ message: payload.error,
116
+ timestamp: payload.timestamp,
117
+ fatal: payload.fatal !== false,
118
+ },
119
+ };
120
+ }
121
+ if (payload.action === "stop") {
122
+ return {
123
+ ...state,
124
+ scriptStatus: state.scriptStatus === "error" ? "error" : "stopped",
125
+ cleanupPending: true,
126
+ ...(payload.scheduleId !== undefined
127
+ ? { scheduleId: payload.scheduleId }
128
+ : {}),
129
+ };
130
+ }
131
+ if (payload.action === "cleanup") {
132
+ const { cleanupError: _, ...rest } = state;
133
+ return {
134
+ ...rest,
135
+ cleanupPending: payload.error !== undefined,
136
+ ...(payload.error !== undefined ? { cleanupError: payload.error } : {}),
137
+ };
138
+ }
139
+ } catch {
140
+ // ignore malformed payloads
141
+ }
142
+
143
+ return state;
144
+ }
145
+
146
+ export function toScheduleScriptRecord(
147
+ summary: ScheduleScriptSummary,
148
+ ): ScheduleScriptSummary | null {
149
+ return summary.skillInvoked ||
150
+ summary.totalRuns > 0 ||
151
+ summary.scriptPath !== undefined
152
+ ? summary
153
+ : null;
154
+ }