@thready-web/dsh-bot-plugin 0.0.0-stage → 0.1.0-beta.1
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 +21 -0
- package/README.md +45 -2
- package/client.js +646 -0
- package/dist/cdc.js +73 -0
- package/dist/cli.js +352 -0
- package/dist/context.js +262 -0
- package/dist/cron.js +98 -0
- package/dist/desk-ledger.js +91 -0
- package/dist/desk.js +518 -0
- package/dist/engine.js +733 -0
- package/dist/errors.js +46 -0
- package/dist/fs-safe.js +100 -0
- package/dist/http-plugin.js +33 -0
- package/dist/http.js +593 -0
- package/dist/inbox.js +194 -0
- package/dist/index.js +411 -0
- package/dist/live-diff.js +188 -0
- package/dist/live-snapshot.js +152 -0
- package/dist/provision.js +44 -0
- package/dist/router-plugin.js +14 -0
- package/dist/runtime-registry.js +36 -0
- package/dist/session-files.js +111 -0
- package/dist/session-previews.js +111 -0
- package/dist/store.js +598 -0
- package/dist/tools.js +357 -0
- package/dist/triggers.js +874 -0
- package/dist/work-admit.js +128 -0
- package/dist/work-child.js +73 -0
- package/dist/work-durable.js +53 -0
- package/dist/work-http.js +287 -0
- package/dist/work-ledger.js +217 -0
- package/dist/work-mock-host.js +187 -0
- package/dist/work-mock.js +131 -0
- package/dist/work-tickets.js +1042 -0
- package/dist/work-tools.js +150 -0
- package/dist/work-worker.js +1108 -0
- package/fixtures/mock-llm.mjs +267 -0
- package/package.json +54 -4
- package/public/assets/index-Be82iGwe.css +1 -0
- package/public/assets/index-ByU9a3Lh.js +61 -0
- package/public/index.html +14 -0
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
/** Admission and host budgets. Neither function calls a model or reorders an inbox. */
|
|
2
|
+
export const DEFAULT_WORK_BUDGET = Object.freeze({
|
|
3
|
+
mainMaxSteps: 2,
|
|
4
|
+
mainWallMs: 20_000,
|
|
5
|
+
chatMaxSteps: 4,
|
|
6
|
+
chatWallMs: 120_000,
|
|
7
|
+
holdMs: 15_000,
|
|
8
|
+
workerMaxSteps: 8,
|
|
9
|
+
workerWallMs: 10 * 60 * 1000,
|
|
10
|
+
workerMaxTokens: 400_000,
|
|
11
|
+
perBot: 1,
|
|
12
|
+
global: 2,
|
|
13
|
+
leaseMs: 60_000,
|
|
14
|
+
starveMs: 30_000,
|
|
15
|
+
mergeWindowMs: 1_000,
|
|
16
|
+
});
|
|
17
|
+
/**
|
|
18
|
+
* Pending next-turn ids whose source is not a ticket notice and not a delivery.
|
|
19
|
+
* @param {string[]} pendingIds
|
|
20
|
+
* @param {Iterable<string>} backgroundIds
|
|
21
|
+
*/
|
|
22
|
+
export function userPending(pendingIds, backgroundIds) {
|
|
23
|
+
const background = backgroundIds instanceof Set ? backgroundIds : new Set(backgroundIds);
|
|
24
|
+
return pendingIds.filter(id => typeof id === 'string' && id !== '' && !background.has(id));
|
|
25
|
+
}
|
|
26
|
+
/**
|
|
27
|
+
* @param {{
|
|
28
|
+
* pendingIds: string[] | null,
|
|
29
|
+
* backgroundIds?: Iterable<string>,
|
|
30
|
+
* noticeOpen: boolean,
|
|
31
|
+
* deliveryOpen: boolean,
|
|
32
|
+
* lastNoticeAt?: number | null,
|
|
33
|
+
* nowMs: number,
|
|
34
|
+
* mergeWindowMs: number,
|
|
35
|
+
* terminalSince?: number | null,
|
|
36
|
+
* starveMs: number,
|
|
37
|
+
* }} input
|
|
38
|
+
*/
|
|
39
|
+
export function decideAdmission(input) {
|
|
40
|
+
if (input.pendingIds == null)
|
|
41
|
+
return { admit: false, reason: 'inbox-unreadable', starve: false, userAhead: 0 };
|
|
42
|
+
const users = userPending(input.pendingIds, input.backgroundIds ?? []);
|
|
43
|
+
const terminalSince = input.terminalSince ?? null;
|
|
44
|
+
const age = terminalSince == null ? null : input.nowMs - terminalSince;
|
|
45
|
+
const starve = age != null && age >= input.starveMs;
|
|
46
|
+
if (starve)
|
|
47
|
+
return { admit: true, reason: 'starve', starve: true, userAhead: users.length };
|
|
48
|
+
if (users.length > 0)
|
|
49
|
+
return { admit: false, reason: 'user-pending', starve: false, userAhead: users.length };
|
|
50
|
+
if (input.noticeOpen)
|
|
51
|
+
return { admit: false, reason: 'notice-open', starve: false, userAhead: 0 };
|
|
52
|
+
if (input.deliveryOpen)
|
|
53
|
+
return { admit: false, reason: 'delivery-open', starve: false, userAhead: 0 };
|
|
54
|
+
const last = input.lastNoticeAt ?? null;
|
|
55
|
+
if (last != null && input.nowMs - last < input.mergeWindowMs) {
|
|
56
|
+
return { admit: false, reason: 'merge-window', starve: false, userAhead: 0 };
|
|
57
|
+
}
|
|
58
|
+
return { admit: true, reason: 'clear', starve: false, userAhead: 0 };
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* @param {{ steps?: number, elapsedMs: number, maxSteps?: number, wallMs: number, tokens?: number, maxTokens?: number }} input
|
|
62
|
+
* @returns {'steps' | 'wall' | 'tokens' | null}
|
|
63
|
+
*/
|
|
64
|
+
export function budgetTrip(input) {
|
|
65
|
+
if (Number.isFinite(input.maxSteps) && Number(input.steps) >= input.maxSteps)
|
|
66
|
+
return 'steps';
|
|
67
|
+
if (Number.isFinite(input.maxTokens) && Number(input.tokens) >= input.maxTokens)
|
|
68
|
+
return 'tokens';
|
|
69
|
+
if (input.elapsedMs >= input.wallMs)
|
|
70
|
+
return 'wall';
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
/**
|
|
74
|
+
* Positive integer inside an inclusive range.
|
|
75
|
+
* @param {unknown} value
|
|
76
|
+
* @param {number} min
|
|
77
|
+
* @param {number} max
|
|
78
|
+
*/
|
|
79
|
+
function clampInt(value, min, max) {
|
|
80
|
+
const number = Number(value);
|
|
81
|
+
if (!Number.isFinite(number))
|
|
82
|
+
return null;
|
|
83
|
+
return Math.max(min, Math.min(max, Math.floor(number)));
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Ticket budget chosen when the main bot dispatches.
|
|
87
|
+
* An explicit estimate is kept inside the host ceiling. An omitted field is
|
|
88
|
+
* derived from the briefing length so every ticket gets its own numbers.
|
|
89
|
+
* @param {string} briefing
|
|
90
|
+
* @param {{ wallMs?: number, maxTokens?: number } | null | undefined} suggestion
|
|
91
|
+
* @param {typeof DEFAULT_WORK_BUDGET} defaults
|
|
92
|
+
*/
|
|
93
|
+
export function estimateWorkerBudget(briefing, suggestion, defaults = DEFAULT_WORK_BUDGET) {
|
|
94
|
+
const chars = typeof briefing === 'string' ? briefing.length : 0;
|
|
95
|
+
const guessedWall = Math.min(defaults.workerWallMs, 180_000 + chars * 100);
|
|
96
|
+
const guessedTokens = Math.min(defaults.workerMaxTokens, 24_000 + chars * 8);
|
|
97
|
+
return {
|
|
98
|
+
wallMs: clampInt(suggestion?.wallMs, 1000, defaults.workerWallMs) ?? guessedWall,
|
|
99
|
+
maxTokens: clampInt(suggestion?.maxTokens, 1000, defaults.workerMaxTokens) ?? guessedTokens,
|
|
100
|
+
perBot: defaults.perBot,
|
|
101
|
+
global: defaults.global,
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Child creation options. parentAgent and meta.parentSession are omitted on purpose:
|
|
106
|
+
* the parent link lives only on the ticket row.
|
|
107
|
+
* Real DSH rejects a turn when AgentOptions.provider and model are both absent
|
|
108
|
+
* (`has no provider/model`). The deployment default is not applied by create()
|
|
109
|
+
* itself, so the caller copies the owner selection or the deployment default.
|
|
110
|
+
* @param {string} sessionId
|
|
111
|
+
* @param {string} [cwd]
|
|
112
|
+
* @param {{ provider?: string, model?: string, reasoningEffort?: string } | null} [model]
|
|
113
|
+
* @param {number} [maxTokens] Test-only output cap. Omit it and the host default stays.
|
|
114
|
+
*/
|
|
115
|
+
export function childCreateOptions(sessionId, cwd, model, maxTokens) {
|
|
116
|
+
const options = { sessionId };
|
|
117
|
+
if (typeof cwd === 'string' && cwd !== '')
|
|
118
|
+
options.meta = { cwd };
|
|
119
|
+
if (model && typeof model.provider === 'string' && model.provider !== '' && typeof model.model === 'string' && model.model !== '') {
|
|
120
|
+
options.agentOptions = { provider: model.provider, model: model.model };
|
|
121
|
+
if (typeof model.reasoningEffort === 'string' && model.reasoningEffort !== '') {
|
|
122
|
+
options.agentOptions.reasoningEffort = model.reasoningEffort;
|
|
123
|
+
}
|
|
124
|
+
if (Number.isSafeInteger(maxTokens) && maxTokens > 0)
|
|
125
|
+
options.agentOptions.maxTokens = maxTokens;
|
|
126
|
+
}
|
|
127
|
+
return options;
|
|
128
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* File tools for a worker. Plugin-created agents do not inherit the web preset,
|
|
3
|
+
* so their request header otherwise lists only host tools.
|
|
4
|
+
* This preset is tool-fs only: read, write, and edit. It does not add bash,
|
|
5
|
+
* and it does not change the sandbox mode or add writable roots.
|
|
6
|
+
* The session cwd copied at create remains the workspace-write boundary.
|
|
7
|
+
*/
|
|
8
|
+
export const WORKER_FILE_PRESET = 'foundations-files';
|
|
9
|
+
/**
|
|
10
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
11
|
+
*/
|
|
12
|
+
function presetsOf(ctx) {
|
|
13
|
+
try {
|
|
14
|
+
if (typeof ctx.get === 'function')
|
|
15
|
+
return ctx.get('agentPresets') ?? null;
|
|
16
|
+
}
|
|
17
|
+
catch { /* preset service is optional until a worker is created */ }
|
|
18
|
+
try {
|
|
19
|
+
return ctx.agentPresets ?? null;
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Register the worker file preset once per process. A duplicate from a reload
|
|
27
|
+
* is the same preset and is not an error.
|
|
28
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
29
|
+
*/
|
|
30
|
+
export function ensureWorkerFilePreset(ctx) {
|
|
31
|
+
const presets = presetsOf(ctx);
|
|
32
|
+
if (!presets?.register || !presets?.mount)
|
|
33
|
+
return Promise.resolve(null);
|
|
34
|
+
return presets.register({
|
|
35
|
+
id: WORKER_FILE_PRESET,
|
|
36
|
+
plugins: [
|
|
37
|
+
{
|
|
38
|
+
id: 'tool-fs',
|
|
39
|
+
name: '@deepseek-ai/dsh-tool-fs',
|
|
40
|
+
config: { applyPatch: false, readImage: false },
|
|
41
|
+
},
|
|
42
|
+
],
|
|
43
|
+
}).then(() => WORKER_FILE_PRESET).catch(error => {
|
|
44
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
45
|
+
if (message.includes('Duplicate'))
|
|
46
|
+
return WORKER_FILE_PRESET;
|
|
47
|
+
throw error;
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* Bind the file preset before the agent is published. Resume uses the id
|
|
52
|
+
* recorded on the session header, because select() refuses a session that
|
|
53
|
+
* has already started a turn.
|
|
54
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
55
|
+
* @param {string | null} presetId
|
|
56
|
+
*/
|
|
57
|
+
export function workerFileSetup(ctx, presetId) {
|
|
58
|
+
return async (agentCtx, agent) => {
|
|
59
|
+
const presets = presetsOf(ctx);
|
|
60
|
+
if (!presets?.mount)
|
|
61
|
+
return;
|
|
62
|
+
const recorded = agent?.session && typeof presets.presetForSession === 'function'
|
|
63
|
+
? presets.presetForSession(agent.session)
|
|
64
|
+
: null;
|
|
65
|
+
const id = presetId || recorded || presets.defaultId;
|
|
66
|
+
if (!id)
|
|
67
|
+
return;
|
|
68
|
+
const resolved = typeof presets.resolve === 'function' ? await presets.resolve(id) : { id };
|
|
69
|
+
if (resolved?.broken)
|
|
70
|
+
throw new Error(`worker file-tool preset is unavailable: ${resolved.broken}`);
|
|
71
|
+
await presets.mount(agentCtx, resolved?.id ?? id);
|
|
72
|
+
};
|
|
73
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared follow-up durability. The caller decides which ledger table is updated.
|
|
3
|
+
* Algorithm matches deliveries: flushing, then followup, then flush.
|
|
4
|
+
* Flush unconfirmed is ambiguous. This is at-least-once, not exactly-once.
|
|
5
|
+
*/
|
|
6
|
+
const MAX_ATTEMPTS = 5;
|
|
7
|
+
/**
|
|
8
|
+
* @param {{
|
|
9
|
+
* attempts: number,
|
|
10
|
+
* markFlushing: () => void,
|
|
11
|
+
* push: () => Promise<{ ok?: boolean, ambiguous?: boolean, seq?: number | null, error?: string }>,
|
|
12
|
+
* markAccepted: (seq: number | null) => void,
|
|
13
|
+
* markAmbiguous: (error: string) => void,
|
|
14
|
+
* markDead: (error: string) => void,
|
|
15
|
+
* markRetry: (error: string) => void,
|
|
16
|
+
* }} spec
|
|
17
|
+
*/
|
|
18
|
+
export async function durableFollowup(spec) {
|
|
19
|
+
if (spec.attempts >= MAX_ATTEMPTS) {
|
|
20
|
+
spec.markDead('retry-limit');
|
|
21
|
+
return { ok: false, status: 'dead' };
|
|
22
|
+
}
|
|
23
|
+
spec.markFlushing();
|
|
24
|
+
try {
|
|
25
|
+
const result = await spec.push();
|
|
26
|
+
if (result?.ok) {
|
|
27
|
+
spec.markAccepted(result.seq ?? null);
|
|
28
|
+
return { ok: true, status: 'accepted', seq: result.seq ?? null };
|
|
29
|
+
}
|
|
30
|
+
if (result?.ambiguous) {
|
|
31
|
+
spec.markAmbiguous(result.error || 'flush-unconfirmed');
|
|
32
|
+
return { ok: false, status: 'ambiguous' };
|
|
33
|
+
}
|
|
34
|
+
const used = spec.attempts + 1;
|
|
35
|
+
const error = result?.error || 'push-failed';
|
|
36
|
+
if (used >= MAX_ATTEMPTS) {
|
|
37
|
+
spec.markDead(error);
|
|
38
|
+
return { ok: false, status: 'dead' };
|
|
39
|
+
}
|
|
40
|
+
spec.markRetry(error);
|
|
41
|
+
return { ok: false, status: 'intent' };
|
|
42
|
+
}
|
|
43
|
+
catch (error) {
|
|
44
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
45
|
+
if (message.includes('not found') || message.includes('NotFound') || message.includes('no session')) {
|
|
46
|
+
spec.markDead('target-not-found');
|
|
47
|
+
return { ok: false, status: 'dead' };
|
|
48
|
+
}
|
|
49
|
+
spec.markAmbiguous(message);
|
|
50
|
+
return { ok: false, status: 'ambiguous' };
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
export const DURABLE_ATTEMPT_LIMIT = MAX_ATTEMPTS;
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { toolError } from "./errors.js";
|
|
2
|
+
import { diffValue } from "./live-diff.js";
|
|
3
|
+
/**
|
|
4
|
+
* One server-sent frame. An unchanged stamp sends nothing.
|
|
5
|
+
* @param {{ liveStamp: () => string, liveBoard: (sessionId: string) => unknown }} work
|
|
6
|
+
* @param {string} sessionId
|
|
7
|
+
* @param {string | null} previousStamp
|
|
8
|
+
*/
|
|
9
|
+
export function nextLiveFrame(work, sessionId, previousStamp) {
|
|
10
|
+
const stamp = work.liveStamp();
|
|
11
|
+
if (previousStamp !== null && stamp === previousStamp)
|
|
12
|
+
return { stamp, frame: '' };
|
|
13
|
+
const body = work.liveBoard(sessionId);
|
|
14
|
+
return { stamp, frame: `event: snapshot\ndata: ${JSON.stringify(body)}\n\n` };
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Holds the response open. The caller waits until the client disconnects.
|
|
18
|
+
* A 1s stamp check is in-process; the browser does not re-fetch tickets.
|
|
19
|
+
* @param {import('node:http').IncomingMessage} req
|
|
20
|
+
* @param {import('node:http').ServerResponse} res
|
|
21
|
+
* @param {string} sessionId
|
|
22
|
+
* @param {{ liveStamp: () => string, liveBoard: (sessionId: string) => unknown }} work
|
|
23
|
+
*/
|
|
24
|
+
export function openWorkLive(req, res, sessionId, work) {
|
|
25
|
+
res.writeHead(200, {
|
|
26
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
27
|
+
'cache-control': 'no-store',
|
|
28
|
+
'x-accel-buffering': 'no',
|
|
29
|
+
});
|
|
30
|
+
req.socket?.setTimeout(0);
|
|
31
|
+
res.socket?.setTimeout(0);
|
|
32
|
+
res.write(`:${' '.repeat(2048)}\n\n`);
|
|
33
|
+
let stopped = false;
|
|
34
|
+
/** @type {string | null} */
|
|
35
|
+
let stamp = null;
|
|
36
|
+
let quiet = 0;
|
|
37
|
+
/** @type {ReturnType<typeof setInterval> | null} */
|
|
38
|
+
let timer = null;
|
|
39
|
+
const stop = () => {
|
|
40
|
+
if (stopped)
|
|
41
|
+
return;
|
|
42
|
+
stopped = true;
|
|
43
|
+
if (timer)
|
|
44
|
+
clearInterval(timer);
|
|
45
|
+
if (!res.writableEnded)
|
|
46
|
+
res.end();
|
|
47
|
+
};
|
|
48
|
+
const pump = () => {
|
|
49
|
+
if (stopped)
|
|
50
|
+
return;
|
|
51
|
+
try {
|
|
52
|
+
const next = nextLiveFrame(work, sessionId, stamp);
|
|
53
|
+
stamp = next.stamp;
|
|
54
|
+
if (next.frame !== '') {
|
|
55
|
+
quiet = 0;
|
|
56
|
+
res.write(next.frame);
|
|
57
|
+
return;
|
|
58
|
+
}
|
|
59
|
+
quiet += 1;
|
|
60
|
+
if (quiet >= 15) {
|
|
61
|
+
quiet = 0;
|
|
62
|
+
res.write(': ping\n\n');
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
stop();
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
pump();
|
|
70
|
+
timer = setInterval(pump, 1000);
|
|
71
|
+
timer.unref?.();
|
|
72
|
+
req.on('close', stop);
|
|
73
|
+
res.on('error', stop);
|
|
74
|
+
return new Promise(resolve => {
|
|
75
|
+
req.on('close', () => resolve(undefined));
|
|
76
|
+
});
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* First sight of a side is a snapshot. Later sights are the patch from the last frame.
|
|
80
|
+
* @param {'desk' | 'work'} name
|
|
81
|
+
* @param {unknown} previous
|
|
82
|
+
* @param {unknown} value
|
|
83
|
+
*/
|
|
84
|
+
function frameFor(name, previous, value) {
|
|
85
|
+
if (previous === undefined) {
|
|
86
|
+
return {
|
|
87
|
+
stored: cloneJson(value),
|
|
88
|
+
frame: `event: snapshot\ndata: ${JSON.stringify({ ok: true, [name]: value })}\n\n`,
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
const patch = diffValue(previous, value);
|
|
92
|
+
if (!patch)
|
|
93
|
+
return { stored: previous, frame: '' };
|
|
94
|
+
return {
|
|
95
|
+
stored: cloneJson(value),
|
|
96
|
+
frame: `event: delta\ndata: ${JSON.stringify({ ok: true, [name]: patch })}\n\n`,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* @param {unknown} value
|
|
101
|
+
*/
|
|
102
|
+
function cloneJson(value) {
|
|
103
|
+
return JSON.parse(JSON.stringify(value));
|
|
104
|
+
}
|
|
105
|
+
/**
|
|
106
|
+
* One stream for the whole desk. Work is checked every second; the host list
|
|
107
|
+
* is checked on deskIntervalMs. The first frame of each side is the whole object.
|
|
108
|
+
* A later frame of that side is only the patch against the previous one.
|
|
109
|
+
* This stream does not cut the page with FastCDC. Session history uses the
|
|
110
|
+
* snapshot routes, and new session events stay event records.
|
|
111
|
+
* @param {import('node:http').IncomingMessage} req
|
|
112
|
+
* @param {import('node:http').ServerResponse} res
|
|
113
|
+
* @param {{
|
|
114
|
+
* workStamp: () => string,
|
|
115
|
+
* workBoard: () => unknown,
|
|
116
|
+
* loadDesk: () => Promise<unknown>,
|
|
117
|
+
* deskIntervalMs?: number,
|
|
118
|
+
* intervalMs?: number,
|
|
119
|
+
* }} source
|
|
120
|
+
*/
|
|
121
|
+
export function openPageLive(req, res, source) {
|
|
122
|
+
res.writeHead(200, {
|
|
123
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
124
|
+
'cache-control': 'no-store',
|
|
125
|
+
'x-accel-buffering': 'no',
|
|
126
|
+
});
|
|
127
|
+
req.socket?.setTimeout(0);
|
|
128
|
+
res.socket?.setTimeout(0);
|
|
129
|
+
res.write(`:${' '.repeat(2048)}\n\n`);
|
|
130
|
+
let stopped = false;
|
|
131
|
+
let busy = false;
|
|
132
|
+
/** @type {string | null} */
|
|
133
|
+
let workStamp = null;
|
|
134
|
+
/** @type {unknown} */
|
|
135
|
+
let sentWork;
|
|
136
|
+
/** @type {unknown} */
|
|
137
|
+
let sentDesk;
|
|
138
|
+
let lastDesk = 0;
|
|
139
|
+
let quiet = 0;
|
|
140
|
+
const deskIntervalMs = source.deskIntervalMs ?? 8000;
|
|
141
|
+
const intervalMs = source.intervalMs ?? 1000;
|
|
142
|
+
/** @type {ReturnType<typeof setInterval> | null} */
|
|
143
|
+
let timer = null;
|
|
144
|
+
const stop = () => {
|
|
145
|
+
if (stopped)
|
|
146
|
+
return;
|
|
147
|
+
stopped = true;
|
|
148
|
+
if (timer)
|
|
149
|
+
clearInterval(timer);
|
|
150
|
+
if (!res.writableEnded)
|
|
151
|
+
res.end();
|
|
152
|
+
};
|
|
153
|
+
const pump = async () => {
|
|
154
|
+
if (stopped || busy)
|
|
155
|
+
return;
|
|
156
|
+
busy = true;
|
|
157
|
+
try {
|
|
158
|
+
/** @type {string} */
|
|
159
|
+
let deskFrame = '';
|
|
160
|
+
/** @type {string} */
|
|
161
|
+
let workFrame = '';
|
|
162
|
+
const stamp = source.workStamp();
|
|
163
|
+
if (stamp !== workStamp) {
|
|
164
|
+
workStamp = stamp;
|
|
165
|
+
const next = frameFor('work', sentWork, source.workBoard());
|
|
166
|
+
sentWork = next.stored;
|
|
167
|
+
workFrame = next.frame;
|
|
168
|
+
}
|
|
169
|
+
if (lastDesk === 0 || Date.now() - lastDesk >= deskIntervalMs) {
|
|
170
|
+
lastDesk = Date.now();
|
|
171
|
+
try {
|
|
172
|
+
const desk = await source.loadDesk();
|
|
173
|
+
if (stopped)
|
|
174
|
+
return;
|
|
175
|
+
const next = frameFor('desk', sentDesk, desk);
|
|
176
|
+
sentDesk = next.stored;
|
|
177
|
+
deskFrame = next.frame;
|
|
178
|
+
}
|
|
179
|
+
catch {
|
|
180
|
+
// A host list failure leaves the ticket stream open.
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
if (deskFrame !== '' || workFrame !== '') {
|
|
184
|
+
quiet = 0;
|
|
185
|
+
if (deskFrame !== '')
|
|
186
|
+
res.write(deskFrame);
|
|
187
|
+
if (workFrame !== '')
|
|
188
|
+
res.write(workFrame);
|
|
189
|
+
return;
|
|
190
|
+
}
|
|
191
|
+
quiet += 1;
|
|
192
|
+
if (quiet >= 15) {
|
|
193
|
+
quiet = 0;
|
|
194
|
+
res.write(': ping\n\n');
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
catch {
|
|
198
|
+
stop();
|
|
199
|
+
}
|
|
200
|
+
finally {
|
|
201
|
+
busy = false;
|
|
202
|
+
}
|
|
203
|
+
};
|
|
204
|
+
void pump();
|
|
205
|
+
timer = setInterval(() => { void pump(); }, intervalMs);
|
|
206
|
+
timer.unref?.();
|
|
207
|
+
req.on('close', stop);
|
|
208
|
+
res.on('error', stop);
|
|
209
|
+
return new Promise(resolve => {
|
|
210
|
+
req.on('close', () => resolve(undefined));
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
/**
|
|
214
|
+
* Loopback JSON for the ticket protocol. This does not serve the workbench.
|
|
215
|
+
* @param {string} method
|
|
216
|
+
* @param {string} path
|
|
217
|
+
* @param {URL} url
|
|
218
|
+
* @param {Record<string, unknown>} body
|
|
219
|
+
* @param {ReturnType<import('./work-worker.js').createWorkRuntime> | null} work
|
|
220
|
+
*/
|
|
221
|
+
export async function handleWorkApi(method, path, url, body, work) {
|
|
222
|
+
if (!path.startsWith('/session-foundations/api/work'))
|
|
223
|
+
return null;
|
|
224
|
+
if (!work)
|
|
225
|
+
return { status: 503, body: toolError('UNAVAILABLE', 'The work host is not attached yet.') };
|
|
226
|
+
if (method === 'GET' && path === '/session-foundations/api/work/tickets') {
|
|
227
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
228
|
+
if (sessionId === '')
|
|
229
|
+
return { status: 400, body: toolError('VALIDATION', 'sessionId is required.') };
|
|
230
|
+
return { status: 200, body: { ok: true, tickets: work.summaries(sessionId) } };
|
|
231
|
+
}
|
|
232
|
+
if (method === 'GET' && path === '/session-foundations/api/work/ticket') {
|
|
233
|
+
const id = url.searchParams.get('id') ?? '';
|
|
234
|
+
const found = work.detail(id);
|
|
235
|
+
if (!found)
|
|
236
|
+
return { status: 404, body: toolError('NOT_FOUND', 'No such ticket.') };
|
|
237
|
+
return { status: 200, body: { ok: true, ...found } };
|
|
238
|
+
}
|
|
239
|
+
if (method === 'POST' && path === '/session-foundations/api/work/tick') {
|
|
240
|
+
await work.tick();
|
|
241
|
+
return { status: 200, body: { ok: true } };
|
|
242
|
+
}
|
|
243
|
+
const sessionId = typeof body.sessionId === 'string' ? body.sessionId : '';
|
|
244
|
+
if (sessionId === '')
|
|
245
|
+
return { status: 400, body: toolError('VALIDATION', 'sessionId is required.') };
|
|
246
|
+
if (method === 'POST' && path === '/session-foundations/api/work/hold') {
|
|
247
|
+
const result = work.holdNotices(sessionId);
|
|
248
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
249
|
+
}
|
|
250
|
+
if (method === 'POST' && path === '/session-foundations/api/work/release') {
|
|
251
|
+
const result = work.releaseHold(sessionId);
|
|
252
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
253
|
+
}
|
|
254
|
+
if (method === 'POST' && path === '/session-foundations/api/work/dispatch') {
|
|
255
|
+
const result = await work.dispatch(sessionId, body);
|
|
256
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
257
|
+
}
|
|
258
|
+
if (method === 'POST' && path === '/session-foundations/api/work/supply') {
|
|
259
|
+
const result = await work.supply(sessionId, body);
|
|
260
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
261
|
+
}
|
|
262
|
+
if (method === 'POST' && path === '/session-foundations/api/work/redirect') {
|
|
263
|
+
const result = await work.redirect(sessionId, body);
|
|
264
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
265
|
+
}
|
|
266
|
+
if (method === 'POST' && path === '/session-foundations/api/work/cancel') {
|
|
267
|
+
const result = await work.cancelTicket(sessionId, body);
|
|
268
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
269
|
+
}
|
|
270
|
+
if (method === 'POST' && path === '/session-foundations/api/work/retry') {
|
|
271
|
+
const result = await work.retry(sessionId, body);
|
|
272
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
273
|
+
}
|
|
274
|
+
if (method === 'POST' && path === '/session-foundations/api/work/publish') {
|
|
275
|
+
const result = await work.publish(sessionId, body);
|
|
276
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
277
|
+
}
|
|
278
|
+
if (method === 'POST' && path === '/session-foundations/api/work/reject') {
|
|
279
|
+
const result = await work.reject(sessionId, body);
|
|
280
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
281
|
+
}
|
|
282
|
+
if (method === 'POST' && path === '/session-foundations/api/work/report') {
|
|
283
|
+
const result = await work.report(sessionId, body);
|
|
284
|
+
return { status: result.ok === false ? 400 : 200, body: result };
|
|
285
|
+
}
|
|
286
|
+
return null;
|
|
287
|
+
}
|