owenloop 0.4.1 → 0.5.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/CHANGELOG.md +26 -0
- package/README.md +58 -31
- package/bin/owenloop.mjs +2 -2
- package/dist/packages/work/src/agent/brief.d.ts +172 -0
- package/dist/packages/work/src/agent/brief.js +193 -0
- package/dist/packages/work/src/agent/loop.d.ts +135 -0
- package/dist/packages/work/src/agent/loop.js +542 -0
- package/dist/packages/work/src/agent/workdir.d.ts +210 -0
- package/dist/packages/work/src/agent/workdir.js +319 -0
- package/dist/packages/work/src/bundle/cache.d.ts +90 -0
- package/dist/packages/work/src/bundle/cache.js +324 -0
- package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
- package/dist/packages/work/src/bundle/fetch.js +325 -0
- package/dist/packages/work/src/bundle/types.d.ts +160 -0
- package/dist/packages/work/src/bundle/types.js +1 -0
- package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
- package/dist/packages/work/src/credentials/owenloop.js +28 -0
- package/dist/packages/work/src/credentials/reader.d.ts +36 -0
- package/dist/packages/work/src/credentials/reader.js +32 -0
- package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
- package/dist/packages/work/src/credentials/resolve.js +56 -0
- package/dist/packages/work/src/exec/loop.d.ts +29 -0
- package/dist/packages/work/src/exec/loop.js +215 -0
- package/dist/packages/work/src/exec/receipt.d.ts +38 -0
- package/dist/packages/work/src/exec/receipt.js +21 -0
- package/dist/packages/work/src/exec/runner.d.ts +65 -0
- package/dist/packages/work/src/exec/runner.js +185 -0
- package/dist/packages/work/src/harness/child-env.d.ts +100 -0
- package/dist/packages/work/src/harness/child-env.js +127 -0
- package/dist/packages/work/src/harness/claude.d.ts +128 -0
- package/dist/packages/work/src/harness/claude.js +635 -0
- package/dist/packages/work/src/harness/codex.d.ts +110 -0
- package/dist/packages/work/src/harness/codex.js +896 -0
- package/dist/packages/work/src/harness/contract.d.ts +283 -0
- package/dist/packages/work/src/harness/contract.js +32 -0
- package/dist/packages/work/src/harness/fake.d.ts +59 -0
- package/dist/packages/work/src/harness/fake.js +90 -0
- package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
- package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
- package/dist/packages/work/src/harness/permissions.d.ts +62 -0
- package/dist/packages/work/src/harness/permissions.js +93 -0
- package/dist/packages/work/src/harness/registry.d.ts +47 -0
- package/dist/packages/work/src/harness/registry.js +45 -0
- package/dist/packages/work/src/harness/session-store.d.ts +163 -0
- package/dist/packages/work/src/harness/session-store.js +319 -0
- package/dist/packages/work/src/harness/types.d.ts +29 -0
- package/dist/packages/work/src/harness/types.js +14 -0
- package/dist/packages/work/src/harnesses.d.ts +38 -0
- package/dist/packages/work/src/harnesses.js +38 -0
- package/dist/packages/work/src/hold/loop.d.ts +36 -0
- package/dist/packages/work/src/hold/loop.js +23 -0
- package/dist/packages/work/src/hold/mcp.d.ts +55 -0
- package/dist/packages/work/src/hold/mcp.js +149 -0
- package/dist/packages/work/src/hub/client.d.ts +22 -0
- package/dist/packages/work/src/hub/client.js +78 -0
- package/dist/packages/work/src/hub/types.d.ts +290 -0
- package/dist/packages/work/src/hub/types.js +28 -0
- package/dist/packages/work/src/lease/loop.d.ts +94 -0
- package/dist/packages/work/src/lease/loop.js +277 -0
- package/dist/packages/work/src/main.d.ts +1 -0
- package/dist/packages/work/src/main.js +48 -0
- package/dist/packages/work/src/mcp/server.d.ts +125 -0
- package/dist/packages/work/src/mcp/server.js +320 -0
- package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
- package/dist/packages/work/src/roles/agent-run.js +447 -0
- package/dist/packages/work/src/roles/exec.d.ts +40 -0
- package/dist/packages/work/src/roles/exec.js +203 -0
- package/dist/packages/work/src/roles/hold.d.ts +68 -0
- package/dist/packages/work/src/roles/hold.js +324 -0
- package/dist/packages/work/src/roles/join.d.ts +18 -0
- package/dist/packages/work/src/roles/join.js +204 -0
- package/dist/packages/work/src/roles/lint.d.ts +59 -0
- package/dist/packages/work/src/roles/lint.js +200 -0
- package/dist/packages/work/src/roles/prepare.d.ts +1 -0
- package/dist/packages/work/src/roles/prepare.js +249 -0
- package/dist/packages/work/src/roles/release.d.ts +48 -0
- package/dist/packages/work/src/roles/release.js +137 -0
- package/dist/packages/work/src/roles/sessions.d.ts +61 -0
- package/dist/packages/work/src/roles/sessions.js +180 -0
- package/dist/packages/work/src/roles/settings.d.ts +6 -0
- package/dist/packages/work/src/roles/settings.js +66 -0
- package/dist/packages/work/src/roles/shift.d.ts +12 -0
- package/dist/packages/work/src/roles/shift.js +228 -0
- package/dist/packages/work/src/roles/signals.d.ts +55 -0
- package/dist/packages/work/src/roles/signals.js +62 -0
- package/dist/packages/work/src/settings/provision.d.ts +21 -0
- package/dist/packages/work/src/settings/provision.js +47 -0
- package/dist/packages/work/src/settings/settings.d.ts +120 -0
- package/dist/packages/work/src/settings/settings.js +116 -0
- package/dist/packages/work/src/shift/client.d.ts +24 -0
- package/dist/packages/work/src/shift/client.js +124 -0
- package/dist/packages/work/src/shift/loop.d.ts +120 -0
- package/dist/packages/work/src/shift/loop.js +468 -0
- package/dist/packages/work/src/shift/protocol.d.ts +91 -0
- package/dist/packages/work/src/shift/protocol.js +24 -0
- package/dist/packages/work/src/shift/routing.d.ts +35 -0
- package/dist/packages/work/src/shift/routing.js +50 -0
- package/dist/packages/work/src/shift/runtime.d.ts +43 -0
- package/dist/packages/work/src/shift/runtime.js +274 -0
- package/dist/packages/work/src/shift/server.d.ts +23 -0
- package/dist/packages/work/src/shift/server.js +716 -0
- package/dist/packages/work/src/shift/spawn.d.ts +86 -0
- package/dist/packages/work/src/shift/spawn.js +100 -0
- package/dist/packages/work/src/shift/state.d.ts +77 -0
- package/dist/packages/work/src/shift/state.js +162 -0
- package/dist/packages/work/src/usage.d.ts +6 -0
- package/dist/packages/work/src/usage.js +175 -0
- package/dist/{cli.d.ts → src/cli.d.ts} +18 -3
- package/dist/{cli.js → src/cli.js} +770 -114
- package/dist/{credentials.d.ts → src/credentials.d.ts} +18 -12
- package/dist/{credentials.js → src/credentials.js} +14 -12
- package/dist/{defs.js → src/defs.js} +36 -36
- package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
- package/dist/{engine.js → src/engine.js} +14 -14
- package/dist/{hub.d.ts → src/hub.d.ts} +205 -10
- package/dist/{hub.js → src/hub.js} +370 -12
- package/dist/{index.d.ts → src/index.d.ts} +1 -1
- package/dist/{index.js → src/index.js} +1 -1
- package/dist/{mcp → src/mcp}/serve.d.ts +5 -4
- package/dist/{mcp → src/mcp}/serve.js +168 -31
- package/dist/{mcp → src/mcp}/server.d.ts +6 -9
- package/dist/{mcp → src/mcp}/server.js +6 -9
- package/dist/{model.js → src/model.js} +1 -1
- package/dist/{types.d.ts → src/types.d.ts} +18 -18
- package/dist/{util.d.ts → src/util.d.ts} +3 -2
- package/dist/{util.js → src/util.js} +3 -2
- package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
- package/dist/{owenwork.js → src/work-settings.js} +27 -27
- package/docs/authoring.md +93 -53
- package/docs/cli.md +597 -76
- package/docs/design.md +33 -33
- package/docs/embedding.md +10 -9
- package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
- package/examples/workflows/compile-dev-playbook.yaml +338 -0
- package/examples/workflows/judges/gate-sharpness.md +39 -0
- package/examples/workflows/judges/security.md +34 -0
- package/package.json +17 -8
- /package/dist/{add.d.ts → src/add.d.ts} +0 -0
- /package/dist/{add.js → src/add.js} +0 -0
- /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
- /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
- /package/dist/{factory.js → src/factory.js} +0 -0
- /package/dist/{lock.d.ts → src/lock.d.ts} +0 -0
- /package/dist/{lock.js → src/lock.js} +0 -0
- /package/dist/{model.d.ts → src/model.d.ts} +0 -0
- /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
- /package/dist/{paths.js → src/paths.js} +0 -0
- /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
- /package/dist/{schema.js → src/schema.js} +0 -0
- /package/dist/{store.d.ts → src/store.d.ts} +0 -0
- /package/dist/{store.js → src/store.js} +0 -0
- /package/dist/{types.js → src/types.js} +0 -0
- /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
- /package/dist/{untar.js → src/untar.js} +0 -0
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shift daemon: owns one Unix socket, one self-driven ShiftLoop, a bounded
|
|
3
|
+
* local event FIFO, and at most one parked `next` client.
|
|
4
|
+
*
|
|
5
|
+
* The loop remains the only owner of hub cursor, presence cadence, capacity,
|
|
6
|
+
* dispatch, and child reconciliation. This wrapper only translates local socket
|
|
7
|
+
* requests and loop observations into the Phase 2 JSON-lines protocol.
|
|
8
|
+
*/
|
|
9
|
+
import { chmodSync, lstatSync, mkdirSync, renameSync, unlinkSync, } from 'node:fs';
|
|
10
|
+
import { createServer, createConnection } from 'node:net';
|
|
11
|
+
import { MAX_EVENT_QUEUE, MAX_REQUEST_LINE_BYTES, MAX_RESPONSE_LINE_BYTES, OVERLAP_ERROR, RESPONSE_TRUNCATION_MARKER, } from "./protocol.js";
|
|
12
|
+
const REQUEST_IDLE_TIMEOUT_MS = 5_000;
|
|
13
|
+
const SHUTDOWN_GRACE_MS = 500;
|
|
14
|
+
function serializedResponseBytes(response) {
|
|
15
|
+
return Buffer.byteLength(`${JSON.stringify(response)}\n`, 'utf8');
|
|
16
|
+
}
|
|
17
|
+
function truncateUtf8(value, maxBytes) {
|
|
18
|
+
if (Buffer.byteLength(value, 'utf8') <= maxBytes)
|
|
19
|
+
return value;
|
|
20
|
+
const markerBytes = Buffer.byteLength(RESPONSE_TRUNCATION_MARKER, 'utf8');
|
|
21
|
+
if (maxBytes <= markerBytes)
|
|
22
|
+
return RESPONSE_TRUNCATION_MARKER;
|
|
23
|
+
let prefix = Buffer.from(value, 'utf8').subarray(0, maxBytes - markerBytes).toString('utf8');
|
|
24
|
+
while (Buffer.byteLength(prefix, 'utf8') > maxBytes - markerBytes)
|
|
25
|
+
prefix = prefix.slice(0, -1);
|
|
26
|
+
return `${prefix}${RESPONSE_TRUNCATION_MARKER}`;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* A single event can be larger than the response ceiling. It is delivered once
|
|
30
|
+
* with its string fields shortened and an explicit marker instead of blocking
|
|
31
|
+
* every later event in the FIFO forever.
|
|
32
|
+
*/
|
|
33
|
+
function truncateEventForResponse(event, envelope) {
|
|
34
|
+
const candidate = { ...event };
|
|
35
|
+
const stringKeys = Object.keys(candidate).filter((key) => typeof candidate[key] === 'string' && key !== 'type');
|
|
36
|
+
const markerBytes = Buffer.byteLength(RESPONSE_TRUNCATION_MARKER, 'utf8');
|
|
37
|
+
while (serializedResponseBytes({ ...envelope, events: [candidate] }) > MAX_RESPONSE_LINE_BYTES) {
|
|
38
|
+
const key = stringKeys
|
|
39
|
+
.filter((name) => candidate[name] !== RESPONSE_TRUNCATION_MARKER)
|
|
40
|
+
.sort((left, right) => Buffer.byteLength(String(candidate[right]), 'utf8') - Buffer.byteLength(String(candidate[left]), 'utf8'))[0];
|
|
41
|
+
if (key === undefined)
|
|
42
|
+
break;
|
|
43
|
+
const value = String(candidate[key]);
|
|
44
|
+
const currentBytes = Buffer.byteLength(value, 'utf8');
|
|
45
|
+
const targetBytes = Math.max(markerBytes, Math.floor(currentBytes / 2));
|
|
46
|
+
const shortened = truncateUtf8(value, targetBytes);
|
|
47
|
+
candidate[key] = shortened === value ? RESPONSE_TRUNCATION_MARKER : shortened;
|
|
48
|
+
}
|
|
49
|
+
// The current event union has a fixed envelope plus only string fields. The
|
|
50
|
+
// marker-only form is a final backstop if a future event shape needs more
|
|
51
|
+
// reduction than the progressive shortening above provided.
|
|
52
|
+
if (serializedResponseBytes({ ...envelope, events: [candidate] }) > MAX_RESPONSE_LINE_BYTES) {
|
|
53
|
+
for (const key of stringKeys)
|
|
54
|
+
candidate[key] = RESPONSE_TRUNCATION_MARKER;
|
|
55
|
+
}
|
|
56
|
+
return candidate;
|
|
57
|
+
}
|
|
58
|
+
function fileIdentity(stat) {
|
|
59
|
+
return { dev: stat.dev, ino: stat.ino, ctimeMs: stat.ctimeMs };
|
|
60
|
+
}
|
|
61
|
+
function sameFileIdentity(left, right) {
|
|
62
|
+
return left.dev === right.dev && left.ino === right.ino && left.ctimeMs === right.ctimeMs;
|
|
63
|
+
}
|
|
64
|
+
function errorResponse(message) {
|
|
65
|
+
return { error: message };
|
|
66
|
+
}
|
|
67
|
+
function errMsg(error) {
|
|
68
|
+
return error instanceof Error ? error.message : String(error);
|
|
69
|
+
}
|
|
70
|
+
function isStaleSocketError(error) {
|
|
71
|
+
const code = error?.code;
|
|
72
|
+
return code === 'ECONNREFUSED' || code === 'ENOENT' || code === 'ENOTCONN' || code === 'EPIPE' || code === 'ETIMEDOUT';
|
|
73
|
+
}
|
|
74
|
+
async function probeSocket(path) {
|
|
75
|
+
return new Promise((resolve, reject) => {
|
|
76
|
+
const socket = createConnection(path);
|
|
77
|
+
let settled = false;
|
|
78
|
+
const finish = (result) => {
|
|
79
|
+
if (settled)
|
|
80
|
+
return;
|
|
81
|
+
settled = true;
|
|
82
|
+
socket.destroy();
|
|
83
|
+
resolve(result);
|
|
84
|
+
};
|
|
85
|
+
socket.once('connect', () => finish('active'));
|
|
86
|
+
socket.once('error', (error) => {
|
|
87
|
+
if (isStaleSocketError(error))
|
|
88
|
+
finish('stale');
|
|
89
|
+
else {
|
|
90
|
+
settled = true;
|
|
91
|
+
socket.destroy();
|
|
92
|
+
reject(error);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
socket.setTimeout(250, () => finish('stale'));
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
async function bindStartupLock(path) {
|
|
99
|
+
const lockServer = createServer();
|
|
100
|
+
try {
|
|
101
|
+
await new Promise((resolve, reject) => {
|
|
102
|
+
const onError = (error) => {
|
|
103
|
+
lockServer.off('listening', onListening);
|
|
104
|
+
reject(error);
|
|
105
|
+
};
|
|
106
|
+
const onListening = () => {
|
|
107
|
+
lockServer.off('error', onError);
|
|
108
|
+
resolve();
|
|
109
|
+
};
|
|
110
|
+
lockServer.once('error', onError);
|
|
111
|
+
lockServer.once('listening', onListening);
|
|
112
|
+
lockServer.listen(path);
|
|
113
|
+
});
|
|
114
|
+
return lockServer;
|
|
115
|
+
}
|
|
116
|
+
catch (error) {
|
|
117
|
+
try {
|
|
118
|
+
lockServer.close();
|
|
119
|
+
}
|
|
120
|
+
catch { /* not listening */ }
|
|
121
|
+
throw error;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Acquire an atomic, probeable startup lock.
|
|
126
|
+
*
|
|
127
|
+
* The lock is itself a Unix listener. `listen()` is the atomic acquisition
|
|
128
|
+
* point, and a crashed owner leaves a socket path that a successor can probe;
|
|
129
|
+
* ownership therefore does not depend on a PID that the OS could later reuse.
|
|
130
|
+
*/
|
|
131
|
+
async function acquireStartupLock(socketPath) {
|
|
132
|
+
const lockPath = `${socketPath}.lock`;
|
|
133
|
+
const waitUntil = Date.now() + 2_000;
|
|
134
|
+
for (;;) {
|
|
135
|
+
try {
|
|
136
|
+
const lockServer = await bindStartupLock(lockPath);
|
|
137
|
+
try {
|
|
138
|
+
chmodSync(lockPath, 0o600);
|
|
139
|
+
return { path: lockPath, server: lockServer, identity: fileIdentity(lstatSync(lockPath)) };
|
|
140
|
+
}
|
|
141
|
+
catch (error) {
|
|
142
|
+
try {
|
|
143
|
+
lockServer.close();
|
|
144
|
+
}
|
|
145
|
+
catch { /* best effort */ }
|
|
146
|
+
try {
|
|
147
|
+
unlinkSync(lockPath);
|
|
148
|
+
}
|
|
149
|
+
catch { /* best effort */ }
|
|
150
|
+
throw error;
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
catch (error) {
|
|
154
|
+
const code = error?.code;
|
|
155
|
+
if (code !== 'EADDRINUSE')
|
|
156
|
+
throw error;
|
|
157
|
+
}
|
|
158
|
+
let current;
|
|
159
|
+
try {
|
|
160
|
+
current = lstatSync(lockPath);
|
|
161
|
+
}
|
|
162
|
+
catch (error) {
|
|
163
|
+
if (error?.code === 'ENOENT')
|
|
164
|
+
continue;
|
|
165
|
+
throw error;
|
|
166
|
+
}
|
|
167
|
+
if (!current.isSocket()) {
|
|
168
|
+
throw new Error(`cannot start shift daemon: startup lock ${lockPath} exists and is not a socket`);
|
|
169
|
+
}
|
|
170
|
+
const observedIdentity = fileIdentity(current);
|
|
171
|
+
const probe = await probeSocket(lockPath);
|
|
172
|
+
if (probe === 'active') {
|
|
173
|
+
if (Date.now() >= waitUntil) {
|
|
174
|
+
throw new Error(`cannot start shift daemon: another daemon is starting at ${socketPath}`);
|
|
175
|
+
}
|
|
176
|
+
await new Promise((resolve) => setTimeout(resolve, 10));
|
|
177
|
+
continue;
|
|
178
|
+
}
|
|
179
|
+
let currentAgain;
|
|
180
|
+
try {
|
|
181
|
+
currentAgain = lstatSync(lockPath);
|
|
182
|
+
}
|
|
183
|
+
catch (error) {
|
|
184
|
+
if (error?.code === 'ENOENT')
|
|
185
|
+
continue;
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
if (!sameFileIdentity(observedIdentity, fileIdentity(currentAgain)))
|
|
189
|
+
continue;
|
|
190
|
+
// ACCEPTED LIMITATION: this lstat-then-unlink sequence is not atomic. A
|
|
191
|
+
// same-user hostile local process could substitute the path between the
|
|
192
|
+
// check and unlink, but the 0600 socket is in the user's own state
|
|
193
|
+
// directory, where that process already has direct write access.
|
|
194
|
+
try {
|
|
195
|
+
unlinkSync(lockPath);
|
|
196
|
+
}
|
|
197
|
+
catch (error) {
|
|
198
|
+
if (error?.code !== 'ENOENT')
|
|
199
|
+
throw error;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
function releaseStartupLock(lock) {
|
|
204
|
+
try {
|
|
205
|
+
lock.server.close();
|
|
206
|
+
}
|
|
207
|
+
catch { /* already closed */ }
|
|
208
|
+
try {
|
|
209
|
+
const current = lstatSync(lock.path);
|
|
210
|
+
if (sameFileIdentity(lock.identity, fileIdentity(current)))
|
|
211
|
+
unlinkSync(lock.path);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
// The lock may already have been reclaimed after a crash or operator action.
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
function forceCloseSocket(socket) {
|
|
218
|
+
socket.unref();
|
|
219
|
+
try {
|
|
220
|
+
// resetAndDestroy aborts queued writes instead of waiting for a client
|
|
221
|
+
// that stopped reading. Older Node versions fall back to destroy().
|
|
222
|
+
if (typeof socket.resetAndDestroy === 'function')
|
|
223
|
+
socket.resetAndDestroy();
|
|
224
|
+
else
|
|
225
|
+
socket.destroy();
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
socket.destroy();
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
function writeResponse(socket, response) {
|
|
232
|
+
if (socket.destroyed)
|
|
233
|
+
return;
|
|
234
|
+
try {
|
|
235
|
+
socket.end(`${JSON.stringify(response)}\n`, () => socket.destroy());
|
|
236
|
+
}
|
|
237
|
+
catch {
|
|
238
|
+
forceCloseSocket(socket);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
function validateRequest(value) {
|
|
242
|
+
if (typeof value !== 'object' || value === null || Array.isArray(value))
|
|
243
|
+
return errorResponse('request must be a JSON object');
|
|
244
|
+
const obj = value;
|
|
245
|
+
const op = obj['op'];
|
|
246
|
+
if (op === 'status' || op === 'end')
|
|
247
|
+
return { op };
|
|
248
|
+
if (op === 'next') {
|
|
249
|
+
const wait = obj['wait_ms'];
|
|
250
|
+
if (typeof wait !== 'number' || !Number.isFinite(wait) || wait < 0) {
|
|
251
|
+
return errorResponse('next wait_ms must be a finite non-negative number');
|
|
252
|
+
}
|
|
253
|
+
return { op: 'next', wait_ms: wait };
|
|
254
|
+
}
|
|
255
|
+
if (op === 'clock_in') {
|
|
256
|
+
const name = obj['name'];
|
|
257
|
+
const crews = obj['serve_crews'];
|
|
258
|
+
if (typeof name !== 'string' || name.trim() === '' || name.trim().length > 200) {
|
|
259
|
+
return errorResponse('clock_in name must be a non-empty string of at most 200 characters');
|
|
260
|
+
}
|
|
261
|
+
if (!Array.isArray(crews) || !crews.every((crew) => typeof crew === 'string' && crew.trim() !== '')) {
|
|
262
|
+
return errorResponse('clock_in serve_crews must be an array of non-empty crew names');
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
op: 'clock_in',
|
|
266
|
+
name: name.trim(),
|
|
267
|
+
serve_crews: crews.map((crew) => crew.trim()),
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
return errorResponse(typeof op === 'string' ? `unknown operation '${op}'` : 'request requires an operation');
|
|
271
|
+
}
|
|
272
|
+
export function createShiftDaemon(opts) {
|
|
273
|
+
let server;
|
|
274
|
+
let socketIdentity;
|
|
275
|
+
let opened = false;
|
|
276
|
+
let shutdownStarted = false;
|
|
277
|
+
let shutdownReason;
|
|
278
|
+
let shutdownPromise;
|
|
279
|
+
let loopPromise;
|
|
280
|
+
let parked;
|
|
281
|
+
let shutdownGraceTimer;
|
|
282
|
+
const connections = new Set();
|
|
283
|
+
const shutdownSockets = new Set();
|
|
284
|
+
const events = [];
|
|
285
|
+
const capacity = () => {
|
|
286
|
+
const cap = opts.loop.getCap();
|
|
287
|
+
const free = opts.loop.freeCapacity();
|
|
288
|
+
return { cap, free, running: cap - free };
|
|
289
|
+
};
|
|
290
|
+
const status = () => {
|
|
291
|
+
const shift = opts.loop.getShift();
|
|
292
|
+
return {
|
|
293
|
+
name: shift.name,
|
|
294
|
+
serve_crews: shift.serveCrews,
|
|
295
|
+
...capacity(),
|
|
296
|
+
attended_at: opts.loop.getAttendedAt() ?? null,
|
|
297
|
+
started_at: opts.startedAt,
|
|
298
|
+
};
|
|
299
|
+
};
|
|
300
|
+
const respond = (socket, response) => {
|
|
301
|
+
writeResponse(socket, response);
|
|
302
|
+
};
|
|
303
|
+
const sendParked = (response) => {
|
|
304
|
+
const current = parked;
|
|
305
|
+
if (current === undefined)
|
|
306
|
+
return;
|
|
307
|
+
parked = undefined;
|
|
308
|
+
if (current.timer !== undefined)
|
|
309
|
+
clearTimeout(current.timer);
|
|
310
|
+
respond(current.socket, response);
|
|
311
|
+
};
|
|
312
|
+
const capacityResponse = () => {
|
|
313
|
+
const envelope = capacity();
|
|
314
|
+
const selected = [];
|
|
315
|
+
while (selected.length < events.length) {
|
|
316
|
+
const next = events[selected.length];
|
|
317
|
+
const candidate = { ...envelope, events: [...selected, next] };
|
|
318
|
+
if (serializedResponseBytes(candidate) <= MAX_RESPONSE_LINE_BYTES) {
|
|
319
|
+
selected.push(next);
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
322
|
+
if (selected.length > 0)
|
|
323
|
+
break;
|
|
324
|
+
// Never let one pathological event block the FIFO permanently. The
|
|
325
|
+
// original event is consumed once as a marked, size-safe representation.
|
|
326
|
+
const shortened = truncateEventForResponse(next, envelope);
|
|
327
|
+
selected.push(shortened);
|
|
328
|
+
}
|
|
329
|
+
events.splice(0, selected.length);
|
|
330
|
+
return { ...envelope, events: selected };
|
|
331
|
+
};
|
|
332
|
+
const enqueue = (event) => {
|
|
333
|
+
if (events.length >= MAX_EVENT_QUEUE) {
|
|
334
|
+
events.shift();
|
|
335
|
+
opts.err(`shift event queue overflow — dropping oldest event`);
|
|
336
|
+
}
|
|
337
|
+
events.push(event);
|
|
338
|
+
if (parked !== undefined)
|
|
339
|
+
sendParked(capacityResponse());
|
|
340
|
+
};
|
|
341
|
+
const onEvent = (event) => enqueue(event);
|
|
342
|
+
const cleanupSocket = () => {
|
|
343
|
+
if (!opened)
|
|
344
|
+
return;
|
|
345
|
+
try {
|
|
346
|
+
const current = lstatSync(opts.socketPath);
|
|
347
|
+
if (!current.isSocket())
|
|
348
|
+
return;
|
|
349
|
+
if (socketIdentity !== undefined && !sameFileIdentity(socketIdentity, fileIdentity(current)))
|
|
350
|
+
return;
|
|
351
|
+
unlinkSync(opts.socketPath);
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
// The socket may already have been removed by an operator or a failed bind.
|
|
355
|
+
}
|
|
356
|
+
opened = false;
|
|
357
|
+
};
|
|
358
|
+
const closeListening = async () => {
|
|
359
|
+
if (server === undefined) {
|
|
360
|
+
cleanupSocket();
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
const current = server;
|
|
364
|
+
server = undefined;
|
|
365
|
+
// Node removes a Unix socket by pathname when Server.close() completes.
|
|
366
|
+
// If another process replaced our path after the original socket was
|
|
367
|
+
// unlinked, move the successor aside until the old server has closed. This
|
|
368
|
+
// prevents the old server from removing the successor by pathname.
|
|
369
|
+
let preservedPath;
|
|
370
|
+
try {
|
|
371
|
+
const currentPath = lstatSync(opts.socketPath);
|
|
372
|
+
if (socketIdentity !== undefined && currentPath.isSocket() && !sameFileIdentity(socketIdentity, fileIdentity(currentPath))) {
|
|
373
|
+
preservedPath = `${opts.socketPath}.closing-${process.pid}-${Date.now()}`;
|
|
374
|
+
renameSync(opts.socketPath, preservedPath);
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
catch {
|
|
378
|
+
// The path may already be absent; the server can still be closed.
|
|
379
|
+
}
|
|
380
|
+
const restoreSuccessor = () => {
|
|
381
|
+
if (preservedPath === undefined)
|
|
382
|
+
return;
|
|
383
|
+
try {
|
|
384
|
+
try {
|
|
385
|
+
lstatSync(opts.socketPath);
|
|
386
|
+
unlinkSync(preservedPath);
|
|
387
|
+
}
|
|
388
|
+
catch {
|
|
389
|
+
renameSync(preservedPath, opts.socketPath);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
catch {
|
|
393
|
+
// Best effort. Never remove a path that appeared after the rename.
|
|
394
|
+
}
|
|
395
|
+
};
|
|
396
|
+
if (preservedPath !== undefined) {
|
|
397
|
+
// Do not await the callback: an end request must still be able to write
|
|
398
|
+
// its acknowledgement on the already accepted connection. The successor
|
|
399
|
+
// is restored when the old listener has finished closing.
|
|
400
|
+
try {
|
|
401
|
+
current.close(() => restoreSuccessor());
|
|
402
|
+
}
|
|
403
|
+
catch {
|
|
404
|
+
restoreSuccessor();
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
else {
|
|
408
|
+
// Do not await the callback: an end request must still be able to write
|
|
409
|
+
// its acknowledgement on the already accepted connection.
|
|
410
|
+
try {
|
|
411
|
+
current.close();
|
|
412
|
+
}
|
|
413
|
+
catch {
|
|
414
|
+
// already closed
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
cleanupSocket();
|
|
418
|
+
};
|
|
419
|
+
const finalClear = async () => {
|
|
420
|
+
const shift = opts.loop.getShift();
|
|
421
|
+
try {
|
|
422
|
+
await opts.hub.presencePing({
|
|
423
|
+
name: shift.name,
|
|
424
|
+
serve_crews: shift.serveCrews,
|
|
425
|
+
...(opts.shiftId !== undefined ? { shift_id: opts.shiftId } : {}),
|
|
426
|
+
started_at: opts.startedAt,
|
|
427
|
+
// Deliberately omit attended_at. The merged hub contract interprets
|
|
428
|
+
// omission as overwrite-to-NULL; JSON null is rejected by validation.
|
|
429
|
+
});
|
|
430
|
+
}
|
|
431
|
+
catch (error) {
|
|
432
|
+
opts.err(`final shift presence clear failed: ${errMsg(error)} (continuing shutdown)`);
|
|
433
|
+
}
|
|
434
|
+
};
|
|
435
|
+
const destroyConnections = () => {
|
|
436
|
+
for (const socket of connections) {
|
|
437
|
+
if (shutdownSockets.has(socket))
|
|
438
|
+
continue;
|
|
439
|
+
forceCloseSocket(socket);
|
|
440
|
+
}
|
|
441
|
+
};
|
|
442
|
+
const armShutdownGrace = () => {
|
|
443
|
+
if (shutdownGraceTimer !== undefined || connections.size === 0)
|
|
444
|
+
return;
|
|
445
|
+
shutdownGraceTimer = setTimeout(() => {
|
|
446
|
+
shutdownGraceTimer = undefined;
|
|
447
|
+
for (const socket of connections)
|
|
448
|
+
forceCloseSocket(socket);
|
|
449
|
+
}, SHUTDOWN_GRACE_MS);
|
|
450
|
+
};
|
|
451
|
+
const requestShutdown = (reason, preserve) => {
|
|
452
|
+
if (shutdownPromise !== undefined) {
|
|
453
|
+
if (preserve !== undefined)
|
|
454
|
+
shutdownSockets.add(preserve);
|
|
455
|
+
return shutdownPromise;
|
|
456
|
+
}
|
|
457
|
+
shutdownStarted = true;
|
|
458
|
+
shutdownReason = reason;
|
|
459
|
+
shutdownSockets.clear();
|
|
460
|
+
if (preserve !== undefined)
|
|
461
|
+
shutdownSockets.add(preserve);
|
|
462
|
+
if (reason === 'end') {
|
|
463
|
+
if (parked !== undefined)
|
|
464
|
+
shutdownSockets.add(parked.socket);
|
|
465
|
+
enqueue({ type: 'ended' });
|
|
466
|
+
}
|
|
467
|
+
else if (parked !== undefined) {
|
|
468
|
+
// A signal or unexpected loop exit does not synthesize an `ended` event,
|
|
469
|
+
// but it must not leave a client socket holding the process open forever.
|
|
470
|
+
const current = parked;
|
|
471
|
+
parked = undefined;
|
|
472
|
+
if (current.timer !== undefined)
|
|
473
|
+
clearTimeout(current.timer);
|
|
474
|
+
}
|
|
475
|
+
// Do not exempt already-responded sockets: socket.end() can still be
|
|
476
|
+
// blocked on a client that stopped reading. New connections are rejected
|
|
477
|
+
// by handleConnection while shutdownStarted is true.
|
|
478
|
+
destroyConnections();
|
|
479
|
+
opts.loop.stop();
|
|
480
|
+
shutdownPromise = (async () => {
|
|
481
|
+
if (loopPromise !== undefined) {
|
|
482
|
+
try {
|
|
483
|
+
await loopPromise;
|
|
484
|
+
}
|
|
485
|
+
catch (error) {
|
|
486
|
+
opts.err(`shift loop failed during shutdown: ${errMsg(error)}`);
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
if (shutdownReason === 'end')
|
|
490
|
+
await finalClear();
|
|
491
|
+
await closeListening();
|
|
492
|
+
// The end acknowledgement and a parked `ended` response are allowed a
|
|
493
|
+
// bounded flush window; an unread client must not keep the daemon alive.
|
|
494
|
+
armShutdownGrace();
|
|
495
|
+
})();
|
|
496
|
+
return shutdownPromise;
|
|
497
|
+
};
|
|
498
|
+
const handleRequest = async (socket, value) => {
|
|
499
|
+
const parsed = validateRequest(value);
|
|
500
|
+
if ('error' in parsed) {
|
|
501
|
+
respond(socket, parsed);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
if (parsed.op === 'status') {
|
|
505
|
+
respond(socket, status());
|
|
506
|
+
return;
|
|
507
|
+
}
|
|
508
|
+
if (shutdownStarted && parsed.op !== 'end') {
|
|
509
|
+
respond(socket, errorResponse('shift daemon is ending'));
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
if (parsed.op === 'clock_in') {
|
|
513
|
+
// validateRequest completed all validation before this mutation.
|
|
514
|
+
opts.loop.setShift({ name: parsed.name, serveCrews: parsed.serve_crews });
|
|
515
|
+
respond(socket, status());
|
|
516
|
+
return;
|
|
517
|
+
}
|
|
518
|
+
if (parsed.op === 'end') {
|
|
519
|
+
await requestShutdown('end', socket);
|
|
520
|
+
respond(socket, { ok: true, ended: true });
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
// `next` is the only operation that can remain parked.
|
|
524
|
+
if (parked !== undefined) {
|
|
525
|
+
respond(socket, errorResponse(OVERLAP_ERROR));
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
opts.loop.noteAttended(opts.now());
|
|
529
|
+
const current = capacityResponse();
|
|
530
|
+
if (current.events.length > 0 || parsed.wait_ms === 0 || shutdownStarted) {
|
|
531
|
+
respond(socket, current);
|
|
532
|
+
return;
|
|
533
|
+
}
|
|
534
|
+
const timer = setTimeout(() => {
|
|
535
|
+
if (parked?.socket !== socket)
|
|
536
|
+
return;
|
|
537
|
+
sendParked(capacityResponse());
|
|
538
|
+
}, parsed.wait_ms);
|
|
539
|
+
parked = { socket, timer };
|
|
540
|
+
};
|
|
541
|
+
const handleConnection = (socket) => {
|
|
542
|
+
connections.add(socket);
|
|
543
|
+
if (shutdownStarted) {
|
|
544
|
+
connections.delete(socket);
|
|
545
|
+
forceCloseSocket(socket);
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
let buffer = Buffer.alloc(0);
|
|
549
|
+
let replied = false;
|
|
550
|
+
const replyError = (message) => {
|
|
551
|
+
if (replied)
|
|
552
|
+
return;
|
|
553
|
+
replied = true;
|
|
554
|
+
respond(socket, errorResponse(message));
|
|
555
|
+
};
|
|
556
|
+
socket.setTimeout(REQUEST_IDLE_TIMEOUT_MS, () => {
|
|
557
|
+
if (!replied)
|
|
558
|
+
replyError('request timed out waiting for a complete line');
|
|
559
|
+
});
|
|
560
|
+
socket.on('data', (chunk) => {
|
|
561
|
+
if (replied)
|
|
562
|
+
return;
|
|
563
|
+
buffer = Buffer.concat([buffer, chunk]);
|
|
564
|
+
if (buffer.length > MAX_REQUEST_LINE_BYTES) {
|
|
565
|
+
replyError(`request line exceeds ${MAX_REQUEST_LINE_BYTES} bytes`);
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
const newline = buffer.indexOf(0x0a);
|
|
569
|
+
if (newline === -1)
|
|
570
|
+
return;
|
|
571
|
+
replied = true;
|
|
572
|
+
socket.setTimeout(0);
|
|
573
|
+
const raw = buffer.subarray(0, newline).toString('utf8');
|
|
574
|
+
let value;
|
|
575
|
+
try {
|
|
576
|
+
value = JSON.parse(raw);
|
|
577
|
+
}
|
|
578
|
+
catch {
|
|
579
|
+
respond(socket, errorResponse('malformed JSON request'));
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
void handleRequest(socket, value).catch((error) => {
|
|
583
|
+
respond(socket, errorResponse(errMsg(error)));
|
|
584
|
+
});
|
|
585
|
+
});
|
|
586
|
+
socket.on('error', () => {
|
|
587
|
+
// A client disappearing while parked is equivalent to cancellation. Do not
|
|
588
|
+
// leave the single-park slot held forever.
|
|
589
|
+
if (parked?.socket === socket) {
|
|
590
|
+
if (parked.timer !== undefined)
|
|
591
|
+
clearTimeout(parked.timer);
|
|
592
|
+
parked = undefined;
|
|
593
|
+
}
|
|
594
|
+
});
|
|
595
|
+
socket.on('close', () => {
|
|
596
|
+
connections.delete(socket);
|
|
597
|
+
shutdownSockets.delete(socket);
|
|
598
|
+
if (parked?.socket === socket) {
|
|
599
|
+
if (parked.timer !== undefined)
|
|
600
|
+
clearTimeout(parked.timer);
|
|
601
|
+
parked = undefined;
|
|
602
|
+
}
|
|
603
|
+
if (connections.size === 0 && shutdownGraceTimer !== undefined) {
|
|
604
|
+
clearTimeout(shutdownGraceTimer);
|
|
605
|
+
shutdownGraceTimer = undefined;
|
|
606
|
+
}
|
|
607
|
+
});
|
|
608
|
+
};
|
|
609
|
+
const openSocket = async () => {
|
|
610
|
+
mkdirSync(opts.stateDir, { recursive: true });
|
|
611
|
+
const startupLock = await acquireStartupLock(opts.socketPath);
|
|
612
|
+
try {
|
|
613
|
+
try {
|
|
614
|
+
const current = lstatSync(opts.socketPath);
|
|
615
|
+
if (!current.isSocket()) {
|
|
616
|
+
throw new Error(`cannot start shift daemon: ${opts.socketPath} exists and is not a socket`);
|
|
617
|
+
}
|
|
618
|
+
const probedIdentity = fileIdentity(current);
|
|
619
|
+
const probe = await probeSocket(opts.socketPath);
|
|
620
|
+
if (probe === 'active')
|
|
621
|
+
throw new Error(`cannot start shift daemon: another daemon is active at ${opts.socketPath}`);
|
|
622
|
+
try {
|
|
623
|
+
const beforeUnlink = lstatSync(opts.socketPath);
|
|
624
|
+
if (!sameFileIdentity(probedIdentity, fileIdentity(beforeUnlink))) {
|
|
625
|
+
throw new Error(`cannot start shift daemon: socket changed while checking ${opts.socketPath}`);
|
|
626
|
+
}
|
|
627
|
+
// ACCEPTED LIMITATION: this lstat-then-unlink sequence is not
|
|
628
|
+
// atomic. A same-user hostile local process could substitute the
|
|
629
|
+
// path between the check and unlink, but the 0600 socket is in the
|
|
630
|
+
// user's own state directory, where that process already has direct
|
|
631
|
+
// write access.
|
|
632
|
+
unlinkSync(opts.socketPath);
|
|
633
|
+
}
|
|
634
|
+
catch (error) {
|
|
635
|
+
if (error?.code !== 'ENOENT')
|
|
636
|
+
throw error;
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
catch (error) {
|
|
640
|
+
const code = error?.code;
|
|
641
|
+
if (code !== 'ENOENT')
|
|
642
|
+
throw error;
|
|
643
|
+
}
|
|
644
|
+
const nextServer = createServer(handleConnection);
|
|
645
|
+
server = nextServer;
|
|
646
|
+
await new Promise((resolve, reject) => {
|
|
647
|
+
const onError = (error) => {
|
|
648
|
+
nextServer.off('listening', onListening);
|
|
649
|
+
server = undefined;
|
|
650
|
+
try {
|
|
651
|
+
nextServer.close();
|
|
652
|
+
}
|
|
653
|
+
catch { /* not listening */ }
|
|
654
|
+
reject(error);
|
|
655
|
+
};
|
|
656
|
+
const onListening = () => {
|
|
657
|
+
nextServer.off('error', onError);
|
|
658
|
+
resolve();
|
|
659
|
+
};
|
|
660
|
+
nextServer.once('error', onError);
|
|
661
|
+
nextServer.once('listening', onListening);
|
|
662
|
+
nextServer.listen(opts.socketPath);
|
|
663
|
+
});
|
|
664
|
+
try {
|
|
665
|
+
chmodSync(opts.socketPath, 0o600);
|
|
666
|
+
socketIdentity = fileIdentity(lstatSync(opts.socketPath));
|
|
667
|
+
opened = true;
|
|
668
|
+
}
|
|
669
|
+
catch (error) {
|
|
670
|
+
server = undefined;
|
|
671
|
+
try {
|
|
672
|
+
nextServer.close();
|
|
673
|
+
}
|
|
674
|
+
catch {
|
|
675
|
+
// best effort
|
|
676
|
+
}
|
|
677
|
+
throw error;
|
|
678
|
+
}
|
|
679
|
+
}
|
|
680
|
+
finally {
|
|
681
|
+
releaseStartupLock(startupLock);
|
|
682
|
+
}
|
|
683
|
+
};
|
|
684
|
+
const daemon = {
|
|
685
|
+
socketPath: opts.socketPath,
|
|
686
|
+
status,
|
|
687
|
+
onEvent,
|
|
688
|
+
stop: (reason = 'signal') => {
|
|
689
|
+
void requestShutdown(reason);
|
|
690
|
+
},
|
|
691
|
+
run: async () => {
|
|
692
|
+
await openSocket();
|
|
693
|
+
// A stop can arrive while openSocket is awaiting listen(). If shutdown
|
|
694
|
+
// already won that race, close the just-opened listener and do not start
|
|
695
|
+
// a loop after shutdown has completed.
|
|
696
|
+
if (shutdownStarted) {
|
|
697
|
+
await closeListening();
|
|
698
|
+
return 0;
|
|
699
|
+
}
|
|
700
|
+
loopPromise = opts.loop.run();
|
|
701
|
+
// A signal or explicit stop can arrive in the small window between
|
|
702
|
+
// binding the socket and starting the loop. Re-apply the stop after the
|
|
703
|
+
// loop promise exists so an early shutdown cannot leave the loop parked.
|
|
704
|
+
if (shutdownStarted)
|
|
705
|
+
opts.loop.stop();
|
|
706
|
+
try {
|
|
707
|
+
await loopPromise;
|
|
708
|
+
}
|
|
709
|
+
finally {
|
|
710
|
+
await requestShutdown('loop');
|
|
711
|
+
}
|
|
712
|
+
return 0;
|
|
713
|
+
},
|
|
714
|
+
};
|
|
715
|
+
return daemon;
|
|
716
|
+
}
|