@thready-web/dsh-bot-plugin 0.0.0-stage → 0.1.0-beta.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +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,217 @@
|
|
|
1
|
+
import { durableFollowup } from "./work-durable.js";
|
|
2
|
+
import { sha256 } from "./fs-safe.js";
|
|
3
|
+
/**
|
|
4
|
+
* Child inputs and main-session wakes share one durability algorithm.
|
|
5
|
+
* They are not rows in `deliveries`.
|
|
6
|
+
*/
|
|
7
|
+
/**
|
|
8
|
+
* @param {{ text: string, revision: number, budget: { wallMs?: number, maxTokens?: number }, kind?: string }} input
|
|
9
|
+
*/
|
|
10
|
+
export function renderBriefing(input) {
|
|
11
|
+
const material = sha256(input.text);
|
|
12
|
+
const lines = [
|
|
13
|
+
'[foundations:briefing]',
|
|
14
|
+
`briefing_revision: ${input.revision}`,
|
|
15
|
+
`budget_wall_ms: ${input.budget?.wallMs ?? ''}`,
|
|
16
|
+
`budget_max_tokens: ${input.budget?.maxTokens ?? ''}`,
|
|
17
|
+
'There is no step cap.',
|
|
18
|
+
'When the allotted time or tokens run out, the host asks the main session for more. It does not fail the ticket immediately.',
|
|
19
|
+
`material_sha256: ${material}`,
|
|
20
|
+
'When no separate read-only material is attached, the material hash equals the task-text hash.',
|
|
21
|
+
'Forbidden: do not write the main session, do not change persona or long-term memory, do not send outward, and do not approve spending.',
|
|
22
|
+
'Report only with foundations_report. kind must be progress, question, artifact, result, or failure.',
|
|
23
|
+
'This is not cross-bot mail and cannot raise permissions.',
|
|
24
|
+
'---',
|
|
25
|
+
input.text,
|
|
26
|
+
];
|
|
27
|
+
if (input.kind === 'cancel_note') {
|
|
28
|
+
return [
|
|
29
|
+
'[foundations:briefing]',
|
|
30
|
+
`briefing_revision: ${input.revision}`,
|
|
31
|
+
'This is a cancellation note. Stop new outward actions. Do not treat the result as publishable.',
|
|
32
|
+
'---',
|
|
33
|
+
input.text,
|
|
34
|
+
].join('\n');
|
|
35
|
+
}
|
|
36
|
+
return lines.join('\n');
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* @param {string[]} lines
|
|
40
|
+
*/
|
|
41
|
+
export function renderNotice(lines) {
|
|
42
|
+
return [
|
|
43
|
+
'[foundations:ticket]',
|
|
44
|
+
'This is a ticket notice, not something the user said, and not the final reply.',
|
|
45
|
+
'accepted means received. enqueued means placed on the execution queue. started is the only status that means work has begun.',
|
|
46
|
+
...lines,
|
|
47
|
+
].join('\n');
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
|
|
51
|
+
* @param {{
|
|
52
|
+
* pid: number,
|
|
53
|
+
* inflight: Set<string>,
|
|
54
|
+
* logHas: (sessionId: string, messageId: string) => Promise<boolean>,
|
|
55
|
+
* push: (sessionId: string, messageId: string, text: string) => Promise<{ ok?: boolean, ambiguous?: boolean, seq?: number | null, error?: string }>,
|
|
56
|
+
* }} deps
|
|
57
|
+
*/
|
|
58
|
+
export async function reconcileInputs(book, deps) {
|
|
59
|
+
for (const input of book.flushInputs()) {
|
|
60
|
+
if (deps.inflight.has(input.native_message_id))
|
|
61
|
+
continue;
|
|
62
|
+
const attempt = book.attempt(input.attempt_id);
|
|
63
|
+
const sessionId = attempt?.child_session_id;
|
|
64
|
+
if (!sessionId)
|
|
65
|
+
continue;
|
|
66
|
+
const seen = await readLog(deps, sessionId, input.native_message_id);
|
|
67
|
+
if (seen.unreadable) {
|
|
68
|
+
book.markInputFlush(input.id, 'ambiguous', deps.pid, 'log-unreadable', null, false);
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
if (seen.found) {
|
|
72
|
+
book.noteInputAccepted(input, seen.seq ?? input.log_seq ?? null);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
if (input.flush_attempts >= 5) {
|
|
76
|
+
book.markInputFlush(input.id, 'dead', input.flush_pid ?? null, 'retry-limit', null, false);
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
if ((input.flush_status === 'ambiguous' || input.flush_status === 'flushing') && input.flush_pid === deps.pid)
|
|
80
|
+
continue;
|
|
81
|
+
await pushInput(book, input, deps);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
/**
|
|
85
|
+
* @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
|
|
86
|
+
* @param {{
|
|
87
|
+
* pid: number,
|
|
88
|
+
* inflight: Set<string>,
|
|
89
|
+
* logHas: (sessionId: string, messageId: string) => Promise<boolean>,
|
|
90
|
+
* push: (sessionId: string, messageId: string, text: string) => Promise<{ ok?: boolean, ambiguous?: boolean, seq?: number | null, error?: string }>,
|
|
91
|
+
* noticeText: (nativeId: string) => string,
|
|
92
|
+
* }} deps
|
|
93
|
+
*/
|
|
94
|
+
export async function reconcileNotices(book, deps) {
|
|
95
|
+
/** @type {Map<string, any[]>} */
|
|
96
|
+
const groups = new Map();
|
|
97
|
+
for (const notice of book.flushNotices()) {
|
|
98
|
+
const list = groups.get(notice.native_message_id) ?? [];
|
|
99
|
+
list.push(notice);
|
|
100
|
+
groups.set(notice.native_message_id, list);
|
|
101
|
+
}
|
|
102
|
+
for (const [nativeId, rows] of groups) {
|
|
103
|
+
if (deps.inflight.has(nativeId))
|
|
104
|
+
continue;
|
|
105
|
+
const sample = rows[0];
|
|
106
|
+
const attempts = Math.max(...rows.map(row => row.flush_attempts));
|
|
107
|
+
const seen = await readLog(deps, sample.owner_session_id, nativeId);
|
|
108
|
+
if (seen.unreadable) {
|
|
109
|
+
book.markNoticeGroup(nativeId, 'ambiguous', deps.pid, 'log-unreadable', null, false);
|
|
110
|
+
continue;
|
|
111
|
+
}
|
|
112
|
+
if (seen.found) {
|
|
113
|
+
book.markNoticeGroup(nativeId, 'accepted', sample.flush_pid ?? deps.pid, '', seen.seq ?? null, false);
|
|
114
|
+
continue;
|
|
115
|
+
}
|
|
116
|
+
if (attempts >= 5) {
|
|
117
|
+
book.markNoticeGroup(nativeId, 'dead', sample.flush_pid ?? null, 'retry-limit', null, false);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
if (rows.some(row => (row.flush_status === 'ambiguous' || row.flush_status === 'flushing') && row.flush_pid === deps.pid))
|
|
121
|
+
continue;
|
|
122
|
+
await pushNotice(book, nativeId, sample.owner_session_id, deps.noticeText(nativeId), attempts, deps);
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
|
|
127
|
+
* @param {Record<string, any>} input
|
|
128
|
+
* @param {{
|
|
129
|
+
* pid: number,
|
|
130
|
+
* inflight: Set<string>,
|
|
131
|
+
* push: (sessionId: string, messageId: string, text: string) => Promise<{ ok?: boolean, ambiguous?: boolean, seq?: number | null, error?: string }>,
|
|
132
|
+
* }} deps
|
|
133
|
+
*/
|
|
134
|
+
export async function pushInput(book, input, deps) {
|
|
135
|
+
const attempt = book.attempt(input.attempt_id);
|
|
136
|
+
const ticket = book.ticket(input.ticket_id);
|
|
137
|
+
if (!attempt?.child_session_id || !ticket)
|
|
138
|
+
return { ok: false, status: 'pending' };
|
|
139
|
+
let budget = { wallMs: 600_000, maxTokens: 400_000 };
|
|
140
|
+
try {
|
|
141
|
+
budget = { ...budget, ...JSON.parse(ticket.budget_json) };
|
|
142
|
+
}
|
|
143
|
+
catch { /* host default */ }
|
|
144
|
+
const text = book.readBriefing(input.payload_hash);
|
|
145
|
+
const body = renderBriefing({ text, revision: input.briefing_revision, budget, kind: input.kind });
|
|
146
|
+
deps.inflight.add(input.native_message_id);
|
|
147
|
+
try {
|
|
148
|
+
return await durableFollowup({
|
|
149
|
+
attempts: input.flush_attempts,
|
|
150
|
+
markFlushing: () => book.markInputFlush(input.id, 'flushing', deps.pid, '', null, true),
|
|
151
|
+
push: () => deps.push(attempt.child_session_id, input.native_message_id, body),
|
|
152
|
+
markAccepted: (seq) => book.noteInputAccepted(input, seq),
|
|
153
|
+
markAmbiguous: (error) => book.markInputFlush(input.id, 'ambiguous', deps.pid, error, null, false),
|
|
154
|
+
markDead: (error) => book.markInputFlush(input.id, 'dead', deps.pid, error, null, false),
|
|
155
|
+
markRetry: (error) => book.markInputFlush(input.id, 'intent', deps.pid, error, null, false),
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
finally {
|
|
159
|
+
deps.inflight.delete(input.native_message_id);
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* @param {ReturnType<import('./work-tickets.js').createTicketBook>} book
|
|
164
|
+
* @param {string} nativeId
|
|
165
|
+
* @param {string} owner
|
|
166
|
+
* @param {string} text
|
|
167
|
+
* @param {number} attempts
|
|
168
|
+
* @param {{
|
|
169
|
+
* pid: number,
|
|
170
|
+
* inflight: Set<string>,
|
|
171
|
+
* push: (sessionId: string, messageId: string, text: string) => Promise<{ ok?: boolean, ambiguous?: boolean, seq?: number | null, error?: string }>,
|
|
172
|
+
* }} deps
|
|
173
|
+
*/
|
|
174
|
+
export async function pushNotice(book, nativeId, owner, text, attempts, deps) {
|
|
175
|
+
deps.inflight.add(nativeId);
|
|
176
|
+
try {
|
|
177
|
+
return await durableFollowup({
|
|
178
|
+
attempts,
|
|
179
|
+
markFlushing: () => book.markNoticeGroup(nativeId, 'flushing', deps.pid, '', null, true),
|
|
180
|
+
push: () => deps.push(owner, nativeId, text),
|
|
181
|
+
markAccepted: (seq) => book.markNoticeGroup(nativeId, 'accepted', deps.pid, '', seq, false),
|
|
182
|
+
markAmbiguous: (error) => book.markNoticeGroup(nativeId, 'ambiguous', deps.pid, error, null, false),
|
|
183
|
+
markDead: (error) => book.markNoticeGroup(nativeId, 'dead', deps.pid, error, null, false),
|
|
184
|
+
markRetry: (error) => book.markNoticeGroup(nativeId, 'intent', deps.pid, error, null, false),
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
finally {
|
|
188
|
+
deps.inflight.delete(nativeId);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* @param {{ logHas: (sessionId: string, messageId: string) => Promise<boolean> }} deps
|
|
193
|
+
* @param {string} sessionId
|
|
194
|
+
* @param {string} messageId
|
|
195
|
+
*/
|
|
196
|
+
async function readLog(deps, sessionId, messageId) {
|
|
197
|
+
try {
|
|
198
|
+
const found = await deps.logHas(sessionId, messageId);
|
|
199
|
+
return { found: found === true, unreadable: false, seq: null };
|
|
200
|
+
}
|
|
201
|
+
catch {
|
|
202
|
+
return { found: false, unreadable: true, seq: null };
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
/**
|
|
206
|
+
* @param {{ data?: { id?: string, message?: { id?: string } } }} event
|
|
207
|
+
*/
|
|
208
|
+
export function messageIdOf(event) {
|
|
209
|
+
return event?.data?.id ?? event?.data?.message?.id ?? '';
|
|
210
|
+
}
|
|
211
|
+
/**
|
|
212
|
+
* @param {{ data?: { reason?: { kind?: string } } }} event
|
|
213
|
+
*/
|
|
214
|
+
export function reasonKindOf(event) {
|
|
215
|
+
const reason = event?.data?.reason;
|
|
216
|
+
return reason && typeof reason === 'object' ? reason.kind ?? '' : '';
|
|
217
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { mkdirSync } from 'node:fs';
|
|
3
|
+
import { openStore } from "./store.js";
|
|
4
|
+
import { createEngine } from "./engine.js";
|
|
5
|
+
import { createMockWorld } from "./work-mock.js";
|
|
6
|
+
import { createWorkRuntime } from "./work-worker.js";
|
|
7
|
+
import { handleWorkApi } from "./work-http.js";
|
|
8
|
+
/**
|
|
9
|
+
* Loopback mock of the native inbox. It is not the workbench and not a real DSH host.
|
|
10
|
+
* @param {{ dataDir: string, port?: number, now?: () => Date }} options
|
|
11
|
+
*/
|
|
12
|
+
export async function startWorkMock(options) {
|
|
13
|
+
const store = openStore(options.dataDir);
|
|
14
|
+
const engine = createEngine(store);
|
|
15
|
+
const world = createMockWorld();
|
|
16
|
+
const clock = { ms: Date.now() };
|
|
17
|
+
const now = options.now ?? (() => new Date(clock.ms));
|
|
18
|
+
const work = createWorkRuntime(store, engine, {
|
|
19
|
+
createChild: (spec) => world.createChild(spec),
|
|
20
|
+
push: (sessionId, messageId, text) => world.push(sessionId, messageId, text),
|
|
21
|
+
logHas: (sessionId, messageId) => world.logHas(sessionId, messageId),
|
|
22
|
+
remove: (sessionId, messageId) => world.remove(sessionId, messageId),
|
|
23
|
+
pendingIds: (sessionId) => world.pendingIds(sessionId),
|
|
24
|
+
cancel: (sessionId, cancelOptions) => world.cancel(sessionId, cancelOptions),
|
|
25
|
+
snapshot: (sessionId) => world.snapshot(sessionId),
|
|
26
|
+
now,
|
|
27
|
+
pid: process.pid,
|
|
28
|
+
});
|
|
29
|
+
const server = createServer(async (req, res) => {
|
|
30
|
+
const remote = req.socket.remoteAddress ?? '';
|
|
31
|
+
if (remote !== '127.0.0.1' && remote !== '::1' && remote !== '::ffff:127.0.0.1') {
|
|
32
|
+
send(res, 403, { ok: false, code: 'FORBIDDEN' });
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
const url = new URL(req.url ?? '/', 'http://127.0.0.1');
|
|
36
|
+
const path = url.pathname.replace(/\/+$/, '') || '/';
|
|
37
|
+
try {
|
|
38
|
+
const body = req.method === 'GET' ? {} : await readJson(req);
|
|
39
|
+
if (req.method === 'POST' && path === '/session-foundations/api/sessions/mark') {
|
|
40
|
+
const binding = engine.markBot(String(body.sessionId ?? ''));
|
|
41
|
+
send(res, 200, { ok: true, kind: 'bot', sessionId: binding.session_id });
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
if (req.method === 'POST' && path === '/session-foundations/api/sessions/plain') {
|
|
45
|
+
const binding = engine.ensureSession(String(body.sessionId ?? ''));
|
|
46
|
+
send(res, 200, { ok: true, kind: binding.kind, sessionId: binding.session_id });
|
|
47
|
+
return;
|
|
48
|
+
}
|
|
49
|
+
if (req.method === 'POST' && path === '/session-foundations/api/work/mock/user-message') {
|
|
50
|
+
const messageId = world.postUser(String(body.sessionId), String(body.text ?? ''));
|
|
51
|
+
send(res, 200, { ok: true, messageId, pending: world.pendingIds(String(body.sessionId)) });
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
54
|
+
if (req.method === 'POST' && path === '/session-foundations/api/work/mock/claim') {
|
|
55
|
+
const claimed = world.claim(String(body.sessionId));
|
|
56
|
+
if (claimed)
|
|
57
|
+
work.observeClaimed(String(body.sessionId), claimed.messageId, claimed.turn);
|
|
58
|
+
send(res, 200, { ok: true, claimed, ticketStatus: statusOf(work, body.ticketId) });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (req.method === 'POST' && path === '/session-foundations/api/work/mock/user-seen') {
|
|
62
|
+
const event = world.seeUser(String(body.sessionId), String(body.messageId), Number(body.turn ?? 1));
|
|
63
|
+
work.observeSession(String(body.sessionId), event);
|
|
64
|
+
send(res, 200, { ok: true, seq: event.seq, ticketStatus: statusOf(work, body.ticketId) });
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (req.method === 'POST' && path === '/session-foundations/api/work/mock/turn-end') {
|
|
68
|
+
const event = world.endTurn(String(body.sessionId), Number(body.turn ?? 1), String(body.reasonKind ?? 'completed'));
|
|
69
|
+
work.observeSession(String(body.sessionId), event);
|
|
70
|
+
send(res, 200, { ok: true, ticketStatus: statusOf(work, body.ticketId) });
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
73
|
+
if (req.method === 'POST' && path === '/session-foundations/api/work/mock/assistant') {
|
|
74
|
+
if (body.tool && typeof body.tool === 'object') {
|
|
75
|
+
world.toolCall(String(body.sessionId), String(body.tool.name ?? ''), body.tool.arguments ?? {});
|
|
76
|
+
}
|
|
77
|
+
const event = world.assistant(String(body.sessionId), String(body.text ?? ''));
|
|
78
|
+
await work.tick();
|
|
79
|
+
send(res, 200, { ok: true, seq: event.seq, ticketStatus: statusOf(work, body.ticketId) });
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (req.method === 'POST' && path === '/session-foundations/api/work/mock/clock') {
|
|
83
|
+
clock.ms = Date.parse(String(body.iso));
|
|
84
|
+
send(res, 200, { ok: true, iso: new Date(clock.ms).toISOString() });
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
if (req.method === 'GET' && path === '/session-foundations/api/work/mock/inbox') {
|
|
88
|
+
const sessionId = url.searchParams.get('sessionId') ?? '';
|
|
89
|
+
send(res, 200, {
|
|
90
|
+
ok: true,
|
|
91
|
+
pending: world.pendingIds(sessionId),
|
|
92
|
+
events: world.events(sessionId),
|
|
93
|
+
cancels: world.cancels,
|
|
94
|
+
});
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const handled = await handleWorkApi(req.method ?? 'GET', path, url, body, work);
|
|
98
|
+
if (!handled) {
|
|
99
|
+
send(res, 404, { ok: false, code: 'NOT_FOUND' });
|
|
100
|
+
return;
|
|
101
|
+
}
|
|
102
|
+
send(res, handled.status, handled.body);
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
send(res, 500, { ok: false, message: error instanceof Error ? error.message : String(error) });
|
|
106
|
+
}
|
|
107
|
+
});
|
|
108
|
+
await new Promise((resolve, reject) => {
|
|
109
|
+
server.once('error', reject);
|
|
110
|
+
server.listen(options.port ?? 0, '127.0.0.1', () => resolve(undefined));
|
|
111
|
+
});
|
|
112
|
+
const address = server.address();
|
|
113
|
+
const port = typeof address === 'object' && address ? address.port : options.port;
|
|
114
|
+
return {
|
|
115
|
+
port,
|
|
116
|
+
origin: `http://127.0.0.1:${port}`,
|
|
117
|
+
close: () => new Promise(resolve => {
|
|
118
|
+
server.close(() => {
|
|
119
|
+
try {
|
|
120
|
+
store.close();
|
|
121
|
+
}
|
|
122
|
+
catch { /* closed */ }
|
|
123
|
+
resolve();
|
|
124
|
+
});
|
|
125
|
+
}),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
/**
|
|
129
|
+
* @param {ReturnType<import('./work-worker.js').createWorkRuntime>} work
|
|
130
|
+
* @param {unknown} ticketId
|
|
131
|
+
*/
|
|
132
|
+
function statusOf(work, ticketId) {
|
|
133
|
+
if (typeof ticketId !== 'string' || ticketId === '')
|
|
134
|
+
return null;
|
|
135
|
+
return work.detail(ticketId)?.ticket.status ?? null;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* @param {import('node:http').ServerResponse} res
|
|
139
|
+
* @param {number} status
|
|
140
|
+
* @param {unknown} body
|
|
141
|
+
*/
|
|
142
|
+
function send(res, status, body) {
|
|
143
|
+
const text = JSON.stringify(body);
|
|
144
|
+
res.writeHead(status, {
|
|
145
|
+
'content-type': 'application/json; charset=utf-8',
|
|
146
|
+
'content-length': Buffer.byteLength(text),
|
|
147
|
+
'cache-control': 'no-store',
|
|
148
|
+
});
|
|
149
|
+
res.end(text);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* @param {import('node:http').IncomingMessage} req
|
|
153
|
+
*/
|
|
154
|
+
function readJson(req) {
|
|
155
|
+
return new Promise((resolve, reject) => {
|
|
156
|
+
const chunks = [];
|
|
157
|
+
req.on('data', chunk => chunks.push(chunk));
|
|
158
|
+
req.on('end', () => {
|
|
159
|
+
const raw = Buffer.concat(chunks).toString('utf8');
|
|
160
|
+
if (raw === '') {
|
|
161
|
+
resolve({});
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
try {
|
|
165
|
+
resolve(JSON.parse(raw));
|
|
166
|
+
}
|
|
167
|
+
catch (error) {
|
|
168
|
+
reject(error);
|
|
169
|
+
}
|
|
170
|
+
});
|
|
171
|
+
req.on('error', reject);
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
const isMain = process.argv[1] && /work-mock-host\.(?:js|ts)$/.test(process.argv[1]);
|
|
175
|
+
if (isMain) {
|
|
176
|
+
const portFlag = process.argv.indexOf('--port');
|
|
177
|
+
const dirFlag = process.argv.indexOf('--data-dir');
|
|
178
|
+
const port = portFlag >= 0 ? Number(process.argv[portFlag + 1]) : 31993;
|
|
179
|
+
const dataDir = dirFlag >= 0 ? process.argv[dirFlag + 1] : '';
|
|
180
|
+
if (dataDir === '') {
|
|
181
|
+
console.error('pass --data-dir');
|
|
182
|
+
process.exit(1);
|
|
183
|
+
}
|
|
184
|
+
mkdirSync(dataDir, { recursive: true });
|
|
185
|
+
const started = await startWorkMock({ dataDir, port });
|
|
186
|
+
console.log(JSON.stringify({ ok: true, mock: true, realLlm: false, origin: started.origin, dataDir }));
|
|
187
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
2
|
+
/**
|
|
3
|
+
* In-process stand-in for the native inbox and agents.create.
|
|
4
|
+
* It is not a DSH process and not a real model.
|
|
5
|
+
*/
|
|
6
|
+
export function createMockWorld() {
|
|
7
|
+
/** @type {Map<string, { nextTurn: Array<{ id: string, text: string }>, events: Array<Record<string, unknown>>, seq: number, turn: number }>} */
|
|
8
|
+
const sessions = new Map();
|
|
9
|
+
const calls = [];
|
|
10
|
+
const cancels = [];
|
|
11
|
+
const pushes = [];
|
|
12
|
+
const state = {
|
|
13
|
+
failCreate: false,
|
|
14
|
+
flushMode: 'accepted',
|
|
15
|
+
};
|
|
16
|
+
return {
|
|
17
|
+
calls,
|
|
18
|
+
cancels,
|
|
19
|
+
pushes,
|
|
20
|
+
state,
|
|
21
|
+
session,
|
|
22
|
+
pendingIds(sessionId) {
|
|
23
|
+
return session(sessionId).nextTurn.map(item => item.id);
|
|
24
|
+
},
|
|
25
|
+
events(sessionId) {
|
|
26
|
+
return session(sessionId).events.map(event => ({ ...event }));
|
|
27
|
+
},
|
|
28
|
+
postUser(sessionId, text) {
|
|
29
|
+
const id = randomUUID();
|
|
30
|
+
const slot = session(sessionId);
|
|
31
|
+
slot.nextTurn.push({ id, text });
|
|
32
|
+
append(slot, 'agent/inbox/spliced', { inserted: [{ id }], target: 'next-turn' });
|
|
33
|
+
return id;
|
|
34
|
+
},
|
|
35
|
+
claim(sessionId) {
|
|
36
|
+
const slot = session(sessionId);
|
|
37
|
+
const message = slot.nextTurn.shift();
|
|
38
|
+
if (!message)
|
|
39
|
+
return null;
|
|
40
|
+
slot.turn += 1;
|
|
41
|
+
append(slot, 'agent/inbox/claimed', { id: message.id, turn: slot.turn });
|
|
42
|
+
return { messageId: message.id, turn: slot.turn, text: message.text };
|
|
43
|
+
},
|
|
44
|
+
seeUser(sessionId, messageId, turn) {
|
|
45
|
+
const slot = session(sessionId);
|
|
46
|
+
append(slot, 'user/message', { id: messageId, turn, message: { id: messageId } });
|
|
47
|
+
return slot.events.at(-1);
|
|
48
|
+
},
|
|
49
|
+
endTurn(sessionId, turn, reasonKind) {
|
|
50
|
+
const slot = session(sessionId);
|
|
51
|
+
append(slot, 'turn/end', { turn, reason: { kind: reasonKind } });
|
|
52
|
+
return slot.events.at(-1);
|
|
53
|
+
},
|
|
54
|
+
toolCall(sessionId, name, args) {
|
|
55
|
+
const slot = session(sessionId);
|
|
56
|
+
append(slot, 'tool/call', { name, arguments: args });
|
|
57
|
+
return slot.events.at(-1);
|
|
58
|
+
},
|
|
59
|
+
assistant(sessionId, text) {
|
|
60
|
+
const slot = session(sessionId);
|
|
61
|
+
append(slot, 'assistant/message', { text, message: { content: [{ type: 'text', text }] } });
|
|
62
|
+
return slot.events.at(-1);
|
|
63
|
+
},
|
|
64
|
+
forgetLog(sessionId, messageId) {
|
|
65
|
+
const slot = session(sessionId);
|
|
66
|
+
slot.events = slot.events.filter(event => !(event.type === 'agent/inbox/spliced'
|
|
67
|
+
&& Array.isArray(event.data?.inserted)
|
|
68
|
+
&& event.data.inserted.some(item => item?.id === messageId)));
|
|
69
|
+
slot.nextTurn = slot.nextTurn.filter(item => item.id !== messageId);
|
|
70
|
+
},
|
|
71
|
+
async createChild(spec) {
|
|
72
|
+
calls.push({ ...spec });
|
|
73
|
+
if (state.failCreate)
|
|
74
|
+
throw new Error('create failed');
|
|
75
|
+
session(spec.sessionId);
|
|
76
|
+
return spec.sessionId;
|
|
77
|
+
},
|
|
78
|
+
async push(sessionId, messageId, text) {
|
|
79
|
+
pushes.push({ sessionId, messageId, text });
|
|
80
|
+
if (state.flushMode === 'fail')
|
|
81
|
+
return { ok: false, ambiguous: false, seq: null, error: 'push-failed' };
|
|
82
|
+
if (state.flushMode === 'ambiguous')
|
|
83
|
+
return { ok: false, ambiguous: true, seq: null, error: 'flush-unconfirmed' };
|
|
84
|
+
const slot = session(sessionId);
|
|
85
|
+
if (!slot.nextTurn.some(item => item.id === messageId))
|
|
86
|
+
slot.nextTurn.push({ id: messageId, text });
|
|
87
|
+
const seq = append(slot, 'agent/inbox/spliced', { inserted: [{ id: messageId }], target: 'next-turn' });
|
|
88
|
+
return { ok: true, ambiguous: false, seq, target: 'next-turn' };
|
|
89
|
+
},
|
|
90
|
+
async logHas(sessionId, messageId) {
|
|
91
|
+
return session(sessionId).events.some(event => (event.type === 'agent/inbox/spliced'
|
|
92
|
+
&& Array.isArray(event.data?.inserted)
|
|
93
|
+
&& event.data.inserted.some(item => item?.id === messageId)));
|
|
94
|
+
},
|
|
95
|
+
async remove(sessionId, messageId) {
|
|
96
|
+
const slot = session(sessionId);
|
|
97
|
+
const index = slot.nextTurn.findIndex(item => item.id === messageId);
|
|
98
|
+
if (index < 0)
|
|
99
|
+
return false;
|
|
100
|
+
slot.nextTurn.splice(index, 1);
|
|
101
|
+
return true;
|
|
102
|
+
},
|
|
103
|
+
async cancel(sessionId, options) {
|
|
104
|
+
cancels.push({ sessionId, keepInbox: options?.keepInbox === true });
|
|
105
|
+
},
|
|
106
|
+
async snapshot(sessionId) {
|
|
107
|
+
return session(sessionId).events.map(event => ({ ...event, data: event.data }));
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
/**
|
|
111
|
+
* @param {string} sessionId
|
|
112
|
+
*/
|
|
113
|
+
function session(sessionId) {
|
|
114
|
+
let slot = sessions.get(sessionId);
|
|
115
|
+
if (!slot) {
|
|
116
|
+
slot = { nextTurn: [], events: [], seq: 0, turn: 0 };
|
|
117
|
+
sessions.set(sessionId, slot);
|
|
118
|
+
}
|
|
119
|
+
return slot;
|
|
120
|
+
}
|
|
121
|
+
/**
|
|
122
|
+
* @param {{ events: Array<Record<string, unknown>>, seq: number }} slot
|
|
123
|
+
* @param {string} type
|
|
124
|
+
* @param {Record<string, unknown>} data
|
|
125
|
+
*/
|
|
126
|
+
function append(slot, type, data) {
|
|
127
|
+
slot.seq += 1;
|
|
128
|
+
slot.events.push({ type, seq: slot.seq, data });
|
|
129
|
+
return slot.seq;
|
|
130
|
+
}
|
|
131
|
+
}
|