deployontime 0.0.0-stage → 0.1.0
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 +661 -0
- package/README.md +259 -2
- package/SECURITY.md +61 -0
- package/mcp/jobs.mjs +137 -0
- package/mcp/runner.mjs +64 -0
- package/mcp/server.mjs +209 -0
- package/mcp/tools.mjs +380 -0
- package/package.json +47 -4
- package/queue/README.md +880 -0
- package/queue/args.mjs +136 -0
- package/queue/cli.mjs +207 -0
- package/queue/clock.mjs +49 -0
- package/queue/commands.mjs +35 -0
- package/queue/failstop.mjs +45 -0
- package/queue/files.mjs +71 -0
- package/queue/fingerprint.mjs +63 -0
- package/queue/gate.mjs +37 -0
- package/queue/git.mjs +61 -0
- package/queue/health.mjs +154 -0
- package/queue/idle.mjs +63 -0
- package/queue/job-wrapper.mjs +116 -0
- package/queue/journal.mjs +216 -0
- package/queue/kinds.mjs +95 -0
- package/queue/limits.mjs +79 -0
- package/queue/linux.mjs +72 -0
- package/queue/nested.mjs +83 -0
- package/queue/notices.mjs +114 -0
- package/queue/notify.mjs +47 -0
- package/queue/probes.mjs +162 -0
- package/queue/proctree.mjs +124 -0
- package/queue/project.mjs +26 -0
- package/queue/ps.mjs +54 -0
- package/queue/reaper.mjs +278 -0
- package/queue/run.mjs +612 -0
- package/queue/schedule-check.mjs +177 -0
- package/queue/settings.mjs +145 -0
- package/queue/setup.mjs +270 -0
- package/queue/slots.mjs +144 -0
- package/queue/stats.mjs +8 -0
- package/queue/stray.mjs +38 -0
- package/queue/timer.mjs +47 -0
- package/queue/units.mjs +8 -0
package/mcp/server.mjs
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The dotime-mcp command: an MCP server on standard input and output that offers the machine queue as tools
|
|
3
|
+
// (queue_status, queue_passed, queue_history, queue_run, queue_job). It is JSON-RPC 2.0, one message per line, written
|
|
4
|
+
// by hand with no SDK. It serves both kinds of MCP client:
|
|
5
|
+
// - revision 2026-07-28, which has no handshake: every request names its protocol version in
|
|
6
|
+
// _meta["io.modelcontextprotocol/protocolVersion"], and server/discover lists the versions this server supports;
|
|
7
|
+
// - revision 2025-11-25 and the ones before it, which open with initialize and notifications/initialized.
|
|
8
|
+
// A request with no version in _meta is served the earlier way, whether initialize came first or not. Logging goes
|
|
9
|
+
// to standard error only. Input that is not a valid message is answered with a JSON-RPC error and never ends the
|
|
10
|
+
// server; it ends when its input closes, or on INT, TERM or HUP. Jobs started with queue_run run detached and go on.
|
|
11
|
+
import { readFileSync } from "node:fs";
|
|
12
|
+
import { isMainModule, loadSettings, paths, timeZone } from "../queue/settings.mjs";
|
|
13
|
+
import { jobsDir, pruneJobs } from "./jobs.mjs";
|
|
14
|
+
import { callTool, realToolDeps, TOOLS } from "./tools.mjs";
|
|
15
|
+
|
|
16
|
+
export const MODERN_VERSIONS = Object.freeze(["2026-07-28"]);
|
|
17
|
+
/** Revisions answered with initialize; the first is the one offered to a client that asks for another. */
|
|
18
|
+
export const HANDSHAKE_VERSIONS = Object.freeze(["2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05"]);
|
|
19
|
+
/** The versions a request may name in _meta. */
|
|
20
|
+
export const SUPPORTED_VERSIONS = Object.freeze([...MODERN_VERSIONS, HANDSHAKE_VERSIONS[0]]);
|
|
21
|
+
export const ERRORS = Object.freeze({
|
|
22
|
+
parse: -32700, invalidRequest: -32600, methodNotFound: -32601, invalidParams: -32602, internal: -32603,
|
|
23
|
+
unsupportedVersion: -32022,
|
|
24
|
+
});
|
|
25
|
+
/** The longest message line read; a longer one is dropped and answered with a parse error. */
|
|
26
|
+
export const MAX_LINE_BYTES = 1024 * 1024;
|
|
27
|
+
const META = "io.modelcontextprotocol/";
|
|
28
|
+
const LIST_TTL_MS = 60 * 60 * 1000;
|
|
29
|
+
const VERSION = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
30
|
+
export const SERVER_INFO = Object.freeze({ name: "dotime-mcp", title: "DeployOnTime machine queue", version: VERSION });
|
|
31
|
+
const INSTRUCTIONS = "Run heavy commands (test suites, builds) with queue_run instead of starting them directly, "
|
|
32
|
+
+ "then poll queue_job with the job id until it is finished. queue_status shows the slots and the line; "
|
|
33
|
+
+ "queue_passed finds the pass stamp of a folder's commit; queue_history sums up the journal.";
|
|
34
|
+
|
|
35
|
+
const isPlain = (x) => !!x && typeof x === "object" && !Array.isArray(x);
|
|
36
|
+
const isId = (id) => typeof id === "string" || Number.isInteger(id);
|
|
37
|
+
const reply = (id, result) => ({ jsonrpc: "2.0", id, result });
|
|
38
|
+
const failure = (id, code, message, data) => ({ jsonrpc: "2.0", id, error: { code, message, ...(data ? { data } : {}) } });
|
|
39
|
+
const short = (text) => (text.length > 100 ? `${text.slice(0, 100)}...` : text);
|
|
40
|
+
|
|
41
|
+
/** How a request is to be served, from the version in its _meta: { modern } or { error } with the reply to send. */
|
|
42
|
+
function eraOf(id, params) {
|
|
43
|
+
const meta = isPlain(params?._meta) ? params._meta : {};
|
|
44
|
+
const requested = meta[`${META}protocolVersion`];
|
|
45
|
+
if (requested === undefined) return { modern: false };
|
|
46
|
+
if (typeof requested !== "string" || !SUPPORTED_VERSIONS.includes(requested)) {
|
|
47
|
+
return { error: failure(id, ERRORS.unsupportedVersion, "Unsupported protocol version", { supported: [...SUPPORTED_VERSIONS], requested }) };
|
|
48
|
+
}
|
|
49
|
+
const modern = MODERN_VERSIONS.includes(requested);
|
|
50
|
+
if (modern && !isPlain(meta[`${META}clientCapabilities`])) {
|
|
51
|
+
return { error: failure(id, ERRORS.invalidParams, `Invalid params: _meta needs ${META}clientCapabilities, an object`) };
|
|
52
|
+
}
|
|
53
|
+
return { modern };
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** A result in the shape of the era it is sent in: a modern one names its type and the server. */
|
|
57
|
+
const shaped = (result, modern) => (modern ? { resultType: "complete", ...result, _meta: { [`${META}serverInfo`]: SERVER_INFO } } : result);
|
|
58
|
+
|
|
59
|
+
/** The server: handleLine(text) gives the reply to one input line, or null when none is due (a notification, a
|
|
60
|
+
* reply from the client, an empty line). context() gives the settings, files and zone for one tool call, plus the
|
|
61
|
+
* tool deps. Nothing in here throws or ends the process. */
|
|
62
|
+
export function createServer({ context, log = () => {} }) {
|
|
63
|
+
const methods = {
|
|
64
|
+
initialize(params) {
|
|
65
|
+
const asked = params?.protocolVersion;
|
|
66
|
+
if (typeof asked !== "string") return { error: "Invalid params: initialize needs protocolVersion, a string" };
|
|
67
|
+
const protocolVersion = HANDSHAKE_VERSIONS.includes(asked) ? asked : HANDSHAKE_VERSIONS[0];
|
|
68
|
+
return {
|
|
69
|
+
result: {
|
|
70
|
+
protocolVersion, capabilities: { tools: { listChanged: false } }, serverInfo: SERVER_INFO, instructions: INSTRUCTIONS,
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
ping: () => ({ result: {} }),
|
|
75
|
+
"server/discover": () => ({
|
|
76
|
+
modern: true,
|
|
77
|
+
result: {
|
|
78
|
+
supportedVersions: [...SUPPORTED_VERSIONS], capabilities: { tools: {} }, instructions: INSTRUCTIONS,
|
|
79
|
+
ttlMs: LIST_TTL_MS, cacheScope: "public",
|
|
80
|
+
},
|
|
81
|
+
}),
|
|
82
|
+
"tools/list": (_params, modern) => ({
|
|
83
|
+
result: { tools: TOOLS.map((tool) => structuredClone(tool)), ...(modern ? { ttlMs: LIST_TTL_MS, cacheScope: "public" } : {}) },
|
|
84
|
+
}),
|
|
85
|
+
"tools/call"(params) {
|
|
86
|
+
if (typeof params?.name !== "string") return { error: "Invalid params: tools/call needs name, a string" };
|
|
87
|
+
const args = params.arguments ?? {};
|
|
88
|
+
if (!isPlain(args)) return { error: "Invalid params: arguments must be an object" };
|
|
89
|
+
const out = callTool(params.name, args, context());
|
|
90
|
+
return out ? { result: out } : { error: `Unknown tool: ${short(params.name)}` };
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
function handleMessage(message) {
|
|
95
|
+
if (Array.isArray(message)) return failure(null, ERRORS.invalidRequest, "Invalid request: batches are not supported, send one message per line");
|
|
96
|
+
if (!isPlain(message) || message.jsonrpc !== "2.0") {
|
|
97
|
+
const id = isId(message?.id) ? message.id : null;
|
|
98
|
+
return failure(id, ERRORS.invalidRequest, 'Invalid request: expected a JSON-RPC 2.0 object with "jsonrpc": "2.0"');
|
|
99
|
+
}
|
|
100
|
+
const hasId = Object.hasOwn(message, "id");
|
|
101
|
+
if (typeof message.method !== "string") {
|
|
102
|
+
// A reply from the client to a request: this server sends none, so there is nothing to match it with.
|
|
103
|
+
if (hasId && (Object.hasOwn(message, "result") || Object.hasOwn(message, "error"))) return null;
|
|
104
|
+
return failure(isId(message.id) ? message.id : null, ERRORS.invalidRequest, "Invalid request: method must be a string");
|
|
105
|
+
}
|
|
106
|
+
// Notifications (initialized, cancelled and any other) are never answered; every request here ends at once.
|
|
107
|
+
if (!hasId) return null;
|
|
108
|
+
if (!isId(message.id)) return failure(null, ERRORS.invalidRequest, "Invalid request: id must be a string or a whole number");
|
|
109
|
+
const { id, method, params } = message;
|
|
110
|
+
if (params !== undefined && !isPlain(params)) return failure(id, ERRORS.invalidParams, "Invalid params: params must be an object");
|
|
111
|
+
const handler = Object.hasOwn(methods, method) ? methods[method] : null;
|
|
112
|
+
if (!handler) return failure(id, ERRORS.methodNotFound, `Method not found: ${short(method)}`);
|
|
113
|
+
const era = method === "initialize" ? { modern: false } : eraOf(id, params);
|
|
114
|
+
if (era.error) return era.error;
|
|
115
|
+
const out = handler(params, era.modern);
|
|
116
|
+
if (out.error) return failure(id, ERRORS.invalidParams, out.error);
|
|
117
|
+
return reply(id, shaped(out.result, era.modern || !!out.modern));
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
return {
|
|
121
|
+
handleLine(line) {
|
|
122
|
+
const text = line.trim();
|
|
123
|
+
if (!text) return null;
|
|
124
|
+
let message;
|
|
125
|
+
try { message = JSON.parse(text); } catch { return failure(null, ERRORS.parse, "Parse error: the line is not valid JSON"); }
|
|
126
|
+
try {
|
|
127
|
+
return handleMessage(message);
|
|
128
|
+
} catch (e) {
|
|
129
|
+
log(`internal error: ${e?.stack ?? e}`);
|
|
130
|
+
return failure(isPlain(message) && isId(message.id) ? message.id : null, ERRORS.internal, "Internal error");
|
|
131
|
+
}
|
|
132
|
+
},
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/** Splits a byte stream into lines and hands each one to onLine. A line longer than maxBytes, its newline not
|
|
137
|
+
* counted, is dropped as it comes, and onTooLong() is called once for it. Returns { push(chunk), end() }. */
|
|
138
|
+
export function lineReader(onLine, onTooLong, maxBytes = MAX_LINE_BYTES) {
|
|
139
|
+
let parts = [];
|
|
140
|
+
let size = 0;
|
|
141
|
+
let dropping = false;
|
|
142
|
+
const flush = () => {
|
|
143
|
+
const line = Buffer.concat(parts).toString("utf8");
|
|
144
|
+
parts = [];
|
|
145
|
+
size = 0;
|
|
146
|
+
onLine(line);
|
|
147
|
+
};
|
|
148
|
+
return {
|
|
149
|
+
push(chunk) {
|
|
150
|
+
let from = 0;
|
|
151
|
+
for (let at = chunk.indexOf(10); at >= 0; at = chunk.indexOf(10, from)) {
|
|
152
|
+
if (dropping) dropping = false;
|
|
153
|
+
else if (size + at - from > maxBytes) {
|
|
154
|
+
parts = [];
|
|
155
|
+
size = 0;
|
|
156
|
+
onTooLong();
|
|
157
|
+
} else {
|
|
158
|
+
parts.push(chunk.subarray(from, at));
|
|
159
|
+
flush();
|
|
160
|
+
}
|
|
161
|
+
from = at + 1;
|
|
162
|
+
}
|
|
163
|
+
if (from >= chunk.length || dropping) return;
|
|
164
|
+
parts.push(chunk.subarray(from));
|
|
165
|
+
size += chunk.length - from;
|
|
166
|
+
if (size > maxBytes) {
|
|
167
|
+
parts = [];
|
|
168
|
+
size = 0;
|
|
169
|
+
dropping = true;
|
|
170
|
+
onTooLong();
|
|
171
|
+
}
|
|
172
|
+
},
|
|
173
|
+
end() { if (size && !dropping) flush(); },
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Runs the server on standard input and output until the input closes. Resolves with the exit code. */
|
|
178
|
+
export async function main(env = process.env) {
|
|
179
|
+
const log = (text) => process.stderr.write(`dotime-mcp: ${text}\n`);
|
|
180
|
+
// Read again for every call, as each run of dotime-queue reads them, so a change to config.json counts at once.
|
|
181
|
+
const context = () => ({ settings: loadSettings(env), files: paths(env), tz: timeZone(env), ...realToolDeps(env) });
|
|
182
|
+
try { pruneJobs(jobsDir(paths(env).home)); } catch (e) { log(`old jobs could not be pruned: ${e.message}`); }
|
|
183
|
+
const server = createServer({ context, log });
|
|
184
|
+
let closed = false;
|
|
185
|
+
const send = (message) => {
|
|
186
|
+
if (!message || closed) return;
|
|
187
|
+
process.stdout.write(`${JSON.stringify(message)}\n`);
|
|
188
|
+
};
|
|
189
|
+
return new Promise((resolve) => {
|
|
190
|
+
const finish = (code) => {
|
|
191
|
+
if (closed) return;
|
|
192
|
+
closed = true;
|
|
193
|
+
// Whatever is still buffered for stdout is written before the process ends.
|
|
194
|
+
if (process.stdout.writableLength) process.stdout.once("drain", () => resolve(code));
|
|
195
|
+
else resolve(code);
|
|
196
|
+
};
|
|
197
|
+
process.stdout.on("error", () => finish(0));
|
|
198
|
+
for (const [signal, code] of [["SIGINT", 130], ["SIGTERM", 143], ["SIGHUP", 129]]) process.once(signal, () => finish(code));
|
|
199
|
+
const reader = lineReader(
|
|
200
|
+
(line) => send(server.handleLine(line)),
|
|
201
|
+
() => send(failure(null, ERRORS.parse, `Parse error: a message line is longer than ${MAX_LINE_BYTES} bytes`)),
|
|
202
|
+
);
|
|
203
|
+
process.stdin.on("data", (chunk) => reader.push(chunk));
|
|
204
|
+
process.stdin.on("end", () => { reader.end(); finish(0); });
|
|
205
|
+
process.stdin.on("error", () => finish(0));
|
|
206
|
+
});
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (isMainModule(import.meta.url)) process.exit(await main());
|
package/mcp/tools.mjs
ADDED
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
// The queue tools of the MCP server: their definitions, the strict check of their arguments, and what each one does.
|
|
2
|
+
// The read tools use the queue's own modules in this process, the same way the dotime-queue command does. queue_run
|
|
3
|
+
// never runs a command itself: it stores the request and starts runner.mjs detached, which starts dotime-queue run, so
|
|
4
|
+
// the job keeps its own process group, waits under the queue's slot and line rules, and outlives the server. No text
|
|
5
|
+
// is ever handed to a shell: the command is an array of words, passed on as separate arguments.
|
|
6
|
+
import { spawn } from "node:child_process";
|
|
7
|
+
import { realpathSync, statSync } from "node:fs";
|
|
8
|
+
import { isAbsolute } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import { statusLines, historyRow } from "../queue/cli.mjs";
|
|
11
|
+
import { gateReason } from "../queue/gate.mjs";
|
|
12
|
+
import { gitState, isRepository } from "../queue/git.mjs";
|
|
13
|
+
import { healthVerdict, readHealth, savedCpuTimes } from "../queue/health.mjs";
|
|
14
|
+
import { cmdString, findStamp, historyWindow, parseLines, readLines, summarize } from "../queue/journal.mjs";
|
|
15
|
+
import { folderProject } from "../queue/project.mjs";
|
|
16
|
+
import { snapshot } from "../queue/slots.mjs";
|
|
17
|
+
import {
|
|
18
|
+
activeJobs, createJob, JOB_ID_RE, jobsDir, KEEP_DAYS, newJobId, pruneJobs, readJob, runnerActive, sameProcess, START_GRACE_MS, tailLines,
|
|
19
|
+
} from "./jobs.mjs";
|
|
20
|
+
|
|
21
|
+
const RUNNER = fileURLToPath(new URL("./runner.mjs", import.meta.url));
|
|
22
|
+
export const KINDS = Object.freeze(["test", "lint", "build", "deploy", "debug", "other"]);
|
|
23
|
+
// A usage error is the one end of dotime-queue run that writes no journal line (see queue/README.md, Exit codes).
|
|
24
|
+
const USAGE_EXIT = 2;
|
|
25
|
+
const CONTROL_RE = /[\u0000-\u001f\u007f]/;
|
|
26
|
+
// "<project>: <task>": the project part is what the queue reads as the project, up to 40 characters before the colon.
|
|
27
|
+
const LABEL_RE = /^[^:\s][^:]{0,39}:\s*\S/;
|
|
28
|
+
|
|
29
|
+
const text = (type, description, more = {}) => ({ type, description, ...more });
|
|
30
|
+
const cwdProperty = (what) => text("string", `Absolute path of an existing folder ${what}. Default: the server's folder.`);
|
|
31
|
+
|
|
32
|
+
/** The tools, in the order tools/list gives them. */
|
|
33
|
+
export const TOOLS = Object.freeze([
|
|
34
|
+
{
|
|
35
|
+
name: "queue_status",
|
|
36
|
+
title: "Queue status",
|
|
37
|
+
description: "Shows the queue: taken and free slots, running and waiting jobs, and whether the health gate is "
|
|
38
|
+
+ "open. The same lines as `dotime-queue status`.",
|
|
39
|
+
inputSchema: { type: "object", properties: {}, additionalProperties: false },
|
|
40
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
41
|
+
},
|
|
42
|
+
{
|
|
43
|
+
name: "queue_passed",
|
|
44
|
+
title: "Pass stamp",
|
|
45
|
+
description: "Looks up the pass stamp of a folder: the newest clean run on its current commit whose label or "
|
|
46
|
+
+ "command contains match. The same as `dotime-queue passed --match <text> --cwd <dir>`.",
|
|
47
|
+
inputSchema: {
|
|
48
|
+
type: "object",
|
|
49
|
+
properties: {
|
|
50
|
+
match: text("string", "Text to find in the label or command of the run, such as \"unit tests\".", {
|
|
51
|
+
minLength: 1, maxLength: 500,
|
|
52
|
+
}),
|
|
53
|
+
cwd: cwdProperty("inside the git checkout to look at"),
|
|
54
|
+
},
|
|
55
|
+
required: ["match"],
|
|
56
|
+
additionalProperties: false,
|
|
57
|
+
},
|
|
58
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
59
|
+
},
|
|
60
|
+
{
|
|
61
|
+
name: "queue_history",
|
|
62
|
+
title: "Queue history",
|
|
63
|
+
description: "Totals of the queue journal per project: jobs, failures, skips and time spent waiting. The same "
|
|
64
|
+
+ "as `dotime-queue history --days <n>`.",
|
|
65
|
+
inputSchema: {
|
|
66
|
+
type: "object",
|
|
67
|
+
properties: { days: text("integer", "Number of days to sum up, ending today. Default: 7.", { minimum: 1, maximum: 365 }) },
|
|
68
|
+
additionalProperties: false,
|
|
69
|
+
},
|
|
70
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
name: "queue_run",
|
|
74
|
+
title: "Run a job through the queue",
|
|
75
|
+
description: "Starts a heavy command (a test suite, a build) through the queue and returns at once with a job "
|
|
76
|
+
+ "id; poll queue_job for its state and output. The job waits for a free slot and an open health gate, "
|
|
77
|
+
+ "runs in a process group of its own under a run limit, and keeps running if this server exits. A test "
|
|
78
|
+
+ "or lint check that already passed on the same clean commit is skipped (outcome skipped) unless noSkip "
|
|
79
|
+
+ "is true. The command is a list of words and is never read by a shell. Job records are kept for "
|
|
80
|
+
+ "7 days.",
|
|
81
|
+
inputSchema: {
|
|
82
|
+
type: "object",
|
|
83
|
+
properties: {
|
|
84
|
+
label: text("string", "\"<project>: <task>\", such as \"shop-api: unit tests\".", { minLength: 3, maxLength: 200 }),
|
|
85
|
+
command: text("array", "The command and its arguments, one word each, such as [\"npm\", \"test\"].", {
|
|
86
|
+
items: { type: "string", maxLength: 32768 }, minItems: 1, maxItems: 1000,
|
|
87
|
+
}),
|
|
88
|
+
cwd: cwdProperty("to run the command in"),
|
|
89
|
+
kind: text("string", "Job kind, in place of the one guessed from the label and command.", { enum: KINDS }),
|
|
90
|
+
maxRunMin: text("number", "Run limit for this job in minutes.", { exclusiveMinimum: 0, maximum: 10080 }),
|
|
91
|
+
noSkip: text("boolean", "Run a test or lint check even when it already passed on this commit."),
|
|
92
|
+
afterFix: text("string", "A note on what was fixed, to run a check that failed twice on unchanged code.", {
|
|
93
|
+
minLength: 1, maxLength: 500,
|
|
94
|
+
}),
|
|
95
|
+
},
|
|
96
|
+
required: ["label", "command"],
|
|
97
|
+
additionalProperties: false,
|
|
98
|
+
},
|
|
99
|
+
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
name: "queue_job",
|
|
103
|
+
title: "Job state",
|
|
104
|
+
description: "The state of a job started with queue_run: starting, waiting, running, finished or lost (its "
|
|
105
|
+
+ "runner ended without a result). For a finished job: the exit code and the outcome from the queue "
|
|
106
|
+
+ "journal (ran, skipped, refused, timed-out, gave-up, left, stopped, could-not-start). Also the last "
|
|
107
|
+
+ "lines of its output.",
|
|
108
|
+
inputSchema: {
|
|
109
|
+
type: "object",
|
|
110
|
+
properties: {
|
|
111
|
+
jobId: text("string", "The job id queue_run returned.", { minLength: 1, maxLength: 100 }),
|
|
112
|
+
tailLines: text("integer", "How many lines of output to return, from the end. Default: 40.", { minimum: 0, maximum: 500 }),
|
|
113
|
+
},
|
|
114
|
+
required: ["jobId"],
|
|
115
|
+
additionalProperties: false,
|
|
116
|
+
},
|
|
117
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
118
|
+
},
|
|
119
|
+
]);
|
|
120
|
+
|
|
121
|
+
const TYPES = {
|
|
122
|
+
string: (v) => typeof v === "string",
|
|
123
|
+
integer: (v) => Number.isInteger(v),
|
|
124
|
+
number: (v) => typeof v === "number" && Number.isFinite(v),
|
|
125
|
+
boolean: (v) => typeof v === "boolean",
|
|
126
|
+
array: Array.isArray,
|
|
127
|
+
};
|
|
128
|
+
|
|
129
|
+
/** The problems of one value against a schema of the small subset the tools use, each a short sentence. */
|
|
130
|
+
function problemsOf(name, value, schema) {
|
|
131
|
+
if (!TYPES[schema.type](value)) {
|
|
132
|
+
const a = schema.type === "array" ? "an array" : schema.type === "integer" ? "a whole number" : `a ${schema.type}`;
|
|
133
|
+
return [`${name} must be ${a}${schema.type === "array" && schema.items ? ` of ${schema.items.type}s` : ""}`];
|
|
134
|
+
}
|
|
135
|
+
const out = [];
|
|
136
|
+
if (schema.enum && !schema.enum.includes(value)) out.push(`${name} must be one of ${schema.enum.join(", ")}`);
|
|
137
|
+
if (schema.minLength !== undefined && value.length < schema.minLength) {
|
|
138
|
+
out.push(schema.minLength === 1 ? `${name} must not be empty` : `${name} must have at least ${schema.minLength} characters`);
|
|
139
|
+
}
|
|
140
|
+
if (schema.maxLength !== undefined && value.length > schema.maxLength) out.push(`${name} must have at most ${schema.maxLength} characters`);
|
|
141
|
+
if (schema.minimum !== undefined && value < schema.minimum) out.push(`${name} must be at least ${schema.minimum}`);
|
|
142
|
+
if (schema.exclusiveMinimum !== undefined && value <= schema.exclusiveMinimum) out.push(`${name} must be above ${schema.exclusiveMinimum}`);
|
|
143
|
+
if (schema.maximum !== undefined && value > schema.maximum) out.push(`${name} must be at most ${schema.maximum}`);
|
|
144
|
+
if (schema.type === "array") {
|
|
145
|
+
if (value.length < (schema.minItems ?? 0)) out.push(`${name} must have at least ${schema.minItems} item${schema.minItems > 1 ? "s" : ""}`);
|
|
146
|
+
if (schema.maxItems !== undefined && value.length > schema.maxItems) out.push(`${name} must have at most ${schema.maxItems} items`);
|
|
147
|
+
if (schema.items) {
|
|
148
|
+
const bad = value.findIndex((item) => problemsOf("", item, schema.items).length);
|
|
149
|
+
if (bad >= 0) out.push(`${name}[${bad}]: ${problemsOf("item", value[bad], schema.items).join("; ")}`);
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return out;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** The problems of a tool's arguments against its input schema: unknown names, missing ones, and values that do not
|
|
156
|
+
* fit. An empty list means they fit. */
|
|
157
|
+
export function argumentProblems(args, schema) {
|
|
158
|
+
const out = [];
|
|
159
|
+
for (const name of Object.keys(args)) if (!Object.hasOwn(schema.properties, name)) out.push(`unknown argument ${JSON.stringify(name)}`);
|
|
160
|
+
for (const name of schema.required ?? []) if (args[name] === undefined) out.push(`${name} is required`);
|
|
161
|
+
for (const [name, property] of Object.entries(schema.properties)) {
|
|
162
|
+
if (args[name] !== undefined) out.push(...problemsOf(name, args[name], property));
|
|
163
|
+
}
|
|
164
|
+
return out;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
class ArgumentError extends Error {}
|
|
168
|
+
class Refusal extends Error {}
|
|
169
|
+
const fail = (message) => { throw new ArgumentError(message); };
|
|
170
|
+
const refuse = (message) => { throw new Refusal(message); };
|
|
171
|
+
|
|
172
|
+
/** The folder a tool works in: an absolute path to an existing folder, given as its real path, or the server's own
|
|
173
|
+
* folder when none is given. */
|
|
174
|
+
function folderOf(given, ctx) {
|
|
175
|
+
if (given === undefined) {
|
|
176
|
+
try { return realpathSync(ctx.cwd()); } catch { fail("the server's own folder was removed; give cwd"); }
|
|
177
|
+
}
|
|
178
|
+
if (given.includes("\u0000")) fail("cwd must not contain a NUL character");
|
|
179
|
+
if (!isAbsolute(given)) fail(`cwd must be an absolute path, got ${JSON.stringify(given)}`);
|
|
180
|
+
let stat;
|
|
181
|
+
try { stat = statSync(given); } catch { fail(`cwd does not exist: ${given}`); }
|
|
182
|
+
if (!stat.isDirectory()) fail(`cwd is not a folder: ${given}`);
|
|
183
|
+
return realpathSync(given);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
const result = (lines, structured) => ({ text: lines.join("\n"), structured });
|
|
187
|
+
|
|
188
|
+
function queueStatus(_args, ctx) {
|
|
189
|
+
const { settings, files } = ctx;
|
|
190
|
+
const { holders, queue, nested } = snapshot({ dirs: files });
|
|
191
|
+
const health = healthVerdict(ctx.readHealth({ limits: settings.health, cpuSince: savedCpuTimes(files.healthCache) }), settings.health);
|
|
192
|
+
const gate = gateReason({ holders, health }, settings.slots);
|
|
193
|
+
const lines = statusLines({ holders, queue, nested, gate, max: settings.slots });
|
|
194
|
+
const now = Date.now();
|
|
195
|
+
const job = (entry) => ({
|
|
196
|
+
label: entry.label, pid: entry.pid, minutes: Math.max(0, Math.round((now - (entry.startedAt ?? entry.at)) / 60_000)),
|
|
197
|
+
...(entry.kind ? { kind: entry.kind } : {}),
|
|
198
|
+
});
|
|
199
|
+
return result(lines, {
|
|
200
|
+
slots: settings.slots, taken: holders.length, waiting: queue.length, gateOpen: !gate, gate: gate || null,
|
|
201
|
+
running: holders.map(job), line: queue.map(job), lines,
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function queuePassed(args, ctx) {
|
|
206
|
+
const cwd = folderOf(args.cwd, ctx);
|
|
207
|
+
const commit = gitState(cwd);
|
|
208
|
+
const folder = { project: folderProject(cwd), ...commit, repository: commit.head !== null || isRepository(cwd) };
|
|
209
|
+
const found = findStamp(readLines(ctx.files.journal), folder, args.match, { tz: ctx.tz });
|
|
210
|
+
const stamp = found.stamp;
|
|
211
|
+
return result([found.text], {
|
|
212
|
+
stamp: !!stamp, text: found.text, cwd,
|
|
213
|
+
...(stamp ? { head: stamp.head, label: stamp.label, command: stamp.cmd, endedAt: stamp.endedAt, runMin: stamp.runMin } : {}),
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function queueHistory(args, ctx) {
|
|
218
|
+
const days = args.days ?? 7;
|
|
219
|
+
const range = historyWindow({ days, tz: ctx.tz });
|
|
220
|
+
const { all, byProject } = summarize(readLines(ctx.files.journal), range.from, range.to);
|
|
221
|
+
const lines = [`history: ${range.title}, jobs ${all.jobs}`];
|
|
222
|
+
if (all.jobs) for (const [name, totals] of [["all projects", all], ...Object.entries(byProject)]) lines.push(historyRow(name, totals));
|
|
223
|
+
return result(lines, { days, jobs: all.jobs, all, byProject, lines });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** The words of `dotime-queue run` for a request. Every value is joined to its flag with "=", so a value that starts
|
|
227
|
+
* with "--" is never read as the next flag, and the command follows "--". */
|
|
228
|
+
export function queueArgs({ label, command, kind, maxRunMin, noSkip, afterFix }) {
|
|
229
|
+
return [
|
|
230
|
+
"run", `--label=${label}`,
|
|
231
|
+
...(kind ? [`--kind=${kind}`] : []),
|
|
232
|
+
...(maxRunMin !== undefined ? [`--max-run=${maxRunMin}`] : []),
|
|
233
|
+
...(noSkip ? ["--no-skip"] : []),
|
|
234
|
+
...(afterFix !== undefined ? [`--after-fix=${afterFix}`] : []),
|
|
235
|
+
"--", ...command,
|
|
236
|
+
];
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
function queueRun(args, ctx) {
|
|
240
|
+
const label = args.label.trim();
|
|
241
|
+
if (CONTROL_RE.test(args.label)) fail("label must not contain line breaks or other control characters");
|
|
242
|
+
if (!LABEL_RE.test(label)) fail(`label must look like "<project>: <task>", with at most 40 characters before the colon`);
|
|
243
|
+
if (args.command[0].trim() === "") fail("command[0] must name the program to run");
|
|
244
|
+
const nul = args.command.findIndex((word) => word.includes("\u0000"));
|
|
245
|
+
if (nul >= 0) fail(`command[${nul}] must not contain a NUL character`);
|
|
246
|
+
if (args.afterFix !== undefined && (CONTROL_RE.test(args.afterFix) || !args.afterFix.trim())) {
|
|
247
|
+
fail("afterFix must be one line of text");
|
|
248
|
+
}
|
|
249
|
+
const cwd = folderOf(args.cwd, ctx);
|
|
250
|
+
const dir = jobsDir(ctx.files.home);
|
|
251
|
+
pruneJobs(dir, { check: ctx.sameProcess });
|
|
252
|
+
const max = ctx.settings.mcpMaxJobs;
|
|
253
|
+
const active = activeJobs(dir, { check: ctx.sameProcess }).length;
|
|
254
|
+
if (active >= max) {
|
|
255
|
+
refuse(`refused: ${active} jobs started here are still waiting or running, and mcpMaxJobs in config.json allows `
|
|
256
|
+
+ `${max}; wait until one has finished (see queue_job and queue_status), then start this one again`);
|
|
257
|
+
}
|
|
258
|
+
const id = newJobId();
|
|
259
|
+
const request = {
|
|
260
|
+
v: 1, id, label, command: args.command, cwd, createdAt: Date.now(),
|
|
261
|
+
queueArgs: queueArgs({ ...args, label, afterFix: args.afterFix?.trim() }),
|
|
262
|
+
...(args.kind ? { kind: args.kind } : {}),
|
|
263
|
+
...(args.maxRunMin !== undefined ? { maxRunMin: args.maxRunMin } : {}),
|
|
264
|
+
...(args.noSkip ? { noSkip: true } : {}),
|
|
265
|
+
...(args.afterFix !== undefined ? { afterFix: args.afterFix.trim() } : {}),
|
|
266
|
+
};
|
|
267
|
+
createJob(dir, id, request);
|
|
268
|
+
ctx.startRunner(dir, id, cwd, ctx.files.home);
|
|
269
|
+
const lines = [
|
|
270
|
+
`started job ${id}: "${label}", command ${cmdString(args.command)}, in ${cwd}`,
|
|
271
|
+
"it waits for a slot under the queue's rules; call queue_job with this jobId for its state and output",
|
|
272
|
+
];
|
|
273
|
+
return result(lines, { jobId: id, state: "starting", label, command: args.command, cwd });
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** Starts the runner of a job detached: in a session and process group of its own, with no tie to this process's
|
|
277
|
+
* standard streams, so it keeps going when the server exits or is stopped. home is the state folder as an absolute
|
|
278
|
+
* path: the runner and the queue run in the job's folder, where a relative DOTIME_HOME would name another folder. */
|
|
279
|
+
export function startRunner(dir, id, cwd, home, env = process.env) {
|
|
280
|
+
const child = spawn(process.execPath, [RUNNER, dir, id], { cwd, detached: true, stdio: "ignore", env: { ...env, DOTIME_HOME: home } });
|
|
281
|
+
child.on("error", () => { /* the job shows as lost once START_GRACE_MS has passed */ });
|
|
282
|
+
child.unref();
|
|
283
|
+
return child.pid;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
/** The journal line of a finished job: the one its own queue process wrote, found by that process's pid. A line
|
|
287
|
+
* queued before the process started is from an earlier process that had the same pid. No line: null, never the
|
|
288
|
+
* line of another job. */
|
|
289
|
+
function journalLine(request, pid, journalFile) {
|
|
290
|
+
if (!Number.isInteger(pid?.queuePid)) return null;
|
|
291
|
+
const from = pid.startedAt - 2000;
|
|
292
|
+
return parseLines(readLines(journalFile))
|
|
293
|
+
.find((row) => row.pid === pid.queuePid && row.label === request.label && Date.parse(row.queuedAt) >= from) ?? null;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Where a job stands now: { state, position? }. */
|
|
297
|
+
function stateOf(job, files, check) {
|
|
298
|
+
if (job.exit) return { state: "finished" };
|
|
299
|
+
if (!runnerActive(job, Date.now(), check)) return { state: "lost" };
|
|
300
|
+
const pid = job.pid?.queuePid;
|
|
301
|
+
if (!pid) return { state: "starting" };
|
|
302
|
+
const { holders, queue, nested } = snapshot({ dirs: files });
|
|
303
|
+
if (holders.some((h) => h.pid === pid)) return { state: "running" };
|
|
304
|
+
const at = queue.findIndex((q) => q.pid === pid);
|
|
305
|
+
if (at >= 0) return { state: "waiting", position: at + 1 };
|
|
306
|
+
const inner = nested.find((n) => n.pid === pid);
|
|
307
|
+
if (inner) return { state: inner.waiting ? "waiting" : "running", nested: true };
|
|
308
|
+
return { state: "starting" };
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function queueJob(args, ctx) {
|
|
312
|
+
const id = args.jobId;
|
|
313
|
+
if (!JOB_ID_RE.test(id)) fail(`jobId ${JSON.stringify(id)} is not a job id; queue_run returns one`);
|
|
314
|
+
const dir = jobsDir(ctx.files.home);
|
|
315
|
+
const job = readJob(dir, id);
|
|
316
|
+
if (!job.request) fail(`unknown job ${id}: it was never started here or was pruned after ${KEEP_DAYS} days`);
|
|
317
|
+
const { request } = job;
|
|
318
|
+
const where = stateOf(job, ctx.files, ctx.sameProcess);
|
|
319
|
+
const info = {
|
|
320
|
+
jobId: id, state: where.state, label: request.label, command: request.command, cwd: request.cwd,
|
|
321
|
+
createdAt: new Date(request.createdAt).toISOString(),
|
|
322
|
+
...(where.position ? { position: where.position } : {}),
|
|
323
|
+
...(where.nested ? { nested: true } : {}),
|
|
324
|
+
};
|
|
325
|
+
let head = `job ${id} "${request.label}": ${where.state}`;
|
|
326
|
+
if (where.position) head += `, position ${where.position} in line`;
|
|
327
|
+
if (where.state === "starting" && !job.pid) head += ` (no runner yet; lost after ${START_GRACE_MS / 1000} s)`;
|
|
328
|
+
if (where.state === "lost") head += "; its runner ended without a result, see the output";
|
|
329
|
+
if (job.exit) {
|
|
330
|
+
const row = journalLine(request, job.pid, ctx.files.journal);
|
|
331
|
+
const outcome = row?.outcome ?? (job.exit.exit === USAGE_EXIT ? "usage-error" : null);
|
|
332
|
+
Object.assign(info, {
|
|
333
|
+
exitCode: job.exit.exit, outcome, ok: job.exit.exit === 0 && (outcome === "ran" || outcome === "skipped"),
|
|
334
|
+
endedAt: new Date(job.exit.endedAt).toISOString(),
|
|
335
|
+
...(job.exit.signal ? { signal: job.exit.signal } : {}),
|
|
336
|
+
...(job.exit.error ? { error: job.exit.error } : {}),
|
|
337
|
+
...(row?.stamp ? { stamp: row.stamp } : {}),
|
|
338
|
+
});
|
|
339
|
+
head += `, exit ${job.exit.exit ?? "none"}${job.exit.signal ? ` (signal ${job.exit.signal})` : ""}`;
|
|
340
|
+
head += `, outcome ${outcome ?? "unknown (no journal line found)"}`;
|
|
341
|
+
if (job.exit.error) head += `; ${job.exit.error}`;
|
|
342
|
+
}
|
|
343
|
+
const count = args.tailLines ?? 40;
|
|
344
|
+
const tail = tailLines(job.files.log, count);
|
|
345
|
+
info.tail = tail.join("\n");
|
|
346
|
+
const lines = [head];
|
|
347
|
+
if (count > 0) lines.push(tail.length ? `last ${tail.length} lines of output:` : job.exit ? "no output" : "no output yet", ...tail);
|
|
348
|
+
return result(lines, info);
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const HANDLERS = {
|
|
352
|
+
queue_status: queueStatus, queue_passed: queuePassed, queue_history: queueHistory, queue_run: queueRun, queue_job: queueJob,
|
|
353
|
+
};
|
|
354
|
+
|
|
355
|
+
/** The deps a real server hands to the tools, on top of the settings, files and zone read for each call. */
|
|
356
|
+
export const realToolDeps = (env) => ({
|
|
357
|
+
env, cwd: () => process.cwd(), readHealth, sameProcess,
|
|
358
|
+
startRunner: (dir, id, cwd, home) => startRunner(dir, id, cwd, home, env),
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
/** Runs a tool and gives the tools/call result: { content, structuredContent, isError }. A tool name that is not
|
|
362
|
+
* in TOOLS gives null, for the caller to answer with a protocol error. Arguments that do not fit, and any failure
|
|
363
|
+
* inside a tool, give a result with isError and a sentence on what went wrong; nothing here throws. */
|
|
364
|
+
export function callTool(name, args, ctx) {
|
|
365
|
+
const tool = TOOLS.find((t) => t.name === name);
|
|
366
|
+
if (!tool) return null;
|
|
367
|
+
const error = (message) => ({ content: [{ type: "text", text: message }], isError: true });
|
|
368
|
+
const problems = argumentProblems(args, tool.inputSchema);
|
|
369
|
+
if (problems.length) return error(`invalid arguments for ${name}: ${problems.join("; ")}`);
|
|
370
|
+
try {
|
|
371
|
+
const out = HANDLERS[name](args, ctx);
|
|
372
|
+
// The fields again as JSON text, for clients that do not read structuredContent.
|
|
373
|
+
const content = [{ type: "text", text: out.text }, { type: "text", text: JSON.stringify(out.structured) }];
|
|
374
|
+
return { content, structuredContent: out.structured, isError: false };
|
|
375
|
+
} catch (e) {
|
|
376
|
+
if (e instanceof ArgumentError) return error(`invalid arguments for ${name}: ${e.message}`);
|
|
377
|
+
if (e instanceof Refusal) return error(`${name} ${e.message}`);
|
|
378
|
+
return error(`${name} failed: ${e?.message ?? String(e)}`);
|
|
379
|
+
}
|
|
380
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,49 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "deployontime",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A shared job queue that lets several coding agents use one computer without overloading it.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"license": "AGPL-3.0-only",
|
|
7
|
+
"keywords": [
|
|
8
|
+
"coding-agents",
|
|
9
|
+
"queue",
|
|
10
|
+
"ai-agents",
|
|
11
|
+
"claude-code",
|
|
12
|
+
"codex",
|
|
13
|
+
"mcp",
|
|
14
|
+
"test-runner",
|
|
15
|
+
"developer-tools"
|
|
16
|
+
],
|
|
17
|
+
"homepage": "https://github.com/Moezat220/deployontime#readme",
|
|
18
|
+
"repository": {
|
|
19
|
+
"type": "git",
|
|
20
|
+
"url": "git+https://github.com/Moezat220/deployontime.git"
|
|
21
|
+
},
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/Moezat220/deployontime/issues"
|
|
24
|
+
},
|
|
25
|
+
"engines": {
|
|
26
|
+
"node": ">=22"
|
|
27
|
+
},
|
|
28
|
+
"os": [
|
|
29
|
+
"darwin",
|
|
30
|
+
"linux"
|
|
31
|
+
],
|
|
32
|
+
"bin": {
|
|
33
|
+
"dotime-queue": "queue/cli.mjs",
|
|
34
|
+
"dotime-mcp": "mcp/server.mjs"
|
|
35
|
+
},
|
|
36
|
+
"files": [
|
|
37
|
+
"queue/*.mjs",
|
|
38
|
+
"!queue/*.test.mjs",
|
|
39
|
+
"!queue/testkit.mjs",
|
|
40
|
+
"mcp/*.mjs",
|
|
41
|
+
"!mcp/*.test.mjs",
|
|
42
|
+
"README.md",
|
|
43
|
+
"LICENSE",
|
|
44
|
+
"SECURITY.md"
|
|
45
|
+
],
|
|
46
|
+
"scripts": {
|
|
47
|
+
"test": "node --test"
|
|
48
|
+
}
|
|
49
|
+
}
|