@thready-web/dsh-bot-plugin 0.1.0-beta.0 → 0.1.0-beta.10
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 +109 -1
- package/client.js +646 -621
- package/dist/approvals.js +160 -0
- package/dist/authorization.js +225 -0
- package/dist/cli.js +32 -12
- package/dist/context.js +59 -17
- package/dist/cron.js +1 -1
- package/dist/cua-access.js +79 -0
- package/dist/desk.js +314 -37
- package/dist/engine.js +178 -84
- package/dist/fs-safe.js +1 -1
- package/dist/host.js +1 -0
- package/dist/http-plugin.js +14 -4
- package/dist/http.js +383 -85
- package/dist/inbox.js +51 -40
- package/dist/index.js +190 -47
- package/dist/live-diff.js +3 -1
- package/dist/live-snapshot.js +2 -13
- package/dist/log/canonical.js +37 -0
- package/dist/log/plan.js +62 -0
- package/dist/log/routes.js +144 -0
- package/dist/log/snapshot-service.js +76 -0
- package/dist/log/source.js +173 -0
- package/dist/memory-catalog.js +798 -0
- package/dist/permissions.js +86 -0
- package/dist/provision.js +2 -0
- package/dist/questions.js +407 -0
- package/dist/runtime-registry.js +4 -4
- package/dist/session-files.js +2 -2
- package/dist/session-previews.js +5 -1
- package/dist/store.js +20 -5
- package/dist/tools.js +150 -32
- package/dist/triggers.js +83 -39
- package/dist/work-admit.js +222 -25
- package/dist/work-child.js +17 -9
- package/dist/work-http.js +33 -2
- package/dist/work-ledger.js +256 -16
- package/dist/work-mock-host.js +9 -6
- package/dist/work-mock.js +29 -19
- package/dist/work-tickets.js +423 -96
- package/dist/work-tools.js +43 -6
- package/dist/work-worker.js +1028 -207
- package/dist/workspace-files.js +319 -0
- package/dist/workspace-image.js +91 -0
- package/fixtures/mock-llm.mjs +17 -2
- package/package.json +15 -5
- package/public/assets/SourceEditor-BEQaScgR.js +669 -0
- package/public/assets/SourceEditor-CJwK846Z.css +1 -0
- package/public/assets/abap-CRCWOmpq.js +1 -0
- package/public/assets/apex-DnsZk_dE.js +1 -0
- package/public/assets/azcli-1IWB1ccx.js +1 -0
- package/public/assets/bat-DPkNLes8.js +1 -0
- package/public/assets/bicep-Corcdgou.js +2 -0
- package/public/assets/cameligo-CGrWLZr3.js +1 -0
- package/public/assets/clojure-D9WOWImG.js +1 -0
- package/public/assets/codicon-DCmgc-ay.ttf +0 -0
- package/public/assets/coffee-B7EJu28W.js +1 -0
- package/public/assets/cpp-SEyurbux.js +1 -0
- package/public/assets/csharp-BoL64M5l.js +1 -0
- package/public/assets/csp-C46ZqvIl.js +1 -0
- package/public/assets/css-DQU6DXDx.js +3 -0
- package/public/assets/css.worker-DYpkewsP.js +79 -0
- package/public/assets/cssMode-gpcjCFFS.js +4 -0
- package/public/assets/cypher-D84EuPTj.js +1 -0
- package/public/assets/dart-D8lhlL1r.js +1 -0
- package/public/assets/dockerfile-DLk6rpji.js +1 -0
- package/public/assets/ecl-BO6FnfXk.js +1 -0
- package/public/assets/editor.worker-B4pQIWZD.js +12 -0
- package/public/assets/elixir-BRjLKONM.js +1 -0
- package/public/assets/flow9-Cac8vKd7.js +1 -0
- package/public/assets/freemarker2-C1qemGIt.js +3 -0
- package/public/assets/fsharp-fd1GTHhf.js +1 -0
- package/public/assets/go-O9LJTZXk.js +1 -0
- package/public/assets/graphql-LQdxqEYJ.js +1 -0
- package/public/assets/handlebars-sZqIfAlP.js +1 -0
- package/public/assets/hcl-DxDQ3s82.js +1 -0
- package/public/assets/html-Bn1WXB8L.js +1 -0
- package/public/assets/html.worker-tnXziJOq.js +456 -0
- package/public/assets/htmlMode-CvQyXnaW.js +4 -0
- package/public/assets/index-DRNkUrer.css +1 -0
- package/public/assets/index-DhL5Kdlz.js +63 -0
- package/public/assets/ini-BvajGCUy.js +1 -0
- package/public/assets/java-SYsfObOQ.js +1 -0
- package/public/assets/javascript-Ox4Jg12j.js +1 -0
- package/public/assets/json.worker-aFakAbRR.js +44 -0
- package/public/assets/jsonMode-DMR7R2dQ.js +10 -0
- package/public/assets/julia-DQXNmw_w.js +1 -0
- package/public/assets/kotlin-qQ0MG-9I.js +1 -0
- package/public/assets/less-GGFNNJHn.js +2 -0
- package/public/assets/lexon-Canl7DCW.js +1 -0
- package/public/assets/liquid-B6HxtpBd.js +1 -0
- package/public/assets/lua-D28Ae8-K.js +1 -0
- package/public/assets/m3-DPitgjJI.js +1 -0
- package/public/assets/markdown-B811l8j2.js +1 -0
- package/public/assets/mdx--jDhmrXq.js +1 -0
- package/public/assets/mips-CdjsipkG.js +1 -0
- package/public/assets/msdax-CYqgjx_P.js +1 -0
- package/public/assets/mysql-BHd6q0vd.js +1 -0
- package/public/assets/objective-c-B1aVtJYH.js +1 -0
- package/public/assets/pascal-BhNW15KB.js +1 -0
- package/public/assets/pascaligo-5jv8CcQD.js +1 -0
- package/public/assets/perl-DlYyT36c.js +1 -0
- package/public/assets/pgsql-Dy0bjov7.js +1 -0
- package/public/assets/php-120yhfDK.js +1 -0
- package/public/assets/pla-CjnFlu4u.js +1 -0
- package/public/assets/postiats-CQpG440k.js +1 -0
- package/public/assets/powerquery-DdJtto1Z.js +1 -0
- package/public/assets/powershell-Bu_VLpJB.js +1 -0
- package/public/assets/protobuf-IBS6jZEB.js +2 -0
- package/public/assets/pug-kFxLfcjb.js +1 -0
- package/public/assets/python-YjG50skX.js +1 -0
- package/public/assets/qsharp-q7JyzKFN.js +1 -0
- package/public/assets/r-BIFz-_sK.js +1 -0
- package/public/assets/razor-CEcFE3UK.js +1 -0
- package/public/assets/redis-CHOsPHWR.js +1 -0
- package/public/assets/redshift-CBifECDb.js +1 -0
- package/public/assets/restructuredtext-CghPJEOS.js +1 -0
- package/public/assets/ruby-CYWGW-b1.js +1 -0
- package/public/assets/rust-DMDD0SHb.js +1 -0
- package/public/assets/sb-BYAiYHFx.js +1 -0
- package/public/assets/scala-Bqvq8jcR.js +1 -0
- package/public/assets/scheme-Dhb-2j9p.js +1 -0
- package/public/assets/scss-CTwUZ5N7.js +3 -0
- package/public/assets/shell-CsDZo4DB.js +1 -0
- package/public/assets/solidity-CME5AdoB.js +1 -0
- package/public/assets/sophia-RYC1BQQz.js +1 -0
- package/public/assets/sparql-KEyrF7De.js +1 -0
- package/public/assets/sql-BdTr02Mf.js +1 -0
- package/public/assets/st-C7iG7M4S.js +1 -0
- package/public/assets/swift-D7IUmUK8.js +1 -0
- package/public/assets/systemverilog-DgMryOEJ.js +1 -0
- package/public/assets/tcl-PloMZuKG.js +1 -0
- package/public/assets/ts.worker-Bij5J2kb.js +51316 -0
- package/public/assets/tsMode-g4kTQl09.js +11 -0
- package/public/assets/twig-BfRIq3la.js +1 -0
- package/public/assets/typescript-CnHeFmPW.js +1 -0
- package/public/assets/typespec-CzxlYoT_.js +1 -0
- package/public/assets/vb-BwAE3J76.js +1 -0
- package/public/assets/wgsl-B_1kOXbF.js +298 -0
- package/public/assets/xml-BFXMY9nb.js +1 -0
- package/public/assets/yaml-DNm87nSf.js +1 -0
- package/public/index.html +2 -2
- package/public/assets/index-Be82iGwe.css +0 -1
- package/public/assets/index-ByU9a3Lh.js +0 -61
package/dist/inbox.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
* agent.followup(), which appends agent/inbox/spliced and wakes a later turn.
|
|
4
4
|
* This module does not keep a second execution queue.
|
|
5
5
|
*/
|
|
6
|
+
import { createLogSource, logHasMessage as eventsHaveMessage, spliceSeq as seqOfSplice, } from "./log/source.js";
|
|
6
7
|
import { workerFileSetup } from "./work-child.js";
|
|
7
8
|
const handles = new Map();
|
|
8
9
|
const loading = new Map();
|
|
@@ -24,6 +25,28 @@ export function liveAgent(ctx, sessionId) {
|
|
|
24
25
|
}
|
|
25
26
|
return handles.get(sessionId)?.agent ?? null;
|
|
26
27
|
}
|
|
28
|
+
/**
|
|
29
|
+
* Close a session this module resumed, so its writer drains before a hard delete.
|
|
30
|
+
* A session owned by another fiber is left alone.
|
|
31
|
+
* @param {string} sessionId
|
|
32
|
+
*/
|
|
33
|
+
export async function releaseLoadedAgent(sessionId) {
|
|
34
|
+
const pending = loading.get(sessionId);
|
|
35
|
+
if (pending) {
|
|
36
|
+
try {
|
|
37
|
+
await pending;
|
|
38
|
+
}
|
|
39
|
+
catch {
|
|
40
|
+
return;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
const owned = handles.get(sessionId);
|
|
44
|
+
if (!owned || typeof owned.dispose !== 'function')
|
|
45
|
+
return;
|
|
46
|
+
await owned.dispose();
|
|
47
|
+
if (handles.get(sessionId) === owned)
|
|
48
|
+
handles.delete(sessionId);
|
|
49
|
+
}
|
|
27
50
|
/**
|
|
28
51
|
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
29
52
|
* @param {string} sessionId
|
|
@@ -38,14 +61,17 @@ export async function loadAgent(ctx, sessionId) {
|
|
|
38
61
|
const pending = loading.get(sessionId);
|
|
39
62
|
if (pending)
|
|
40
63
|
return pending;
|
|
41
|
-
const job = ctx.agents
|
|
64
|
+
const job = ctx.agents
|
|
65
|
+
.resume({
|
|
42
66
|
resumeSessionId: sessionId,
|
|
43
|
-
...sessionId.startsWith('worker-') ? { setup: workerFileSetup(ctx, null) } : {},
|
|
44
|
-
})
|
|
67
|
+
...(sessionId.startsWith('worker-') ? { setup: workerFileSetup(ctx, null) } : {}),
|
|
68
|
+
})
|
|
69
|
+
.then((handle) => {
|
|
45
70
|
handles.set(sessionId, handle);
|
|
46
71
|
loading.delete(sessionId);
|
|
47
72
|
return { agent: handle.agent, owned: true };
|
|
48
|
-
})
|
|
73
|
+
})
|
|
74
|
+
.catch((error) => {
|
|
49
75
|
loading.delete(sessionId);
|
|
50
76
|
throw error;
|
|
51
77
|
});
|
|
@@ -76,11 +102,17 @@ export async function followupDurable(ctx, sessionId, messageId, text) {
|
|
|
76
102
|
if (!message.includes('already pending'))
|
|
77
103
|
throw error;
|
|
78
104
|
}
|
|
79
|
-
|
|
105
|
+
let seq = null;
|
|
106
|
+
try {
|
|
107
|
+
seq = seqOfSplice((await createLogSource(ctx).read(sessionId, -1)).events, messageId);
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
seq = spliceSeq(agent.session, messageId);
|
|
111
|
+
}
|
|
80
112
|
let flushed = false;
|
|
81
113
|
let flushError = '';
|
|
82
114
|
try {
|
|
83
|
-
flushed = await ctx.sessions.flush(agent.session) === true;
|
|
115
|
+
flushed = (await ctx.sessions.flush(agent.session)) === true;
|
|
84
116
|
}
|
|
85
117
|
catch (error) {
|
|
86
118
|
flushError = error instanceof Error ? error.message : String(error);
|
|
@@ -99,9 +131,12 @@ export async function followupDurable(ctx, sessionId, messageId, text) {
|
|
|
99
131
|
* @param {string} messageId
|
|
100
132
|
*/
|
|
101
133
|
export function logHasMessage(session, messageId) {
|
|
102
|
-
const events =
|
|
103
|
-
|
|
104
|
-
|
|
134
|
+
const events = Array.isArray(session)
|
|
135
|
+
? session
|
|
136
|
+
: 'snapshotEvents' in session
|
|
137
|
+
? (session.snapshotEvents?.() ?? [])
|
|
138
|
+
: [];
|
|
139
|
+
return eventsHaveMessage(events, messageId);
|
|
105
140
|
}
|
|
106
141
|
/**
|
|
107
142
|
* Live snapshot when the agent is already entered. Otherwise a read-only
|
|
@@ -111,34 +146,8 @@ export function logHasMessage(session, messageId) {
|
|
|
111
146
|
* @returns {Promise<Array<{ type?: string, seq?: number, data?: { id?: string, message?: { id?: string }, inserted?: Array<{ id?: string }> } }>>}
|
|
112
147
|
*/
|
|
113
148
|
export async function sessionEvents(ctx, sessionId) {
|
|
114
|
-
const
|
|
115
|
-
|
|
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';
|
|
149
|
+
const { events } = await createLogSource(ctx).read(sessionId, -1);
|
|
150
|
+
return events;
|
|
142
151
|
}
|
|
143
152
|
/**
|
|
144
153
|
* @param {{ snapshotEvents?: () => Array<{ type?: string, seq?: number, data?: { inserted?: Array<{ id?: string }> } }> }} session
|
|
@@ -181,14 +190,16 @@ export function userMessage(messageId, text) {
|
|
|
181
190
|
* @param {{ data?: { inserted?: Array<{ id?: string }> } }} event
|
|
182
191
|
*/
|
|
183
192
|
function insertedIds(event) {
|
|
184
|
-
const
|
|
193
|
+
const data = event.data && typeof event.data === 'object' ? event.data : null;
|
|
194
|
+
const inserted = data?.inserted;
|
|
185
195
|
if (!Array.isArray(inserted))
|
|
186
196
|
return [];
|
|
187
|
-
return inserted.map(message => message?.id).filter(id => typeof id === 'string');
|
|
197
|
+
return inserted.map(message => message?.id).filter((id) => typeof id === 'string');
|
|
188
198
|
}
|
|
189
199
|
/**
|
|
190
200
|
* @param {{ data?: { id?: string, message?: { id?: string } } }} event
|
|
191
201
|
*/
|
|
192
202
|
function messageIdOf(event) {
|
|
193
|
-
|
|
203
|
+
const data = event.data && typeof event.data === 'object' ? event.data : null;
|
|
204
|
+
return data?.id ?? data?.message?.id ?? '';
|
|
194
205
|
}
|
package/dist/index.js
CHANGED
|
@@ -2,20 +2,34 @@ import { appendFileSync, mkdirSync, readFileSync, rmSync, writeFileSync } from '
|
|
|
2
2
|
import { join } from 'node:path';
|
|
3
3
|
import { openStore, pidAlive } from "./store.js";
|
|
4
4
|
import { createEngine } from "./engine.js";
|
|
5
|
-
import { renderPeers, renderSession, renderTickets } from "./context.js";
|
|
6
|
-
import { toolDefinitions } from "./tools.js";
|
|
5
|
+
import { renderPeers, renderSession, renderTickets, WORKER_MEMORY } from "./context.js";
|
|
6
|
+
import { callMemoryTool, memorySessionFor, toolDefinitions } from "./tools.js";
|
|
7
7
|
import { createTriggers } from "./triggers.js";
|
|
8
|
-
import { followupDurable, liveAgent, logHasMessage, removePending
|
|
8
|
+
import { followupDurable, liveAgent, logHasMessage, removePending } from "./inbox.js";
|
|
9
|
+
import { createLogSource } from "./log/source.js";
|
|
9
10
|
import { toolError } from "./errors.js";
|
|
11
|
+
import { createQuestionAnswerer, publishQuestionAnswerer, questionAnswererFor } from "./questions.js";
|
|
12
|
+
import { createApprovalAnswerer, publishApprovalAnswerer, approvalAnswererFor } from "./approvals.js";
|
|
13
|
+
import { createAuthorizationController, publishAuthorization, authorizationFor } from "./authorization.js";
|
|
10
14
|
import { publishRuntime, publishWorkRuntime, runtimeFor } from "./runtime-registry.js";
|
|
11
|
-
import { childCreateOptions } from "./work-admit.js";
|
|
15
|
+
import { childCreateOptions, effectiveWorkLimits, pinMainReasoning, resolveWorkBudget, workerModelSelection, WORK_BUDGET_ENV, } from "./work-admit.js";
|
|
12
16
|
import { ensureWorkerFilePreset, WORKER_FILE_PRESET, workerFileSetup } from "./work-child.js";
|
|
13
|
-
import { createWorkRuntime } from "./work-worker.js";
|
|
17
|
+
import { BUDGET_NOTICE_PREFIX, createWorkRuntime } from "./work-worker.js";
|
|
14
18
|
import { workToolDefinitions } from "./work-tools.js";
|
|
15
19
|
export const name = 'session-foundations';
|
|
16
|
-
|
|
20
|
+
// Cordis throws if a plugin reads a service it did not inject. Crash recovery reads the session log through this one.
|
|
21
|
+
export const inject = [
|
|
22
|
+
'systemPrompt',
|
|
23
|
+
'tools',
|
|
24
|
+
'sessions',
|
|
25
|
+
'agents',
|
|
26
|
+
'agentPresets',
|
|
27
|
+
'sessionPersistence',
|
|
28
|
+
'sessionQuery',
|
|
29
|
+
'userQuestions',
|
|
30
|
+
];
|
|
17
31
|
/**
|
|
18
|
-
* @param {import('
|
|
32
|
+
* @param {import('./host.ts').PluginHost} ctx
|
|
19
33
|
* @param {{ dataDir?: string, contextWindow?: number, traceEvents?: boolean, timerTickMs?: number }} [config]
|
|
20
34
|
*/
|
|
21
35
|
export function apply(ctx, config = {}) {
|
|
@@ -33,11 +47,15 @@ export function apply(ctx, config = {}) {
|
|
|
33
47
|
if (owner.pid === process.pid)
|
|
34
48
|
rmSync(ownerFile, { force: true });
|
|
35
49
|
}
|
|
36
|
-
catch {
|
|
50
|
+
catch {
|
|
51
|
+
/* already gone */
|
|
52
|
+
}
|
|
37
53
|
try {
|
|
38
54
|
store.close();
|
|
39
55
|
}
|
|
40
|
-
catch {
|
|
56
|
+
catch {
|
|
57
|
+
/* closed */
|
|
58
|
+
}
|
|
41
59
|
});
|
|
42
60
|
/** @type {ReturnType<typeof createTriggers> | null} */
|
|
43
61
|
let triggers = null;
|
|
@@ -56,11 +74,22 @@ export function apply(ctx, config = {}) {
|
|
|
56
74
|
rendered.set(sessionId, view);
|
|
57
75
|
return view;
|
|
58
76
|
};
|
|
77
|
+
const memoryOf = (sessionId) => memorySessionFor(id => engine.isBot(id), sessionId, id => work?.ownerOf(id) ?? null);
|
|
59
78
|
const textFor = (sessionId, name) => {
|
|
60
|
-
if (!sessionId
|
|
79
|
+
if (!sessionId)
|
|
80
|
+
return '';
|
|
81
|
+
const source = memoryOf(sessionId);
|
|
82
|
+
if (!source)
|
|
61
83
|
return '';
|
|
62
|
-
|
|
63
|
-
|
|
84
|
+
if (source !== sessionId && name === 'foundations:chat')
|
|
85
|
+
return '';
|
|
86
|
+
const view = source === sessionId
|
|
87
|
+
? (rendered.get(sessionId) ?? render(sessionId))
|
|
88
|
+
: renderSession(engine, source, window, { persist: false });
|
|
89
|
+
const text = view.texts[name] ?? '';
|
|
90
|
+
if (source !== sessionId && name === 'foundations:rules' && text !== '')
|
|
91
|
+
return `${text}\n${WORKER_MEMORY}`;
|
|
92
|
+
return text;
|
|
64
93
|
};
|
|
65
94
|
const sessionFrom = (assemble) => assemble?.agent?.id;
|
|
66
95
|
const section = (name, order, pick) => {
|
|
@@ -68,7 +97,7 @@ export function apply(ctx, config = {}) {
|
|
|
68
97
|
name,
|
|
69
98
|
order,
|
|
70
99
|
interpolate: false,
|
|
71
|
-
text: (assemble) => pick(sessionFrom(assemble)),
|
|
100
|
+
text: (assemble) => pick(sessionFrom(assemble) ?? ''),
|
|
72
101
|
});
|
|
73
102
|
};
|
|
74
103
|
const context = (name, order, required, pick) => {
|
|
@@ -79,9 +108,9 @@ export function apply(ctx, config = {}) {
|
|
|
79
108
|
interpolate: false,
|
|
80
109
|
text: (assemble) => {
|
|
81
110
|
const sessionId = sessionFrom(assemble);
|
|
82
|
-
if (!sessionId || !
|
|
111
|
+
if (!sessionId || !memoryOf(sessionId))
|
|
83
112
|
return '';
|
|
84
|
-
if (!rendered.has(sessionId))
|
|
113
|
+
if (engine.isBot(sessionId) && !rendered.has(sessionId))
|
|
85
114
|
render(sessionId);
|
|
86
115
|
return pick(sessionId);
|
|
87
116
|
},
|
|
@@ -103,22 +132,21 @@ export function apply(ctx, config = {}) {
|
|
|
103
132
|
for (const definition of toolDefinitions(engine, () => 0)) {
|
|
104
133
|
const original = definition.execute;
|
|
105
134
|
definition.execute = async (args, exec) => {
|
|
135
|
+
const result = await callMemoryTool(original, args ?? {}, exec, memoryOf);
|
|
106
136
|
const sessionId = exec?.agent?.id;
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
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;
|
|
137
|
+
const memoryId = typeof sessionId === 'string' ? memoryOf(sessionId) : null;
|
|
138
|
+
if (result?.ok === true && memoryId && (result.viewRevisionFrozen === 0 || result.viewRevisionFrozen == null)) {
|
|
139
|
+
result.viewRevisionFrozen = revisionOf(memoryId);
|
|
114
140
|
}
|
|
115
141
|
return result;
|
|
116
142
|
};
|
|
117
143
|
ctx.tools.register(definition);
|
|
118
144
|
}
|
|
119
145
|
ctx.on('session/event', (session, event) => {
|
|
120
|
-
|
|
121
|
-
|
|
146
|
+
if (session == null || event == null || typeof event.type !== 'string')
|
|
147
|
+
return;
|
|
148
|
+
const sessionId = session.id;
|
|
149
|
+
if (typeof sessionId !== 'string')
|
|
122
150
|
return;
|
|
123
151
|
const bot = engine.isBot(sessionId);
|
|
124
152
|
const worker = work?.isWorkerSession(sessionId) === true;
|
|
@@ -156,16 +184,17 @@ export function apply(ctx, config = {}) {
|
|
|
156
184
|
}
|
|
157
185
|
const op = event.surfaceOp;
|
|
158
186
|
if (op && typeof op === 'object' && op.op === 'replace' && Array.isArray(event.sourceEventSeqs)) {
|
|
159
|
-
engine.noteRemoval(sessionId, event.sourceEventSeqs.filter(seq => typeof seq === 'number'));
|
|
187
|
+
engine.noteRemoval(sessionId, event.sourceEventSeqs.filter((seq) => typeof seq === 'number'));
|
|
160
188
|
}
|
|
161
189
|
}
|
|
162
190
|
if (triggers && event.type === 'turn/end') {
|
|
163
191
|
const reason = event.data?.reason;
|
|
164
|
-
triggers.observeTurnEnd(sessionId, event.data?.turn ?? null, reason && typeof reason === 'object' ? reason.kind ?? '' : '');
|
|
192
|
+
triggers.observeTurnEnd(sessionId, event.data?.turn ?? null, reason && typeof reason === 'object' ? (reason.kind ?? '') : '');
|
|
165
193
|
}
|
|
166
194
|
});
|
|
167
195
|
ctx.on('agent/created', (payload) => {
|
|
168
196
|
const agent = payload?.agent;
|
|
197
|
+
pinMainReasoning(agent, id => engine.isBot(id));
|
|
169
198
|
if (!agent?.id || !engine.isBot(agent.id))
|
|
170
199
|
return;
|
|
171
200
|
let session = null;
|
|
@@ -180,6 +209,9 @@ export function apply(ctx, config = {}) {
|
|
|
180
209
|
seeded: session?.header?.isSeeded === true,
|
|
181
210
|
});
|
|
182
211
|
});
|
|
212
|
+
ctx.on('agent/inbox/inserted', (payload) => {
|
|
213
|
+
pinMainReasoning(payload?.agent, id => engine.isBot(id));
|
|
214
|
+
});
|
|
183
215
|
triggers = ctx.agents ? startTriggers(ctx, store, engine) : null;
|
|
184
216
|
work = ctx.agents ? startWork(ctx, store, engine, config) : null;
|
|
185
217
|
if (triggers) {
|
|
@@ -189,6 +221,24 @@ export function apply(ctx, config = {}) {
|
|
|
189
221
|
if (work) {
|
|
190
222
|
for (const definition of workToolDefinitions(work, engine))
|
|
191
223
|
ctx.tools.register(definition);
|
|
224
|
+
const gate = work;
|
|
225
|
+
// Main-session step budget: refuse the next step instead of cancelling a
|
|
226
|
+
// step that already ended. A refused step ends the turn as `blocked`.
|
|
227
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
228
|
+
const sessionId = payload?.agent?.id;
|
|
229
|
+
if (typeof sessionId !== 'string' || sessionId === '')
|
|
230
|
+
return next();
|
|
231
|
+
if (!(await gate.waitForBudget(sessionId, payload?.signal)))
|
|
232
|
+
return { kind: 'reject' };
|
|
233
|
+
const decision = gate.gateStep(sessionId, {
|
|
234
|
+
turn: payload?.turn,
|
|
235
|
+
step: payload?.step,
|
|
236
|
+
claimed: Array.isArray(payload?.messages) ? payload.messages.length : 0,
|
|
237
|
+
});
|
|
238
|
+
if (decision.kind === 'reject')
|
|
239
|
+
return Promise.resolve({ kind: 'reject' });
|
|
240
|
+
return next();
|
|
241
|
+
});
|
|
192
242
|
}
|
|
193
243
|
if (triggers || work) {
|
|
194
244
|
const timer = setInterval(() => {
|
|
@@ -200,10 +250,31 @@ export function apply(ctx, config = {}) {
|
|
|
200
250
|
triggers?.tick().catch(() => { });
|
|
201
251
|
work?.tick().catch(() => { });
|
|
202
252
|
}
|
|
253
|
+
const questions = createQuestionAnswerer();
|
|
254
|
+
publishQuestionAnswerer(store.root, questions);
|
|
255
|
+
ctx.effect(() => questions.listen(ctx));
|
|
256
|
+
ctx.effect(() => () => {
|
|
257
|
+
if (questionAnswererFor(store.root) === questions)
|
|
258
|
+
publishQuestionAnswerer(store.root, null);
|
|
259
|
+
});
|
|
260
|
+
const approvals = createApprovalAnswerer();
|
|
261
|
+
publishApprovalAnswerer(store.root, approvals);
|
|
262
|
+
ctx.effect(() => approvals.listen(ctx));
|
|
263
|
+
ctx.effect(() => () => {
|
|
264
|
+
if (approvalAnswererFor(store.root) === approvals)
|
|
265
|
+
publishApprovalAnswerer(store.root, null);
|
|
266
|
+
});
|
|
267
|
+
const authorization = createAuthorizationController();
|
|
268
|
+
publishAuthorization(store.root, authorization);
|
|
269
|
+
ctx.effect(() => authorization.bind(ctx));
|
|
270
|
+
ctx.effect(() => () => {
|
|
271
|
+
if (authorizationFor(store.root) === authorization)
|
|
272
|
+
publishAuthorization(store.root, null);
|
|
273
|
+
});
|
|
203
274
|
ctx.logger?.info?.('session-foundations: ready dir=%s bindings=%s promoted=%s', dataDir, recovery.bindings, recovery.promoted.length);
|
|
204
275
|
}
|
|
205
276
|
/**
|
|
206
|
-
* @param {import('
|
|
277
|
+
* @param {import('./host.ts').PluginHost} ctx
|
|
207
278
|
* @param {import('./src/store.js').Store} store
|
|
208
279
|
* @param {import('./src/engine.js').Engine} engine
|
|
209
280
|
*/
|
|
@@ -220,14 +291,18 @@ function startTriggers(ctx, store, engine) {
|
|
|
220
291
|
publishRuntime(store.root, null);
|
|
221
292
|
});
|
|
222
293
|
ctx.on('agent/inbox/claimed', (payload) => {
|
|
223
|
-
|
|
224
|
-
|
|
294
|
+
if (payload == null)
|
|
295
|
+
return;
|
|
296
|
+
const sessionId = payload.agent?.id;
|
|
297
|
+
const messageId = payload.message?.id;
|
|
225
298
|
if (typeof sessionId === 'string' && typeof messageId === 'string')
|
|
226
299
|
triggers.observeClaimed(sessionId, messageId, payload.turn ?? null);
|
|
227
300
|
});
|
|
228
301
|
ctx.on('agent/inbox/discarded', (payload) => {
|
|
229
|
-
|
|
230
|
-
|
|
302
|
+
if (payload == null)
|
|
303
|
+
return;
|
|
304
|
+
const sessionId = payload.agent?.id;
|
|
305
|
+
const messageId = payload.message?.id;
|
|
231
306
|
if (typeof sessionId === 'string' && typeof messageId === 'string')
|
|
232
307
|
triggers.observeDiscarded(sessionId, messageId);
|
|
233
308
|
});
|
|
@@ -236,7 +311,7 @@ function startTriggers(ctx, store, engine) {
|
|
|
236
311
|
/**
|
|
237
312
|
* Bot dual-loop. Ordinary sessions never enter this runtime's tools.
|
|
238
313
|
* Child agents are created without parentAgent so the main handle does not dispose them.
|
|
239
|
-
* @param {import('
|
|
314
|
+
* @param {import('./host.ts').PluginHost} ctx
|
|
240
315
|
* @param {import('./src/store.js').Store} store
|
|
241
316
|
* @param {import('./src/engine.js').Engine} engine
|
|
242
317
|
* @param {{ work?: Partial<import('./src/work-admit.js').DEFAULT_WORK_BUDGET> }} config
|
|
@@ -245,17 +320,43 @@ function startWork(ctx, store, engine, config) {
|
|
|
245
320
|
/** @type {Map<string, { dispose?: () => Promise<void> }>} */
|
|
246
321
|
const workerHandles = new Map();
|
|
247
322
|
const filePreset = ensureWorkerFilePreset(ctx);
|
|
323
|
+
const resolved = resolveWorkBudget(config.work ?? {}, process.env[WORK_BUDGET_ENV]);
|
|
324
|
+
if (resolved.ignored.length > 0) {
|
|
325
|
+
ctx.logger?.warn?.('session-foundations: ignored work budget keys %s', resolved.ignored.join(','));
|
|
326
|
+
}
|
|
327
|
+
if (resolved.clamped.length > 0) {
|
|
328
|
+
ctx.logger?.warn?.('session-foundations: clamped work budget keys %s', resolved.clamped.join(','));
|
|
329
|
+
}
|
|
330
|
+
const slots = effectiveWorkLimits(resolved.budget);
|
|
331
|
+
ctx.logger?.info?.('session-foundations: main budget chat=%s steps/%sms main=%s steps/%sms slots perBot=%s global=%s queue perBot=%s global=%s', resolved.budget.chatMaxSteps, resolved.budget.chatWallMs, resolved.budget.mainMaxSteps, resolved.budget.mainWallMs, slots.perBot, slots.global, slots.perBotQueue, slots.globalQueue);
|
|
332
|
+
if (resolved.budget.perBot > resolved.budget.global || resolved.budget.perBotQueue > resolved.budget.globalQueue) {
|
|
333
|
+
ctx.logger?.info?.('session-foundations: per-bot cap reduced to the global cap (perBot=%s global=%s perBotQueue=%s globalQueue=%s)', resolved.budget.perBot, resolved.budget.global, resolved.budget.perBotQueue, resolved.budget.globalQueue);
|
|
334
|
+
}
|
|
248
335
|
const work = createWorkRuntime(store, engine, {
|
|
249
|
-
|
|
336
|
+
resumePaused: true,
|
|
337
|
+
budget: resolved.budget,
|
|
338
|
+
log: (level, message) => {
|
|
339
|
+
const sink = level === 'warn' ? (ctx.logger?.warn ?? ctx.logger?.info) : ctx.logger?.info;
|
|
340
|
+
sink?.call(ctx.logger, message);
|
|
341
|
+
// DSH 0.2.2-rc.1 does not print plugin ctx.logger output by default, so a
|
|
342
|
+
// budget trip also goes to stderr (journald under systemd). No secrets.
|
|
343
|
+
if (level === 'warn')
|
|
344
|
+
console.warn(message);
|
|
345
|
+
},
|
|
346
|
+
onMainBudget: (sessionId, trip) => {
|
|
347
|
+
if (config.budgetNotice === false)
|
|
348
|
+
return;
|
|
349
|
+
postBudgetNotice(ctx, sessionId, trip).catch(error => {
|
|
350
|
+
ctx.logger?.warn?.('session-foundations: budget notice failed session=%s %s', sessionId, String(error));
|
|
351
|
+
});
|
|
352
|
+
},
|
|
250
353
|
createChild: async (spec) => {
|
|
251
354
|
let cwd = '';
|
|
252
355
|
let model = null;
|
|
253
356
|
try {
|
|
254
|
-
const owner = ctx.agents
|
|
255
|
-
cwd = owner?.session?.header?.cwd
|
|
256
|
-
|
|
257
|
-
?? '';
|
|
258
|
-
model = owner?.model?.current?.() ?? null;
|
|
357
|
+
const owner = ctx.agents?.get(spec.ownerSessionId);
|
|
358
|
+
cwd = owner?.session?.header?.cwd ?? ctx.sessions?.get(spec.ownerSessionId)?.header?.cwd ?? '';
|
|
359
|
+
model = workerModelSelection(owner?.model?.current?.() ?? null);
|
|
259
360
|
}
|
|
260
361
|
catch {
|
|
261
362
|
cwd = '';
|
|
@@ -263,7 +364,7 @@ function startWork(ctx, store, engine, config) {
|
|
|
263
364
|
}
|
|
264
365
|
if (!model?.provider || !model?.model) {
|
|
265
366
|
try {
|
|
266
|
-
model = ctx.agentDefaultModel?.currentSelection?.() ?? null;
|
|
367
|
+
model = workerModelSelection(ctx.agentDefaultModel?.currentSelection?.() ?? null);
|
|
267
368
|
}
|
|
268
369
|
catch {
|
|
269
370
|
model = null;
|
|
@@ -296,16 +397,19 @@ function startWork(ctx, store, engine, config) {
|
|
|
296
397
|
const agent = liveAgent(ctx, sessionId);
|
|
297
398
|
if (!agent)
|
|
298
399
|
return;
|
|
299
|
-
|
|
400
|
+
// Never report a host cancel as a user cancel: the turn records
|
|
401
|
+
// { kind: 'aborted', reason: { kind: 'hook', reason } }.
|
|
402
|
+
agent.cancel({ kind: 'hook', reason: options.reason || 'session-foundations' }, { keepInbox: options.keepInbox === true });
|
|
300
403
|
},
|
|
301
404
|
snapshot: async (sessionId) => {
|
|
302
405
|
try {
|
|
303
|
-
return await
|
|
406
|
+
return (await createLogSource(ctx).read(sessionId, -1)).events;
|
|
304
407
|
}
|
|
305
408
|
catch {
|
|
306
409
|
return [];
|
|
307
410
|
}
|
|
308
411
|
},
|
|
412
|
+
childPresent: sessionId => liveAgent(ctx, sessionId) != null,
|
|
309
413
|
});
|
|
310
414
|
publishWorkRuntime(store.root, work);
|
|
311
415
|
ctx.effect(() => () => {
|
|
@@ -313,13 +417,49 @@ function startWork(ctx, store, engine, config) {
|
|
|
313
417
|
workerHandles.clear();
|
|
314
418
|
});
|
|
315
419
|
ctx.on('agent/inbox/claimed', (payload) => {
|
|
316
|
-
|
|
317
|
-
|
|
420
|
+
if (payload == null)
|
|
421
|
+
return;
|
|
422
|
+
const sessionId = payload.agent?.id;
|
|
423
|
+
const messageId = payload.message?.id;
|
|
318
424
|
if (typeof sessionId === 'string' && typeof messageId === 'string')
|
|
319
425
|
work.observeClaimed(sessionId, messageId, payload.turn ?? null);
|
|
320
426
|
});
|
|
321
427
|
return work;
|
|
322
428
|
}
|
|
429
|
+
/**
|
|
430
|
+
* Text of the inbox notice that follows a main-session budget trip.
|
|
431
|
+
* @param {MainBudgetTrip} trip
|
|
432
|
+
*/
|
|
433
|
+
export function budgetNoticeText(trip) {
|
|
434
|
+
const seconds = Math.round(trip.elapsedMs / 1000);
|
|
435
|
+
const what = trip.reason === 'steps'
|
|
436
|
+
? `it reached the step limit (${trip.steps}/${trip.maxSteps} steps)`
|
|
437
|
+
: `it reached the time limit (${seconds}s of ${Math.round(trip.wallMs / 1000)}s)`;
|
|
438
|
+
return [
|
|
439
|
+
'[foundations:budget]',
|
|
440
|
+
`The previous turn (turn ${trip.turn}) was stopped by the bot host because ${what}. The user did not cancel it.`,
|
|
441
|
+
`cause: ${trip.cause}`,
|
|
442
|
+
'In one short message, tell the user the turn was cut off by the budget and what is already done.',
|
|
443
|
+
'If work remains, call foundations_dispatch with a briefing for the remaining work so a worker continues it, and say so. Otherwise ask the user whether to continue.',
|
|
444
|
+
].join('\n');
|
|
445
|
+
}
|
|
446
|
+
/**
|
|
447
|
+
* Wait until the stopped turn is idle, then post the notice as a next-turn
|
|
448
|
+
* message. Posting while the turn is still unwinding could leave it unclaimed.
|
|
449
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
450
|
+
* @param {string} sessionId
|
|
451
|
+
* @param {MainBudgetTrip} trip
|
|
452
|
+
*/
|
|
453
|
+
async function postBudgetNotice(ctx, sessionId, trip) {
|
|
454
|
+
const agent = liveAgent(ctx, sessionId);
|
|
455
|
+
if (!agent)
|
|
456
|
+
return;
|
|
457
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
458
|
+
if (typeof agent.whenIdle === 'function')
|
|
459
|
+
await agent.whenIdle();
|
|
460
|
+
const messageId = `${BUDGET_NOTICE_PREFIX}${trip.turn}:${Date.now().toString(36)}`;
|
|
461
|
+
await followupDurable(ctx, sessionId, messageId, budgetNoticeText(trip));
|
|
462
|
+
}
|
|
323
463
|
/**
|
|
324
464
|
* @param {ReturnType<typeof createTriggers>} triggers
|
|
325
465
|
* @param {import('./src/engine.js').Engine} engine
|
|
@@ -391,13 +531,13 @@ function triggerTool(name, description, parameters, run, isBot) {
|
|
|
391
531
|
};
|
|
392
532
|
}
|
|
393
533
|
/**
|
|
394
|
-
* @param {import('
|
|
534
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
395
535
|
* @param {string} sessionId
|
|
396
536
|
* @param {string} messageId
|
|
397
537
|
*/
|
|
398
538
|
async function logHasDurable(ctx, sessionId, messageId) {
|
|
399
|
-
const events = await
|
|
400
|
-
return logHasMessage(
|
|
539
|
+
const { events } = await createLogSource(ctx).read(sessionId, -1);
|
|
540
|
+
return logHasMessage(events, messageId);
|
|
401
541
|
}
|
|
402
542
|
/**
|
|
403
543
|
* @param {{ data?: { message?: { content?: Array<{ type?: string, text?: string }> }, content?: Array<{ type?: string, text?: string }> } }} event
|
|
@@ -406,6 +546,9 @@ function messageText(event) {
|
|
|
406
546
|
const content = event.data?.message?.content ?? event.data?.content;
|
|
407
547
|
if (!Array.isArray(content))
|
|
408
548
|
return '';
|
|
409
|
-
return content
|
|
549
|
+
return content
|
|
550
|
+
.filter(block => block?.type === 'text')
|
|
551
|
+
.map(block => block.text ?? '')
|
|
552
|
+
.join('\n');
|
|
410
553
|
}
|
|
411
554
|
export { pidAlive };
|
package/dist/live-diff.js
CHANGED
|
@@ -15,7 +15,9 @@ function stable(value) {
|
|
|
15
15
|
if (Array.isArray(value))
|
|
16
16
|
return `[${value.map(item => stable(item)).join(',')}]`;
|
|
17
17
|
const record = value;
|
|
18
|
-
const keys = Object.keys(record)
|
|
18
|
+
const keys = Object.keys(record)
|
|
19
|
+
.filter(key => record[key] !== undefined)
|
|
20
|
+
.sort();
|
|
19
21
|
return `{${keys.map(key => `${JSON.stringify(key)}:${stable(record[key])}`).join(',')}}`;
|
|
20
22
|
}
|
|
21
23
|
function isObject(value) {
|
package/dist/live-snapshot.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { planChunks } from "./cdc.js";
|
|
2
|
+
import { stableStringify } from "./log/canonical.js";
|
|
2
3
|
/**
|
|
3
4
|
* Session history is one canonical JSON array of the host event log.
|
|
4
5
|
* FastCDC is only for that blob, and only when a session is opened.
|
|
@@ -9,19 +10,7 @@ const PLAN_LIMIT = 8;
|
|
|
9
10
|
* Sorted-key JSON, so the same log cuts into the same chunks.
|
|
10
11
|
* Array order is the host order.
|
|
11
12
|
*/
|
|
12
|
-
export
|
|
13
|
-
if (value === undefined)
|
|
14
|
-
return 'null';
|
|
15
|
-
if (value instanceof Date)
|
|
16
|
-
return JSON.stringify(value);
|
|
17
|
-
if (value === null || typeof value !== 'object')
|
|
18
|
-
return JSON.stringify(value) ?? 'null';
|
|
19
|
-
if (Array.isArray(value))
|
|
20
|
-
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
|
21
|
-
const record = value;
|
|
22
|
-
const keys = Object.keys(record).filter(key => record[key] !== undefined).sort();
|
|
23
|
-
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
|
|
24
|
-
}
|
|
13
|
+
export { stableStringify } from "./log/canonical.js";
|
|
25
14
|
export function canonicalBytes(value) {
|
|
26
15
|
return Buffer.from(stableStringify(value), 'utf8');
|
|
27
16
|
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sorted-key JSON used as the event-log canonical form.
|
|
3
|
+
* NDJSON is one event per line, so an append only changes the tail.
|
|
4
|
+
*/
|
|
5
|
+
export function stableStringify(value) {
|
|
6
|
+
if (value === undefined)
|
|
7
|
+
return 'null';
|
|
8
|
+
if (value instanceof Date)
|
|
9
|
+
return JSON.stringify(value);
|
|
10
|
+
if (value === null || typeof value !== 'object')
|
|
11
|
+
return JSON.stringify(value) ?? 'null';
|
|
12
|
+
if (Array.isArray(value))
|
|
13
|
+
return `[${value.map(item => stableStringify(item)).join(',')}]`;
|
|
14
|
+
const record = value;
|
|
15
|
+
const keys = Object.keys(record)
|
|
16
|
+
.filter(key => record[key] !== undefined)
|
|
17
|
+
.sort();
|
|
18
|
+
return `{${keys.map(key => `${JSON.stringify(key)}:${stableStringify(record[key])}`).join(',')}}`;
|
|
19
|
+
}
|
|
20
|
+
export function canonicalBytes(value) {
|
|
21
|
+
return Buffer.from(stableStringify(value), 'utf8');
|
|
22
|
+
}
|
|
23
|
+
export function eventNdjson(events) {
|
|
24
|
+
const parts = [];
|
|
25
|
+
const lines = [];
|
|
26
|
+
let offset = 0;
|
|
27
|
+
for (const event of events) {
|
|
28
|
+
const seq = event && typeof event === 'object' && typeof event.seq === 'number'
|
|
29
|
+
? event.seq
|
|
30
|
+
: lines.length;
|
|
31
|
+
const line = Buffer.from(`${stableStringify(event)}\n`, 'utf8');
|
|
32
|
+
lines.push({ seq, start: offset, end: offset + line.length });
|
|
33
|
+
parts.push(line);
|
|
34
|
+
offset += line.length;
|
|
35
|
+
}
|
|
36
|
+
return { bytes: parts.length ? Buffer.concat(parts) : Buffer.alloc(0), lines };
|
|
37
|
+
}
|