agentschat-mcp 0.36.17 → 0.36.19
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 +25 -14
- package/codex/README.md +2 -2
- package/cordis.patch.yml +23 -0
- package/dist/codex-bridge.js +10 -9
- package/dist/connector.js +3 -2
- package/dist/dsh.js +932 -0
- package/dist/muse.js +612 -0
- package/dist/server.js +1215 -436
- package/dsh/README.md +83 -0
- package/dsh/identity-ui/README.md +76 -0
- package/dsh/identity-ui/client.js +260 -0
- package/dsh/identity-ui/cordis.patch.yml +11 -0
- package/dsh/identity-ui/index.js +21 -0
- package/dsh/identity-ui/package.json +29 -0
- package/dsh/inbound-bridge/README.md +84 -0
- package/dsh/inbound-bridge/index.js +716 -0
- package/dsh/inbound-bridge/package.json +14 -0
- package/dsh/src/cli.ts +374 -0
- package/dsh/src/patch.ts +117 -0
- package/dsh/tests/dsh.test.ts +113 -0
- package/muse/README.md +179 -0
- package/muse/scripts/ensure-muse-wakes.mjs +108 -0
- package/muse/scripts/keepalive-hook.sh +45 -0
- package/muse/scripts/muse-wake-receiver.mjs +51 -0
- package/muse/scripts/setup-muse-keepalive.sh +68 -0
- package/muse/scripts/smoke.mjs +17 -0
- package/muse/skills/muse-keepalive.md +95 -0
- package/muse/skills/onboarding.md +137 -0
- package/muse/src/bridge.ts +83 -0
- package/muse/src/cli.ts +155 -0
- package/muse/src/client.ts +241 -0
- package/muse/src/config.ts +79 -0
- package/muse/src/index.ts +10 -0
- package/muse/src/policy.ts +68 -0
- package/muse/src/types.ts +38 -0
- package/muse/src/typing.ts +51 -0
- package/muse/src/wake.ts +176 -0
- package/muse/tests/bridge.test.mjs +51 -0
- package/muse/tests/client.test.mjs +178 -0
- package/muse/tests/config.test.mjs +24 -0
- package/muse/tests/policy.test.mjs +47 -0
- package/muse/tests/typing.test.mjs +26 -0
- package/muse/tests/wake.test.mjs +81 -0
- package/package.json +17 -3
- package/skills/grok-wake-keepalive.md +1 -1
- package/skills/onboarding.md +40 -34
- package/src/cli.mjs +17 -7
- package/src/redact.ts +10 -4
- package/src/server.ts +852 -430
- package/src/session-bind.ts +348 -12
- package/src/session-route.ts +87 -0
- package/src/tool-annotations.ts +1 -0
- package/src/wake.ts +75 -8
|
@@ -0,0 +1,716 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* agentschat-inbound — machine-local DSH plugin (no upstream package).
|
|
3
|
+
*
|
|
4
|
+
* Why it exists: @deepseek-ai/dsh-mcp-client bridges only outbound tool calls,
|
|
5
|
+
* so an AgentsChat DM / @mention never reaches a running DSH conversation on its
|
|
6
|
+
* own. DSH does expose a plugin seam for exactly this: `agent.followup(message)`
|
|
7
|
+
* queues an ordinary user-role message and wakes the agent loop (the built-in
|
|
8
|
+
* `schedule` plugin wakes agents the same way).
|
|
9
|
+
*
|
|
10
|
+
* Architecture (reuse over reimplementation):
|
|
11
|
+
* 1. This plugin hosts a loopback-only HTTP endpoint with HMAC-SHA256
|
|
12
|
+
* verification (same signature scheme as `muse/src/wake.ts`).
|
|
13
|
+
* 2. It supervises `agentschat-mcp --dsh --wake`, the already-tested
|
|
14
|
+
* WebSocket listener, and points DSH_WAKE_URL at that endpoint.
|
|
15
|
+
* 3. On a signed wake it hands a plugin-sourced user message to the session the
|
|
16
|
+
* wake names (`payload.target_session_id`, resolved from `session-binds.json`
|
|
17
|
+
* by the daemon). Delivery is bound-only: no target, or a target that is no
|
|
18
|
+
* longer live, is dropped rather than guessed into another conversation. A
|
|
19
|
+
* wake that arrives while the bound session is mid-turn stays queued until
|
|
20
|
+
* it goes idle. The GUI then shows the inbound message and the model can
|
|
21
|
+
* answer with the `mcp__agentschat__reply` tool.
|
|
22
|
+
*
|
|
23
|
+
* Session format v4 attribution: every durable message needs a producer-owned
|
|
24
|
+
* `source.kind`. The retired `{ kind: 'plugin', plugin: <name> }` wrapper is
|
|
25
|
+
* rejected at append time with "format v4 message requires a producer-owned
|
|
26
|
+
* source kind", which silently kills the persisted turn. DSH's own convention
|
|
27
|
+
* for third-party producers is `plugin:<name>` (see producerKind() in the
|
|
28
|
+
* released V3->V4 source migration), so that is what we emit.
|
|
29
|
+
*
|
|
30
|
+
* Mid-turn delivery wedge: `agent.followup()` splices the Session inbox
|
|
31
|
+
* synchronously. If the target Session has a step in flight — including the
|
|
32
|
+
* step whose own tool call produced the wake — that splice races the open
|
|
33
|
+
* step: the step never receives its tool result and the Session is stuck in
|
|
34
|
+
* `running` with no further rows. Both 2026-10-28 wedges (session-41a8d6f0 at
|
|
35
|
+
* 09:41:13 and session-dd7406c7 at 09:53:32) end on the tool/call row that
|
|
36
|
+
* POSTed the wake, milliseconds before the injection log line. Delivery is
|
|
37
|
+
* therefore gated on `agent.status === 'idle'`.
|
|
38
|
+
*
|
|
39
|
+
* Security: the endpoint binds 127.0.0.1 and rejects unsigned bodies. The wake
|
|
40
|
+
* secret lives in ~/.agentschat/dsh-inbound.secret (0600) and is shared with
|
|
41
|
+
* the child process through its environment only. The AgentsChat token remains
|
|
42
|
+
* in ~/.agentschat/dsh.json and is read by the child, never by this file.
|
|
43
|
+
*/
|
|
44
|
+
|
|
45
|
+
import {
|
|
46
|
+
appendFileSync,
|
|
47
|
+
chmodSync,
|
|
48
|
+
existsSync,
|
|
49
|
+
mkdirSync,
|
|
50
|
+
readFileSync,
|
|
51
|
+
readdirSync,
|
|
52
|
+
renameSync,
|
|
53
|
+
statSync,
|
|
54
|
+
writeFileSync,
|
|
55
|
+
} from 'node:fs';
|
|
56
|
+
import { dirname, join } from 'node:path';
|
|
57
|
+
import { homedir } from 'node:os';
|
|
58
|
+
import { createHmac, randomBytes, randomUUID, timingSafeEqual } from 'node:crypto';
|
|
59
|
+
import { spawn } from 'node:child_process';
|
|
60
|
+
import { createServer } from 'node:http';
|
|
61
|
+
|
|
62
|
+
export const name = 'agentschat-inbound';
|
|
63
|
+
|
|
64
|
+
const LOG_PATH = join(homedir(), '.dsh', 'agentschat-inbound.log');
|
|
65
|
+
const SECRET_PATH = join(homedir(), '.agentschat', 'dsh-inbound.secret');
|
|
66
|
+
const QUEUE_PATH = join(homedir(), '.agentschat', 'dsh-wake-queue.jsonl');
|
|
67
|
+
/** Config root shared with the MCP server: profiles live in `<dir>/profiles/`. */
|
|
68
|
+
const AGENTSCHAT_DIR = join(homedir(), '.agentschat');
|
|
69
|
+
const PROFILES_DIR = join(AGENTSCHAT_DIR, 'profiles');
|
|
70
|
+
const BINDS_PATH = join(AGENTSCHAT_DIR, 'session-binds.json');
|
|
71
|
+
const LOG_MAX_BYTES = 512 * 1024;
|
|
72
|
+
const MAX_SEEN_IDS = 200;
|
|
73
|
+
/**
|
|
74
|
+
* Hard cap on queued wakes. Distinct message_ids — and payloads without a string
|
|
75
|
+
* message_id, which bypass dedupe entirely — must not grow the queue forever.
|
|
76
|
+
*/
|
|
77
|
+
const MAX_PENDING = 100;
|
|
78
|
+
const WAKE_PATH = '/agentschat/wake';
|
|
79
|
+
/**
|
|
80
|
+
* Identifies the code the *running* instance actually has in memory.
|
|
81
|
+
*
|
|
82
|
+
* Local plugins are loaded from `file://` by the profile patch, and a reload is
|
|
83
|
+
* not the same thing as a re-import: editing this file did not reload the
|
|
84
|
+
* running plugin, while editing the profile patch did. Without a marker there
|
|
85
|
+
* is no way to tell which version is live from the outside, which is how a
|
|
86
|
+
* "fixed" build once delivered into a busy Session. `/health` reports it.
|
|
87
|
+
*/
|
|
88
|
+
const BUILD = 'inbound/2026-10-29.14-config-bin';
|
|
89
|
+
/** Producer-owned source kind; a bare `plugin` wrapper is refused by session format v4. */
|
|
90
|
+
const SOURCE_KIND = 'plugin:agentschat-inbound';
|
|
91
|
+
/** Poll interval while wakes wait for a root agent to finish its turn. */
|
|
92
|
+
const DEFAULT_RETRY_MS = 2000;
|
|
93
|
+
/** A flush that never settles must not hold delivery (or the next wake) hostage. */
|
|
94
|
+
const DEFAULT_FLUSH_TIMEOUT_MS = 2000;
|
|
95
|
+
|
|
96
|
+
/** Await `promise`, reporting a timeout instead of hanging on it. */
|
|
97
|
+
function settleWithin(promise, ms) {
|
|
98
|
+
let timer;
|
|
99
|
+
const timedOut = new Promise((resolve) => {
|
|
100
|
+
timer = setTimeout(() => resolve({ timedOut: true }), ms);
|
|
101
|
+
});
|
|
102
|
+
return Promise.race([
|
|
103
|
+
promise.then(
|
|
104
|
+
(value) => ({ ok: true, value }),
|
|
105
|
+
(error) => ({ ok: false, error }),
|
|
106
|
+
),
|
|
107
|
+
timedOut,
|
|
108
|
+
]).finally(() => clearTimeout(timer));
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function log(line) {
|
|
112
|
+
try {
|
|
113
|
+
try {
|
|
114
|
+
if (statSync(LOG_PATH).size > LOG_MAX_BYTES) writeFileSync(LOG_PATH, '');
|
|
115
|
+
} catch {}
|
|
116
|
+
appendFileSync(LOG_PATH, `${new Date().toISOString()} ${line}\n`);
|
|
117
|
+
} catch {}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Read the shared wake secret, creating it (0600) when absent. */
|
|
121
|
+
function loadSecret() {
|
|
122
|
+
try {
|
|
123
|
+
if (existsSync(SECRET_PATH)) {
|
|
124
|
+
const existing = readFileSync(SECRET_PATH, 'utf8').trim();
|
|
125
|
+
if (existing) return existing;
|
|
126
|
+
}
|
|
127
|
+
mkdirSync(dirname(SECRET_PATH), { recursive: true });
|
|
128
|
+
const secret = randomBytes(32).toString('hex');
|
|
129
|
+
writeFileSync(SECRET_PATH, `${secret}\n`, { mode: 0o600 });
|
|
130
|
+
try {
|
|
131
|
+
chmodSync(SECRET_PATH, 0o600);
|
|
132
|
+
} catch (error) {
|
|
133
|
+
log(`WARNING: could not chmod ${SECRET_PATH}: ${error?.message ?? error}`);
|
|
134
|
+
}
|
|
135
|
+
return secret;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
log(`cannot load wake secret: ${error?.message ?? error}`);
|
|
138
|
+
return undefined;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
function verifySignature(body, sigHex, secret) {
|
|
143
|
+
if (typeof sigHex !== 'string' || sigHex.length === 0) return false;
|
|
144
|
+
let received;
|
|
145
|
+
try {
|
|
146
|
+
received = Buffer.from(sigHex, 'hex');
|
|
147
|
+
} catch {
|
|
148
|
+
return false;
|
|
149
|
+
}
|
|
150
|
+
const expected = createHmac('sha256', secret).update(body, 'utf8').digest();
|
|
151
|
+
return received.length === expected.length && timingSafeEqual(received, expected);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** Render the inbound message as a normal user turn for the agent. */
|
|
155
|
+
function renderInbound(payload) {
|
|
156
|
+
const channel = payload.channel_id ?? '(unknown)';
|
|
157
|
+
const kind = channel.startsWith('dm-') ? 'direct message' : 'channel message';
|
|
158
|
+
return [
|
|
159
|
+
'[AgentsChat inbound message]',
|
|
160
|
+
`channel_id: ${channel}`,
|
|
161
|
+
payload.message_id ? `message_id: ${payload.message_id}` : undefined,
|
|
162
|
+
`from: ${payload.sender_id ?? '(unknown)'}`,
|
|
163
|
+
`kind: ${kind}`,
|
|
164
|
+
'content:',
|
|
165
|
+
payload.content ?? '(empty)',
|
|
166
|
+
'',
|
|
167
|
+
`When a reply is appropriate, use the mcp__agentschat__reply tool with chat_id "${channel}".`,
|
|
168
|
+
'Keep the reply concise. Never include tokens, keys, or claim URLs.',
|
|
169
|
+
]
|
|
170
|
+
.filter((line) => line !== undefined)
|
|
171
|
+
.join('\n');
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
const seen = [];
|
|
175
|
+
const seenSet = new Set();
|
|
176
|
+
|
|
177
|
+
/** Deduplicate wake retries by message_id; bounded memory. */
|
|
178
|
+
function firstDelivery(payload) {
|
|
179
|
+
const id = typeof payload.message_id === 'string' ? payload.message_id : undefined;
|
|
180
|
+
if (!id) return true;
|
|
181
|
+
if (seenSet.has(id)) return false;
|
|
182
|
+
seenSet.add(id);
|
|
183
|
+
seen.push(id);
|
|
184
|
+
if (seen.length > MAX_SEEN_IDS) {
|
|
185
|
+
const evicted = seen.shift();
|
|
186
|
+
if (evicted !== undefined) seenSet.delete(evicted);
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* Release a claim taken by firstDelivery() after a delivery that never landed.
|
|
193
|
+
*
|
|
194
|
+
* The claim happens *before* the attempt (so a retry storm cannot double-queue),
|
|
195
|
+
* which means a wake that fails to splice has to be un-claimed here — otherwise
|
|
196
|
+
* the daemon's next attempt is swallowed as a duplicate and the message is lost
|
|
197
|
+
* for good.
|
|
198
|
+
*/
|
|
199
|
+
function forgetDelivery(payload) {
|
|
200
|
+
const id = typeof payload.message_id === 'string' ? payload.message_id : undefined;
|
|
201
|
+
if (!id || !seenSet.delete(id)) return;
|
|
202
|
+
const index = seen.indexOf(id);
|
|
203
|
+
if (index >= 0) seen.splice(index, 1);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function apply(ctx, config = {}) {
|
|
207
|
+
const port = Number(config.port ?? 8799);
|
|
208
|
+
// The wake daemon is a separate process; its entry point is deployment-specific,
|
|
209
|
+
// so it comes from config/env rather than a hardcoded checkout path. Without it
|
|
210
|
+
// the HTTP side (wakes in, identity API out) still works.
|
|
211
|
+
const mcpBin = config.mcpBin ?? process.env.AGENTSCHAT_DSH_BRIDGE_BIN;
|
|
212
|
+
const nodeBin = config.nodeBin ?? process.env.DSH_NODE_BIN ?? 'node';
|
|
213
|
+
const channels = Array.isArray(config.channels) && config.channels.length > 0 ? config.channels : ['welcome'];
|
|
214
|
+
const retryMs = Number(config.retryMs ?? DEFAULT_RETRY_MS);
|
|
215
|
+
const flushTimeoutMs = Number(config.flushTimeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS);
|
|
216
|
+
|
|
217
|
+
const secret = loadSecret();
|
|
218
|
+
if (secret === undefined) {
|
|
219
|
+
log('not starting: no wake secret');
|
|
220
|
+
return;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
let stopping = false;
|
|
224
|
+
let daemon;
|
|
225
|
+
let restartTimer;
|
|
226
|
+
let consecutiveFailures = 0;
|
|
227
|
+
|
|
228
|
+
/** Live root agents, oldest first, with the status the gate reads. */
|
|
229
|
+
function rootStatuses() {
|
|
230
|
+
return liveRoots().map((agent) => {
|
|
231
|
+
let status;
|
|
232
|
+
try {
|
|
233
|
+
status = agent.status;
|
|
234
|
+
} catch (error) {
|
|
235
|
+
status = `error: ${error?.message ?? error}`;
|
|
236
|
+
}
|
|
237
|
+
return { id: agent.id, status };
|
|
238
|
+
});
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** Live root agents, oldest first. */
|
|
242
|
+
function liveRoots() {
|
|
243
|
+
let agents;
|
|
244
|
+
try {
|
|
245
|
+
agents = ctx.get('agents');
|
|
246
|
+
} catch (error) {
|
|
247
|
+
log(`agents service unavailable: ${error?.message ?? error}`);
|
|
248
|
+
return [];
|
|
249
|
+
}
|
|
250
|
+
if (agents === undefined || agents === null) return [];
|
|
251
|
+
try {
|
|
252
|
+
return agents.roots();
|
|
253
|
+
} catch (error) {
|
|
254
|
+
log(`cannot list root agents: ${error?.message ?? error}`);
|
|
255
|
+
return [];
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/** Wake deliveries waiting for their bound session to go idle, oldest first. */
|
|
260
|
+
const pending = [];
|
|
261
|
+
let retryTimer;
|
|
262
|
+
let draining = false;
|
|
263
|
+
|
|
264
|
+
function scheduleRetry() {
|
|
265
|
+
if (stopping || retryTimer !== undefined || pending.length === 0) return;
|
|
266
|
+
retryTimer = setTimeout(() => {
|
|
267
|
+
retryTimer = undefined;
|
|
268
|
+
drain().catch((error) => log(`drain failed: ${error?.message ?? error}`));
|
|
269
|
+
}, retryMs);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
/**
|
|
273
|
+
* Deliver the queued head to its bound session, or report why it must wait.
|
|
274
|
+
*
|
|
275
|
+
* Delivery is bound-only: a wake lands in the session named by
|
|
276
|
+
* `payload.target_session_id` (resolved from `session-binds.json` by the
|
|
277
|
+
* daemon), never in a guess. A busy target is steered into its current turn
|
|
278
|
+
* rather than waited for; an idle one takes the plain `followup()` splice.
|
|
279
|
+
*/
|
|
280
|
+
async function attempt(entry) {
|
|
281
|
+
const id = entry.payload.message_id ?? '(no id)';
|
|
282
|
+
const wanted = typeof entry.payload.target_session_id === 'string' ? entry.payload.target_session_id : undefined;
|
|
283
|
+
if (wanted === undefined) {
|
|
284
|
+
log(`wake ${id} dropped: identity is unbound (bind a session in the identity chip to receive it here)`);
|
|
285
|
+
return 'dropped';
|
|
286
|
+
}
|
|
287
|
+
const target = liveRoots().find((agent) => agent.id === wanted);
|
|
288
|
+
if (target === undefined) {
|
|
289
|
+
log(`wake ${id} dropped: bound session ${wanted} is not live (bind the identity to an open session)`);
|
|
290
|
+
return 'dropped';
|
|
291
|
+
}
|
|
292
|
+
if (target.status !== 'idle') {
|
|
293
|
+
// Busy target → cut in, do not wait. `agent.steer()` hands the message to the
|
|
294
|
+
// *running* turn at its next step boundary; it is the same call DSH's own
|
|
295
|
+
// session controller uses for a prompt typed while the agent works. Only if
|
|
296
|
+
// that API is absent or throws do we fall back to waiting for idle.
|
|
297
|
+
if (typeof target.steer === 'function') {
|
|
298
|
+
try {
|
|
299
|
+
target.steer(entry.message);
|
|
300
|
+
log(
|
|
301
|
+
`injected ${id} from ${entry.payload.sender_id ?? '?'} into agent=${wanted} ` +
|
|
302
|
+
'(steered into the running turn)',
|
|
303
|
+
);
|
|
304
|
+
return 'delivered';
|
|
305
|
+
} catch (error) {
|
|
306
|
+
log(`steer failed for ${wanted}: ${error?.message ?? error}; queuing instead`);
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
if (entry.waited !== true) {
|
|
310
|
+
entry.waited = true;
|
|
311
|
+
log(`wake ${id} queued: bound session ${wanted} is not idle`);
|
|
312
|
+
}
|
|
313
|
+
return 'deferred';
|
|
314
|
+
}
|
|
315
|
+
try {
|
|
316
|
+
target.followup(entry.message);
|
|
317
|
+
} catch (error) {
|
|
318
|
+
log(`followup failed for agent=${target.id}: ${error?.message ?? error}`);
|
|
319
|
+
forgetDelivery(entry.payload);
|
|
320
|
+
return 'dropped';
|
|
321
|
+
}
|
|
322
|
+
// followup splices the inbox synchronously; flushing here only proves the
|
|
323
|
+
// Session log accepted the row, so a rejected message is reported in this
|
|
324
|
+
// log instead of surfacing as a dead turn in the GUI.
|
|
325
|
+
try {
|
|
326
|
+
const sessions = ctx.get('sessions');
|
|
327
|
+
if (sessions === undefined) {
|
|
328
|
+
log(`WARNING: sessions service unavailable; ${id} queued unverified`);
|
|
329
|
+
} else {
|
|
330
|
+
const outcome = await settleWithin(sessions.flush(target.session), flushTimeoutMs);
|
|
331
|
+
if (outcome.timedOut === true) {
|
|
332
|
+
log(`WARNING: flush for ${id} did not finish within ${flushTimeoutMs}ms`);
|
|
333
|
+
} else if (outcome.ok !== true) {
|
|
334
|
+
log(`persist failed for agent=${target.id}: ${outcome.error?.message ?? outcome.error}`);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
} catch (error) {
|
|
338
|
+
log(`persist failed for agent=${target.id}: ${error?.message ?? error}`);
|
|
339
|
+
}
|
|
340
|
+
log(
|
|
341
|
+
`injected ${id} from ${entry.payload.sender_id ?? '?'} into agent=${target.id} ` +
|
|
342
|
+
`roots=[${liveRoots()
|
|
343
|
+
.map((root) => root.id)
|
|
344
|
+
.join(', ')}]`,
|
|
345
|
+
);
|
|
346
|
+
return 'delivered';
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
async function drain() {
|
|
350
|
+
if (draining) return;
|
|
351
|
+
draining = true;
|
|
352
|
+
try {
|
|
353
|
+
while (pending.length > 0 && !stopping) {
|
|
354
|
+
let outcome;
|
|
355
|
+
try {
|
|
356
|
+
outcome = await attempt(pending[0]);
|
|
357
|
+
} catch (error) {
|
|
358
|
+
log(`attempt failed: ${error?.message ?? error}`);
|
|
359
|
+
break;
|
|
360
|
+
}
|
|
361
|
+
if (outcome === 'deferred') break;
|
|
362
|
+
pending.shift();
|
|
363
|
+
}
|
|
364
|
+
} finally {
|
|
365
|
+
draining = false;
|
|
366
|
+
// Reschedule inside `finally`: an unexpected throw above must not strand
|
|
367
|
+
// the queue head without a timer.
|
|
368
|
+
scheduleRetry();
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
async function inject(payload) {
|
|
373
|
+
if (payload === null || typeof payload !== 'object') {
|
|
374
|
+
log('ignoring non-object wake payload');
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (!firstDelivery(payload)) {
|
|
378
|
+
log(`duplicate wake for ${payload.message_id}, ignored`);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (pending.length >= MAX_PENDING) {
|
|
382
|
+
// Bounded, not lossless: drop the oldest so the newest inbound — the one a
|
|
383
|
+
// human is most likely waiting on — still gets delivered.
|
|
384
|
+
const dropped = pending.shift();
|
|
385
|
+
log(`pending at ${MAX_PENDING}; dropped oldest wake ${dropped?.payload?.message_id ?? '(no id)'}`);
|
|
386
|
+
}
|
|
387
|
+
pending.push({
|
|
388
|
+
payload,
|
|
389
|
+
message: {
|
|
390
|
+
id: randomUUID(),
|
|
391
|
+
role: 'user',
|
|
392
|
+
content: [{ type: 'text', text: renderInbound(payload) }],
|
|
393
|
+
source: { kind: SOURCE_KIND },
|
|
394
|
+
},
|
|
395
|
+
});
|
|
396
|
+
await drain();
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Profiles the identity chip may bind, newest first. Never exposes tokens.
|
|
401
|
+
*
|
|
402
|
+
* Both layouts are scanned because the MCP server resolves either: nested
|
|
403
|
+
* `<config>/profiles/<name>.json` first, then the flat legacy `<config>/<name>.json`
|
|
404
|
+
* (that is where a hand-written `DSH_Live.json` lives). Nested wins on a name
|
|
405
|
+
* collision, matching the server's precedence; entries without `agent_id` are
|
|
406
|
+
* cursors/manifests, not profiles.
|
|
407
|
+
*/
|
|
408
|
+
function listProfiles() {
|
|
409
|
+
const out = [];
|
|
410
|
+
const seen = new Set();
|
|
411
|
+
const scan = (dir) => {
|
|
412
|
+
let files;
|
|
413
|
+
try {
|
|
414
|
+
files = readdirSync(dir).filter((file) => file.endsWith('.json'));
|
|
415
|
+
} catch {
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
for (const file of files) {
|
|
419
|
+
const name = file.replace(/\.json$/, '');
|
|
420
|
+
if (seen.has(name)) continue;
|
|
421
|
+
const path = join(dir, file);
|
|
422
|
+
try {
|
|
423
|
+
const parsed = JSON.parse(readFileSync(path, 'utf8'));
|
|
424
|
+
const agentId = typeof parsed.agent_id === 'string' ? parsed.agent_id : '';
|
|
425
|
+
if (!agentId) continue;
|
|
426
|
+
seen.add(name);
|
|
427
|
+
out.push({
|
|
428
|
+
name,
|
|
429
|
+
agentId,
|
|
430
|
+
displayName: typeof parsed.display_name === 'string' ? parsed.display_name : undefined,
|
|
431
|
+
mtime: statSync(path).mtimeMs,
|
|
432
|
+
});
|
|
433
|
+
} catch {}
|
|
434
|
+
}
|
|
435
|
+
};
|
|
436
|
+
scan(PROFILES_DIR);
|
|
437
|
+
scan(AGENTSCHAT_DIR);
|
|
438
|
+
out.sort((a, b) => b.mtime - a.mtime);
|
|
439
|
+
return out;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
function readBinds() {
|
|
443
|
+
try {
|
|
444
|
+
const parsed = JSON.parse(readFileSync(BINDS_PATH, 'utf8'));
|
|
445
|
+
return parsed !== null && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : {};
|
|
446
|
+
} catch {
|
|
447
|
+
return {};
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
/** Same shape the MCP server reads: `{ [sessionId]: profileName }`. */
|
|
452
|
+
function writeBinds(binds) {
|
|
453
|
+
mkdirSync(AGENTSCHAT_DIR, { recursive: true });
|
|
454
|
+
const tmp = `${BINDS_PATH}.${process.pid}.tmp`;
|
|
455
|
+
writeFileSync(tmp, JSON.stringify(binds, null, 2));
|
|
456
|
+
renameSync(tmp, BINDS_PATH);
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
function sendJson(res, status, value) {
|
|
460
|
+
res.writeHead(status, {
|
|
461
|
+
'content-type': 'application/json',
|
|
462
|
+
'access-control-allow-origin': '*',
|
|
463
|
+
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
464
|
+
'access-control-allow-headers': 'content-type',
|
|
465
|
+
});
|
|
466
|
+
res.end(JSON.stringify(value));
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** Read a bounded JSON body; the endpoint is loopback-only and unauthenticated. */
|
|
470
|
+
function readJsonBody(req, res, onBody) {
|
|
471
|
+
const chunks = [];
|
|
472
|
+
let size = 0;
|
|
473
|
+
req.on('data', (chunk) => {
|
|
474
|
+
size += chunk.length;
|
|
475
|
+
if (size > 64 * 1024) {
|
|
476
|
+
req.destroy();
|
|
477
|
+
return;
|
|
478
|
+
}
|
|
479
|
+
chunks.push(chunk);
|
|
480
|
+
});
|
|
481
|
+
req.on('end', () => {
|
|
482
|
+
let parsed;
|
|
483
|
+
try {
|
|
484
|
+
parsed = JSON.parse(Buffer.concat(chunks).toString('utf8'));
|
|
485
|
+
} catch {
|
|
486
|
+
sendJson(res, 400, { ok: false, error: 'invalid JSON' });
|
|
487
|
+
return;
|
|
488
|
+
}
|
|
489
|
+
onBody(parsed);
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
const server = createServer((req, res) => {
|
|
494
|
+
if (req.method === 'OPTIONS') {
|
|
495
|
+
res.writeHead(204, {
|
|
496
|
+
'access-control-allow-origin': '*',
|
|
497
|
+
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
498
|
+
'access-control-allow-headers': 'content-type',
|
|
499
|
+
});
|
|
500
|
+
res.end();
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
// Identity API for the Client chip: which profiles exist, which one this
|
|
504
|
+
// conversation is bound to, and binding it. Bindings are the same
|
|
505
|
+
// `session-binds.json` the MCP server reads per tool call, so the chip needs
|
|
506
|
+
// no separate storage — and the next tool call from this session picks the
|
|
507
|
+
// identity up without a restart.
|
|
508
|
+
if (req.method === 'GET' && req.url === '/identity') {
|
|
509
|
+
sendJson(res, 200, { ok: true, build: BUILD, profiles: listProfiles(), binds: readBinds() });
|
|
510
|
+
return;
|
|
511
|
+
}
|
|
512
|
+
if (req.method === 'POST' && req.url === '/identity/bind') {
|
|
513
|
+
readJsonBody(req, res, (body) => {
|
|
514
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
|
|
515
|
+
const profileName = typeof body?.profileName === 'string' ? body.profileName.trim() : '';
|
|
516
|
+
if (!sessionId || !listProfiles().some((entry) => entry.name === profileName)) {
|
|
517
|
+
sendJson(res, 400, { ok: false, error: 'sessionId and a known profileName are required' });
|
|
518
|
+
return;
|
|
519
|
+
}
|
|
520
|
+
const binds = readBinds();
|
|
521
|
+
binds[sessionId] = profileName;
|
|
522
|
+
try {
|
|
523
|
+
writeBinds(binds);
|
|
524
|
+
} catch (error) {
|
|
525
|
+
sendJson(res, 500, { ok: false, error: String(error?.message ?? error) });
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
log(`identity bound: ${sessionId} -> ${profileName}`);
|
|
529
|
+
sendJson(res, 200, { ok: true, binds });
|
|
530
|
+
});
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
// Probe used by the Client chip: proves the browser module actually ran, and
|
|
534
|
+
// carries whatever failed. Without it a blank UI is indistinguishable from a
|
|
535
|
+
// module that never loaded.
|
|
536
|
+
if (req.method === 'POST' && req.url === '/identity/alive') {
|
|
537
|
+
readJsonBody(req, res, (body) => {
|
|
538
|
+
log(`client-alive ${JSON.stringify(body)}`);
|
|
539
|
+
sendJson(res, 200, { ok: true, build: BUILD });
|
|
540
|
+
});
|
|
541
|
+
return;
|
|
542
|
+
}
|
|
543
|
+
if (req.method === 'POST' && req.url === '/identity/unbind') {
|
|
544
|
+
readJsonBody(req, res, (body) => {
|
|
545
|
+
const sessionId = typeof body?.sessionId === 'string' ? body.sessionId.trim() : '';
|
|
546
|
+
if (!sessionId) {
|
|
547
|
+
sendJson(res, 400, { ok: false, error: 'sessionId required' });
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
const binds = readBinds();
|
|
551
|
+
delete binds[sessionId];
|
|
552
|
+
try {
|
|
553
|
+
writeBinds(binds);
|
|
554
|
+
} catch (error) {
|
|
555
|
+
sendJson(res, 500, { ok: false, error: String(error?.message ?? error) });
|
|
556
|
+
return;
|
|
557
|
+
}
|
|
558
|
+
log(`identity unbound: ${sessionId}`);
|
|
559
|
+
sendJson(res, 200, { ok: true, binds });
|
|
560
|
+
});
|
|
561
|
+
return;
|
|
562
|
+
}
|
|
563
|
+
if (req.method === 'GET' && (req.url === '/health' || req.url === '/selftest')) {
|
|
564
|
+
const roots = rootStatuses();
|
|
565
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
566
|
+
if (req.url === '/health') {
|
|
567
|
+
// `build` is the only way to tell which file:// version is actually in
|
|
568
|
+
// memory; `agents` is kept for scripts that predate `roots`.
|
|
569
|
+
res.end(
|
|
570
|
+
JSON.stringify({
|
|
571
|
+
ok: true,
|
|
572
|
+
plugin: name,
|
|
573
|
+
build: BUILD,
|
|
574
|
+
port,
|
|
575
|
+
agents: roots.map((root) => root.id),
|
|
576
|
+
roots,
|
|
577
|
+
daemon: daemon !== undefined,
|
|
578
|
+
}),
|
|
579
|
+
);
|
|
580
|
+
return;
|
|
581
|
+
}
|
|
582
|
+
// Dry run: which bound sessions would accept a wake *right now*, with no
|
|
583
|
+
// splice. The gate's failure mode (freezing a busy Session) is
|
|
584
|
+
// unrecoverable, so it has to be answerable before anything is delivered.
|
|
585
|
+
// Delivery is bound-only, so the useful answer is per binding, not "the
|
|
586
|
+
// newest idle root".
|
|
587
|
+
const byId = new Map(liveRoots().map((agent) => [agent.id, agent]));
|
|
588
|
+
const bound = Object.entries(readBinds()).map(([sessionId, profileName]) => {
|
|
589
|
+
const agent = byId.get(sessionId);
|
|
590
|
+
return {
|
|
591
|
+
sessionId,
|
|
592
|
+
profile: profileName,
|
|
593
|
+
status: agent === undefined ? 'missing' : agent.status,
|
|
594
|
+
decision:
|
|
595
|
+
agent === undefined
|
|
596
|
+
? 'drop'
|
|
597
|
+
: agent.status === 'idle'
|
|
598
|
+
? 'deliver'
|
|
599
|
+
: typeof agent.steer === 'function'
|
|
600
|
+
? 'steer'
|
|
601
|
+
: 'queue',
|
|
602
|
+
};
|
|
603
|
+
});
|
|
604
|
+
res.end(
|
|
605
|
+
JSON.stringify({
|
|
606
|
+
ok: true,
|
|
607
|
+
build: BUILD,
|
|
608
|
+
dryRun: true,
|
|
609
|
+
policy: 'bound-only',
|
|
610
|
+
busyPolicy: 'steer',
|
|
611
|
+
bound,
|
|
612
|
+
roots,
|
|
613
|
+
pending: pending.length,
|
|
614
|
+
}),
|
|
615
|
+
);
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
if (req.method !== 'POST' || req.url !== WAKE_PATH) {
|
|
619
|
+
res.writeHead(404, { 'content-type': 'text/plain' });
|
|
620
|
+
res.end('not found');
|
|
621
|
+
return;
|
|
622
|
+
}
|
|
623
|
+
const chunks = [];
|
|
624
|
+
req.on('data', (chunk) => chunks.push(chunk));
|
|
625
|
+
req.on('end', () => {
|
|
626
|
+
const body = Buffer.concat(chunks).toString('utf8');
|
|
627
|
+
const signature = req.headers['x-agentschat-signature'];
|
|
628
|
+
if (!verifySignature(body, typeof signature === 'string' ? signature : '', secret)) {
|
|
629
|
+
log('rejected wake: bad or missing signature');
|
|
630
|
+
res.writeHead(403, { 'content-type': 'text/plain' });
|
|
631
|
+
res.end('forbidden');
|
|
632
|
+
return;
|
|
633
|
+
}
|
|
634
|
+
let payload;
|
|
635
|
+
try {
|
|
636
|
+
payload = JSON.parse(body);
|
|
637
|
+
} catch (error) {
|
|
638
|
+
log(`rejected wake: invalid JSON (${error?.message ?? error})`);
|
|
639
|
+
res.writeHead(400, { 'content-type': 'text/plain' });
|
|
640
|
+
res.end('bad request');
|
|
641
|
+
return;
|
|
642
|
+
}
|
|
643
|
+
res.writeHead(200, { 'content-type': 'application/json' });
|
|
644
|
+
res.end('{"ok":true}');
|
|
645
|
+
inject(payload).catch((error) => log(`inject failed: ${error?.message ?? error}`));
|
|
646
|
+
});
|
|
647
|
+
});
|
|
648
|
+
server.on('error', (error) => {
|
|
649
|
+
log(`http server error: ${error?.message ?? error}`);
|
|
650
|
+
// The supervisor must not exist without an endpoint of its own: it would post
|
|
651
|
+
// to whatever else happens to own the port.
|
|
652
|
+
log('not starting the wake daemon: the endpoint is not ours');
|
|
653
|
+
});
|
|
654
|
+
server.listen(port, '127.0.0.1', () => {
|
|
655
|
+
log(`listening on http://127.0.0.1:${port}${WAKE_PATH} (health: /health, selftest: /selftest, build: ${BUILD})`);
|
|
656
|
+
startDaemon();
|
|
657
|
+
});
|
|
658
|
+
|
|
659
|
+
function startDaemon() {
|
|
660
|
+
if (stopping) return;
|
|
661
|
+
if (typeof mcpBin !== 'string' || mcpBin.length === 0) {
|
|
662
|
+
log('not starting the wake daemon: no mcpBin configured (set config.mcpBin or AGENTSCHAT_DSH_BRIDGE_BIN)');
|
|
663
|
+
return;
|
|
664
|
+
}
|
|
665
|
+
const args = [mcpBin, '--dsh', '--wake'];
|
|
666
|
+
for (const channel of channels) args.push('--channel', channel);
|
|
667
|
+
const env = {
|
|
668
|
+
...process.env,
|
|
669
|
+
DSH_WAKE_URL: `http://127.0.0.1:${port}${WAKE_PATH}`,
|
|
670
|
+
DSH_WAKE_SECRET: secret,
|
|
671
|
+
DSH_WAKE_QUEUE: QUEUE_PATH,
|
|
672
|
+
};
|
|
673
|
+
log(`starting wake daemon: ${nodeBin} ${args.join(' ')}`);
|
|
674
|
+
daemon = spawn(nodeBin, args, { env, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
675
|
+
daemon.stdout.on('data', (chunk) => {
|
|
676
|
+
const text = String(chunk).trim();
|
|
677
|
+
if (text) log(`[daemon] ${text}`);
|
|
678
|
+
if (text.includes('wake daemon listening')) consecutiveFailures = 0;
|
|
679
|
+
});
|
|
680
|
+
daemon.stderr.on('data', (chunk) => {
|
|
681
|
+
const text = String(chunk).trim();
|
|
682
|
+
if (text) log(`[daemon] ${text}`);
|
|
683
|
+
});
|
|
684
|
+
daemon.on('error', (error) => log(`[daemon] spawn failed: ${error?.message ?? error}`));
|
|
685
|
+
daemon.on('exit', (code, signal) => {
|
|
686
|
+
log(`[daemon] exited code=${code} signal=${signal}`);
|
|
687
|
+
daemon = undefined;
|
|
688
|
+
if (stopping) return;
|
|
689
|
+
consecutiveFailures += 1;
|
|
690
|
+
if (consecutiveFailures > 10) {
|
|
691
|
+
log('wake daemon failed 10 times; giving up until the plugin reloads');
|
|
692
|
+
return;
|
|
693
|
+
}
|
|
694
|
+
const delay = Math.min(5000 * consecutiveFailures, 60000);
|
|
695
|
+
log(`[daemon] restarting in ${Math.round(delay / 1000)}s`);
|
|
696
|
+
restartTimer = setTimeout(startDaemon, delay);
|
|
697
|
+
});
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
ctx.effect(
|
|
701
|
+
() => () => {
|
|
702
|
+
stopping = true;
|
|
703
|
+
if (restartTimer !== undefined) clearTimeout(restartTimer);
|
|
704
|
+
if (retryTimer !== undefined) clearTimeout(retryTimer);
|
|
705
|
+
if (pending.length > 0) log(`stopping with ${pending.length} undelivered wake(s)`);
|
|
706
|
+
try {
|
|
707
|
+
daemon?.kill('SIGTERM');
|
|
708
|
+
} catch {}
|
|
709
|
+
try {
|
|
710
|
+
server.close();
|
|
711
|
+
} catch {}
|
|
712
|
+
log('stopped');
|
|
713
|
+
},
|
|
714
|
+
'agentschat-inbound',
|
|
715
|
+
);
|
|
716
|
+
}
|