@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/dist/inbox.js ADDED
@@ -0,0 +1,194 @@
1
+ /**
2
+ * Host adapter over the native DSH inbox. The durable pending queue is
3
+ * agent.followup(), which appends agent/inbox/spliced and wakes a later turn.
4
+ * This module does not keep a second execution queue.
5
+ */
6
+ import { workerFileSetup } from "./work-child.js";
7
+ const handles = new Map();
8
+ const loading = new Map();
9
+ /**
10
+ * An agent already entered in this process. Reading must not call `resume`:
11
+ * resume announces `session/created`, and disposing that handle announces
12
+ * `session/disposed`, which the native session list treats as removal.
13
+ * @param {import('@deepseek-ai/cordis').Context} ctx
14
+ * @param {string} sessionId
15
+ */
16
+ export function liveAgent(ctx, sessionId) {
17
+ try {
18
+ const live = ctx.agents?.get?.(sessionId);
19
+ if (live)
20
+ return live;
21
+ }
22
+ catch {
23
+ /* not entered */
24
+ }
25
+ return handles.get(sessionId)?.agent ?? null;
26
+ }
27
+ /**
28
+ * @param {import('@deepseek-ai/cordis').Context} ctx
29
+ * @param {string} sessionId
30
+ */
31
+ export async function loadAgent(ctx, sessionId) {
32
+ const live = ctx.agents.get(sessionId);
33
+ if (live)
34
+ return { agent: live, owned: false };
35
+ const owned = handles.get(sessionId);
36
+ if (owned)
37
+ return { agent: owned.agent, owned: true };
38
+ const pending = loading.get(sessionId);
39
+ if (pending)
40
+ return pending;
41
+ const job = ctx.agents.resume({
42
+ resumeSessionId: sessionId,
43
+ ...sessionId.startsWith('worker-') ? { setup: workerFileSetup(ctx, null) } : {},
44
+ }).then(handle => {
45
+ handles.set(sessionId, handle);
46
+ loading.delete(sessionId);
47
+ return { agent: handle.agent, owned: true };
48
+ }).catch(error => {
49
+ loading.delete(sessionId);
50
+ throw error;
51
+ });
52
+ loading.set(sessionId, job);
53
+ return job;
54
+ }
55
+ /**
56
+ * Follow-up into the native next-turn inbox, then flush. Flush failure does
57
+ * not by itself mean the append is durable. session/event is not the boundary.
58
+ * @param {import('@deepseek-ai/cordis').Context} ctx
59
+ * @param {string} sessionId
60
+ * @param {string} messageId
61
+ * @param {string} text
62
+ */
63
+ export async function followupDurable(ctx, sessionId, messageId, text) {
64
+ if (process.env.SESSION_FOUNDATIONS_CRASH_BEFORE_FLUSH === '1') {
65
+ const loaded = await loadAgent(ctx, sessionId);
66
+ loaded.agent.followup(userMessage(messageId, text));
67
+ process.exit(97);
68
+ }
69
+ const loaded = await loadAgent(ctx, sessionId);
70
+ const agent = loaded.agent;
71
+ try {
72
+ agent.followup(userMessage(messageId, text));
73
+ }
74
+ catch (error) {
75
+ const message = error instanceof Error ? error.message : String(error);
76
+ if (!message.includes('already pending'))
77
+ throw error;
78
+ }
79
+ const seq = spliceSeq(agent.session, messageId);
80
+ let flushed = false;
81
+ let flushError = '';
82
+ try {
83
+ flushed = await ctx.sessions.flush(agent.session) === true;
84
+ }
85
+ catch (error) {
86
+ flushError = error instanceof Error ? error.message : String(error);
87
+ }
88
+ return {
89
+ ok: flushed && seq != null,
90
+ ambiguous: !flushed,
91
+ seq,
92
+ error: flushError,
93
+ target: 'next-turn',
94
+ wakeup: true,
95
+ };
96
+ }
97
+ /**
98
+ * @param {{ snapshotEvents?: () => Array<{ type?: string, seq?: number, data?: { inserted?: Array<{ id?: string }> } }> }} session
99
+ * @param {string} messageId
100
+ */
101
+ export function logHasMessage(session, messageId) {
102
+ const events = session.snapshotEvents?.() ?? [];
103
+ return events.some(event => event.type === 'agent/inbox/spliced' && insertedIds(event).includes(messageId))
104
+ || events.some(event => event.type === 'user/message' && messageIdOf(event) === messageId);
105
+ }
106
+ /**
107
+ * Live snapshot when the agent is already entered. Otherwise a read-only
108
+ * stored log, which does not enter the session or take the write claim.
109
+ * @param {import('@deepseek-ai/cordis').Context} ctx
110
+ * @param {string} sessionId
111
+ * @returns {Promise<Array<{ type?: string, seq?: number, data?: { id?: string, message?: { id?: string }, inserted?: Array<{ id?: string }> } }>>}
112
+ */
113
+ export async function sessionEvents(ctx, sessionId) {
114
+ const agent = liveAgent(ctx, sessionId);
115
+ if (agent?.session?.snapshotEvents)
116
+ return agent.session.snapshotEvents();
117
+ const persistence = ctx.sessionPersistence;
118
+ if (!persistence?.open)
119
+ throw new Error('session log is not readable');
120
+ /** @type {{ read?: () => Promise<{ events?: unknown[] }>, close?: () => Promise<void> } | undefined} */
121
+ let handle;
122
+ try {
123
+ handle = await persistence.open(sessionId, 'read');
124
+ const page = typeof handle?.read === 'function' ? await handle.read() : { events: [] };
125
+ return Array.isArray(page?.events) ? page.events : [];
126
+ }
127
+ catch (error) {
128
+ if (missingSession(error))
129
+ return [];
130
+ throw error;
131
+ }
132
+ finally {
133
+ await handle?.close?.().catch(() => { });
134
+ }
135
+ }
136
+ /**
137
+ * @param {unknown} error
138
+ */
139
+ function missingSession(error) {
140
+ const name = error instanceof Error ? error.name : '';
141
+ return name === 'SessionPersistenceNotFoundError' || name === 'SessionNotFoundError';
142
+ }
143
+ /**
144
+ * @param {{ snapshotEvents?: () => Array<{ type?: string, seq?: number, data?: { inserted?: Array<{ id?: string }> } }> }} session
145
+ * @param {string} messageId
146
+ */
147
+ export function spliceSeq(session, messageId) {
148
+ const events = session.snapshotEvents?.() ?? [];
149
+ for (let index = events.length - 1; index >= 0; index -= 1) {
150
+ const event = events[index];
151
+ if (event.type === 'agent/inbox/spliced' && insertedIds(event).includes(messageId))
152
+ return event.seq ?? null;
153
+ }
154
+ return null;
155
+ }
156
+ /**
157
+ * Drop a still-pending native inbox item. Claimed messages are left alone.
158
+ * @param {import('@deepseek-ai/cordis').Context} ctx
159
+ * @param {string} sessionId
160
+ * @param {string} messageId
161
+ */
162
+ export async function removePending(ctx, sessionId, messageId) {
163
+ const live = ctx.agents.get(sessionId) ?? handles.get(sessionId)?.agent;
164
+ if (!live?.inbox?.remove)
165
+ return false;
166
+ return live.inbox.remove(messageId) === true;
167
+ }
168
+ /**
169
+ * @param {string} messageId
170
+ * @param {string} text
171
+ */
172
+ export function userMessage(messageId, text) {
173
+ return Object.freeze({
174
+ id: messageId,
175
+ role: 'user',
176
+ content: Object.freeze([Object.freeze({ type: 'text', text })]),
177
+ source: Object.freeze({ kind: 'user' }),
178
+ });
179
+ }
180
+ /**
181
+ * @param {{ data?: { inserted?: Array<{ id?: string }> } }} event
182
+ */
183
+ function insertedIds(event) {
184
+ const inserted = event.data?.inserted;
185
+ if (!Array.isArray(inserted))
186
+ return [];
187
+ return inserted.map(message => message?.id).filter(id => typeof id === 'string');
188
+ }
189
+ /**
190
+ * @param {{ data?: { id?: string, message?: { id?: string } } }} event
191
+ */
192
+ function messageIdOf(event) {
193
+ return event.data?.id ?? event.data?.message?.id ?? '';
194
+ }
package/dist/index.js ADDED
@@ -0,0 +1,411 @@
1
+ import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { openStore, pidAlive } from "./store.js";
4
+ import { createEngine } from "./engine.js";
5
+ import { renderPeers, renderSession, renderTickets } from "./context.js";
6
+ import { toolDefinitions } from "./tools.js";
7
+ import { createTriggers } from "./triggers.js";
8
+ import { followupDurable, liveAgent, logHasMessage, removePending, sessionEvents } from "./inbox.js";
9
+ import { toolError } from "./errors.js";
10
+ import { publishRuntime, publishWorkRuntime, runtimeFor } from "./runtime-registry.js";
11
+ import { childCreateOptions } from "./work-admit.js";
12
+ import { ensureWorkerFilePreset, WORKER_FILE_PRESET, workerFileSetup } from "./work-child.js";
13
+ import { createWorkRuntime } from "./work-worker.js";
14
+ import { workToolDefinitions } from "./work-tools.js";
15
+ export const name = 'session-foundations';
16
+ export const inject = ['systemPrompt', 'tools', 'sessions', 'agents', 'agentPresets'];
17
+ /**
18
+ * @param {import('@deepseek-ai/cordis').Context} ctx
19
+ * @param {{ dataDir?: string, contextWindow?: number, traceEvents?: boolean, timerTickMs?: number }} [config]
20
+ */
21
+ export function apply(ctx, config = {}) {
22
+ const dataDir = config.dataDir ?? (ctx.profileContext?.dir ? join(ctx.profileContext.dir, 'session-foundations') : '');
23
+ if (dataDir === '')
24
+ throw new Error('session-foundations: pass dataDir or launch with dsh profileContext');
25
+ const store = openStore(dataDir);
26
+ const engine = createEngine(store);
27
+ const recovery = engine.recover();
28
+ const ownerFile = join(dataDir, 'owner.json');
29
+ writeFileSync(ownerFile, JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }), { mode: 0o600 });
30
+ ctx.effect(() => () => {
31
+ try {
32
+ const owner = JSON.parse(readFileSync(ownerFile, 'utf8'));
33
+ if (owner.pid === process.pid)
34
+ rmSync(ownerFile, { force: true });
35
+ }
36
+ catch { /* already gone */ }
37
+ try {
38
+ store.close();
39
+ }
40
+ catch { /* closed */ }
41
+ });
42
+ /** @type {ReturnType<typeof createTriggers> | null} */
43
+ let triggers = null;
44
+ const trace = config.traceEvents === true ? join(dataDir, 'observed-events.jsonl') : '';
45
+ if (trace)
46
+ mkdirSync(dataDir, { recursive: true });
47
+ const logEvent = (sessionId, type, extra) => {
48
+ if (!trace)
49
+ return;
50
+ appendFileSync(trace, `${JSON.stringify({ at: new Date().toISOString(), sessionId, type, ...extra })}\n`);
51
+ };
52
+ const window = config.contextWindow;
53
+ const rendered = new Map();
54
+ const render = (sessionId) => {
55
+ const view = renderSession(engine, sessionId, window);
56
+ rendered.set(sessionId, view);
57
+ return view;
58
+ };
59
+ const textFor = (sessionId, name) => {
60
+ if (!sessionId || !engine.isBot(sessionId))
61
+ return '';
62
+ const view = rendered.get(sessionId) ?? render(sessionId);
63
+ return view.texts[name] ?? '';
64
+ };
65
+ const sessionFrom = (assemble) => assemble?.agent?.id;
66
+ const section = (name, order, pick) => {
67
+ ctx.systemPrompt.section({
68
+ name,
69
+ order,
70
+ interpolate: false,
71
+ text: (assemble) => pick(sessionFrom(assemble)),
72
+ });
73
+ };
74
+ const context = (name, order, required, pick) => {
75
+ ctx.systemPrompt.context({
76
+ name,
77
+ order,
78
+ required,
79
+ interpolate: false,
80
+ text: (assemble) => {
81
+ const sessionId = sessionFrom(assemble);
82
+ if (!sessionId || !engine.isBot(sessionId))
83
+ return '';
84
+ if (!rendered.has(sessionId))
85
+ render(sessionId);
86
+ return pick(sessionId);
87
+ },
88
+ });
89
+ };
90
+ section('foundations:chat', 39, id => (id ? textFor(id, 'foundations:chat') : ''));
91
+ section('foundations:soul', 40, id => (id ? textFor(id, 'foundations:soul') : ''));
92
+ section('foundations:rules', 41, id => (id ? textFor(id, 'foundations:rules') : ''));
93
+ section('foundations:peers', 42, id => (id && engine.isBot(id) ? renderPeers(engine.listBots(), id) : ''));
94
+ context('foundations:revocation', 900, true, id => textFor(id, 'foundations:revocation'));
95
+ context('foundations:user', 1000, false, id => textFor(id, 'foundations:user'));
96
+ context('foundations:facts', 1010, false, id => textFor(id, 'foundations:facts'));
97
+ context('foundations:state', 1020, false, id => textFor(id, 'foundations:state'));
98
+ context('foundations:skills', 1030, false, id => textFor(id, 'foundations:skills'));
99
+ /** @type {ReturnType<typeof createWorkRuntime> | null} */
100
+ let work = null;
101
+ section('foundations:tickets', 43, id => (id && work && engine.isBot(id) ? renderTickets(work.summaries(id)) : ''));
102
+ const revisionOf = (sessionId) => rendered.get(sessionId)?.viewRevision ?? engine.currentView(sessionId)?.revision ?? 0;
103
+ for (const definition of toolDefinitions(engine, () => 0)) {
104
+ const original = definition.execute;
105
+ definition.execute = async (args, exec) => {
106
+ const sessionId = exec?.agent?.id;
107
+ if (typeof sessionId !== 'string' || sessionId === '')
108
+ return toolError('UNAVAILABLE', 'The host did not bind a sessionId.');
109
+ if (!engine.isBot(sessionId))
110
+ return toolError('FORBIDDEN', 'This session is not a bot, so persona and memory do not apply here.');
111
+ const result = await original(args, exec);
112
+ if (result && result.ok === true && (result.viewRevisionFrozen === 0 || result.viewRevisionFrozen == null)) {
113
+ result.viewRevisionFrozen = typeof sessionId === 'string' ? revisionOf(sessionId) : 0;
114
+ }
115
+ return result;
116
+ };
117
+ ctx.tools.register(definition);
118
+ }
119
+ ctx.on('session/event', (session, event) => {
120
+ const sessionId = session?.id;
121
+ if (typeof sessionId !== 'string' || event == null || typeof event.type !== 'string')
122
+ return;
123
+ const bot = engine.isBot(sessionId);
124
+ const worker = work?.isWorkerSession(sessionId) === true;
125
+ if (!bot && !worker)
126
+ return;
127
+ if (work)
128
+ work.observeSession(sessionId, event);
129
+ if (!bot)
130
+ return;
131
+ engine.ensureSession(sessionId, {
132
+ parentSessionId: session.header?.parentSession ?? null,
133
+ seeded: session.header?.isSeeded === true,
134
+ });
135
+ if (typeof event.seq === 'number')
136
+ engine.noteWatermark(sessionId, String(event.seq));
137
+ logEvent(sessionId, event.type, { seq: event.seq ?? null });
138
+ if (event.type === 'turn/start') {
139
+ rendered.delete(sessionId);
140
+ engine.openViews.delete(sessionId);
141
+ }
142
+ if (event.type === 'compaction/end' || event.type === 'compaction/start' || event.type === 'compaction/summary') {
143
+ if (event.type === 'compaction/end') {
144
+ rendered.delete(sessionId);
145
+ engine.bumpEpoch(sessionId, 'needs_reinject');
146
+ }
147
+ }
148
+ if (event.type === 'user/message') {
149
+ const text = messageText(event);
150
+ const messageId = event.data?.id ?? event.data?.message?.id;
151
+ if (triggers && typeof messageId === 'string')
152
+ triggers.observeUserMessage(sessionId, messageId, event.data?.turn ?? null);
153
+ const source = event.data?.message?.source ?? event.data?.source;
154
+ if (source?.kind === 'runtime-context' && typeof text === 'string' && text.includes('[foundations:')) {
155
+ engine.noteSurface(sessionId, typeof event.seq === 'number' ? event.seq : null);
156
+ }
157
+ const op = event.surfaceOp;
158
+ if (op && typeof op === 'object' && op.op === 'replace' && Array.isArray(event.sourceEventSeqs)) {
159
+ engine.noteRemoval(sessionId, event.sourceEventSeqs.filter(seq => typeof seq === 'number'));
160
+ }
161
+ }
162
+ if (triggers && event.type === 'turn/end') {
163
+ const reason = event.data?.reason;
164
+ triggers.observeTurnEnd(sessionId, event.data?.turn ?? null, reason && typeof reason === 'object' ? reason.kind ?? '' : '');
165
+ }
166
+ });
167
+ ctx.on('agent/created', (payload) => {
168
+ const agent = payload?.agent;
169
+ if (!agent?.id || !engine.isBot(agent.id))
170
+ return;
171
+ let session = null;
172
+ try {
173
+ session = ctx.sessions.get(agent.id);
174
+ }
175
+ catch {
176
+ session = null;
177
+ }
178
+ engine.ensureSession(agent.id, {
179
+ parentSessionId: session?.header?.parentSession ?? null,
180
+ seeded: session?.header?.isSeeded === true,
181
+ });
182
+ });
183
+ triggers = ctx.agents ? startTriggers(ctx, store, engine) : null;
184
+ work = ctx.agents ? startWork(ctx, store, engine, config) : null;
185
+ if (triggers) {
186
+ for (const definition of triggerTools(triggers, engine))
187
+ ctx.tools.register(definition);
188
+ }
189
+ if (work) {
190
+ for (const definition of workToolDefinitions(work, engine))
191
+ ctx.tools.register(definition);
192
+ }
193
+ if (triggers || work) {
194
+ const timer = setInterval(() => {
195
+ triggers?.tick().catch(() => { });
196
+ work?.tick().catch(() => { });
197
+ }, config.timerTickMs ?? 1000);
198
+ timer.unref?.();
199
+ ctx.effect(() => () => clearInterval(timer));
200
+ triggers?.tick().catch(() => { });
201
+ work?.tick().catch(() => { });
202
+ }
203
+ ctx.logger?.info?.('session-foundations: ready dir=%s bindings=%s promoted=%s', dataDir, recovery.bindings, recovery.promoted.length);
204
+ }
205
+ /**
206
+ * @param {import('@deepseek-ai/cordis').Context} ctx
207
+ * @param {import('./src/store.js').Store} store
208
+ * @param {import('./src/engine.js').Engine} engine
209
+ */
210
+ function startTriggers(ctx, store, engine) {
211
+ const triggers = createTriggers(store, {
212
+ secretDir: store.root,
213
+ push: (sessionId, messageId, text) => followupDurable(ctx, sessionId, messageId, text),
214
+ logHas: (sessionId, messageId) => logHasDurable(ctx, sessionId, messageId),
215
+ removePending: (sessionId, messageId) => removePending(ctx, sessionId, messageId),
216
+ });
217
+ publishRuntime(store.root, triggers);
218
+ ctx.effect(() => () => {
219
+ if (runtimeFor(store.root) === triggers)
220
+ publishRuntime(store.root, null);
221
+ });
222
+ ctx.on('agent/inbox/claimed', (payload) => {
223
+ const sessionId = payload?.agent?.id;
224
+ const messageId = payload?.message?.id;
225
+ if (typeof sessionId === 'string' && typeof messageId === 'string')
226
+ triggers.observeClaimed(sessionId, messageId, payload.turn ?? null);
227
+ });
228
+ ctx.on('agent/inbox/discarded', (payload) => {
229
+ const sessionId = payload?.agent?.id;
230
+ const messageId = payload?.message?.id;
231
+ if (typeof sessionId === 'string' && typeof messageId === 'string')
232
+ triggers.observeDiscarded(sessionId, messageId);
233
+ });
234
+ return triggers;
235
+ }
236
+ /**
237
+ * Bot dual-loop. Ordinary sessions never enter this runtime's tools.
238
+ * Child agents are created without parentAgent so the main handle does not dispose them.
239
+ * @param {import('@deepseek-ai/cordis').Context} ctx
240
+ * @param {import('./src/store.js').Store} store
241
+ * @param {import('./src/engine.js').Engine} engine
242
+ * @param {{ work?: Partial<import('./src/work-admit.js').DEFAULT_WORK_BUDGET> }} config
243
+ */
244
+ function startWork(ctx, store, engine, config) {
245
+ /** @type {Map<string, { dispose?: () => Promise<void> }>} */
246
+ const workerHandles = new Map();
247
+ const filePreset = ensureWorkerFilePreset(ctx);
248
+ const work = createWorkRuntime(store, engine, {
249
+ budget: config.work ?? {},
250
+ createChild: async (spec) => {
251
+ let cwd = '';
252
+ let model = null;
253
+ try {
254
+ const owner = ctx.agents.get(spec.ownerSessionId);
255
+ cwd = owner?.session?.header?.cwd
256
+ ?? ctx.sessions.get(spec.ownerSessionId)?.header?.cwd
257
+ ?? '';
258
+ model = owner?.model?.current?.() ?? null;
259
+ }
260
+ catch {
261
+ cwd = '';
262
+ model = null;
263
+ }
264
+ if (!model?.provider || !model?.model) {
265
+ try {
266
+ model = ctx.agentDefaultModel?.currentSelection?.() ?? null;
267
+ }
268
+ catch {
269
+ model = null;
270
+ }
271
+ }
272
+ const cap = Number(process.env.WORK_EVAL_MAX_OUTPUT_TOKENS);
273
+ const options = childCreateOptions(spec.sessionId, cwd, model, cap);
274
+ const presetId = await filePreset;
275
+ if (presetId) {
276
+ options.meta = { ...(options.meta ?? {}), agentPreset: WORKER_FILE_PRESET };
277
+ options.setup = workerFileSetup(ctx, WORKER_FILE_PRESET);
278
+ }
279
+ const handle = await ctx.agents.create(options);
280
+ workerHandles.set(spec.sessionId, handle);
281
+ return spec.sessionId;
282
+ },
283
+ push: (sessionId, messageId, text) => followupDurable(ctx, sessionId, messageId, text),
284
+ logHas: (sessionId, messageId) => logHasDurable(ctx, sessionId, messageId),
285
+ remove: (sessionId, messageId) => removePending(ctx, sessionId, messageId),
286
+ pendingIds: async (sessionId) => {
287
+ const agent = liveAgent(ctx, sessionId);
288
+ if (!agent)
289
+ return [];
290
+ const list = agent.inbox?.nextTurn;
291
+ if (!Array.isArray(list))
292
+ return null;
293
+ return list.map(message => message?.id).filter(id => typeof id === 'string');
294
+ },
295
+ cancel: async (sessionId, options) => {
296
+ const agent = liveAgent(ctx, sessionId);
297
+ if (!agent)
298
+ return;
299
+ agent.cancel({ kind: 'user' }, { keepInbox: options.keepInbox === true });
300
+ },
301
+ snapshot: async (sessionId) => {
302
+ try {
303
+ return await sessionEvents(ctx, sessionId);
304
+ }
305
+ catch {
306
+ return [];
307
+ }
308
+ },
309
+ });
310
+ publishWorkRuntime(store.root, work);
311
+ ctx.effect(() => () => {
312
+ publishWorkRuntime(store.root, null);
313
+ workerHandles.clear();
314
+ });
315
+ ctx.on('agent/inbox/claimed', (payload) => {
316
+ const sessionId = payload?.agent?.id;
317
+ const messageId = payload?.message?.id;
318
+ if (typeof sessionId === 'string' && typeof messageId === 'string')
319
+ work.observeClaimed(sessionId, messageId, payload.turn ?? null);
320
+ });
321
+ return work;
322
+ }
323
+ /**
324
+ * @param {ReturnType<typeof createTriggers>} triggers
325
+ * @param {import('./src/engine.js').Engine} engine
326
+ */
327
+ function triggerTools(triggers, engine) {
328
+ const isBot = (sessionId) => engine.isBot(sessionId);
329
+ return [
330
+ triggerTool('foundations_send', 'Send an explicit message to another bot. Bots may message each other by default. Use the sessionId at the end of the other-bot roster in the system prompt, or the id in parentheses after @Name (sessionId) in a user message, as targetSessionId. This does not share persona, memory, or skills. An explicit refusal returns FORBIDDEN.', {
331
+ type: 'object',
332
+ properties: {
333
+ targetSessionId: { type: 'string' },
334
+ text: { type: 'string' },
335
+ idempotencyKey: { type: 'string' },
336
+ correlationId: { type: 'string' },
337
+ sessionId: { type: 'string', description: 'Ignored. The host binds the sender.' },
338
+ hop: { type: 'integer', description: 'Ignored. The host computes the hop count.' },
339
+ },
340
+ required: ['targetSessionId', 'text', 'idempotencyKey'],
341
+ }, (args, hostId) => triggers.send(hostId, args), isBot),
342
+ triggerTool('foundations_reply', 'Reply to a correlated message sent to this session. The target comes from the ledger, not from another id in the arguments.', {
343
+ type: 'object',
344
+ properties: {
345
+ correlationId: { type: 'string' },
346
+ text: { type: 'string' },
347
+ idempotencyKey: { type: 'string' },
348
+ sessionId: { type: 'string', description: 'Ignored. The host binds the sender.' },
349
+ targetSessionId: { type: 'string', description: 'Ignored.' },
350
+ },
351
+ required: ['correlationId', 'text', 'idempotencyKey'],
352
+ }, (args, hostId) => triggers.reply(hostId, args), isBot),
353
+ ];
354
+ }
355
+ /**
356
+ * @param {string} name
357
+ * @param {string} description
358
+ * @param {Record<string, unknown>} parameters
359
+ * @param {(args: Record<string, unknown>, hostId: string) => Promise<unknown>} run
360
+ * @param {(sessionId: string) => boolean} isBot
361
+ */
362
+ function triggerTool(name, description, parameters, run, isBot) {
363
+ return {
364
+ name,
365
+ description,
366
+ parameters,
367
+ output: {
368
+ schema: {
369
+ type: 'object',
370
+ properties: {
371
+ ok: { type: 'boolean' },
372
+ code: { type: 'string' },
373
+ message: { type: 'string' },
374
+ status: { type: 'string' },
375
+ deliveryId: { type: 'string' },
376
+ },
377
+ required: ['ok'],
378
+ },
379
+ render(_args, value) {
380
+ return [{ type: 'text', text: JSON.stringify(value) }];
381
+ },
382
+ },
383
+ async execute(args, exec) {
384
+ const hostId = exec?.agent?.id;
385
+ if (typeof hostId !== 'string' || hostId === '')
386
+ return toolError('UNAVAILABLE', 'The host did not bind a sessionId.');
387
+ if (!isBot(hostId))
388
+ return toolError('FORBIDDEN', 'This session is not a bot, so cross-session messages do not apply here.');
389
+ return run(args ?? {}, hostId);
390
+ },
391
+ };
392
+ }
393
+ /**
394
+ * @param {import('@deepseek-ai/cordis').Context} ctx
395
+ * @param {string} sessionId
396
+ * @param {string} messageId
397
+ */
398
+ async function logHasDurable(ctx, sessionId, messageId) {
399
+ const events = await sessionEvents(ctx, sessionId);
400
+ return logHasMessage({ snapshotEvents: () => events }, messageId);
401
+ }
402
+ /**
403
+ * @param {{ data?: { message?: { content?: Array<{ type?: string, text?: string }> }, content?: Array<{ type?: string, text?: string }> } }} event
404
+ */
405
+ function messageText(event) {
406
+ const content = event.data?.message?.content ?? event.data?.content;
407
+ if (!Array.isArray(content))
408
+ return '';
409
+ return content.filter(block => block?.type === 'text').map(block => block.text ?? '').join('\n');
410
+ }
411
+ export { pidAlive };