@botbotgo/agent-harness 0.0.475 → 0.0.476

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.
Files changed (227) hide show
  1. package/README.md +3 -1234
  2. package/README.zh.md +3 -1191
  3. package/dist/acp.js +1 -1
  4. package/dist/api.js +1 -404
  5. package/dist/benchmark/checkpoint-resume-cost-benchmark.js +1 -55
  6. package/dist/benchmark/deepagent-local-model-benchmark.js +2 -35
  7. package/dist/benchmark/upstream-runtime-ab-benchmark.js +1 -179
  8. package/dist/cli/chat-interactive.js +25 -244
  9. package/dist/cli/chat-rendering.js +6 -100
  10. package/dist/cli/chat-stream.js +23 -512
  11. package/dist/cli/chat-ui.js +21 -199
  12. package/dist/cli/chat-workspace.js +2 -210
  13. package/dist/cli/main.js +21 -428
  14. package/dist/cli/managed-service-commands.js +9 -63
  15. package/dist/cli/managed-service.js +2 -137
  16. package/dist/cli/options-init-chat.js +1 -108
  17. package/dist/cli/options-runtime.js +1 -158
  18. package/dist/cli/options-serve.js +1 -282
  19. package/dist/cli/options.js +2 -19
  20. package/dist/cli/process-guards.js +1 -139
  21. package/dist/cli/request-tree.js +7 -296
  22. package/dist/cli/runtime-commands.js +12 -258
  23. package/dist/cli/runtime-output.js +16 -155
  24. package/dist/cli/server-commands.js +16 -270
  25. package/dist/cli/workspace.js +1 -67
  26. package/dist/cli.js +1 -7
  27. package/dist/client/acp.js +1 -1
  28. package/dist/client/in-process.js +1 -67
  29. package/dist/client/index.js +1 -2
  30. package/dist/client/types.js +0 -1
  31. package/dist/client.js +1 -1
  32. package/dist/contracts/core.js +1 -1
  33. package/dist/contracts/runtime-evaluation.js +0 -1
  34. package/dist/contracts/runtime-memory.js +0 -1
  35. package/dist/contracts/runtime-observability.js +0 -1
  36. package/dist/contracts/runtime-requests.js +0 -1
  37. package/dist/contracts/runtime-scheduling.js +0 -1
  38. package/dist/contracts/runtime.js +1 -27
  39. package/dist/contracts/types.js +1 -3
  40. package/dist/contracts/workspace.js +0 -1
  41. package/dist/flow/build-flow-graph.js +1 -50
  42. package/dist/flow/export-mermaid.js +2 -464
  43. package/dist/flow/export-sequence-mermaid.js +2 -325
  44. package/dist/flow/flow-graph-normalization.js +1 -214
  45. package/dist/flow/flow-graph-runtime.js +1 -107
  46. package/dist/flow/flow-graph-upstream.js +1 -494
  47. package/dist/flow/index.js +1 -3
  48. package/dist/flow/types.js +0 -1
  49. package/dist/index.js +1 -5
  50. package/dist/init-project.js +1 -1
  51. package/dist/knowledge/config.js +1 -32
  52. package/dist/knowledge/contracts.js +0 -1
  53. package/dist/knowledge/index.js +1 -2
  54. package/dist/knowledge/module.js +12 -909
  55. package/dist/knowledge/procedural/config.js +1 -125
  56. package/dist/knowledge/procedural/index.js +1 -2
  57. package/dist/knowledge/procedural/manager.js +9 -345
  58. package/dist/mcp.js +1 -2
  59. package/dist/package-version.d.ts +1 -1
  60. package/dist/package-version.js +1 -2
  61. package/dist/persistence/file-store.js +3 -758
  62. package/dist/persistence/sqlite-request-context-store.js +5 -54
  63. package/dist/persistence/sqlite-request-queue-store.js +10 -108
  64. package/dist/persistence/sqlite-runtime.js +1 -86
  65. package/dist/persistence/sqlite-store.js +62 -810
  66. package/dist/persistence/types.js +0 -1
  67. package/dist/projections/presentation.js +37 -206
  68. package/dist/projections/request-events.js +2 -502
  69. package/dist/projections/upstream-events.js +1 -201
  70. package/dist/protocol/a2a/http-discovery.js +1 -178
  71. package/dist/protocol/a2a/http-rpc.js +6 -622
  72. package/dist/protocol/a2a/http.js +1 -138
  73. package/dist/protocol/a2a/task-state.js +3 -317
  74. package/dist/protocol/acp/client.js +8 -294
  75. package/dist/protocol/acp/harness-client.js +1 -218
  76. package/dist/protocol/acp/http.js +5 -130
  77. package/dist/protocol/acp/server.js +1 -310
  78. package/dist/protocol/acp/stdio.js +2 -69
  79. package/dist/protocol/ag-ui/http.js +3 -378
  80. package/dist/protocol/mcp/server.js +1 -428
  81. package/dist/resource/backend/workspace-scoped-backend.js +1 -319
  82. package/dist/resource/isolation.js +1 -237
  83. package/dist/resource/mcp/tool-support.js +3 -296
  84. package/dist/resource/mcp-tool-support.js +1 -2
  85. package/dist/resource/providers/resource-provider.js +1 -215
  86. package/dist/resource/resource-impl.js +1 -3
  87. package/dist/resource/resource-types.js +0 -1
  88. package/dist/resource/resource.js +1 -1
  89. package/dist/resource/sources.js +1 -247
  90. package/dist/resource/tools/function-tool-resolver.js +2 -272
  91. package/dist/runtime/adapter/compat/deepagent-compat.js +1 -29
  92. package/dist/runtime/adapter/compat/openai-compatible.js +1 -55
  93. package/dist/runtime/adapter/direct-builtin-utility.js +2 -90
  94. package/dist/runtime/adapter/flow/execution-context.js +1 -71
  95. package/dist/runtime/adapter/flow/invocation-flow.js +8 -425
  96. package/dist/runtime/adapter/flow/invoke-runtime.js +1 -20
  97. package/dist/runtime/adapter/flow/stream-runtime.js +11 -1395
  98. package/dist/runtime/adapter/invocation-result.js +2 -473
  99. package/dist/runtime/adapter/local-tool-invocation.js +6 -638
  100. package/dist/runtime/adapter/middleware/context-hygiene.js +1 -83
  101. package/dist/runtime/adapter/middleware-assembly.js +5 -477
  102. package/dist/runtime/adapter/model/invocation-request.js +3 -183
  103. package/dist/runtime/adapter/model/message-assembly.js +1 -28
  104. package/dist/runtime/adapter/model/model-providers.js +23 -1115
  105. package/dist/runtime/adapter/model/prompted-json-tool-call-capture.js +1 -40
  106. package/dist/runtime/adapter/model/prompted-json-tool-policy.js +1 -22
  107. package/dist/runtime/adapter/resilience.js +1 -104
  108. package/dist/runtime/adapter/runtime-adapter-support.js +3 -141
  109. package/dist/runtime/adapter/runtime-shell.js +5 -166
  110. package/dist/runtime/adapter/stream-event-projection.js +2 -622
  111. package/dist/runtime/adapter/stream-text-consumption.js +1 -18
  112. package/dist/runtime/adapter/terminal-status.js +2 -67
  113. package/dist/runtime/adapter/tool/builtin-middleware-tools.js +6 -627
  114. package/dist/runtime/adapter/tool/declared-middleware.js +1 -154
  115. package/dist/runtime/adapter/tool/interrupt-policy.js +1 -34
  116. package/dist/runtime/adapter/tool/provider-tool.js +1 -25
  117. package/dist/runtime/adapter/tool/resolved-tool.js +1 -225
  118. package/dist/runtime/adapter/tool/tool-arguments.js +3 -486
  119. package/dist/runtime/adapter/tool/tool-hitl.js +1 -346
  120. package/dist/runtime/adapter/tool/tool-name-mapping.js +1 -128
  121. package/dist/runtime/adapter/tool/tool-output-artifacts.js +2 -88
  122. package/dist/runtime/adapter/tool/tool-replay.js +1 -37
  123. package/dist/runtime/adapter/tool-resolution.js +1 -86
  124. package/dist/runtime/adapter/upstream-configurable-keys.js +1 -2
  125. package/dist/runtime/agent-runtime-adapter.js +60 -2338
  126. package/dist/runtime/agent-runtime-assembly.js +7 -249
  127. package/dist/runtime/env/runtime-env.js +1 -62
  128. package/dist/runtime/harness/background-runtime.js +1 -8
  129. package/dist/runtime/harness/bindings.js +1 -58
  130. package/dist/runtime/harness/events/event-bus.js +1 -16
  131. package/dist/runtime/harness/events/event-sink.js +1 -61
  132. package/dist/runtime/harness/events/events.js +1 -80
  133. package/dist/runtime/harness/events/listener-runtime.js +1 -13
  134. package/dist/runtime/harness/events/runtime-event-operations.js +1 -9
  135. package/dist/runtime/harness/events/streaming.js +1 -100
  136. package/dist/runtime/harness/events/timeline.js +1 -52
  137. package/dist/runtime/harness/public-shapes.js +1 -186
  138. package/dist/runtime/harness/run/artifact-paths.js +1 -15
  139. package/dist/runtime/harness/run/governance.js +1 -295
  140. package/dist/runtime/harness/run/helpers.js +1 -71
  141. package/dist/runtime/harness/run/inspection.js +1 -409
  142. package/dist/runtime/harness/run/operator-overview.js +1 -80
  143. package/dist/runtime/harness/run/queue-diagnostics.js +1 -15
  144. package/dist/runtime/harness/run/recovery.js +1 -162
  145. package/dist/runtime/harness/run/resources.js +1 -60
  146. package/dist/runtime/harness/run/resume.js +1 -56
  147. package/dist/runtime/harness/run/routing.js +1 -48
  148. package/dist/runtime/harness/run/run-lifecycle.js +1 -66
  149. package/dist/runtime/harness/run/run-operations.js +1 -217
  150. package/dist/runtime/harness/run/run-queue.js +1 -43
  151. package/dist/runtime/harness/run/run-slot-acquisition.js +1 -157
  152. package/dist/runtime/harness/run/session-records.js +1 -97
  153. package/dist/runtime/harness/run/start-run.js +1 -120
  154. package/dist/runtime/harness/run/startup-runtime.js +1 -69
  155. package/dist/runtime/harness/run/stream-run.js +8 -1418
  156. package/dist/runtime/harness/run/surface-semantics.js +1 -79
  157. package/dist/runtime/harness/runtime-defaults.js +1 -39
  158. package/dist/runtime/harness/system/boundary-analysis.js +1 -234
  159. package/dist/runtime/harness/system/health-monitor.js +1 -258
  160. package/dist/runtime/harness/system/inventory.js +1 -129
  161. package/dist/runtime/harness/system/mem0-ingestion-sync.js +5 -345
  162. package/dist/runtime/harness/system/policy-engine.js +1 -175
  163. package/dist/runtime/harness/system/runtime-memory-candidates.js +4 -110
  164. package/dist/runtime/harness/system/runtime-memory-consolidation.js +1 -51
  165. package/dist/runtime/harness/system/runtime-memory-manager.js +10 -693
  166. package/dist/runtime/harness/system/runtime-memory-policy.js +1 -155
  167. package/dist/runtime/harness/system/runtime-memory-records.js +11 -577
  168. package/dist/runtime/harness/system/runtime-memory-sync.js +5 -206
  169. package/dist/runtime/harness/system/session-memory-sync.js +3 -113
  170. package/dist/runtime/harness/system/skill-requirements.js +1 -112
  171. package/dist/runtime/harness/system/store.js +9 -365
  172. package/dist/runtime/harness/tool-gateway/index.js +1 -2
  173. package/dist/runtime/harness/tool-gateway/policy.js +1 -45
  174. package/dist/runtime/harness/tool-gateway/validation.js +1 -176
  175. package/dist/runtime/harness/tool-schema.js +1 -3
  176. package/dist/runtime/harness.js +3 -1490
  177. package/dist/runtime/index.js +1 -3
  178. package/dist/runtime/layout/runtime-layout.js +1 -31
  179. package/dist/runtime/maintenance/checkpoint-maintenance.js +2 -178
  180. package/dist/runtime/maintenance/file-checkpoint-saver.js +1 -106
  181. package/dist/runtime/maintenance/runtime-record-maintenance.js +2 -169
  182. package/dist/runtime/maintenance/sqlite-checkpoint-saver.js +4 -289
  183. package/dist/runtime/parsing/output-content.js +10 -550
  184. package/dist/runtime/parsing/output-parsing.js +1 -4
  185. package/dist/runtime/parsing/output-recovery.js +3 -213
  186. package/dist/runtime/parsing/output-tool-args.js +7 -663
  187. package/dist/runtime/parsing/stream-event-parsing.js +3 -362
  188. package/dist/runtime/prompts/runtime-prompts.js +4 -73
  189. package/dist/runtime/scheduling/system-schedule-manager.js +11 -532
  190. package/dist/runtime/skills/skill-metadata.js +1 -197
  191. package/dist/runtime/startup-tracing.js +2 -37
  192. package/dist/runtime/support/compiled-binding.js +1 -290
  193. package/dist/runtime/support/embedding-models.js +1 -118
  194. package/dist/runtime/support/harness-support.js +5 -137
  195. package/dist/runtime/support/llamaindex.js +1 -108
  196. package/dist/runtime/support/runtime-adapter-options.js +1 -29
  197. package/dist/runtime/support/runtime-factories.js +1 -51
  198. package/dist/runtime/support/vector-stores.js +9 -270
  199. package/dist/scaffold/init-project.js +54 -233
  200. package/dist/tooling/extensions.js +1 -311
  201. package/dist/tooling/module-loader.js +1 -55
  202. package/dist/tools.js +1 -176
  203. package/dist/utils/agent-display.js +1 -18
  204. package/dist/utils/bundled-text.js +4 -39
  205. package/dist/utils/compiled-binding.js +1 -33
  206. package/dist/utils/fs.js +2 -45
  207. package/dist/utils/id.js +1 -9
  208. package/dist/utils/message-content.js +1 -30
  209. package/dist/utils/object.js +1 -6
  210. package/dist/workspace/agent-binding-compiler.js +3 -613
  211. package/dist/workspace/compile.js +1 -472
  212. package/dist/workspace/framework-contract-validation.js +2 -322
  213. package/dist/workspace/index.js +1 -1
  214. package/dist/workspace/object-loader-paths.js +1 -71
  215. package/dist/workspace/object-loader-readers.js +1 -187
  216. package/dist/workspace/object-loader.js +1 -754
  217. package/dist/workspace/resource-compilers.js +1 -374
  218. package/dist/workspace/support/agent-capabilities.js +1 -37
  219. package/dist/workspace/support/agent-execution-config.js +1 -44
  220. package/dist/workspace/support/discovery.js +1 -147
  221. package/dist/workspace/support/source-collectors.js +1 -30
  222. package/dist/workspace/support/source-protocols.js +2 -192
  223. package/dist/workspace/support/workspace-ref-utils.js +1 -362
  224. package/dist/workspace/tool-hydration.js +1 -280
  225. package/dist/workspace/validate.js +1 -99
  226. package/dist/workspace/yaml-object-reader.js +1 -285
  227. package/package.json +7 -3
@@ -1,532 +1,11 @@
1
- import { mkdir, readFile, readdir, rm, writeFile } from "node:fs/promises";
2
- import { existsSync } from "node:fs";
3
- import os from "node:os";
4
- import path from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { createPersistentId } from "../../utils/id.js";
7
- const MANAGED_PREFIX = "agent-harness";
8
- const SCHEDULES_DIR = "schedules";
9
- const CRON_BEGIN_PREFIX = "# agent-harness schedule begin ";
10
- const CRON_END_PREFIX = "# agent-harness schedule end ";
11
- const WEEKDAY_ORDER = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"];
12
- function shellEscapePosix(value) {
13
- return `'${value.replaceAll("'", `'\"'\"'`)}'`;
14
- }
15
- function shellEscapeWindows(value) {
16
- return `"${value.replaceAll('"', '\\"')}"`;
17
- }
18
- function resolveFrameworkRoot() {
19
- return path.resolve(fileURLToPath(new URL("../../..", import.meta.url)));
20
- }
21
- function resolveDefaultCliPath() {
22
- const frameworkRoot = resolveFrameworkRoot();
23
- const distCliPath = path.join(frameworkRoot, "dist", "cli.js");
24
- if (existsSync(distCliPath)) {
25
- return distCliPath;
26
- }
27
- throw new Error(`System scheduling requires a built CLI at ${distCliPath}. Run the build before creating schedules.`);
28
- }
29
- async function defaultRunCommand(command, args, options = {}) {
30
- const { spawn } = await import("node:child_process");
31
- return new Promise((resolve, reject) => {
32
- const child = spawn(command, args, {
33
- stdio: ["pipe", "pipe", "pipe"],
34
- });
35
- let stdout = "";
36
- let stderr = "";
37
- child.stdout.on("data", (chunk) => {
38
- stdout += String(chunk);
39
- });
40
- child.stderr.on("data", (chunk) => {
41
- stderr += String(chunk);
42
- });
43
- child.on("error", reject);
44
- child.on("close", (exitCode) => {
45
- resolve({
46
- stdout,
47
- stderr,
48
- exitCode: exitCode ?? 0,
49
- });
50
- });
51
- if (typeof options.input === "string") {
52
- child.stdin.write(options.input);
53
- }
54
- child.stdin.end();
55
- });
56
- }
57
- function parseScheduleTime(value) {
58
- const match = /^(\d{2}):(\d{2})$/.exec(value.trim());
59
- if (!match) {
60
- throw new Error(`Invalid schedule time '${value}'. Use HH:mm.`);
61
- }
62
- const hour = Number.parseInt(match[1], 10);
63
- const minute = Number.parseInt(match[2], 10);
64
- if (hour < 0 || hour > 23 || minute < 0 || minute > 59) {
65
- throw new Error(`Invalid schedule time '${value}'. Use HH:mm.`);
66
- }
67
- return { hour, minute };
68
- }
69
- function normalizeWeeklyDays(days) {
70
- const normalized = Array.from(new Set(days
71
- .map((day) => day.trim().toLowerCase().slice(0, 3))
72
- .filter((day) => WEEKDAY_ORDER.includes(day))));
73
- if (normalized.length === 0) {
74
- throw new Error("Weekly schedules require at least one valid weekday.");
75
- }
76
- return WEEKDAY_ORDER.filter((day) => normalized.includes(day));
77
- }
78
- function validateIntervalMinutes(value) {
79
- if (!Number.isInteger(value) || value <= 0) {
80
- throw new Error("Interval schedules require a positive integer everyMinutes value.");
81
- }
82
- return value;
83
- }
84
- function validateScheduleDefinition(definition, platform) {
85
- if (definition.type === "cron") {
86
- const fields = definition.expression.trim().split(/\s+/u);
87
- if (fields.length !== 5) {
88
- throw new Error(`Invalid cron expression '${definition.expression}'. Expected 5 fields.`);
89
- }
90
- if (platform === "win32") {
91
- throw new Error("Cron expressions are not supported on Windows system schedules.");
92
- }
93
- return {
94
- type: "cron",
95
- expression: fields.join(" "),
96
- };
97
- }
98
- if (definition.type === "interval") {
99
- const everyMinutes = validateIntervalMinutes(definition.everyMinutes);
100
- if (platform !== "win32" && 60 % everyMinutes !== 0) {
101
- throw new Error("Crontab interval schedules currently require everyMinutes to divide evenly into 60.");
102
- }
103
- return {
104
- type: "interval",
105
- everyMinutes,
106
- };
107
- }
108
- const time = parseScheduleTime(definition.time);
109
- if (definition.type === "daily") {
110
- return {
111
- type: "daily",
112
- time: `${String(time.hour).padStart(2, "0")}:${String(time.minute).padStart(2, "0")}`,
113
- };
114
- }
115
- return {
116
- type: "weekly",
117
- time: `${String(time.hour).padStart(2, "0")}:${String(time.minute).padStart(2, "0")}`,
118
- days: normalizeWeeklyDays(definition.days),
119
- };
120
- }
121
- function buildCommandLine(input) {
122
- const quote = input.platform === "win32" ? shellEscapeWindows : shellEscapePosix;
123
- return [
124
- quote(input.nodePath),
125
- quote(input.cliPath),
126
- "runtime",
127
- "scheduled-run",
128
- "--workspace",
129
- quote(input.workspaceRoot),
130
- "--schedule",
131
- quote(input.scheduleId),
132
- ].join(" ");
133
- }
134
- function matchesFilter(record, filter) {
135
- if (!filter) {
136
- return true;
137
- }
138
- if (filter.scheduleId && record.scheduleId !== filter.scheduleId) {
139
- return false;
140
- }
141
- if (filter.name && record.name !== filter.name) {
142
- return false;
143
- }
144
- if (filter.agentId && record.agentId !== filter.agentId) {
145
- return false;
146
- }
147
- if (filter.source && record.source !== filter.source) {
148
- return false;
149
- }
150
- if (filter.status && record.status !== filter.status) {
151
- return false;
152
- }
153
- if (filter.query) {
154
- const query = filter.query.trim().toLowerCase();
155
- const haystack = [
156
- record.scheduleId,
157
- record.name,
158
- record.agentId ?? "",
159
- record.instruction,
160
- record.source,
161
- record.schedule.type,
162
- "everyMinutes" in record.schedule ? String(record.schedule.everyMinutes) : "",
163
- "expression" in record.schedule ? record.schedule.expression : "",
164
- "time" in record.schedule ? record.schedule.time : "",
165
- "days" in record.schedule ? record.schedule.days.join(",") : "",
166
- ].join("\n").toLowerCase();
167
- if (!haystack.includes(query)) {
168
- return false;
169
- }
170
- }
171
- return true;
172
- }
173
- function stringifySchedule(record) {
174
- if (record.schedule.type === "cron") {
175
- return `cron ${record.schedule.expression}`;
176
- }
177
- if (record.schedule.type === "interval") {
178
- return `every ${record.schedule.everyMinutes} minute(s)`;
179
- }
180
- if (record.schedule.type === "daily") {
181
- return `daily ${record.schedule.time}`;
182
- }
183
- return `weekly ${record.schedule.days.join(",")} ${record.schedule.time}`;
184
- }
185
- async function safeReadManifest(filePath) {
186
- try {
187
- return JSON.parse(await readFile(filePath, "utf8"));
188
- }
189
- catch {
190
- return null;
191
- }
192
- }
193
- class CrontabAdapter {
194
- runCommand;
195
- source = "crontab";
196
- constructor(runCommand) {
197
- this.runCommand = runCommand;
198
- }
199
- buildCronExpression(definition) {
200
- if (definition.type === "cron") {
201
- return definition.expression;
202
- }
203
- if (definition.type === "interval") {
204
- return `*/${validateIntervalMinutes(definition.everyMinutes)} * * * *`;
205
- }
206
- const { hour, minute } = parseScheduleTime(definition.time);
207
- if (definition.type === "daily") {
208
- return `${minute} ${hour} * * *`;
209
- }
210
- const days = normalizeWeeklyDays(definition.days).map((day) => WEEKDAY_ORDER.indexOf(day)).join(",");
211
- return `${minute} ${hour} * * ${days}`;
212
- }
213
- scheduleBlock(record, commandLine) {
214
- return [
215
- `${CRON_BEGIN_PREFIX}${record.scheduleId}`,
216
- `${this.buildCronExpression(record.schedule)} ${commandLine}`,
217
- `${CRON_END_PREFIX}${record.scheduleId}`,
218
- ].join("\n");
219
- }
220
- stripScheduleBlock(crontabText, scheduleId) {
221
- const lines = crontabText.split(/\r?\n/u);
222
- const result = [];
223
- let skipping = false;
224
- for (const line of lines) {
225
- if (line === `${CRON_BEGIN_PREFIX}${scheduleId}`) {
226
- skipping = true;
227
- continue;
228
- }
229
- if (line === `${CRON_END_PREFIX}${scheduleId}`) {
230
- skipping = false;
231
- continue;
232
- }
233
- if (!skipping) {
234
- result.push(line);
235
- }
236
- }
237
- return result.join("\n").replace(/\n{3,}/gu, "\n\n").trim();
238
- }
239
- async readCrontab() {
240
- const result = await this.runCommand("crontab", ["-l"]);
241
- if (result.exitCode === 0) {
242
- return result.stdout.trim();
243
- }
244
- const errorText = `${result.stdout}\n${result.stderr}`.toLowerCase();
245
- if (errorText.includes("no crontab")) {
246
- return "";
247
- }
248
- throw new Error(result.stderr.trim() || result.stdout.trim() || "Failed to read crontab.");
249
- }
250
- async writeCrontab(contents) {
251
- const result = await this.runCommand("crontab", ["-"], { input: contents.trim() ? `${contents.trim()}\n` : "" });
252
- if (result.exitCode !== 0) {
253
- throw new Error(result.stderr.trim() || result.stdout.trim() || "Failed to write crontab.");
254
- }
255
- }
256
- async install(record, commandLine) {
257
- const current = await this.readCrontab();
258
- const stripped = this.stripScheduleBlock(current, record.scheduleId);
259
- const next = [stripped, this.scheduleBlock(record, commandLine)].filter((part) => part.trim().length > 0).join("\n\n");
260
- await this.writeCrontab(next);
261
- }
262
- async remove(record) {
263
- const current = await this.readCrontab();
264
- await this.writeCrontab(this.stripScheduleBlock(current, record.scheduleId));
265
- }
266
- async exists(record) {
267
- const current = await this.readCrontab();
268
- return current.includes(`${CRON_BEGIN_PREFIX}${record.scheduleId}`);
269
- }
270
- }
271
- class WindowsTaskSchedulerAdapter {
272
- runCommand;
273
- source = "schtasks";
274
- constructor(runCommand) {
275
- this.runCommand = runCommand;
276
- }
277
- taskName(record) {
278
- return `${MANAGED_PREFIX}-${record.scheduleId}`;
279
- }
280
- createArgs(record, commandLine) {
281
- if (record.schedule.type === "cron") {
282
- throw new Error("Cron expressions are not supported on Windows system schedules.");
283
- }
284
- if (record.schedule.type === "interval") {
285
- return [
286
- "/Create",
287
- "/TN",
288
- this.taskName(record),
289
- "/TR",
290
- commandLine,
291
- "/SC",
292
- "MINUTE",
293
- "/MO",
294
- String(validateIntervalMinutes(record.schedule.everyMinutes)),
295
- "/F",
296
- ];
297
- }
298
- const args = [
299
- "/Create",
300
- "/TN",
301
- this.taskName(record),
302
- "/TR",
303
- commandLine,
304
- "/F",
305
- ];
306
- if (record.schedule.type === "daily") {
307
- args.push("/SC", "DAILY", "/ST", record.schedule.time);
308
- return args;
309
- }
310
- args.push("/SC", "WEEKLY", "/ST", record.schedule.time, "/D", normalizeWeeklyDays(record.schedule.days).map((day) => day.toUpperCase()).join(","));
311
- return args;
312
- }
313
- async install(record, commandLine) {
314
- const result = await this.runCommand("schtasks", this.createArgs(record, commandLine));
315
- if (result.exitCode !== 0) {
316
- throw new Error(result.stderr.trim() || result.stdout.trim() || "Failed to create Windows scheduled task.");
317
- }
318
- }
319
- async remove(record) {
320
- const result = await this.runCommand("schtasks", ["/Delete", "/TN", this.taskName(record), "/F"]);
321
- const output = `${result.stdout}\n${result.stderr}`.toLowerCase();
322
- if (result.exitCode !== 0 && !output.includes("cannot find")) {
323
- throw new Error(result.stderr.trim() || result.stdout.trim() || "Failed to delete Windows scheduled task.");
324
- }
325
- }
326
- async exists(record) {
327
- const result = await this.runCommand("schtasks", ["/Query", "/TN", this.taskName(record)]);
328
- return result.exitCode === 0;
329
- }
330
- }
331
- export class SystemScheduleManager {
332
- options;
333
- schedulesRoot;
334
- platform;
335
- nodePath;
336
- cliPath;
337
- adapter;
338
- constructor(options) {
339
- this.options = options;
340
- this.schedulesRoot = path.join(options.runtimeRoot, SCHEDULES_DIR);
341
- this.platform = options.platform ?? os.platform();
342
- this.nodePath = options.nodePath ?? process.execPath;
343
- this.cliPath = options.cliPath ?? resolveDefaultCliPath();
344
- const runCommand = options.runCommand ?? defaultRunCommand;
345
- this.adapter = this.platform === "win32" ? new WindowsTaskSchedulerAdapter(runCommand) : new CrontabAdapter(runCommand);
346
- }
347
- manifestPath(scheduleId) {
348
- return path.join(this.schedulesRoot, `${scheduleId}.json`);
349
- }
350
- async ensureSchedulesRoot() {
351
- await mkdir(this.schedulesRoot, { recursive: true });
352
- }
353
- async writeManifest(record) {
354
- await this.ensureSchedulesRoot();
355
- await writeFile(this.manifestPath(record.scheduleId), JSON.stringify(record, null, 2), "utf8");
356
- }
357
- toPublicRecord(record, status) {
358
- return {
359
- scheduleId: record.scheduleId,
360
- name: record.name,
361
- instruction: record.instruction,
362
- ...(record.agentId ? { agentId: record.agentId } : {}),
363
- schedule: record.schedule,
364
- source: record.source,
365
- platform: record.platform,
366
- status,
367
- systemId: record.systemId,
368
- createdAt: record.createdAt,
369
- updatedAt: record.updatedAt,
370
- ...(record.metadata ? { metadata: record.metadata } : {}),
371
- };
372
- }
373
- async loadStoredRecord(scheduleId) {
374
- return safeReadManifest(this.manifestPath(scheduleId));
375
- }
376
- async resolveStatus(record) {
377
- return (await this.adapter.exists(record)) ? "active" : "missing";
378
- }
379
- async getSchedule(scheduleId) {
380
- const stored = await this.loadStoredRecord(scheduleId);
381
- if (!stored) {
382
- return null;
383
- }
384
- return this.toPublicRecord(stored, await this.resolveStatus(stored));
385
- }
386
- async listStoredRecords() {
387
- try {
388
- const entries = await readdir(this.schedulesRoot, { withFileTypes: true });
389
- const loaded = await Promise.all(entries
390
- .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))
391
- .map((entry) => safeReadManifest(path.join(this.schedulesRoot, entry.name))));
392
- return loaded.filter((entry) => entry !== null);
393
- }
394
- catch {
395
- return [];
396
- }
397
- }
398
- async createSchedule(input) {
399
- if (!input.name?.trim()) {
400
- throw new Error("schedule_task create requires name.");
401
- }
402
- if (!input.instruction?.trim()) {
403
- throw new Error("schedule_task create requires instruction.");
404
- }
405
- if (!input.schedule) {
406
- throw new Error("schedule_task create requires schedule.");
407
- }
408
- const now = new Date().toISOString();
409
- const scheduleId = `${MANAGED_PREFIX}-${createPersistentId()}`;
410
- const validatedSchedule = validateScheduleDefinition(input.schedule, this.platform);
411
- const stored = {
412
- scheduleId,
413
- name: input.name.trim(),
414
- instruction: input.instruction.trim(),
415
- ...(input.agentId?.trim() ? { agentId: input.agentId.trim() } : {}),
416
- schedule: validatedSchedule,
417
- source: this.adapter.source,
418
- platform: this.platform,
419
- systemId: `${MANAGED_PREFIX}:${scheduleId}`,
420
- createdAt: now,
421
- updatedAt: now,
422
- workspaceRoot: this.options.workspaceRoot,
423
- ...(input.metadata ? { metadata: input.metadata } : {}),
424
- };
425
- const commandLine = buildCommandLine({
426
- platform: this.platform,
427
- nodePath: this.nodePath,
428
- cliPath: this.cliPath,
429
- workspaceRoot: this.options.workspaceRoot,
430
- scheduleId,
431
- });
432
- await this.adapter.install(stored, commandLine);
433
- await this.writeManifest(stored);
434
- return {
435
- ok: true,
436
- operation: "create",
437
- schedule: this.toPublicRecord(stored, "active"),
438
- };
439
- }
440
- async listSchedules(filter) {
441
- const records = await this.listStoredRecords();
442
- const resolved = await Promise.all(records.map(async (record) => this.toPublicRecord(record, await this.resolveStatus(record))));
443
- const items = resolved.filter((record) => matchesFilter(record, filter));
444
- return {
445
- ok: true,
446
- operation: "list",
447
- items,
448
- total: items.length,
449
- };
450
- }
451
- async updateSchedule(input) {
452
- if (!input.scheduleId?.trim()) {
453
- throw new Error("schedule_task update requires scheduleId.");
454
- }
455
- const current = await this.loadStoredRecord(input.scheduleId.trim());
456
- if (!current) {
457
- throw new Error(`Unknown schedule '${input.scheduleId}'.`);
458
- }
459
- const updated = {
460
- ...current,
461
- ...(input.name?.trim() ? { name: input.name.trim() } : {}),
462
- ...(input.instruction?.trim() ? { instruction: input.instruction.trim() } : {}),
463
- ...(input.agentId !== undefined ? { agentId: input.agentId.trim() || undefined } : {}),
464
- ...(input.schedule ? { schedule: validateScheduleDefinition(input.schedule, this.platform) } : {}),
465
- ...(input.metadata !== undefined ? { metadata: input.metadata } : {}),
466
- updatedAt: new Date().toISOString(),
467
- };
468
- const commandLine = buildCommandLine({
469
- platform: this.platform,
470
- nodePath: this.nodePath,
471
- cliPath: this.cliPath,
472
- workspaceRoot: this.options.workspaceRoot,
473
- scheduleId: updated.scheduleId,
474
- });
475
- await this.adapter.install(updated, commandLine);
476
- await this.writeManifest(updated);
477
- return {
478
- ok: true,
479
- operation: "update",
480
- schedule: this.toPublicRecord(updated, "active"),
481
- };
482
- }
483
- async deleteSchedule(input) {
484
- if (!input.scheduleId?.trim()) {
485
- throw new Error("schedule_task delete requires scheduleId.");
486
- }
487
- const current = await this.loadStoredRecord(input.scheduleId.trim());
488
- if (!current) {
489
- throw new Error(`Unknown schedule '${input.scheduleId}'.`);
490
- }
491
- await this.adapter.remove(current);
492
- await rm(this.manifestPath(current.scheduleId), { force: true });
493
- return {
494
- ok: true,
495
- operation: "delete",
496
- scheduleId: current.scheduleId,
497
- };
498
- }
499
- async manageSchedule(input) {
500
- const operation = input.operation ?? "create";
501
- if (operation === "create") {
502
- return this.createSchedule(input);
503
- }
504
- if (operation === "list") {
505
- return this.listSchedules(input.filters);
506
- }
507
- if (operation === "get") {
508
- if (!input.scheduleId?.trim()) {
509
- throw new Error("schedule_task get requires scheduleId.");
510
- }
511
- const schedule = await this.getSchedule(input.scheduleId.trim());
512
- if (!schedule) {
513
- throw new Error(`Unknown schedule '${input.scheduleId}'.`);
514
- }
515
- return {
516
- ok: true,
517
- operation: "get",
518
- schedule,
519
- };
520
- }
521
- if (operation === "update") {
522
- return this.updateSchedule(input);
523
- }
524
- if (operation === "delete") {
525
- return this.deleteSchedule(input);
526
- }
527
- throw new Error(`Unsupported schedule_task operation '${operation}'.`);
528
- }
529
- describeSchedule(record) {
530
- return `${record.scheduleId} ${record.name} ${stringifySchedule(record)} status=${record.status}`;
531
- }
532
- }
1
+ import{mkdir as g,readFile as k,readdir as C,rm as R,writeFile as E}from"node:fs/promises";import{existsSync as v}from"node:fs";import P from"node:os";import u from"node:path";import{fileURLToPath as b}from"node:url";import{createPersistentId as x}from"../../utils/id.js";const d="agent-harness",N="schedules",c="# agent-harness schedule begin ",f="# agent-harness schedule end ",l=["sun","mon","tue","wed","thu","fri","sat"];function A(s){return`'${s.replaceAll("'",`'"'"'`)}'`}function M(s){return`"${s.replaceAll('"','\\"')}"`}function j(){return u.resolve(b(new URL("../../..",import.meta.url)))}function F(){const s=j(),e=u.join(s,"dist","cli.js");if(v(e))return e;throw new Error(`System scheduling requires a built CLI at ${e}. Run the build before creating schedules.`)}async function T(s,e,t={}){const{spawn:r}=await import("node:child_process");return new Promise((a,n)=>{const i=r(s,e,{stdio:["pipe","pipe","pipe"]});let w="",p="";i.stdout.on("data",o=>{w+=String(o)}),i.stderr.on("data",o=>{p+=String(o)}),i.on("error",n),i.on("close",o=>{a({stdout:w,stderr:p,exitCode:o??0})}),typeof t.input=="string"&&i.stdin.write(t.input),i.stdin.end()})}function y(s){const e=/^(\d{2}):(\d{2})$/.exec(s.trim());if(!e)throw new Error(`Invalid schedule time '${s}'. Use HH:mm.`);const t=Number.parseInt(e[1],10),r=Number.parseInt(e[2],10);if(t<0||t>23||r<0||r>59)throw new Error(`Invalid schedule time '${s}'. Use HH:mm.`);return{hour:t,minute:r}}function h(s){const e=Array.from(new Set(s.map(t=>t.trim().toLowerCase().slice(0,3)).filter(t=>l.includes(t))));if(e.length===0)throw new Error("Weekly schedules require at least one valid weekday.");return l.filter(t=>e.includes(t))}function m(s){if(!Number.isInteger(s)||s<=0)throw new Error("Interval schedules require a positive integer everyMinutes value.");return s}function I(s,e){if(s.type==="cron"){const r=s.expression.trim().split(/\s+/u);if(r.length!==5)throw new Error(`Invalid cron expression '${s.expression}'. Expected 5 fields.`);if(e==="win32")throw new Error("Cron expressions are not supported on Windows system schedules.");return{type:"cron",expression:r.join(" ")}}if(s.type==="interval"){const r=m(s.everyMinutes);if(e!=="win32"&&60%r!==0)throw new Error("Crontab interval schedules currently require everyMinutes to divide evenly into 60.");return{type:"interval",everyMinutes:r}}const t=y(s.time);return s.type==="daily"?{type:"daily",time:`${String(t.hour).padStart(2,"0")}:${String(t.minute).padStart(2,"0")}`}:{type:"weekly",time:`${String(t.hour).padStart(2,"0")}:${String(t.minute).padStart(2,"0")}`,days:h(s.days)}}function S(s){const e=s.platform==="win32"?M:A;return[e(s.nodePath),e(s.cliPath),"runtime","scheduled-run","--workspace",e(s.workspaceRoot),"--schedule",e(s.scheduleId)].join(" ")}function q(s,e){if(!e)return!0;if(e.scheduleId&&s.scheduleId!==e.scheduleId||e.name&&s.name!==e.name||e.agentId&&s.agentId!==e.agentId||e.source&&s.source!==e.source||e.status&&s.status!==e.status)return!1;if(e.query){const t=e.query.trim().toLowerCase();if(![s.scheduleId,s.name,s.agentId??"",s.instruction,s.source,s.schedule.type,"everyMinutes"in s.schedule?String(s.schedule.everyMinutes):"","expression"in s.schedule?s.schedule.expression:"","time"in s.schedule?s.schedule.time:"","days"in s.schedule?s.schedule.days.join(","):""].join(`
2
+ `).toLowerCase().includes(t))return!1}return!0}function D(s){return s.schedule.type==="cron"?`cron ${s.schedule.expression}`:s.schedule.type==="interval"?`every ${s.schedule.everyMinutes} minute(s)`:s.schedule.type==="daily"?`daily ${s.schedule.time}`:`weekly ${s.schedule.days.join(",")} ${s.schedule.time}`}async function $(s){try{return JSON.parse(await k(s,"utf8"))}catch{return null}}class _{runCommand;source="crontab";constructor(e){this.runCommand=e}buildCronExpression(e){if(e.type==="cron")return e.expression;if(e.type==="interval")return`*/${m(e.everyMinutes)} * * * *`;const{hour:t,minute:r}=y(e.time);if(e.type==="daily")return`${r} ${t} * * *`;const a=h(e.days).map(n=>l.indexOf(n)).join(",");return`${r} ${t} * * ${a}`}scheduleBlock(e,t){return[`${c}${e.scheduleId}`,`${this.buildCronExpression(e.schedule)} ${t}`,`${f}${e.scheduleId}`].join(`
3
+ `)}stripScheduleBlock(e,t){const r=e.split(/\r?\n/u),a=[];let n=!1;for(const i of r){if(i===`${c}${t}`){n=!0;continue}if(i===`${f}${t}`){n=!1;continue}n||a.push(i)}return a.join(`
4
+ `).replace(/\n{3,}/gu,`
5
+
6
+ `).trim()}async readCrontab(){const e=await this.runCommand("crontab",["-l"]);if(e.exitCode===0)return e.stdout.trim();if(`${e.stdout}
7
+ ${e.stderr}`.toLowerCase().includes("no crontab"))return"";throw new Error(e.stderr.trim()||e.stdout.trim()||"Failed to read crontab.")}async writeCrontab(e){const t=await this.runCommand("crontab",["-"],{input:e.trim()?`${e.trim()}
8
+ `:""});if(t.exitCode!==0)throw new Error(t.stderr.trim()||t.stdout.trim()||"Failed to write crontab.")}async install(e,t){const r=await this.readCrontab(),n=[this.stripScheduleBlock(r,e.scheduleId),this.scheduleBlock(e,t)].filter(i=>i.trim().length>0).join(`
9
+
10
+ `);await this.writeCrontab(n)}async remove(e){const t=await this.readCrontab();await this.writeCrontab(this.stripScheduleBlock(t,e.scheduleId))}async exists(e){return(await this.readCrontab()).includes(`${c}${e.scheduleId}`)}}class L{runCommand;source="schtasks";constructor(e){this.runCommand=e}taskName(e){return`${d}-${e.scheduleId}`}createArgs(e,t){if(e.schedule.type==="cron")throw new Error("Cron expressions are not supported on Windows system schedules.");if(e.schedule.type==="interval")return["/Create","/TN",this.taskName(e),"/TR",t,"/SC","MINUTE","/MO",String(m(e.schedule.everyMinutes)),"/F"];const r=["/Create","/TN",this.taskName(e),"/TR",t,"/F"];return e.schedule.type==="daily"?(r.push("/SC","DAILY","/ST",e.schedule.time),r):(r.push("/SC","WEEKLY","/ST",e.schedule.time,"/D",h(e.schedule.days).map(a=>a.toUpperCase()).join(",")),r)}async install(e,t){const r=await this.runCommand("schtasks",this.createArgs(e,t));if(r.exitCode!==0)throw new Error(r.stderr.trim()||r.stdout.trim()||"Failed to create Windows scheduled task.")}async remove(e){const t=await this.runCommand("schtasks",["/Delete","/TN",this.taskName(e),"/F"]),r=`${t.stdout}
11
+ ${t.stderr}`.toLowerCase();if(t.exitCode!==0&&!r.includes("cannot find"))throw new Error(t.stderr.trim()||t.stdout.trim()||"Failed to delete Windows scheduled task.")}async exists(e){return(await this.runCommand("schtasks",["/Query","/TN",this.taskName(e)])).exitCode===0}}class Y{options;schedulesRoot;platform;nodePath;cliPath;adapter;constructor(e){this.options=e,this.schedulesRoot=u.join(e.runtimeRoot,N),this.platform=e.platform??P.platform(),this.nodePath=e.nodePath??process.execPath,this.cliPath=e.cliPath??F();const t=e.runCommand??T;this.adapter=this.platform==="win32"?new L(t):new _(t)}manifestPath(e){return u.join(this.schedulesRoot,`${e}.json`)}async ensureSchedulesRoot(){await g(this.schedulesRoot,{recursive:!0})}async writeManifest(e){await this.ensureSchedulesRoot(),await E(this.manifestPath(e.scheduleId),JSON.stringify(e,null,2),"utf8")}toPublicRecord(e,t){return{scheduleId:e.scheduleId,name:e.name,instruction:e.instruction,...e.agentId?{agentId:e.agentId}:{},schedule:e.schedule,source:e.source,platform:e.platform,status:t,systemId:e.systemId,createdAt:e.createdAt,updatedAt:e.updatedAt,...e.metadata?{metadata:e.metadata}:{}}}async loadStoredRecord(e){return $(this.manifestPath(e))}async resolveStatus(e){return await this.adapter.exists(e)?"active":"missing"}async getSchedule(e){const t=await this.loadStoredRecord(e);return t?this.toPublicRecord(t,await this.resolveStatus(t)):null}async listStoredRecords(){try{const e=await C(this.schedulesRoot,{withFileTypes:!0});return(await Promise.all(e.filter(r=>r.isFile()&&r.name.endsWith(".json")).map(r=>$(u.join(this.schedulesRoot,r.name))))).filter(r=>r!==null)}catch{return[]}}async createSchedule(e){if(!e.name?.trim())throw new Error("schedule_task create requires name.");if(!e.instruction?.trim())throw new Error("schedule_task create requires instruction.");if(!e.schedule)throw new Error("schedule_task create requires schedule.");const t=new Date().toISOString(),r=`${d}-${x()}`,a=I(e.schedule,this.platform),n={scheduleId:r,name:e.name.trim(),instruction:e.instruction.trim(),...e.agentId?.trim()?{agentId:e.agentId.trim()}:{},schedule:a,source:this.adapter.source,platform:this.platform,systemId:`${d}:${r}`,createdAt:t,updatedAt:t,workspaceRoot:this.options.workspaceRoot,...e.metadata?{metadata:e.metadata}:{}},i=S({platform:this.platform,nodePath:this.nodePath,cliPath:this.cliPath,workspaceRoot:this.options.workspaceRoot,scheduleId:r});return await this.adapter.install(n,i),await this.writeManifest(n),{ok:!0,operation:"create",schedule:this.toPublicRecord(n,"active")}}async listSchedules(e){const t=await this.listStoredRecords(),a=(await Promise.all(t.map(async n=>this.toPublicRecord(n,await this.resolveStatus(n))))).filter(n=>q(n,e));return{ok:!0,operation:"list",items:a,total:a.length}}async updateSchedule(e){if(!e.scheduleId?.trim())throw new Error("schedule_task update requires scheduleId.");const t=await this.loadStoredRecord(e.scheduleId.trim());if(!t)throw new Error(`Unknown schedule '${e.scheduleId}'.`);const r={...t,...e.name?.trim()?{name:e.name.trim()}:{},...e.instruction?.trim()?{instruction:e.instruction.trim()}:{},...e.agentId!==void 0?{agentId:e.agentId.trim()||void 0}:{},...e.schedule?{schedule:I(e.schedule,this.platform)}:{},...e.metadata!==void 0?{metadata:e.metadata}:{},updatedAt:new Date().toISOString()},a=S({platform:this.platform,nodePath:this.nodePath,cliPath:this.cliPath,workspaceRoot:this.options.workspaceRoot,scheduleId:r.scheduleId});return await this.adapter.install(r,a),await this.writeManifest(r),{ok:!0,operation:"update",schedule:this.toPublicRecord(r,"active")}}async deleteSchedule(e){if(!e.scheduleId?.trim())throw new Error("schedule_task delete requires scheduleId.");const t=await this.loadStoredRecord(e.scheduleId.trim());if(!t)throw new Error(`Unknown schedule '${e.scheduleId}'.`);return await this.adapter.remove(t),await R(this.manifestPath(t.scheduleId),{force:!0}),{ok:!0,operation:"delete",scheduleId:t.scheduleId}}async manageSchedule(e){const t=e.operation??"create";if(t==="create")return this.createSchedule(e);if(t==="list")return this.listSchedules(e.filters);if(t==="get"){if(!e.scheduleId?.trim())throw new Error("schedule_task get requires scheduleId.");const r=await this.getSchedule(e.scheduleId.trim());if(!r)throw new Error(`Unknown schedule '${e.scheduleId}'.`);return{ok:!0,operation:"get",schedule:r}}if(t==="update")return this.updateSchedule(e);if(t==="delete")return this.deleteSchedule(e);throw new Error(`Unsupported schedule_task operation '${t}'.`)}describeSchedule(e){return`${e.scheduleId} ${e.name} ${D(e)} status=${e.status}`}}export{Y as SystemScheduleManager};