loopctl-mcp-server 3.21.2 → 3.32.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/README.md +31 -6
- package/index.js +792 -20
- package/lib/delivery-loop.js +12 -7
- package/lib/factory.js +99 -0
- package/lib/holder-key-file.js +135 -0
- package/lib/holder.js +50 -2
- package/lib/inbox.js +102 -0
- package/lib/interventions.js +74 -0
- package/lib/machine-name.js +40 -0
- package/lib/messages.js +88 -0
- package/lib/rulebook.js +233 -0
- package/lib/work-items.js +31 -0
- package/package.json +1 -1
package/lib/delivery-loop.js
CHANGED
|
@@ -237,15 +237,20 @@ export async function storyStage({ story_id } = {}, { apiCall } = {}) {
|
|
|
237
237
|
export const RESOLUTION_TARGETS = ["detected", "queued", "done", "failed"];
|
|
238
238
|
|
|
239
239
|
/**
|
|
240
|
-
* `POST /api/v1/stories/:id/stage/resolve`: move an escalated story off `escalated
|
|
241
|
-
*
|
|
240
|
+
* `POST /api/v1/stories/:id/stage/resolve`: move an escalated story off `escalated`. `to` is
|
|
241
|
+
* one of `RESOLUTION_TARGETS`. A human (LOOPCTL_USER_KEY) may send it anywhere; a HOLDER
|
|
242
|
+
* (LOOPCTL_AGENT_KEY, US-52.31) may send it back to `queued` only, and never one it raised
|
|
243
|
+
* itself — loopctl refuses that `409 self_resolve_blocked`. `apiCall` is bound to whichever
|
|
244
|
+
* key the caller has, the user key first.
|
|
242
245
|
*/
|
|
243
|
-
export async function resolveEscalation(
|
|
244
|
-
|
|
246
|
+
export async function resolveEscalation(
|
|
247
|
+
{ story_id, to, reason } = {},
|
|
248
|
+
{ userKey, agentKey, apiCall } = {},
|
|
249
|
+
) {
|
|
250
|
+
if (!userKey && !agentKey) {
|
|
245
251
|
return refuse(
|
|
246
|
-
"LOOPCTL_USER_KEY is required:
|
|
247
|
-
"
|
|
248
|
-
"clearing the escalation it raised.",
|
|
252
|
+
"LOOPCTL_USER_KEY or LOOPCTL_AGENT_KEY is required: a human may resolve an escalation " +
|
|
253
|
+
"to any target, and a holder credential may send one it did not raise back to queued.",
|
|
249
254
|
);
|
|
250
255
|
}
|
|
251
256
|
|
package/lib/factory.js
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `factory_overview` (loopctl US-52.30): `GET /api/v1/factory/overview`, per project and for
|
|
3
|
+
* the whole fleet, what is in flight, waiting (with its oldest age), delivered and failing.
|
|
4
|
+
* Every count is read from loopctl's stage machine at request time; drill into one item with
|
|
5
|
+
* `work_item_timeline`. READ-ONLY on any authenticated key.
|
|
6
|
+
*
|
|
7
|
+
* `window_days` is checked here for shape and range so an obvious mistake costs no round trip;
|
|
8
|
+
* the server owns the bound and answers 400 naming it.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { uuid } from "./delivery-loop.js";
|
|
12
|
+
|
|
13
|
+
export function overviewPath() {
|
|
14
|
+
return `/api/v1/factory/overview`;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function refuse(body) {
|
|
18
|
+
return { error: true, status: 0, body };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function readFactoryOverview({ project_id, window_days } = {}, { apiCall } = {}) {
|
|
22
|
+
if (project_id !== undefined && project_id !== null) {
|
|
23
|
+
const bad = uuid(project_id, "project_id");
|
|
24
|
+
if (bad) return bad;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (
|
|
28
|
+
window_days !== undefined &&
|
|
29
|
+
window_days !== null &&
|
|
30
|
+
!(Number.isInteger(window_days) && window_days >= 1 && window_days <= 30)
|
|
31
|
+
) {
|
|
32
|
+
return refuse("`window_days` must be an integer from 1 to 30.");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const query = new URLSearchParams();
|
|
36
|
+
if (typeof project_id === "string") query.set("project_id", project_id);
|
|
37
|
+
if (Number.isInteger(window_days)) query.set("window_days", String(window_days));
|
|
38
|
+
|
|
39
|
+
const qs = query.toString();
|
|
40
|
+
return apiCall("GET", overviewPath() + (qs ? `?${qs}` : ""), null);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* `intake_pause` / `intake_resume` (loopctl US-52.33): `POST /api/v1/projects/:id/intake/pause`
|
|
45
|
+
* and `/resume` on the project's one live intake source. A pause stops PROMOTION and TRIAGE
|
|
46
|
+
* only: the webhook keeps recording, and work past detected carries on. Each call carries an
|
|
47
|
+
* `intervention_id`, generated when absent; pass the first one again to retry after a lost
|
|
48
|
+
* response.
|
|
49
|
+
*/
|
|
50
|
+
export function intakePausePath(projectId) {
|
|
51
|
+
return `/api/v1/projects/${encodeURIComponent(projectId)}/intake/pause`;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export function intakeResumePath(projectId) {
|
|
55
|
+
return `/api/v1/projects/${encodeURIComponent(projectId)}/intake/resume`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function interventionId(intervention_id, randomUUID) {
|
|
59
|
+
if (intervention_id === undefined || intervention_id === null || intervention_id === "") {
|
|
60
|
+
return { id: randomUUID() };
|
|
61
|
+
}
|
|
62
|
+
const bad = uuid(intervention_id, "intervention_id");
|
|
63
|
+
return bad ? { bad } : { id: intervention_id };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function pauseIntake(
|
|
67
|
+
{ project_id, reason, intervention_id } = {},
|
|
68
|
+
{ apiCall, randomUUID } = {},
|
|
69
|
+
) {
|
|
70
|
+
const bad = uuid(project_id, "project_id");
|
|
71
|
+
if (bad) return bad;
|
|
72
|
+
|
|
73
|
+
if (typeof reason !== "string" || reason.trim() === "") {
|
|
74
|
+
return refuse("`reason` is required: why the intake is paused, in words a person can read.");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const id = interventionId(intervention_id, randomUUID);
|
|
78
|
+
if (id.bad) return id.bad;
|
|
79
|
+
|
|
80
|
+
return apiCall("POST", `/api/v1/projects/${encodeURIComponent(project_id)}/intake/pause`, {
|
|
81
|
+
reason,
|
|
82
|
+
intervention_id: id.id,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function resumeIntake(
|
|
87
|
+
{ project_id, intervention_id } = {},
|
|
88
|
+
{ apiCall, randomUUID } = {},
|
|
89
|
+
) {
|
|
90
|
+
const bad = uuid(project_id, "project_id");
|
|
91
|
+
if (bad) return bad;
|
|
92
|
+
|
|
93
|
+
const id = interventionId(intervention_id, randomUUID);
|
|
94
|
+
if (id.bad) return id.bad;
|
|
95
|
+
|
|
96
|
+
return apiCall("POST", `/api/v1/projects/${encodeURIComponent(project_id)}/intake/resume`, {
|
|
97
|
+
intervention_id: id.id,
|
|
98
|
+
});
|
|
99
|
+
}
|
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The holder credential file (US-52.28 AC-52.28.1): a copy of this session's holder
|
|
3
|
+
* credential (lib/holder.js) at $HOME/.claude/loopctl-holders/<session_id>.key, so a hook of
|
|
4
|
+
* the SAME session (claude-config's SessionStart inbox read and its PostToolUse
|
|
5
|
+
* inbox-on-tool.sh) can call GET /api/v1/inbox as that holder. The hook finds the file by the
|
|
6
|
+
* `session_id` of its own stdin JSON.
|
|
7
|
+
*
|
|
8
|
+
* ## The file name is the holder's session id
|
|
9
|
+
*
|
|
10
|
+
* It is the session id the holder registered with (`envClaimSessionId`,
|
|
11
|
+
* CLAUDE_CODE_SESSION_ID first), never CLAUDE_SESSION_ID read on its own: a headless
|
|
12
|
+
* subsession inherits its parent's CLAUDE_SESSION_ID, so keying on that would let the
|
|
13
|
+
* subsession's MCP process overwrite the parent's file with its own credential and delete it
|
|
14
|
+
* when the subsession ends. A process with no session marker at all writes nothing: its id
|
|
15
|
+
* is a per-process uuid no hook can know.
|
|
16
|
+
*
|
|
17
|
+
* ## What the file guarantees
|
|
18
|
+
*
|
|
19
|
+
* - The directory is created 0700 (an existing one is tightened to 0700), and a symlinked or
|
|
20
|
+
* foreign-owned directory is refused: nothing is written through it.
|
|
21
|
+
* - The file is 0600 and written ATOMICALLY: a fresh temp file in the same directory opened
|
|
22
|
+
* `wx` (O_CREAT|O_EXCL, which refuses a planted symlink at the temp path), then renamed
|
|
23
|
+
* over the key path. A hook never reads a half-written key, and a symlink planted at the
|
|
24
|
+
* key path is replaced, never written through.
|
|
25
|
+
* - Every call is best effort and NEVER throws: the file is a convenience for hooks, and a
|
|
26
|
+
* failure to keep it must never stop the session working. A hook that finds no file does
|
|
27
|
+
* nothing.
|
|
28
|
+
*/
|
|
29
|
+
|
|
30
|
+
import fs from "node:fs";
|
|
31
|
+
import path from "node:path";
|
|
32
|
+
import crypto from "node:crypto";
|
|
33
|
+
|
|
34
|
+
const SAFE_ID = /^[A-Za-z0-9._-]{1,128}$/;
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The id as a path component, or null when it is not one: only [A-Za-z0-9._-], at most 128
|
|
38
|
+
* characters, and never `.` or `..`.
|
|
39
|
+
*
|
|
40
|
+
* @param {unknown} id
|
|
41
|
+
* @returns {string|null}
|
|
42
|
+
*/
|
|
43
|
+
export function safeSessionId(id) {
|
|
44
|
+
if (typeof id !== "string" || !SAFE_ID.test(id)) return null;
|
|
45
|
+
if (id === "." || id === "..") return null;
|
|
46
|
+
return id;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* $HOME/.claude/loopctl-holders, or null without a HOME.
|
|
51
|
+
*
|
|
52
|
+
* @param {Record<string, string|undefined>} env
|
|
53
|
+
* @returns {string|null}
|
|
54
|
+
*/
|
|
55
|
+
export function holderKeyDir(env) {
|
|
56
|
+
const home = (env && env.HOME) || "";
|
|
57
|
+
return home ? path.join(home, ".claude", "loopctl-holders") : null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const NOOP = Object.freeze({ path: null, write: () => false, holds: () => false, remove: () => {} });
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* @param {{ dir: string|null, sessionId: string|null, fsImpl?: typeof fs, getuid?: () => number }} opts
|
|
64
|
+
* @returns {{ path: string|null, write: (key: string) => boolean, holds: (key: string) => boolean,
|
|
65
|
+
* remove: (onlyIf?: string) => void }}
|
|
66
|
+
*/
|
|
67
|
+
export function createHolderKeyFile({ dir, sessionId, fsImpl = fs, getuid = process.getuid }) {
|
|
68
|
+
const id = safeSessionId(sessionId);
|
|
69
|
+
if (!dir || !id) return NOOP;
|
|
70
|
+
|
|
71
|
+
const target = path.join(dir, `${id}.key`);
|
|
72
|
+
|
|
73
|
+
function ensureDir() {
|
|
74
|
+
fsImpl.mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
75
|
+
const st = fsImpl.lstatSync(dir);
|
|
76
|
+
if (st.isSymbolicLink() || !st.isDirectory()) return false;
|
|
77
|
+
if (typeof getuid === "function" && st.uid !== getuid()) return false;
|
|
78
|
+
if ((st.mode & 0o777) !== 0o700) fsImpl.chmodSync(dir, 0o700);
|
|
79
|
+
return true;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Writes `key` atomically; true when the file now holds it. */
|
|
83
|
+
function write(key) {
|
|
84
|
+
if (typeof key !== "string" || key === "") return false;
|
|
85
|
+
let tmp = null;
|
|
86
|
+
try {
|
|
87
|
+
if (!ensureDir()) return false;
|
|
88
|
+
tmp = path.join(dir, `.${id}.${process.pid}.${crypto.randomBytes(6).toString("hex")}.tmp`);
|
|
89
|
+
fsImpl.writeFileSync(tmp, key, { encoding: "utf8", flag: "wx", mode: 0o600 });
|
|
90
|
+
fsImpl.renameSync(tmp, target);
|
|
91
|
+
return true;
|
|
92
|
+
} catch {
|
|
93
|
+
if (tmp) {
|
|
94
|
+
try {
|
|
95
|
+
fsImpl.unlinkSync(tmp);
|
|
96
|
+
} catch {
|
|
97
|
+
// nothing was created
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
return false;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** True when the key path is a regular file holding exactly `key`. */
|
|
105
|
+
function holds(key) {
|
|
106
|
+
try {
|
|
107
|
+
return !fsImpl.lstatSync(target).isSymbolicLink() && fsImpl.readFileSync(target, "utf8") === key;
|
|
108
|
+
} catch {
|
|
109
|
+
return false;
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Deletes the file; a missing one is fine. Synchronous, so it is safe in an exit handler.
|
|
115
|
+
*
|
|
116
|
+
* With `onlyIf`, the file is deleted only while it holds that key: on an `/mcp` reconnect
|
|
117
|
+
* the old process ends after the new one (same session id) has written its own key, and
|
|
118
|
+
* the old process must not delete the new one's file. The compare and the unlink are two
|
|
119
|
+
* steps, so a new write landing between them is deleted. Nothing here restores it: the
|
|
120
|
+
* process that holds the key rewrites the file on its next sync (lib/holder.js, every
|
|
121
|
+
* heartbeat), and a file whose owner has ended is never brought back.
|
|
122
|
+
*
|
|
123
|
+
* @param {string} [onlyIf]
|
|
124
|
+
*/
|
|
125
|
+
function remove(onlyIf) {
|
|
126
|
+
if (onlyIf !== undefined && !holds(onlyIf)) return;
|
|
127
|
+
try {
|
|
128
|
+
fsImpl.unlinkSync(target);
|
|
129
|
+
} catch {
|
|
130
|
+
// already gone, or never written
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
return { path: target, write, holds, remove };
|
|
135
|
+
}
|
package/lib/holder.js
CHANGED
|
@@ -35,7 +35,12 @@
|
|
|
35
35
|
* concurrent sessions reading one value would share a holder, the wrong merge #779 exists to
|
|
36
36
|
* prevent. A uuid minted once per process stands in when neither is set.
|
|
37
37
|
*
|
|
38
|
-
* The raw credential
|
|
38
|
+
* The raw credential is never returned by a tool. Outside this process's memory it exists in
|
|
39
|
+
* one place: the holder credential file (US-52.28, lib/holder-key-file.js),
|
|
40
|
+
* $HOME/.claude/loopctl-holders/<session_id>.key, mode 0600, which a hook of the same session
|
|
41
|
+
* reads to call the inbox as this holder. It is written whenever this process adopts a
|
|
42
|
+
* credential (register, every rotation) and deleted the moment it stops holding one (end, a
|
|
43
|
+
* heartbeat refused as gone, process exit). A process with no session marker writes none.
|
|
39
44
|
*
|
|
40
45
|
* ## A runner session registers nothing
|
|
41
46
|
*
|
|
@@ -45,6 +50,7 @@
|
|
|
45
50
|
*/
|
|
46
51
|
|
|
47
52
|
import { envClaimSessionId } from "./claim-session.js";
|
|
53
|
+
import { createHolderKeyFile, holderKeyDir } from "./holder-key-file.js";
|
|
48
54
|
|
|
49
55
|
function present(value) {
|
|
50
56
|
return typeof value === "string" && value.trim() !== "";
|
|
@@ -113,6 +119,9 @@ export function createHolderSession(deps) {
|
|
|
113
119
|
afterBeat = null,
|
|
114
120
|
// US-52.19: where a lapse is reported. stderr, never stdout: stdout is the MCP stream.
|
|
115
121
|
log = (line) => process.stderr.write(`${line}\n`),
|
|
122
|
+
// US-52.28: where the holder credential file goes; $HOME/.claude/loopctl-holders by
|
|
123
|
+
// default, nothing without a HOME.
|
|
124
|
+
keyFileDir = holderKeyDir(env),
|
|
116
125
|
} = deps;
|
|
117
126
|
|
|
118
127
|
async function beat(result) {
|
|
@@ -134,6 +143,26 @@ export function createHolderSession(deps) {
|
|
|
134
143
|
// Bumped by end(): a call started before it adopts nothing that lands after it.
|
|
135
144
|
let generation = 0;
|
|
136
145
|
|
|
146
|
+
// US-52.28: named by the session's own marker only. A generated uuid names a file no hook
|
|
147
|
+
// can find, so a process without a marker gets a no-op file.
|
|
148
|
+
const keyFile = createHolderKeyFile({ dir: keyFileDir, sessionId: envClaimSessionId(env) });
|
|
149
|
+
// The key this process last wrote, so a remove deletes only its own file.
|
|
150
|
+
let writtenKey = null;
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Makes the file match the credential held: written when one is, gone when none is. It reads
|
|
154
|
+
* the file rather than trusting `writtenKey`: an old process of the same session can delete
|
|
155
|
+
* this one's file in a race (lib/holder-key-file.js remove), and the next sync rewrites it.
|
|
156
|
+
*/
|
|
157
|
+
function syncKeyFile() {
|
|
158
|
+
if (credential) {
|
|
159
|
+
if (keyFile.holds(credential) || keyFile.write(credential)) writtenKey = credential;
|
|
160
|
+
} else if (writtenKey !== null) {
|
|
161
|
+
keyFile.remove(writtenKey);
|
|
162
|
+
writtenKey = null;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
137
166
|
function plainKey() {
|
|
138
167
|
return env.LOOPCTL_AGENT_KEY;
|
|
139
168
|
}
|
|
@@ -185,6 +214,7 @@ export function createHolderSession(deps) {
|
|
|
185
214
|
holder = result.holder;
|
|
186
215
|
// `credential: null` means the key we sent is already this holder's; keep what we hold.
|
|
187
216
|
if (result.credential && result.credential.raw_key) credential = result.credential.raw_key;
|
|
217
|
+
syncKeyFile();
|
|
188
218
|
ended = false;
|
|
189
219
|
arm(result.heartbeat_seconds);
|
|
190
220
|
} else if (transient(result)) {
|
|
@@ -219,12 +249,16 @@ export function createHolderSession(deps) {
|
|
|
219
249
|
}
|
|
220
250
|
credential = null;
|
|
221
251
|
holder = null;
|
|
252
|
+
syncKeyFile();
|
|
222
253
|
return register();
|
|
223
254
|
}
|
|
224
255
|
|
|
225
256
|
if (result && !result.error && result.lease_until) {
|
|
226
257
|
holder = { ...holder, lease_until: result.lease_until };
|
|
227
258
|
}
|
|
259
|
+
// Every heartbeat re-checks the file, so a key a racing remove deleted is back within one
|
|
260
|
+
// heartbeat interval.
|
|
261
|
+
syncKeyFile();
|
|
228
262
|
|
|
229
263
|
return beat(result);
|
|
230
264
|
}
|
|
@@ -238,6 +272,8 @@ export function createHolderSession(deps) {
|
|
|
238
272
|
const key = credential;
|
|
239
273
|
ended = true;
|
|
240
274
|
credential = null;
|
|
275
|
+
// Before the request, so a slow or dropped end never leaves a revoked key on disk.
|
|
276
|
+
syncKeyFile();
|
|
241
277
|
|
|
242
278
|
const result = await apiCall("POST", endPath(id), null, key, { exactKey: true });
|
|
243
279
|
if (result && !result.error && result.holder) holder = result.holder;
|
|
@@ -268,5 +304,17 @@ export function createHolderSession(deps) {
|
|
|
268
304
|
};
|
|
269
305
|
}
|
|
270
306
|
|
|
271
|
-
|
|
307
|
+
/**
|
|
308
|
+
* Deletes the holder credential file synchronously, for a `process.on("exit")` handler:
|
|
309
|
+
* an exit that never reached end() (an uncaught error, process.exit elsewhere) still leaves
|
|
310
|
+
* no key behind. The holder itself lapses on its lease.
|
|
311
|
+
*/
|
|
312
|
+
function dropKeyFile() {
|
|
313
|
+
if (writtenKey !== null) {
|
|
314
|
+
keyFile.remove(writtenKey);
|
|
315
|
+
writtenKey = null;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
return { agentKey, register, heartbeat, end, start, status, sessionId, dropKeyFile };
|
|
272
320
|
}
|
package/lib/inbox.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `inbox` (loopctl US-52.24): this session's DMs, the threads of the items it holds and,
|
|
3
|
+
* with `project_id`, that project's channel, each read from the session's stored cursor —
|
|
4
|
+
* `GET /api/v1/inbox` — and the ack that moves those cursors, `POST /api/v1/inbox/ack`.
|
|
5
|
+
*
|
|
6
|
+
* ORDER: with `ack`, the acks are posted FIRST and the read follows, so one call both
|
|
7
|
+
* confirms what the last read returned and fetches what came after it. A refused ack (the
|
|
8
|
+
* server checks the whole batch and moves no cursor) is returned as it is and nothing is
|
|
9
|
+
* read, so the caller never takes a read for proof that its ack landed.
|
|
10
|
+
*
|
|
11
|
+
* KEY: the session's own key (`agentKey()` in index.js — the holder credential once the
|
|
12
|
+
* startup register succeeded). The routes answer only a holder credential: any other key is
|
|
13
|
+
* 403 holder_credential_required.
|
|
14
|
+
*
|
|
15
|
+
* Shapes are checked here only so a typo fails before a round trip. The server owns the
|
|
16
|
+
* rules (`Loopctl.Coordination.Messages.ack/3`): membership, the end of each attachment and
|
|
17
|
+
* the batch cap.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { uuid } from "./delivery-loop.js";
|
|
21
|
+
|
|
22
|
+
export const ACK_KINDS = ["dm", "story", "channel"];
|
|
23
|
+
|
|
24
|
+
export const INBOX_PATH = "/api/v1/inbox";
|
|
25
|
+
export const INBOX_ACK_PATH = "/api/v1/inbox/ack";
|
|
26
|
+
|
|
27
|
+
function refuse(body) {
|
|
28
|
+
return { error: true, status: 0, body };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function checkAcks(ack) {
|
|
32
|
+
if (!Array.isArray(ack)) {
|
|
33
|
+
return refuse("`ack` must be a list of {kind, id, seq}.");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
for (const entry of ack) {
|
|
37
|
+
if (entry === null || typeof entry !== "object" || Array.isArray(entry)) {
|
|
38
|
+
return refuse("each `ack` entry is an object {kind, id, seq}.");
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
if (!ACK_KINDS.includes(entry.kind)) {
|
|
42
|
+
return refuse(`an ack's \`kind\` is one of: ${ACK_KINDS.join(", ")}.`);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const bad = uuid(entry.id, "ack id");
|
|
46
|
+
if (bad) return bad;
|
|
47
|
+
|
|
48
|
+
if (!(Number.isInteger(entry.seq) && entry.seq >= 0)) {
|
|
49
|
+
return refuse("an ack's `seq` is a non-negative integer: the last_seq a read returned.");
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
return null;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** The read's query string (no `?`), from `project_id` and `limit`. */
|
|
57
|
+
export function inboxQuery({ project_id, limit } = {}) {
|
|
58
|
+
const query = new URLSearchParams();
|
|
59
|
+
if (typeof project_id === "string" && project_id !== "") query.set("project_id", project_id);
|
|
60
|
+
if (Number.isInteger(limit)) query.set("limit", String(limit));
|
|
61
|
+
return query.toString();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** The read's path, with `project_id` and `limit` as its query. */
|
|
65
|
+
export function inboxPath(args = {}) {
|
|
66
|
+
const qs = inboxQuery(args);
|
|
67
|
+
return `/api/v1/inbox${qs ? `?${qs}` : ""}`;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/**
|
|
71
|
+
* `inbox`: optional `ack` first (`POST /api/v1/inbox/ack`), then the read
|
|
72
|
+
* (`GET /api/v1/inbox`). Returns the read, with `acked` (the cursors as stored) when acks
|
|
73
|
+
* were sent.
|
|
74
|
+
*/
|
|
75
|
+
export async function readInbox({ project_id, limit, ack } = {}, { apiCall } = {}) {
|
|
76
|
+
if (project_id !== undefined && project_id !== null) {
|
|
77
|
+
const bad = uuid(project_id, "project_id");
|
|
78
|
+
if (bad) return bad;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (limit !== undefined && limit !== null && !(Number.isInteger(limit) && limit > 0)) {
|
|
82
|
+
return refuse("`limit` must be a positive integer (at most 200).");
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const acks = ack === undefined || ack === null ? [] : ack;
|
|
86
|
+
const badAck = checkAcks(acks);
|
|
87
|
+
if (badAck) return badAck;
|
|
88
|
+
|
|
89
|
+
let acked;
|
|
90
|
+
if (acks.length > 0) {
|
|
91
|
+
const result = await apiCall("POST", INBOX_ACK_PATH, {
|
|
92
|
+
acks: acks.map(({ kind, id, seq }) => ({ kind, id, seq })),
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
if (result && result.error) return result;
|
|
96
|
+
acked = result && result.cursors;
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// `acked` rides along even on a failed read, so the caller knows its cursors moved.
|
|
100
|
+
const read = await apiCall("GET", inboxPath({ project_id, limit }), null);
|
|
101
|
+
return acked === undefined ? read : { ...read, acked };
|
|
102
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `work_item_requeue` / `work_item_retriage` / `work_item_cancel` / `work_item_close`
|
|
3
|
+
* (loopctl US-52.32): the intervention verbs on one work item —
|
|
4
|
+
* `POST /api/v1/stories/:id/{requeue,retriage,cancel,close}`.
|
|
5
|
+
*
|
|
6
|
+
* KEY: the session's own key (`agentKey()` in index.js, the holder credential once the
|
|
7
|
+
* startup register succeeded). The server compares that key's holder with the item's: the
|
|
8
|
+
* holder that holds the item is refused 409 self_intervention_blocked, and a key with no
|
|
9
|
+
* holder that is not a human's is 409 holder_required.
|
|
10
|
+
*
|
|
11
|
+
* Each call carries an `intervention_id`; one is generated when the caller gives none, so a
|
|
12
|
+
* caller that retries after a lost response should pass the id it used the first time. The
|
|
13
|
+
* server writes nothing for a repeated id and answers the item's current stage row.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import crypto from "node:crypto";
|
|
17
|
+
|
|
18
|
+
import { uuid } from "./delivery-loop.js";
|
|
19
|
+
|
|
20
|
+
export const INTERVENTION_VERBS = ["requeue", "retriage", "cancel", "close"];
|
|
21
|
+
|
|
22
|
+
function refuse(body) {
|
|
23
|
+
return { error: true, status: 0, body };
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function interventionPath(storyId, verb) {
|
|
27
|
+
return `/api/v1/stories/${encodeURIComponent(storyId)}/${verb}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// One apiCall per verb with its path written out, never `/${verb}`: test/route_coverage.test.js
|
|
31
|
+
// resolves each call site's path statically, and an interpolated final segment reaches no
|
|
32
|
+
// route it can name.
|
|
33
|
+
function postIntervention(apiCall, verb, storyId, body) {
|
|
34
|
+
const id = encodeURIComponent(storyId);
|
|
35
|
+
|
|
36
|
+
switch (verb) {
|
|
37
|
+
case "requeue":
|
|
38
|
+
return apiCall("POST", `/api/v1/stories/${id}/requeue`, body);
|
|
39
|
+
case "retriage":
|
|
40
|
+
return apiCall("POST", `/api/v1/stories/${id}/retriage`, body);
|
|
41
|
+
case "cancel":
|
|
42
|
+
return apiCall("POST", `/api/v1/stories/${id}/cancel`, body);
|
|
43
|
+
case "close":
|
|
44
|
+
return apiCall("POST", `/api/v1/stories/${id}/close`, body);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** `POST /api/v1/stories/:id/<verb>`. */
|
|
49
|
+
export async function intervene(
|
|
50
|
+
verb,
|
|
51
|
+
{ story_id, reason, intervention_id } = {},
|
|
52
|
+
{ apiCall, randomUUID = () => crypto.randomUUID() } = {},
|
|
53
|
+
) {
|
|
54
|
+
if (!INTERVENTION_VERBS.includes(verb)) {
|
|
55
|
+
return refuse(`unknown intervention verb ${verb}`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const bad = uuid(story_id, "story_id");
|
|
59
|
+
if (bad) return bad;
|
|
60
|
+
|
|
61
|
+
if (typeof reason !== "string" || reason.trim() === "") {
|
|
62
|
+
return refuse("`reason` is required: why, in words a person can read.");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
let id = intervention_id;
|
|
66
|
+
if (id === undefined || id === null || id === "") {
|
|
67
|
+
id = randomUUID();
|
|
68
|
+
} else {
|
|
69
|
+
const badId = uuid(id, "intervention_id");
|
|
70
|
+
if (badId) return badId;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
return postIntervention(apiCall, verb, story_id, { reason, intervention_id: id });
|
|
74
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// US-52.27a: the machine name a holder reports as its `host`.
|
|
2
|
+
//
|
|
3
|
+
// loopctl wakes an idle session through the runner on the session's machine, and finds that
|
|
4
|
+
// runner by comparing the holder's `host` with the runner's enrolled machine name
|
|
5
|
+
// (Loopctl.Runners.InboxWake). os.hostname() is not that name: on a Mac it is
|
|
6
|
+
// "Marks-Mac-mini" or "Marks-Mac-mini.local" while the runner is enrolled as "mac-mini". So the
|
|
7
|
+
// runner's own config is read first: `control.machine` in the file the runner reads
|
|
8
|
+
// (LOOPCTL_RUNNER_CONFIG, else ~/.config/loopctl-runner/runner.json;
|
|
9
|
+
// runner/lib/loopctl_runner/application.ex). A machine with no runner config, or one that
|
|
10
|
+
// cannot be read, falls back to os.hostname(). Either is normalised the way loopctl compares
|
|
11
|
+
// them (InboxWake.machine/1): trimmed, lowercased, first DNS label.
|
|
12
|
+
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
|
|
15
|
+
const DEFAULT_CONFIG = [".config", "loopctl-runner", "runner.json"];
|
|
16
|
+
|
|
17
|
+
/** Trimmed, lowercased, first DNS label. */
|
|
18
|
+
export function normalizeMachine(name) {
|
|
19
|
+
return String(name).trim().toLowerCase().split(".")[0];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* @param {{ env: object, homedir: () => string, hostname: () => string,
|
|
24
|
+
* readFile: (path: string) => string }} deps
|
|
25
|
+
* @returns {string}
|
|
26
|
+
*/
|
|
27
|
+
export function machineName({ env, homedir, hostname, readFile }) {
|
|
28
|
+
const configured = runnerMachine(env, homedir, readFile);
|
|
29
|
+
return normalizeMachine(configured ?? hostname());
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function runnerMachine(env, homedir, readFile) {
|
|
33
|
+
try {
|
|
34
|
+
const file = env.LOOPCTL_RUNNER_CONFIG || path.join(homedir(), ...DEFAULT_CONFIG);
|
|
35
|
+
const machine = JSON.parse(readFile(file))?.control?.machine;
|
|
36
|
+
return typeof machine === "string" && machine.trim() !== "" ? machine : null;
|
|
37
|
+
} catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
package/lib/messages.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `message_send` (loopctl US-52.23): send one message to a work item's thread (`story_id`), a
|
|
3
|
+
* session's DMs (`to_holder_id`) or a repo channel (`project_id`) — `POST /api/v1/messages`.
|
|
4
|
+
* The keyless refusal of `channel_post` lives here too, because message_send is what replaces
|
|
5
|
+
* free-text channel_post.
|
|
6
|
+
*
|
|
7
|
+
* KEY: the session's own key (`agentKey()` in index.js — the holder credential once the startup
|
|
8
|
+
* register succeeded, else LOOPCTL_AGENT_KEY). The server stamps the author from it: agent_id
|
|
9
|
+
* from the key and author_holder_id from its holder.
|
|
10
|
+
*
|
|
11
|
+
* IDEMPOTENCY: each call mints one idempotency_key (`randomUUID`) and sends that same key on
|
|
12
|
+
* its own retries after a transport error (the request may have been stored before the
|
|
13
|
+
* connection dropped), so a retry returns the stored message (200, created: false) and never
|
|
14
|
+
* stores a second one. A send that got an HTTP answer is never retried here.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { uuid } from "./delivery-loop.js";
|
|
18
|
+
|
|
19
|
+
export const MESSAGE_TARGETS = ["story_id", "to_holder_id", "project_id"];
|
|
20
|
+
|
|
21
|
+
/** Transport retries after the first attempt, each with the same idempotency_key. */
|
|
22
|
+
export const MESSAGE_SEND_RETRIES = 2;
|
|
23
|
+
|
|
24
|
+
export const KEYLESS_CHANNEL_POST_REFUSAL =
|
|
25
|
+
"channel_post now takes only a handoff slot: pass a key starting handoff: (or use the " +
|
|
26
|
+
"handoff tool). Free-text messages go through message_send: message_send {project_id, body} " +
|
|
27
|
+
"posts the same message to the repo channel, and message_send also reaches a work item's " +
|
|
28
|
+
"thread (story_id) or a session's DMs (to_holder_id). Nothing was sent.";
|
|
29
|
+
|
|
30
|
+
function refuse(body) {
|
|
31
|
+
return { error: true, status: 0, body };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function present(value) {
|
|
35
|
+
return value !== undefined && value !== null && !(typeof value === "string" && value.trim() === "");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The local refusal for a channel_post with no `handoff:` key, or null when the call may go
|
|
40
|
+
* ahead. A key that does not start handoff: is left to the server, which refuses it 422
|
|
41
|
+
* keyed_slot_retired with its own remedy.
|
|
42
|
+
*/
|
|
43
|
+
export function refuseKeylessChannelPost({ key } = {}) {
|
|
44
|
+
return present(key) ? null : refuse(KEYLESS_CHANNEL_POST_REFUSAL);
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** True for the `{error, status: 0}` shape index.js's apiCall returns when no HTTP answer came. */
|
|
48
|
+
export function transportError(result) {
|
|
49
|
+
return (
|
|
50
|
+
Boolean(result) &&
|
|
51
|
+
result.error === true &&
|
|
52
|
+
result.status === 0 &&
|
|
53
|
+
typeof result.body === "string" &&
|
|
54
|
+
/^(Network error|Request timed out)/.test(result.body)
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** `POST /api/v1/messages`: send one message, retrying a transport error with the same key. */
|
|
59
|
+
export async function sendMessage(args = {}, { apiCall, randomUUID, retries = MESSAGE_SEND_RETRIES } = {}) {
|
|
60
|
+
const named = MESSAGE_TARGETS.filter((field) => present(args[field]));
|
|
61
|
+
|
|
62
|
+
if (named.length !== 1) {
|
|
63
|
+
return refuse(
|
|
64
|
+
`exactly_one_attachment: pass exactly one of ${MESSAGE_TARGETS.join(", ")}` +
|
|
65
|
+
(named.length === 0 ? "; none was given." : `; got ${named.join(" and ")}.`),
|
|
66
|
+
);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const [target] = named;
|
|
70
|
+
const bad = uuid(args[target], target);
|
|
71
|
+
if (bad) return bad;
|
|
72
|
+
|
|
73
|
+
if (typeof args.body !== "string" || args.body.trim() === "") {
|
|
74
|
+
return refuse("`body` is required: the message text.");
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const payload = {
|
|
78
|
+
[target]: args[target],
|
|
79
|
+
body: args.body,
|
|
80
|
+
idempotency_key: randomUUID(),
|
|
81
|
+
};
|
|
82
|
+
|
|
83
|
+
let result = await apiCall("POST", "/api/v1/messages", payload);
|
|
84
|
+
for (let attempt = 0; attempt < retries && transportError(result); attempt += 1) {
|
|
85
|
+
result = await apiCall("POST", "/api/v1/messages", payload);
|
|
86
|
+
}
|
|
87
|
+
return result;
|
|
88
|
+
}
|