@thready-web/dsh-bot-plugin 0.1.0-beta.1 → 0.1.0-beta.11
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/canvas-http.js +248 -0
- package/dist/canvas-skills.js +56 -0
- package/dist/canvas-store.js +794 -0
- package/dist/canvas-tools.js +211 -0
- package/dist/cli.js +32 -12
- package/dist/context.js +60 -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 +402 -85
- package/dist/inbox.js +51 -40
- package/dist/index.js +201 -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 +52 -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 +1033 -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 +16 -5
- package/public/assets/SourceEditor-CJwK846Z.css +1 -0
- package/public/assets/SourceEditor-uu0G7jsM.js +669 -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-C5DAFF5H.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-DExNwSiZ.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-BK7YAvpQ.js +1 -0
- package/public/assets/hcl-DxDQ3s82.js +1 -0
- package/public/assets/html-CdDm_zae.js +1 -0
- package/public/assets/html.worker-tnXziJOq.js +456 -0
- package/public/assets/htmlMode-CLdn9oa1.js +4 -0
- package/public/assets/index-BB-QDSf2.css +1 -0
- package/public/assets/index-CsX-_qbo.js +62 -0
- package/public/assets/ini-BvajGCUy.js +1 -0
- package/public/assets/java-SYsfObOQ.js +1 -0
- package/public/assets/javascript-mLl83_3W.js +1 -0
- package/public/assets/json.worker-aFakAbRR.js +44 -0
- package/public/assets/jsonMode-B1-bihFd.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-Cv8m0HUb.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-Q12b91rL.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-Kda811W0.js +1 -0
- package/public/assets/qsharp-q7JyzKFN.js +1 -0
- package/public/assets/r-BIFz-_sK.js +1 -0
- package/public/assets/razor-CRuCpdOW.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-BGHcz-M3.js +11 -0
- package/public/assets/twig-BfRIq3la.js +1 -0
- package/public/assets/typescript-Db1e0DCT.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-H3zzFmnd.js +1 -0
- package/public/assets/yaml-BQrKvmTF.js +1 -0
- package/public/index.html +2 -2
- package/skills/ui/baseline-ui/SKILL.md +85 -0
- package/skills/ui/bencium-innovative-ux-designer/SKILL.md +227 -0
- package/skills/ui/better-ui/SKILL.md +133 -0
- package/skills/ui/design-lab/SKILL.md +920 -0
- package/skills/ui/frontend-design/SKILL.md +71 -0
- package/skills/ui/impeccable/SKILL.md +93 -0
- package/skills/ui/interface-design/SKILL.md +320 -0
- package/skills/ui/sources.json +66 -0
- package/skills/ui/ui-design/SKILL.md +35 -0
- package/skills/ui/ui-skills-root/SKILL.md +59 -0
- package/skills/ui/visual-design-foundations/SKILL.md +318 -0
- package/skills/ui/web-design-guidelines/SKILL.md +39 -0
- 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,36 @@ 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";
|
|
19
|
+
import { openCanvasStore } from "./canvas-store.js";
|
|
20
|
+
import { canvasToolDefinitions } from "./canvas-tools.js";
|
|
15
21
|
export const name = 'session-foundations';
|
|
16
|
-
|
|
22
|
+
// Cordis throws if a plugin reads a service it did not inject. Crash recovery reads the session log through this one.
|
|
23
|
+
export const inject = [
|
|
24
|
+
'systemPrompt',
|
|
25
|
+
'tools',
|
|
26
|
+
'sessions',
|
|
27
|
+
'agents',
|
|
28
|
+
'agentPresets',
|
|
29
|
+
'sessionPersistence',
|
|
30
|
+
'sessionQuery',
|
|
31
|
+
'userQuestions',
|
|
32
|
+
];
|
|
17
33
|
/**
|
|
18
|
-
* @param {import('
|
|
34
|
+
* @param {import('./host.ts').PluginHost} ctx
|
|
19
35
|
* @param {{ dataDir?: string, contextWindow?: number, traceEvents?: boolean, timerTickMs?: number }} [config]
|
|
20
36
|
*/
|
|
21
37
|
export function apply(ctx, config = {}) {
|
|
@@ -23,6 +39,7 @@ export function apply(ctx, config = {}) {
|
|
|
23
39
|
if (dataDir === '')
|
|
24
40
|
throw new Error('session-foundations: pass dataDir or launch with dsh profileContext');
|
|
25
41
|
const store = openStore(dataDir);
|
|
42
|
+
const canvas = openCanvasStore(join(dataDir, 'canvas.sqlite'));
|
|
26
43
|
const engine = createEngine(store);
|
|
27
44
|
const recovery = engine.recover();
|
|
28
45
|
const ownerFile = join(dataDir, 'owner.json');
|
|
@@ -33,11 +50,21 @@ export function apply(ctx, config = {}) {
|
|
|
33
50
|
if (owner.pid === process.pid)
|
|
34
51
|
rmSync(ownerFile, { force: true });
|
|
35
52
|
}
|
|
36
|
-
catch {
|
|
53
|
+
catch {
|
|
54
|
+
/* already gone */
|
|
55
|
+
}
|
|
37
56
|
try {
|
|
38
57
|
store.close();
|
|
39
58
|
}
|
|
40
|
-
catch {
|
|
59
|
+
catch {
|
|
60
|
+
/* closed */
|
|
61
|
+
}
|
|
62
|
+
try {
|
|
63
|
+
canvas.close();
|
|
64
|
+
}
|
|
65
|
+
catch {
|
|
66
|
+
/* closed */
|
|
67
|
+
}
|
|
41
68
|
});
|
|
42
69
|
/** @type {ReturnType<typeof createTriggers> | null} */
|
|
43
70
|
let triggers = null;
|
|
@@ -56,11 +83,22 @@ export function apply(ctx, config = {}) {
|
|
|
56
83
|
rendered.set(sessionId, view);
|
|
57
84
|
return view;
|
|
58
85
|
};
|
|
86
|
+
const memoryOf = (sessionId) => memorySessionFor(id => engine.isBot(id), sessionId, id => work?.ownerOf(id) ?? null);
|
|
59
87
|
const textFor = (sessionId, name) => {
|
|
60
|
-
if (!sessionId
|
|
88
|
+
if (!sessionId)
|
|
89
|
+
return '';
|
|
90
|
+
const source = memoryOf(sessionId);
|
|
91
|
+
if (!source)
|
|
92
|
+
return '';
|
|
93
|
+
if (source !== sessionId && name === 'foundations:chat')
|
|
61
94
|
return '';
|
|
62
|
-
const view =
|
|
63
|
-
|
|
95
|
+
const view = source === sessionId
|
|
96
|
+
? (rendered.get(sessionId) ?? render(sessionId))
|
|
97
|
+
: renderSession(engine, source, window, { persist: false });
|
|
98
|
+
const text = view.texts[name] ?? '';
|
|
99
|
+
if (source !== sessionId && name === 'foundations:rules' && text !== '')
|
|
100
|
+
return `${text}\n${WORKER_MEMORY}`;
|
|
101
|
+
return text;
|
|
64
102
|
};
|
|
65
103
|
const sessionFrom = (assemble) => assemble?.agent?.id;
|
|
66
104
|
const section = (name, order, pick) => {
|
|
@@ -68,7 +106,7 @@ export function apply(ctx, config = {}) {
|
|
|
68
106
|
name,
|
|
69
107
|
order,
|
|
70
108
|
interpolate: false,
|
|
71
|
-
text: (assemble) => pick(sessionFrom(assemble)),
|
|
109
|
+
text: (assemble) => pick(sessionFrom(assemble) ?? ''),
|
|
72
110
|
});
|
|
73
111
|
};
|
|
74
112
|
const context = (name, order, required, pick) => {
|
|
@@ -79,9 +117,9 @@ export function apply(ctx, config = {}) {
|
|
|
79
117
|
interpolate: false,
|
|
80
118
|
text: (assemble) => {
|
|
81
119
|
const sessionId = sessionFrom(assemble);
|
|
82
|
-
if (!sessionId || !
|
|
120
|
+
if (!sessionId || !memoryOf(sessionId))
|
|
83
121
|
return '';
|
|
84
|
-
if (!rendered.has(sessionId))
|
|
122
|
+
if (engine.isBot(sessionId) && !rendered.has(sessionId))
|
|
85
123
|
render(sessionId);
|
|
86
124
|
return pick(sessionId);
|
|
87
125
|
},
|
|
@@ -103,22 +141,21 @@ export function apply(ctx, config = {}) {
|
|
|
103
141
|
for (const definition of toolDefinitions(engine, () => 0)) {
|
|
104
142
|
const original = definition.execute;
|
|
105
143
|
definition.execute = async (args, exec) => {
|
|
144
|
+
const result = await callMemoryTool(original, args ?? {}, exec, memoryOf);
|
|
106
145
|
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;
|
|
146
|
+
const memoryId = typeof sessionId === 'string' ? memoryOf(sessionId) : null;
|
|
147
|
+
if (result?.ok === true && memoryId && (result.viewRevisionFrozen === 0 || result.viewRevisionFrozen == null)) {
|
|
148
|
+
result.viewRevisionFrozen = revisionOf(memoryId);
|
|
114
149
|
}
|
|
115
150
|
return result;
|
|
116
151
|
};
|
|
117
152
|
ctx.tools.register(definition);
|
|
118
153
|
}
|
|
119
154
|
ctx.on('session/event', (session, event) => {
|
|
120
|
-
|
|
121
|
-
|
|
155
|
+
if (session == null || event == null || typeof event.type !== 'string')
|
|
156
|
+
return;
|
|
157
|
+
const sessionId = session.id;
|
|
158
|
+
if (typeof sessionId !== 'string')
|
|
122
159
|
return;
|
|
123
160
|
const bot = engine.isBot(sessionId);
|
|
124
161
|
const worker = work?.isWorkerSession(sessionId) === true;
|
|
@@ -156,16 +193,17 @@ export function apply(ctx, config = {}) {
|
|
|
156
193
|
}
|
|
157
194
|
const op = event.surfaceOp;
|
|
158
195
|
if (op && typeof op === 'object' && op.op === 'replace' && Array.isArray(event.sourceEventSeqs)) {
|
|
159
|
-
engine.noteRemoval(sessionId, event.sourceEventSeqs.filter(seq => typeof seq === 'number'));
|
|
196
|
+
engine.noteRemoval(sessionId, event.sourceEventSeqs.filter((seq) => typeof seq === 'number'));
|
|
160
197
|
}
|
|
161
198
|
}
|
|
162
199
|
if (triggers && event.type === 'turn/end') {
|
|
163
200
|
const reason = event.data?.reason;
|
|
164
|
-
triggers.observeTurnEnd(sessionId, event.data?.turn ?? null, reason && typeof reason === 'object' ? reason.kind ?? '' : '');
|
|
201
|
+
triggers.observeTurnEnd(sessionId, event.data?.turn ?? null, reason && typeof reason === 'object' ? (reason.kind ?? '') : '');
|
|
165
202
|
}
|
|
166
203
|
});
|
|
167
204
|
ctx.on('agent/created', (payload) => {
|
|
168
205
|
const agent = payload?.agent;
|
|
206
|
+
pinMainReasoning(agent, id => engine.isBot(id));
|
|
169
207
|
if (!agent?.id || !engine.isBot(agent.id))
|
|
170
208
|
return;
|
|
171
209
|
let session = null;
|
|
@@ -180,6 +218,9 @@ export function apply(ctx, config = {}) {
|
|
|
180
218
|
seeded: session?.header?.isSeeded === true,
|
|
181
219
|
});
|
|
182
220
|
});
|
|
221
|
+
ctx.on('agent/inbox/inserted', (payload) => {
|
|
222
|
+
pinMainReasoning(payload?.agent, id => engine.isBot(id));
|
|
223
|
+
});
|
|
183
224
|
triggers = ctx.agents ? startTriggers(ctx, store, engine) : null;
|
|
184
225
|
work = ctx.agents ? startWork(ctx, store, engine, config) : null;
|
|
185
226
|
if (triggers) {
|
|
@@ -189,6 +230,26 @@ export function apply(ctx, config = {}) {
|
|
|
189
230
|
if (work) {
|
|
190
231
|
for (const definition of workToolDefinitions(work, engine))
|
|
191
232
|
ctx.tools.register(definition);
|
|
233
|
+
for (const definition of canvasToolDefinitions(canvas, work, engine))
|
|
234
|
+
ctx.tools.register(definition);
|
|
235
|
+
const gate = work;
|
|
236
|
+
// Main-session step budget: refuse the next step instead of cancelling a
|
|
237
|
+
// step that already ended. A refused step ends the turn as `blocked`.
|
|
238
|
+
ctx.on('agent/pre-step', async (payload, next) => {
|
|
239
|
+
const sessionId = payload?.agent?.id;
|
|
240
|
+
if (typeof sessionId !== 'string' || sessionId === '')
|
|
241
|
+
return next();
|
|
242
|
+
if (!(await gate.waitForBudget(sessionId, payload?.signal)))
|
|
243
|
+
return { kind: 'reject' };
|
|
244
|
+
const decision = gate.gateStep(sessionId, {
|
|
245
|
+
turn: payload?.turn,
|
|
246
|
+
step: payload?.step,
|
|
247
|
+
claimed: Array.isArray(payload?.messages) ? payload.messages.length : 0,
|
|
248
|
+
});
|
|
249
|
+
if (decision.kind === 'reject')
|
|
250
|
+
return Promise.resolve({ kind: 'reject' });
|
|
251
|
+
return next();
|
|
252
|
+
});
|
|
192
253
|
}
|
|
193
254
|
if (triggers || work) {
|
|
194
255
|
const timer = setInterval(() => {
|
|
@@ -200,10 +261,31 @@ export function apply(ctx, config = {}) {
|
|
|
200
261
|
triggers?.tick().catch(() => { });
|
|
201
262
|
work?.tick().catch(() => { });
|
|
202
263
|
}
|
|
264
|
+
const questions = createQuestionAnswerer();
|
|
265
|
+
publishQuestionAnswerer(store.root, questions);
|
|
266
|
+
ctx.effect(() => questions.listen(ctx));
|
|
267
|
+
ctx.effect(() => () => {
|
|
268
|
+
if (questionAnswererFor(store.root) === questions)
|
|
269
|
+
publishQuestionAnswerer(store.root, null);
|
|
270
|
+
});
|
|
271
|
+
const approvals = createApprovalAnswerer();
|
|
272
|
+
publishApprovalAnswerer(store.root, approvals);
|
|
273
|
+
ctx.effect(() => approvals.listen(ctx));
|
|
274
|
+
ctx.effect(() => () => {
|
|
275
|
+
if (approvalAnswererFor(store.root) === approvals)
|
|
276
|
+
publishApprovalAnswerer(store.root, null);
|
|
277
|
+
});
|
|
278
|
+
const authorization = createAuthorizationController();
|
|
279
|
+
publishAuthorization(store.root, authorization);
|
|
280
|
+
ctx.effect(() => authorization.bind(ctx));
|
|
281
|
+
ctx.effect(() => () => {
|
|
282
|
+
if (authorizationFor(store.root) === authorization)
|
|
283
|
+
publishAuthorization(store.root, null);
|
|
284
|
+
});
|
|
203
285
|
ctx.logger?.info?.('session-foundations: ready dir=%s bindings=%s promoted=%s', dataDir, recovery.bindings, recovery.promoted.length);
|
|
204
286
|
}
|
|
205
287
|
/**
|
|
206
|
-
* @param {import('
|
|
288
|
+
* @param {import('./host.ts').PluginHost} ctx
|
|
207
289
|
* @param {import('./src/store.js').Store} store
|
|
208
290
|
* @param {import('./src/engine.js').Engine} engine
|
|
209
291
|
*/
|
|
@@ -220,14 +302,18 @@ function startTriggers(ctx, store, engine) {
|
|
|
220
302
|
publishRuntime(store.root, null);
|
|
221
303
|
});
|
|
222
304
|
ctx.on('agent/inbox/claimed', (payload) => {
|
|
223
|
-
|
|
224
|
-
|
|
305
|
+
if (payload == null)
|
|
306
|
+
return;
|
|
307
|
+
const sessionId = payload.agent?.id;
|
|
308
|
+
const messageId = payload.message?.id;
|
|
225
309
|
if (typeof sessionId === 'string' && typeof messageId === 'string')
|
|
226
310
|
triggers.observeClaimed(sessionId, messageId, payload.turn ?? null);
|
|
227
311
|
});
|
|
228
312
|
ctx.on('agent/inbox/discarded', (payload) => {
|
|
229
|
-
|
|
230
|
-
|
|
313
|
+
if (payload == null)
|
|
314
|
+
return;
|
|
315
|
+
const sessionId = payload.agent?.id;
|
|
316
|
+
const messageId = payload.message?.id;
|
|
231
317
|
if (typeof sessionId === 'string' && typeof messageId === 'string')
|
|
232
318
|
triggers.observeDiscarded(sessionId, messageId);
|
|
233
319
|
});
|
|
@@ -236,7 +322,7 @@ function startTriggers(ctx, store, engine) {
|
|
|
236
322
|
/**
|
|
237
323
|
* Bot dual-loop. Ordinary sessions never enter this runtime's tools.
|
|
238
324
|
* Child agents are created without parentAgent so the main handle does not dispose them.
|
|
239
|
-
* @param {import('
|
|
325
|
+
* @param {import('./host.ts').PluginHost} ctx
|
|
240
326
|
* @param {import('./src/store.js').Store} store
|
|
241
327
|
* @param {import('./src/engine.js').Engine} engine
|
|
242
328
|
* @param {{ work?: Partial<import('./src/work-admit.js').DEFAULT_WORK_BUDGET> }} config
|
|
@@ -245,17 +331,43 @@ function startWork(ctx, store, engine, config) {
|
|
|
245
331
|
/** @type {Map<string, { dispose?: () => Promise<void> }>} */
|
|
246
332
|
const workerHandles = new Map();
|
|
247
333
|
const filePreset = ensureWorkerFilePreset(ctx);
|
|
334
|
+
const resolved = resolveWorkBudget(config.work ?? {}, process.env[WORK_BUDGET_ENV]);
|
|
335
|
+
if (resolved.ignored.length > 0) {
|
|
336
|
+
ctx.logger?.warn?.('session-foundations: ignored work budget keys %s', resolved.ignored.join(','));
|
|
337
|
+
}
|
|
338
|
+
if (resolved.clamped.length > 0) {
|
|
339
|
+
ctx.logger?.warn?.('session-foundations: clamped work budget keys %s', resolved.clamped.join(','));
|
|
340
|
+
}
|
|
341
|
+
const slots = effectiveWorkLimits(resolved.budget);
|
|
342
|
+
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);
|
|
343
|
+
if (resolved.budget.perBot > resolved.budget.global || resolved.budget.perBotQueue > resolved.budget.globalQueue) {
|
|
344
|
+
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);
|
|
345
|
+
}
|
|
248
346
|
const work = createWorkRuntime(store, engine, {
|
|
249
|
-
|
|
347
|
+
resumePaused: true,
|
|
348
|
+
budget: resolved.budget,
|
|
349
|
+
log: (level, message) => {
|
|
350
|
+
const sink = level === 'warn' ? (ctx.logger?.warn ?? ctx.logger?.info) : ctx.logger?.info;
|
|
351
|
+
sink?.call(ctx.logger, message);
|
|
352
|
+
// DSH 0.2.2-rc.1 does not print plugin ctx.logger output by default, so a
|
|
353
|
+
// budget trip also goes to stderr (journald under systemd). No secrets.
|
|
354
|
+
if (level === 'warn')
|
|
355
|
+
console.warn(message);
|
|
356
|
+
},
|
|
357
|
+
onMainBudget: (sessionId, trip) => {
|
|
358
|
+
if (config.budgetNotice === false)
|
|
359
|
+
return;
|
|
360
|
+
postBudgetNotice(ctx, sessionId, trip).catch(error => {
|
|
361
|
+
ctx.logger?.warn?.('session-foundations: budget notice failed session=%s %s', sessionId, String(error));
|
|
362
|
+
});
|
|
363
|
+
},
|
|
250
364
|
createChild: async (spec) => {
|
|
251
365
|
let cwd = '';
|
|
252
366
|
let model = null;
|
|
253
367
|
try {
|
|
254
|
-
const owner = ctx.agents
|
|
255
|
-
cwd = owner?.session?.header?.cwd
|
|
256
|
-
|
|
257
|
-
?? '';
|
|
258
|
-
model = owner?.model?.current?.() ?? null;
|
|
368
|
+
const owner = ctx.agents?.get(spec.ownerSessionId);
|
|
369
|
+
cwd = owner?.session?.header?.cwd ?? ctx.sessions?.get(spec.ownerSessionId)?.header?.cwd ?? '';
|
|
370
|
+
model = workerModelSelection(owner?.model?.current?.() ?? null);
|
|
259
371
|
}
|
|
260
372
|
catch {
|
|
261
373
|
cwd = '';
|
|
@@ -263,7 +375,7 @@ function startWork(ctx, store, engine, config) {
|
|
|
263
375
|
}
|
|
264
376
|
if (!model?.provider || !model?.model) {
|
|
265
377
|
try {
|
|
266
|
-
model = ctx.agentDefaultModel?.currentSelection?.() ?? null;
|
|
378
|
+
model = workerModelSelection(ctx.agentDefaultModel?.currentSelection?.() ?? null);
|
|
267
379
|
}
|
|
268
380
|
catch {
|
|
269
381
|
model = null;
|
|
@@ -296,16 +408,19 @@ function startWork(ctx, store, engine, config) {
|
|
|
296
408
|
const agent = liveAgent(ctx, sessionId);
|
|
297
409
|
if (!agent)
|
|
298
410
|
return;
|
|
299
|
-
|
|
411
|
+
// Never report a host cancel as a user cancel: the turn records
|
|
412
|
+
// { kind: 'aborted', reason: { kind: 'hook', reason } }.
|
|
413
|
+
agent.cancel({ kind: 'hook', reason: options.reason || 'session-foundations' }, { keepInbox: options.keepInbox === true });
|
|
300
414
|
},
|
|
301
415
|
snapshot: async (sessionId) => {
|
|
302
416
|
try {
|
|
303
|
-
return await
|
|
417
|
+
return (await createLogSource(ctx).read(sessionId, -1)).events;
|
|
304
418
|
}
|
|
305
419
|
catch {
|
|
306
420
|
return [];
|
|
307
421
|
}
|
|
308
422
|
},
|
|
423
|
+
childPresent: sessionId => liveAgent(ctx, sessionId) != null,
|
|
309
424
|
});
|
|
310
425
|
publishWorkRuntime(store.root, work);
|
|
311
426
|
ctx.effect(() => () => {
|
|
@@ -313,13 +428,49 @@ function startWork(ctx, store, engine, config) {
|
|
|
313
428
|
workerHandles.clear();
|
|
314
429
|
});
|
|
315
430
|
ctx.on('agent/inbox/claimed', (payload) => {
|
|
316
|
-
|
|
317
|
-
|
|
431
|
+
if (payload == null)
|
|
432
|
+
return;
|
|
433
|
+
const sessionId = payload.agent?.id;
|
|
434
|
+
const messageId = payload.message?.id;
|
|
318
435
|
if (typeof sessionId === 'string' && typeof messageId === 'string')
|
|
319
436
|
work.observeClaimed(sessionId, messageId, payload.turn ?? null);
|
|
320
437
|
});
|
|
321
438
|
return work;
|
|
322
439
|
}
|
|
440
|
+
/**
|
|
441
|
+
* Text of the inbox notice that follows a main-session budget trip.
|
|
442
|
+
* @param {MainBudgetTrip} trip
|
|
443
|
+
*/
|
|
444
|
+
export function budgetNoticeText(trip) {
|
|
445
|
+
const seconds = Math.round(trip.elapsedMs / 1000);
|
|
446
|
+
const what = trip.reason === 'steps'
|
|
447
|
+
? `it reached the step limit (${trip.steps}/${trip.maxSteps} steps)`
|
|
448
|
+
: `it reached the time limit (${seconds}s of ${Math.round(trip.wallMs / 1000)}s)`;
|
|
449
|
+
return [
|
|
450
|
+
'[foundations:budget]',
|
|
451
|
+
`The previous turn (turn ${trip.turn}) was stopped by the bot host because ${what}. The user did not cancel it.`,
|
|
452
|
+
`cause: ${trip.cause}`,
|
|
453
|
+
'In one short message, tell the user the turn was cut off by the budget and what is already done.',
|
|
454
|
+
'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.',
|
|
455
|
+
].join('\n');
|
|
456
|
+
}
|
|
457
|
+
/**
|
|
458
|
+
* Wait until the stopped turn is idle, then post the notice as a next-turn
|
|
459
|
+
* message. Posting while the turn is still unwinding could leave it unclaimed.
|
|
460
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
461
|
+
* @param {string} sessionId
|
|
462
|
+
* @param {MainBudgetTrip} trip
|
|
463
|
+
*/
|
|
464
|
+
async function postBudgetNotice(ctx, sessionId, trip) {
|
|
465
|
+
const agent = liveAgent(ctx, sessionId);
|
|
466
|
+
if (!agent)
|
|
467
|
+
return;
|
|
468
|
+
await new Promise(resolve => setImmediate(resolve));
|
|
469
|
+
if (typeof agent.whenIdle === 'function')
|
|
470
|
+
await agent.whenIdle();
|
|
471
|
+
const messageId = `${BUDGET_NOTICE_PREFIX}${trip.turn}:${Date.now().toString(36)}`;
|
|
472
|
+
await followupDurable(ctx, sessionId, messageId, budgetNoticeText(trip));
|
|
473
|
+
}
|
|
323
474
|
/**
|
|
324
475
|
* @param {ReturnType<typeof createTriggers>} triggers
|
|
325
476
|
* @param {import('./src/engine.js').Engine} engine
|
|
@@ -391,13 +542,13 @@ function triggerTool(name, description, parameters, run, isBot) {
|
|
|
391
542
|
};
|
|
392
543
|
}
|
|
393
544
|
/**
|
|
394
|
-
* @param {import('
|
|
545
|
+
* @param {import('./host.ts').HostContext} ctx
|
|
395
546
|
* @param {string} sessionId
|
|
396
547
|
* @param {string} messageId
|
|
397
548
|
*/
|
|
398
549
|
async function logHasDurable(ctx, sessionId, messageId) {
|
|
399
|
-
const events = await
|
|
400
|
-
return logHasMessage(
|
|
550
|
+
const { events } = await createLogSource(ctx).read(sessionId, -1);
|
|
551
|
+
return logHasMessage(events, messageId);
|
|
401
552
|
}
|
|
402
553
|
/**
|
|
403
554
|
* @param {{ data?: { message?: { content?: Array<{ type?: string, text?: string }> }, content?: Array<{ type?: string, text?: string }> } }} event
|
|
@@ -406,6 +557,9 @@ function messageText(event) {
|
|
|
406
557
|
const content = event.data?.message?.content ?? event.data?.content;
|
|
407
558
|
if (!Array.isArray(content))
|
|
408
559
|
return '';
|
|
409
|
-
return content
|
|
560
|
+
return content
|
|
561
|
+
.filter(block => block?.type === 'text')
|
|
562
|
+
.map(block => block.text ?? '')
|
|
563
|
+
.join('\n');
|
|
410
564
|
}
|
|
411
565
|
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
|
+
}
|