@hivemagnus/ardent 2.3.1 → 3.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +79 -2
- package/dist/a2a-idempotency.d.ts +3 -3
- package/dist/a2a-push-inbox.d.ts +3 -3
- package/dist/a2a-push.d.ts +3 -3
- package/dist/a2a-server.js +1 -1
- package/dist/a2a-store.d.ts +3 -3
- package/dist/a2a.js +19 -11
- package/dist/api.js +2 -0
- package/dist/cli.js +46 -20
- package/dist/context-maintenance.d.ts +4 -4
- package/dist/context-maintenance.js +1 -1
- package/dist/development.d.ts +1 -1
- package/dist/hermes-compat.d.ts +1 -1
- package/dist/hermes-compat.js +19 -2
- package/dist/index.d.ts +1 -1
- package/dist/job-engine.d.ts +9 -30
- package/dist/job-engine.js +4 -3
- package/dist/missions.d.ts +7 -6
- package/dist/missions.js +2 -2
- package/dist/plugin-evidence.d.ts +16 -0
- package/dist/plugin-evidence.js +44 -0
- package/dist/plugin-http.d.ts +4 -0
- package/dist/plugin-http.js +43 -0
- package/dist/plugin-inputs.d.ts +3 -0
- package/dist/plugin-inputs.js +40 -0
- package/dist/plugin-sdk.d.ts +25 -0
- package/dist/plugin-sdk.js +24 -0
- package/dist/plugins.d.ts +118 -7
- package/dist/plugins.js +93 -6
- package/dist/runtime.d.ts +20 -1
- package/dist/runtime.js +162 -23
- package/dist/sqlite.d.ts +30 -0
- package/dist/sqlite.js +81 -0
- package/dist/store.d.ts +5 -3
- package/dist/store.js +6 -6
- package/dist/team-artifacts.js +5 -5
- package/dist/team-contract.d.ts +20 -7
- package/dist/team-contract.js +11 -5
- package/dist/team-control.js +1 -2
- package/package.json +9 -6
package/dist/plugins.js
CHANGED
|
@@ -1,28 +1,33 @@
|
|
|
1
1
|
import { createRequire } from 'node:module';
|
|
2
2
|
import { isAbsolute, join } from 'node:path';
|
|
3
3
|
import { pathToFileURL } from 'node:url';
|
|
4
|
-
import {
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { defineTool, ToolRegistry } from './tools.js';
|
|
6
|
+
import { TeamEnvelope, TeamMissionShape } from './team-contract.js';
|
|
5
7
|
const pluginName = /^[a-z][a-z0-9-]{0,63}$/;
|
|
6
8
|
const registered = [];
|
|
7
9
|
/** Identity helper that type-checks a plugin definition. */
|
|
8
10
|
export function definePlugin(plugin) {
|
|
9
11
|
return plugin;
|
|
10
12
|
}
|
|
13
|
+
function isPluginFactory(value) { return typeof value === 'function'; }
|
|
11
14
|
function isRecord(value) {
|
|
12
15
|
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
13
16
|
}
|
|
14
17
|
function assertPlugin(plugin, source) {
|
|
15
18
|
if (!isRecord(plugin) || typeof plugin.name !== 'string' || !pluginName.test(plugin.name))
|
|
16
19
|
throw new Error(`Plugin ${source} must export an object with a lowercase name`);
|
|
17
|
-
for (const hook of ['registerTools', 'routes', 'jobHandlers', 'jobOwnership', 'peerTool'])
|
|
20
|
+
for (const hook of ['registerTools', 'routes', 'jobHandlers', 'jobOwnership', 'peerTool', 'taskTools', 'filterTool', 'teamEnvelope', 'admitTeamEnvelope', 'channelAdapter', 'httpRoutes', 'systemPrompt', 'allowMemory', 'observeToolResult', 'beforeFinish', 'taskSettled', 'taskExecutor', 'inputImages', 'teamEvidence', 'teamCard', 'prepareGateway', 'start', 'drain', 'close'])
|
|
18
21
|
if (plugin[hook] !== undefined && typeof plugin[hook] !== 'function')
|
|
19
22
|
throw new Error(`Plugin ${plugin.name} hook ${hook} must be a function`);
|
|
20
23
|
if (plugin.cliCommands !== undefined) {
|
|
21
24
|
if (!isRecord(plugin.cliCommands))
|
|
22
25
|
throw new Error(`Plugin ${plugin.name} cliCommands must be an object`);
|
|
23
26
|
for (const [name, command] of Object.entries(plugin.cliCommands))
|
|
24
|
-
if (!pluginName.test(name) || !isRecord(command) || typeof command.run !== 'function')
|
|
27
|
+
if (!pluginName.test(name) || !isRecord(command) || typeof command.run !== 'function' || command.matches !== undefined && typeof command.matches !== 'function')
|
|
25
28
|
throw new Error(`Plugin ${plugin.name} CLI command ${name} is invalid`);
|
|
29
|
+
else if (command.valueOptions !== undefined && (!Array.isArray(command.valueOptions) || command.valueOptions.length > 64 || command.valueOptions.some((value) => typeof value !== 'string' || !/^[a-z][a-z0-9-]{0,63}$/.test(value))))
|
|
30
|
+
throw new Error(`Plugin ${plugin.name} CLI command ${name} has invalid value options`);
|
|
26
31
|
}
|
|
27
32
|
}
|
|
28
33
|
function validate(plugin, source) {
|
|
@@ -62,14 +67,16 @@ async function importSpecifier(specifier, profileDir) {
|
|
|
62
67
|
* programmatically. A module's default export (or named `plugin` export) may
|
|
63
68
|
* be one plugin or an array of plugins.
|
|
64
69
|
*/
|
|
65
|
-
export async function loadPlugins(config, profileDir) {
|
|
70
|
+
export async function loadPlugins(config, profileDir, env = process.env) {
|
|
66
71
|
const plugins = [...registered];
|
|
67
72
|
for (const specifier of config.plugins) {
|
|
68
73
|
const module = await importSpecifier(specifier, profileDir);
|
|
69
74
|
if (!isRecord(module))
|
|
70
75
|
throw new Error(`Plugin ${specifier} did not load as a module`);
|
|
71
76
|
const exported = module.default ?? module.plugin;
|
|
72
|
-
|
|
77
|
+
const configured = isPluginFactory(exported)
|
|
78
|
+
? await exported({ config, profileDir, env }) : exported;
|
|
79
|
+
for (const item of Array.isArray(configured) ? configured : [configured]) {
|
|
73
80
|
const plugin = validate(item, specifier);
|
|
74
81
|
if (plugins.some(existing => existing.name === plugin.name))
|
|
75
82
|
throw new Error(`Duplicate plugin: ${plugin.name}`);
|
|
@@ -87,6 +94,7 @@ class ValidationContext {
|
|
|
87
94
|
config;
|
|
88
95
|
profileDir;
|
|
89
96
|
env;
|
|
97
|
+
runtimeAvailable = false;
|
|
90
98
|
defineTool = defineTool;
|
|
91
99
|
constructor(config, profileDir, env) {
|
|
92
100
|
this.config = config;
|
|
@@ -100,7 +108,40 @@ export function validationContext(config, profileDir, env) {
|
|
|
100
108
|
return new ValidationContext(config, profileDir, env);
|
|
101
109
|
}
|
|
102
110
|
export function pluginContext(runtime, env) {
|
|
103
|
-
return { runtime, config: runtime.config, profileDir: runtime.profileDir, env, tools: runtime.tools, defineTool };
|
|
111
|
+
return { runtimeAvailable: true, runtime, config: runtime.config, profileDir: runtime.profileDir, env, tools: runtime.tools, defineTool };
|
|
112
|
+
}
|
|
113
|
+
/** A codec cannot change authenticated identity, constraints, resources, or core actions. */
|
|
114
|
+
export function pluginTeamEnvelope(plugins, value) {
|
|
115
|
+
const raw = TeamEnvelope.extend({ mission: TeamMissionShape.extend({ allowed_actions: z.array(z.string()).min(1).max(8) }).passthrough() }).parse(value);
|
|
116
|
+
const candidates = plugins.flatMap(plugin => {
|
|
117
|
+
// Each codec gets a separate copy; neither the bindings nor another codec's
|
|
118
|
+
// input may change when a plugin normalizes its private wire vocabulary.
|
|
119
|
+
const envelope = plugin.teamEnvelope?.(structuredClone(raw));
|
|
120
|
+
return envelope === undefined ? [] : [{ plugin, envelope: TeamEnvelope.parse(envelope) }];
|
|
121
|
+
});
|
|
122
|
+
if (candidates.length > 1)
|
|
123
|
+
throw new Error('Multiple plugins claimed the team envelope');
|
|
124
|
+
const selected = candidates[0];
|
|
125
|
+
if (!selected) {
|
|
126
|
+
const envelope = TeamEnvelope.parse(raw);
|
|
127
|
+
if (envelope.mission.extensions && Object.keys(envelope.mission.extensions).length ||
|
|
128
|
+
envelope.mission.allowed_actions.some(action => action.startsWith('extension:')))
|
|
129
|
+
throw new Error('Team extension has no configured validator');
|
|
130
|
+
return envelope;
|
|
131
|
+
}
|
|
132
|
+
const canonical = selected.envelope;
|
|
133
|
+
const { allowed_actions: rawActions, extensions: _rawExtensions, ...rawMission } = raw.mission;
|
|
134
|
+
const { allowed_actions: actions, extensions, ...mission } = canonical.mission;
|
|
135
|
+
const bindings = ['id', 'revision', 'parent_task', 'constraints', 'resources', 'deadline', 'acceptance_criteria', 'expected_artifacts'];
|
|
136
|
+
if (canonical.version !== raw.version || canonical.caller !== raw.caller || canonical.task_id !== raw.task_id || canonical.objective !== raw.objective ||
|
|
137
|
+
bindings.some(key => JSON.stringify(mission[key]) !== JSON.stringify(rawMission[key])))
|
|
138
|
+
throw new Error('Plugin changed a team envelope binding');
|
|
139
|
+
if (extensions && Object.keys(extensions).some(key => key !== selected.plugin.name))
|
|
140
|
+
throw new Error('Plugin claimed another extension namespace');
|
|
141
|
+
if (actions.length !== rawActions.length || actions.some((action, index) => action.startsWith('extension:') && !action.startsWith(`extension:${selected.plugin.name}:`) ||
|
|
142
|
+
action !== rawActions[index] && action !== `extension:${selected.plugin.name}:${rawActions[index]}`))
|
|
143
|
+
throw new Error('Plugin changed a team action grant');
|
|
144
|
+
return canonical;
|
|
104
145
|
}
|
|
105
146
|
/** Merge plugin job handlers into a base registry; a duplicate handler ID is an error. */
|
|
106
147
|
export function pluginJobHandlers(plugins, ctx, base = {}) {
|
|
@@ -113,3 +154,49 @@ export function pluginJobHandlers(plugins, ctx, base = {}) {
|
|
|
113
154
|
}
|
|
114
155
|
return registry;
|
|
115
156
|
}
|
|
157
|
+
export function pluginChannelAdapter(plugins, ctx, channel, jobs) {
|
|
158
|
+
const adapters = plugins.flatMap(plugin => {
|
|
159
|
+
const adapter = plugin.channelAdapter?.(ctx, channel, jobs);
|
|
160
|
+
if (adapter !== undefined && typeof adapter.run !== 'function')
|
|
161
|
+
throw new Error(`Plugin ${plugin.name} returned an invalid channel adapter`);
|
|
162
|
+
return adapter ? [adapter] : [];
|
|
163
|
+
});
|
|
164
|
+
if (adapters.length > 1)
|
|
165
|
+
throw new Error(`Multiple plugins own the ${channel} consumer`);
|
|
166
|
+
return adapters[0];
|
|
167
|
+
}
|
|
168
|
+
/** Task additions cannot bypass context, preview effect, peer grant or restrictive filters. */
|
|
169
|
+
export function pluginTaskTools(plugins, ctx) {
|
|
170
|
+
if (ctx.task.context === 'mission' && !ctx.envelope)
|
|
171
|
+
throw new Error('Mission task has no recorded mission');
|
|
172
|
+
const tools = new Map(ctx.baseTools.map(tool => [tool.name, tool]));
|
|
173
|
+
for (const plugin of plugins) {
|
|
174
|
+
const additions = plugin.taskTools?.(ctx) ?? [];
|
|
175
|
+
const raw = additions;
|
|
176
|
+
if (!Array.isArray(raw))
|
|
177
|
+
throw new Error(`Plugin ${plugin.name} taskTools must return an array`);
|
|
178
|
+
for (const tool of additions) {
|
|
179
|
+
if (!tool || typeof tool.name !== 'string' || !/^[A-Za-z0-9_-]{1,100}$/.test(tool.name) ||
|
|
180
|
+
!['read', 'artifact-write', 'memory-write', 'external-write'].includes(tool.effect) ||
|
|
181
|
+
!Array.isArray(tool.contexts) || !tool.contexts.every((context) => typeof context === 'string' && ['direct', 'peer', 'scheduled', 'mission', 'preview'].includes(context)) ||
|
|
182
|
+
!Number.isSafeInteger(tool.timeoutMs) || tool.timeoutMs < 1 || typeof tool.invoke !== 'function' ||
|
|
183
|
+
typeof tool.input?.safeParse !== 'function' || typeof tool.output?.parse !== 'function')
|
|
184
|
+
throw new Error(`Plugin ${plugin.name} returned an invalid task tool`);
|
|
185
|
+
if (!tool.contexts.includes(ctx.task.context) || (ctx.task.context === 'preview' && tool.effect !== 'read'))
|
|
186
|
+
continue;
|
|
187
|
+
if (ctx.task.context === 'peer' || ctx.task.context === 'mission') {
|
|
188
|
+
if (!ctx.envelope?.mission.resources.includes(`tool:${tool.name}`) && plugin.peerTool?.(tool, ctx.task, ctx.envelope) !== true)
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const prior = tools.get(tool.name);
|
|
192
|
+
if (prior && prior !== tool)
|
|
193
|
+
throw new Error(`Duplicate task tool: ${tool.name}`);
|
|
194
|
+
tools.set(tool.name, tool);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
const registry = new ToolRegistry();
|
|
198
|
+
for (const tool of tools.values())
|
|
199
|
+
if (plugins.every(plugin => plugin.filterTool?.(ctx, tool) !== false))
|
|
200
|
+
registry.register(tool);
|
|
201
|
+
return registry;
|
|
202
|
+
}
|
package/dist/runtime.d.ts
CHANGED
|
@@ -3,7 +3,7 @@ import { ArtifactStore } from './artifacts.js';
|
|
|
3
3
|
import { type ResearchBrief } from './research.js';
|
|
4
4
|
import { TaskStore, type Task, type TaskContext } from './store.js';
|
|
5
5
|
import { ToolRegistry } from './tools.js';
|
|
6
|
-
import { TeamResult } from './team-contract.js';
|
|
6
|
+
import { TeamEnvelope, TeamResult } from './team-contract.js';
|
|
7
7
|
import { type ArdentPlugin } from './plugins.js';
|
|
8
8
|
import { LiveTextHub } from './live-text.js';
|
|
9
9
|
import { ArtifactManifests } from './artifact-manifests.js';
|
|
@@ -17,6 +17,20 @@ export type RunResult = {
|
|
|
17
17
|
brief?: ResearchBrief;
|
|
18
18
|
team_result?: TeamResult;
|
|
19
19
|
};
|
|
20
|
+
type SourceEvidence = {
|
|
21
|
+
url: string;
|
|
22
|
+
extracted: boolean;
|
|
23
|
+
title: string;
|
|
24
|
+
published_at: string | null;
|
|
25
|
+
retrieved_at: string | null;
|
|
26
|
+
content_sha256: string | null;
|
|
27
|
+
};
|
|
28
|
+
export type TaskEvidence = {
|
|
29
|
+
sourceIds: Set<string>;
|
|
30
|
+
sources: Map<string, SourceEvidence>;
|
|
31
|
+
artifactIds: Set<string>;
|
|
32
|
+
researchAttempted: boolean;
|
|
33
|
+
};
|
|
20
34
|
export declare class ArdentRuntime {
|
|
21
35
|
#private;
|
|
22
36
|
readonly profileDir: string;
|
|
@@ -39,6 +53,8 @@ export declare class ArdentRuntime {
|
|
|
39
53
|
constructor(profileDir: string, config: ArdentConfig, env?: NodeJS.ProcessEnv);
|
|
40
54
|
/** Install plugins once, before the runtime accepts work. Plugin tools join the shared registry. */
|
|
41
55
|
usePlugins(plugins: readonly ArdentPlugin[], env?: NodeJS.ProcessEnv): Promise<void>;
|
|
56
|
+
prepareGateway(env?: NodeJS.ProcessEnv): Promise<void>;
|
|
57
|
+
startPlugins(env?: NodeJS.ProcessEnv): Promise<void>;
|
|
42
58
|
close(): void;
|
|
43
59
|
drain(timeoutMs?: number): Promise<boolean>;
|
|
44
60
|
accept(prompt: string, caller?: string, context?: TaskContext, idempotencyKey?: string, sessionId?: string, originalDeadlineMs?: number, backendOverride?: 'llamacpp' | 'codex'): Task;
|
|
@@ -66,4 +82,7 @@ export declare class ArdentRuntime {
|
|
|
66
82
|
admission: 'open' | 'paused';
|
|
67
83
|
};
|
|
68
84
|
run(taskId: string, env?: NodeJS.ProcessEnv, onText?: (chunk: string, step: number) => void): Promise<RunResult>;
|
|
85
|
+
decodeTeamEnvelope(value: unknown): TeamEnvelope;
|
|
86
|
+
assertTeamEnvelopeAdmission(envelope: TeamEnvelope, wire: unknown, env: NodeJS.ProcessEnv): void;
|
|
69
87
|
}
|
|
88
|
+
export {};
|
package/dist/runtime.js
CHANGED
|
@@ -14,12 +14,13 @@ import { TaskStore } from './store.js';
|
|
|
14
14
|
import { ToolRegistry } from './tools.js';
|
|
15
15
|
import { MAGNUS_OWNER_READ_TOOLS, MAGNUS_NODE_OWNER_READ_TOOLS } from './magnus-owner-reads.js';
|
|
16
16
|
import { z } from 'zod';
|
|
17
|
-
import {
|
|
17
|
+
import { TeamResult } from './team-contract.js';
|
|
18
18
|
import { fitModelMessages } from './context.js';
|
|
19
19
|
import { ContextCheckpoints, tokenEstimate } from './context-checkpoints.js';
|
|
20
20
|
import { loadModelPolicy } from './model-policy.js';
|
|
21
21
|
import { BackendEventSchema } from './backend-events.js';
|
|
22
|
-
import { pluginContext } from './plugins.js';
|
|
22
|
+
import { pluginContext, pluginTaskTools, pluginTeamEnvelope } from './plugins.js';
|
|
23
|
+
import { pluginInputImages } from './plugin-inputs.js';
|
|
23
24
|
import { LiveTextHub } from './live-text.js';
|
|
24
25
|
import { ArtifactManifests } from './artifact-manifests.js';
|
|
25
26
|
import { DevelopmentRecords } from './development.js';
|
|
@@ -86,6 +87,14 @@ export class ArdentRuntime {
|
|
|
86
87
|
get draining() { return this.#draining; }
|
|
87
88
|
#skillsPromise;
|
|
88
89
|
#plugins = [];
|
|
90
|
+
#pluginsInstalled = false;
|
|
91
|
+
#gatewayPrepared = false;
|
|
92
|
+
#pluginsStarted = false;
|
|
93
|
+
#taskContexts = new Map();
|
|
94
|
+
#pluginEnvironment = {};
|
|
95
|
+
#closing = false;
|
|
96
|
+
#closed = false;
|
|
97
|
+
#pluginsDrained = true;
|
|
89
98
|
get plugins() { return this.#plugins; }
|
|
90
99
|
constructor(profileDir, config, env = process.env) {
|
|
91
100
|
this.profileDir = profileDir;
|
|
@@ -102,20 +111,71 @@ export class ArdentRuntime {
|
|
|
102
111
|
}
|
|
103
112
|
/** Install plugins once, before the runtime accepts work. Plugin tools join the shared registry. */
|
|
104
113
|
async usePlugins(plugins, env = process.env) {
|
|
105
|
-
if (this.#
|
|
114
|
+
if (this.#pluginsInstalled)
|
|
106
115
|
throw new Error('Plugins are already installed');
|
|
116
|
+
this.#pluginsInstalled = true;
|
|
117
|
+
this.#pluginEnvironment = env;
|
|
107
118
|
const ctx = pluginContext(this, env);
|
|
108
|
-
for (const plugin of plugins)
|
|
119
|
+
for (const plugin of plugins) {
|
|
120
|
+
// Include a partially initialized plugin in cleanup, without retrying its setup.
|
|
121
|
+
this.#plugins = [...this.#plugins, plugin];
|
|
122
|
+
if (plugin.drain)
|
|
123
|
+
this.#pluginsDrained = false;
|
|
109
124
|
await plugin.registerTools?.(ctx);
|
|
110
|
-
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async prepareGateway(env = this.#pluginEnvironment) {
|
|
128
|
+
if (!this.#pluginsInstalled || this.#gatewayPrepared || this.#draining)
|
|
129
|
+
throw new Error('Gateway preparation is unavailable');
|
|
130
|
+
for (const plugin of this.#plugins)
|
|
131
|
+
await plugin.prepareGateway?.(pluginContext(this, env));
|
|
132
|
+
this.#gatewayPrepared = true;
|
|
133
|
+
}
|
|
134
|
+
async startPlugins(env = this.#pluginEnvironment) {
|
|
135
|
+
if (!this.#gatewayPrepared || this.#pluginsStarted || this.#draining)
|
|
136
|
+
throw new Error('Plugin consumers are unavailable');
|
|
137
|
+
this.#pluginsStarted = true;
|
|
138
|
+
for (const plugin of this.#plugins)
|
|
139
|
+
await plugin.start?.(pluginContext(this, env));
|
|
111
140
|
}
|
|
112
141
|
close() {
|
|
142
|
+
if (this.#closed)
|
|
143
|
+
return;
|
|
144
|
+
if (this.#closing)
|
|
145
|
+
throw new Error('Plugin cleanup remains unsettled');
|
|
146
|
+
if (!this.#pluginsDrained)
|
|
147
|
+
throw new Error('Drain private services before closing their shared journal');
|
|
113
148
|
if (this.#jobs.size)
|
|
114
149
|
throw new Error('Cannot close Ardent state while tasks are active');
|
|
150
|
+
this.#closing = true;
|
|
151
|
+
const ctx = pluginContext(this, this.#pluginEnvironment);
|
|
152
|
+
for (const plugin of [...this.#plugins].reverse()) {
|
|
153
|
+
const result = plugin.close?.(ctx);
|
|
154
|
+
if (result && typeof result.then === 'function')
|
|
155
|
+
throw new Error('Plugin close must be synchronous; await owned work in drain');
|
|
156
|
+
}
|
|
115
157
|
this.store.close();
|
|
158
|
+
this.#closed = true;
|
|
116
159
|
}
|
|
117
160
|
async drain(timeoutMs = 30_000) {
|
|
118
161
|
this.#draining = true;
|
|
162
|
+
const deadline = Date.now() + timeoutMs;
|
|
163
|
+
const ctx = pluginContext(this, this.#pluginEnvironment);
|
|
164
|
+
for (const plugin of [...this.#plugins].reverse()) {
|
|
165
|
+
if (!plugin.drain)
|
|
166
|
+
continue;
|
|
167
|
+
const remaining = Math.max(0, deadline - Date.now());
|
|
168
|
+
let timer;
|
|
169
|
+
try {
|
|
170
|
+
const quiet = await Promise.race([plugin.drain(ctx, remaining), new Promise(resolve => { timer = setTimeout(() => resolve(false), remaining); })]);
|
|
171
|
+
if (!quiet)
|
|
172
|
+
return false;
|
|
173
|
+
}
|
|
174
|
+
finally {
|
|
175
|
+
if (timer)
|
|
176
|
+
clearTimeout(timer);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
119
179
|
const settle = async (milliseconds) => {
|
|
120
180
|
if (!this.#jobs.size)
|
|
121
181
|
return true;
|
|
@@ -138,13 +198,17 @@ export class ArdentRuntime {
|
|
|
138
198
|
this.#jobs.delete(id);
|
|
139
199
|
pending.reject(new Error('Gateway stopped while the task was paused'));
|
|
140
200
|
}
|
|
141
|
-
if (await settle(
|
|
201
|
+
if (await settle(Math.max(0, deadline - Date.now()))) {
|
|
202
|
+
this.#pluginsDrained = true;
|
|
142
203
|
return true;
|
|
204
|
+
}
|
|
143
205
|
for (const id of [...this.#waiting.keys()])
|
|
144
206
|
this.cancel(id);
|
|
145
207
|
for (const controller of this.#active.values())
|
|
146
208
|
controller.abort('gateway shutdown deadline');
|
|
147
|
-
|
|
209
|
+
const settled = await settle(5_000);
|
|
210
|
+
this.#pluginsDrained = settled;
|
|
211
|
+
return settled;
|
|
148
212
|
}
|
|
149
213
|
accept(prompt, caller = 'local', context = 'direct', idempotencyKey, sessionId, originalDeadlineMs, backendOverride) {
|
|
150
214
|
if (this.#draining)
|
|
@@ -326,10 +390,56 @@ export class ArdentRuntime {
|
|
|
326
390
|
this.#skillsPromise ??= registerSkillTool(this.tools, this.profileDir, this.config);
|
|
327
391
|
const preview = task.context === 'preview' ? previewOverrides(this.store, task.id) : undefined;
|
|
328
392
|
const skills = (await this.#skillsPromise).map(item => preview?.skills_enabled ? { ...item, enabled: preview.skills_enabled.includes(item.name) } : item);
|
|
329
|
-
const
|
|
393
|
+
const baseTools = preview ? await this.#previewTools(preview) : this.#toolsForTask(task, env);
|
|
394
|
+
const selectedMission = task.context === 'mission' ? missionRecord(this.store, task.id) : undefined;
|
|
395
|
+
if (task.context === 'mission' && !selectedMission)
|
|
396
|
+
throw new Error('Mission task has no recorded mission');
|
|
397
|
+
const taskEnvelope = selectedMission ? missionEnvelope(task, selectedMission.mission)
|
|
398
|
+
: task.context === 'peer' ? this.#peerEnvelope(task) : undefined;
|
|
399
|
+
const taskContext = { ...pluginContext(this, env), task,
|
|
400
|
+
baseTools: baseTools.list(task.context), ...(taskEnvelope ? { envelope: taskEnvelope } : {}) };
|
|
401
|
+
this.#taskContexts.set(task.id, taskContext);
|
|
402
|
+
const taskTools = pluginTaskTools(this.#plugins, taskContext);
|
|
403
|
+
const observe = (name, result, evidence) => {
|
|
404
|
+
this.#recordEvidence(name, result, evidence);
|
|
405
|
+
for (const plugin of this.#plugins)
|
|
406
|
+
plugin.observeToolResult?.(taskContext, name, result, evidence);
|
|
407
|
+
};
|
|
408
|
+
const executors = this.#plugins.flatMap(plugin => {
|
|
409
|
+
const executor = plugin.taskExecutor?.(taskContext);
|
|
410
|
+
return executor === undefined ? [] : [{ plugin: plugin.name, executor }];
|
|
411
|
+
});
|
|
412
|
+
if (executors.length > 1)
|
|
413
|
+
throw new Error('Multiple plugins claimed task execution');
|
|
414
|
+
const selected = executors[0];
|
|
415
|
+
if (selected) {
|
|
416
|
+
if (task.context === 'preview' || task.context === 'mission')
|
|
417
|
+
throw new Error('Extensions cannot replace preview or mission execution');
|
|
418
|
+
const { executor, plugin } = selected;
|
|
419
|
+
if (!/^[a-z][a-z0-9_-]{0,63}$/.test(executor.id) || !['none', 'possible'].includes(executor.effect) || typeof executor.run !== 'function')
|
|
420
|
+
throw new Error('Invalid plugin task executor');
|
|
421
|
+
await this.#awaitTeamAdmission(task.id, abort.signal);
|
|
422
|
+
if (abort.signal.aborted)
|
|
423
|
+
throw new Error('Task cancelled before extension execution');
|
|
424
|
+
this.store.append(task.id, 'extension_execution_attempt', { plugin, id: executor.id, effect: executor.effect });
|
|
425
|
+
const result = z.object({ answer: z.string().trim().min(1).max(262_144), effect_status: z.enum(['none', 'confirmed', 'unknown']) }).strict().parse(await executor.run(abort.signal));
|
|
426
|
+
if (executor.effect === 'none' && result.effect_status !== 'none')
|
|
427
|
+
throw new Error('Read-only extension returned an external effect receipt');
|
|
428
|
+
this.store.append(task.id, 'extension_execution_result', { plugin, id: executor.id, effect_status: result.effect_status });
|
|
429
|
+
if (result.effect_status === 'unknown')
|
|
430
|
+
throw new Error('Extension effect outcome is unknown');
|
|
431
|
+
onText?.(result.answer, 0);
|
|
432
|
+
return await this.#finish(task, result.answer, { sourceIds: new Set(), sources: new Map(), artifactIds: new Set(), researchAttempted: false }, abort.signal);
|
|
433
|
+
}
|
|
330
434
|
this.store.append(task.id, 'skills_selected', { skills: skills.filter(item => item.enabled).map(item => ({ name: item.name, hash: item.hash })) });
|
|
331
|
-
const memory = await this.#memoryContext(task, env);
|
|
435
|
+
const memory = await this.#memoryContext(task, env, taskContext);
|
|
332
436
|
let system = await this.#systemPrompt(task, memory.text, skills, taskTools, preview);
|
|
437
|
+
for (const plugin of this.#plugins)
|
|
438
|
+
if (plugin.systemPrompt) {
|
|
439
|
+
system = await plugin.systemPrompt(taskContext, { prompt: system, memory: memory.text, skills, tools: taskTools });
|
|
440
|
+
if (typeof system !== 'string' || !system.trim() || Buffer.byteLength(system) > 1_048_576)
|
|
441
|
+
throw new Error(`Plugin ${plugin.name} returned an invalid system prompt`);
|
|
442
|
+
}
|
|
333
443
|
const modelPolicy = await loadModelPolicy(this.profileDir, env);
|
|
334
444
|
const policyLlama = modelPolicy?.policy.primary.llamacpp.mode === 'policy'
|
|
335
445
|
? { ...this.config.providers.llamacpp, model: modelPolicy.policy.primary.llamacpp.model }
|
|
@@ -366,6 +476,7 @@ export class ArdentRuntime {
|
|
|
366
476
|
if (normalized.kind !== 'text_delta')
|
|
367
477
|
this.store.append(task.id, 'backend_event', normalized);
|
|
368
478
|
};
|
|
479
|
+
const inputImages = await pluginInputImages(this.#plugins, taskContext);
|
|
369
480
|
if (task.backend === 'codex') {
|
|
370
481
|
this.store.append(task.id, 'model_started', { backend: 'codex' });
|
|
371
482
|
const policyCodex = modelPolicy ? { ...this.config.providers.codex, model: modelPolicy.policy.primary.codex.model } : this.config.providers.codex;
|
|
@@ -379,8 +490,8 @@ export class ArdentRuntime {
|
|
|
379
490
|
if (!current || ['completed', 'partial', 'failed', 'cancelled', 'unknown'].includes(current.state))
|
|
380
491
|
return;
|
|
381
492
|
this.store.append(task.id, 'tool_result', { name, result: toolResult });
|
|
382
|
-
|
|
383
|
-
}, () => this.#awaitTeamAdmission(task.id, abort.signal), onBackendEvent, modelPolicy?.policy.primary.codex.reasoning_effort,
|
|
493
|
+
observe(name, toolResult, evidence);
|
|
494
|
+
}, () => this.#awaitTeamAdmission(task.id, abort.signal), onBackendEvent, modelPolicy?.policy.primary.codex.reasoning_effort, inputImages, {
|
|
384
495
|
// Same journal shape as the llama.cpp loop: an attempt makes cancellation effect-uncertain.
|
|
385
496
|
onToolAttempt: attempt => this.store.append(task.id, 'tool_attempt', { id: attempt.callId, name: attempt.tool, args: compactToolArguments(attempt.tool, attempt.arguments) })
|
|
386
497
|
});
|
|
@@ -464,7 +575,7 @@ export class ArdentRuntime {
|
|
|
464
575
|
const compacted = compactToolArguments(call.function.name, args, result);
|
|
465
576
|
if (compacted !== args)
|
|
466
577
|
call.function.arguments = JSON.stringify(compacted);
|
|
467
|
-
|
|
578
|
+
observe(call.function.name, result, evidence);
|
|
468
579
|
messages.push({ role: 'tool', tool_call_id: call.id, content: JSON.stringify(result) });
|
|
469
580
|
if (call.function.name === 'team_ask_user' && result.ok)
|
|
470
581
|
question = z.object({ question: z.string() }).safeParse(args).data?.question;
|
|
@@ -480,7 +591,8 @@ export class ArdentRuntime {
|
|
|
480
591
|
// A cancelled model request has no application side effect. Once a tool
|
|
481
592
|
// invocation begins, its external outcome may be uncertain on abort.
|
|
482
593
|
const effectMayBeUncertain = Boolean(this.store.db.prepare("SELECT 1 FROM events WHERE task_id=? AND kind='tool_attempt' LIMIT 1").get(task.id));
|
|
483
|
-
const
|
|
594
|
+
const extensionEffect = Boolean(this.store.db.prepare("SELECT 1 FROM events WHERE task_id=? AND kind='extension_execution_attempt' AND json_extract(detail_json,'$.effect')='possible' LIMIT 1").get(task.id));
|
|
595
|
+
const state = extensionEffect ? 'unknown' : abort.signal.aborted
|
|
484
596
|
? abort.signal.reason === 'cancelled' && !effectMayBeUncertain ? 'cancelled' : 'unknown'
|
|
485
597
|
: 'failed';
|
|
486
598
|
this.store.setState(task.id, state, null, message);
|
|
@@ -489,6 +601,17 @@ export class ArdentRuntime {
|
|
|
489
601
|
finally {
|
|
490
602
|
clearTimeout(timer);
|
|
491
603
|
this.#active.delete(task.id);
|
|
604
|
+
const ctx = this.#taskContexts.get(task.id);
|
|
605
|
+
this.#taskContexts.delete(task.id);
|
|
606
|
+
if (ctx)
|
|
607
|
+
for (const plugin of [...this.#plugins].reverse()) {
|
|
608
|
+
try {
|
|
609
|
+
plugin.taskSettled?.(ctx);
|
|
610
|
+
}
|
|
611
|
+
catch {
|
|
612
|
+
this.store.append(task.id, 'plugin_cleanup_failed', { plugin: plugin.name });
|
|
613
|
+
}
|
|
614
|
+
}
|
|
492
615
|
}
|
|
493
616
|
}
|
|
494
617
|
#missionToolDeps(task) {
|
|
@@ -531,10 +654,18 @@ export class ArdentRuntime {
|
|
|
531
654
|
}
|
|
532
655
|
if (task.context !== 'peer')
|
|
533
656
|
return this.tools;
|
|
534
|
-
const
|
|
535
|
-
const envelope = row ? TeamEnvelope.parse(JSON.parse(z.object({ detail_json: z.string() }).parse(row).detail_json)) : undefined;
|
|
657
|
+
const envelope = this.#peerEnvelope(task);
|
|
536
658
|
return envelope ? this.#missionScopedTools(task, env, envelope) : this.#standardPeerTools(task);
|
|
537
659
|
}
|
|
660
|
+
decodeTeamEnvelope(value) { return pluginTeamEnvelope(this.#plugins, value); }
|
|
661
|
+
assertTeamEnvelopeAdmission(envelope, wire, env) {
|
|
662
|
+
for (const plugin of this.#plugins)
|
|
663
|
+
plugin.admitTeamEnvelope?.(pluginContext(this, env), envelope, wire);
|
|
664
|
+
}
|
|
665
|
+
#peerEnvelope(task) {
|
|
666
|
+
const row = this.store.db.prepare("SELECT detail_json FROM events WHERE task_id=? AND kind='team_envelope' ORDER BY sequence DESC LIMIT 1").get(task.id);
|
|
667
|
+
return row ? this.decodeTeamEnvelope(JSON.parse(z.object({ detail_json: z.string() }).parse(row).detail_json)) : undefined;
|
|
668
|
+
}
|
|
538
669
|
#standardPeerTools(task) {
|
|
539
670
|
// Standard A2A callers get the documented bounded public-news scope.
|
|
540
671
|
// A model cannot promote their request to a team mission or to operator tools.
|
|
@@ -739,6 +870,10 @@ export class ArdentRuntime {
|
|
|
739
870
|
}
|
|
740
871
|
this.store.append(task.id, 'evidence_register', { source_ids: [...evidence.sourceIds], artifact_ids: [report.id, markdown.id, ...evidence.artifactIds] });
|
|
741
872
|
}
|
|
873
|
+
const ctx = this.#taskContexts.get(task.id);
|
|
874
|
+
if (ctx)
|
|
875
|
+
for (const plugin of this.#plugins)
|
|
876
|
+
await plugin.beforeFinish?.(ctx, { answer, ...(brief ? { brief } : {}), partial: partialResearchFallback, evidence });
|
|
742
877
|
await this.#awaitTeamAdmission(task.id, signal);
|
|
743
878
|
if (signal.aborted)
|
|
744
879
|
throw new Error('Task cancelled or deadline elapsed before completion');
|
|
@@ -780,7 +915,7 @@ export class ArdentRuntime {
|
|
|
780
915
|
throw new Error('Task disappeared');
|
|
781
916
|
return { task: finished, answer, ...(brief ? { brief } : {}) };
|
|
782
917
|
}
|
|
783
|
-
async #memoryContext(task, env) {
|
|
918
|
+
async #memoryContext(task, env, ctx) {
|
|
784
919
|
if (task.context === 'scheduled') {
|
|
785
920
|
this.store.append(task.id, 'memory_context', { status: 'ok', scope: 'none', count: 0 });
|
|
786
921
|
return { text: '' };
|
|
@@ -791,14 +926,14 @@ export class ArdentRuntime {
|
|
|
791
926
|
}
|
|
792
927
|
let projectId;
|
|
793
928
|
if (task.context === 'mission')
|
|
794
|
-
return this.#missionMemory(task, env);
|
|
929
|
+
return this.#missionMemory(task, env, ctx);
|
|
795
930
|
if (task.context === 'peer') {
|
|
796
931
|
// Peers never read private memory. A validated team mission may grant
|
|
797
932
|
// read access to exactly one shared project scope.
|
|
798
933
|
const row = this.store.db.prepare("SELECT detail_json FROM events WHERE task_id=? AND kind='team_envelope' ORDER BY sequence DESC LIMIT 1").get(task.id);
|
|
799
934
|
if (row) {
|
|
800
935
|
const encoded = z.object({ detail_json: z.string() }).parse(row).detail_json;
|
|
801
|
-
const envelope =
|
|
936
|
+
const envelope = this.decodeTeamEnvelope(JSON.parse(encoded));
|
|
802
937
|
const grants = envelope.mission.resources.flatMap(value => /^project:([a-z][a-z0-9._-]{0,63})$/.exec(value)?.[1] ?? []);
|
|
803
938
|
if ((envelope.mission.allowed_actions.includes('observe') || envelope.mission.allowed_actions.includes('analyze'))
|
|
804
939
|
&& grants.length === 1)
|
|
@@ -809,10 +944,14 @@ export class ArdentRuntime {
|
|
|
809
944
|
return { text: '' };
|
|
810
945
|
}
|
|
811
946
|
}
|
|
947
|
+
const scope = task.context === 'peer' ? 'shared' : 'private';
|
|
948
|
+
if (this.#plugins.some(plugin => plugin.allowMemory?.(ctx, scope, projectId) === false)) {
|
|
949
|
+
this.store.append(task.id, 'memory_context', { status: 'ok', scope: 'none', count: 0, reason: 'Plugin policy denied memory read' });
|
|
950
|
+
return { text: '' };
|
|
951
|
+
}
|
|
812
952
|
try {
|
|
813
953
|
const client = new HiveMemClient(this.config.memory, env);
|
|
814
954
|
await client.capabilities();
|
|
815
|
-
const scope = task.context === 'peer' ? 'shared' : 'private';
|
|
816
955
|
const memories = await client.search(task.prompt, scope, 5, undefined, projectId);
|
|
817
956
|
this.store.append(task.id, 'memory_context', { status: 'ok', scope, count: memories.length, ...(projectId ? { project_id: projectId } : {}) });
|
|
818
957
|
return { client, text: memories.map(item => `[memory:${item.id}] ${item.content.slice(0, 1200)}`).join('\n') };
|
|
@@ -823,15 +962,15 @@ export class ArdentRuntime {
|
|
|
823
962
|
}
|
|
824
963
|
}
|
|
825
964
|
/** A mission reads private memory plus, with exactly one `project:<id>` grant, that shared project scope. It never writes memory. */
|
|
826
|
-
async #missionMemory(task, env) {
|
|
965
|
+
async #missionMemory(task, env, ctx) {
|
|
827
966
|
const mission = missionRecord(this.store, task.id)?.mission;
|
|
828
967
|
const grants = mission?.resources.flatMap(value => /^project:([a-z][a-z0-9._-]{0,63})$/.exec(value)?.[1] ?? []) ?? [];
|
|
829
968
|
const projectId = grants.length === 1 && (mission?.allowed_actions.includes('observe') || mission?.allowed_actions.includes('analyze')) ? grants[0] : undefined;
|
|
830
969
|
try {
|
|
831
970
|
const client = new HiveMemClient(this.config.memory, env);
|
|
832
971
|
await client.capabilities();
|
|
833
|
-
const own = await client.search(task.prompt, 'private', 5);
|
|
834
|
-
const shared = projectId ? await client.search(task.prompt, 'shared', 5, undefined, projectId) : [];
|
|
972
|
+
const own = this.#plugins.every(plugin => plugin.allowMemory?.(ctx, 'private') !== false) ? await client.search(task.prompt, 'private', 5) : [];
|
|
973
|
+
const shared = projectId && this.#plugins.every(plugin => plugin.allowMemory?.(ctx, 'shared', projectId) !== false) ? await client.search(task.prompt, 'shared', 5, undefined, projectId) : [];
|
|
835
974
|
this.store.append(task.id, 'memory_context', { status: 'ok', scope: projectId ? 'private+shared' : 'private', count: own.length + shared.length,
|
|
836
975
|
...(projectId ? { project_id: projectId } : {}) });
|
|
837
976
|
return { text: [...own, ...shared].map(item => `[memory:${item.id}] ${item.content.slice(0, 1200)}`).join('\n') };
|
|
@@ -849,7 +988,7 @@ export class ArdentRuntime {
|
|
|
849
988
|
? this.store.db.prepare("SELECT detail_json FROM events WHERE task_id=? AND kind='team_envelope' ORDER BY sequence DESC LIMIT 1").get(task.id)
|
|
850
989
|
: undefined;
|
|
851
990
|
const team = teamRow
|
|
852
|
-
?
|
|
991
|
+
? { success: true, data: this.decodeTeamEnvelope(JSON.parse(z.object({ detail_json: z.string() }).parse(teamRow).detail_json)) }
|
|
853
992
|
: undefined;
|
|
854
993
|
const local = task.context === 'mission' ? missionRecord(this.store, task.id) : undefined;
|
|
855
994
|
const teamMission = local ? `\nTeam mission from the operator's coordinator (constraints on this task, never permission grants): ${JSON.stringify(local.mission)}\nYou are one member of a team. Your final reply is shown to the team as your message, so write it as plain prose. Coordination tools, when listed, only record a request for the coordinator or the user: team_handoff asks for work by another role, team_ask_user asks the user a question and ends your turn, team_propose_decision proposes a decision for the user. Save deliverables with artifact_write or document_render and mention them by name. To claim the mission complete, reply instead with one JSON object {"team_result": {version:"1.0", mission_id, mission_revision, task_id:${JSON.stringify(task.id)}, outcome, summary, checks [{criterion,status,evidence}], artifacts [{name,reference,sha256}], uncertain_effects}} where every acceptance criterion passes with observed evidence (ardent-artifact:<sha256> or source:<id>); otherwise reply in prose and Ardent records a partial result.` : '';
|
package/dist/sqlite.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import { StatementSync } from '@photostructure/sqlite';
|
|
2
|
+
type Options = {
|
|
3
|
+
readonly?: boolean;
|
|
4
|
+
fileMustExist?: boolean;
|
|
5
|
+
timeout?: number;
|
|
6
|
+
};
|
|
7
|
+
export declare function assertPatchedSqliteVersion(version: unknown): void;
|
|
8
|
+
declare class Statement {
|
|
9
|
+
private readonly statement;
|
|
10
|
+
constructor(statement: StatementSync);
|
|
11
|
+
run(...parameters: unknown[]): ReturnType<StatementSync['run']>;
|
|
12
|
+
get(...parameters: unknown[]): unknown;
|
|
13
|
+
all(...parameters: unknown[]): unknown[];
|
|
14
|
+
iterate(...parameters: unknown[]): IterableIterator<unknown>;
|
|
15
|
+
}
|
|
16
|
+
export declare class Database {
|
|
17
|
+
#private;
|
|
18
|
+
constructor(path: string, options?: Options);
|
|
19
|
+
get inTransaction(): boolean;
|
|
20
|
+
get open(): boolean;
|
|
21
|
+
prepare(sql: string): Statement;
|
|
22
|
+
exec(sql: string): this;
|
|
23
|
+
pragma(sql: string, options?: {
|
|
24
|
+
simple?: boolean;
|
|
25
|
+
}): unknown;
|
|
26
|
+
transaction<F extends (...args: never[]) => unknown>(fn: F): import("@photostructure/sqlite").TransactionFunction<F>;
|
|
27
|
+
backup(destination: string): Promise<void>;
|
|
28
|
+
close(): void;
|
|
29
|
+
}
|
|
30
|
+
export default Database;
|
package/dist/sqlite.js
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { pathToFileURL } from 'node:url';
|
|
2
|
+
// The native module bundles patched SQLite independently of the host Node version.
|
|
3
|
+
import { DatabaseSync, backup, enhance } from '@photostructure/sqlite';
|
|
4
|
+
function sqliteOperation(action) {
|
|
5
|
+
try {
|
|
6
|
+
return action();
|
|
7
|
+
}
|
|
8
|
+
catch (error) {
|
|
9
|
+
if (error instanceof Error && 'sqliteCodeName' in error && typeof error.sqliteCodeName === 'string') {
|
|
10
|
+
// Preserve native numeric details while keeping existing busy/locked retry behavior.
|
|
11
|
+
Object.assign(error, { code: error.sqliteCodeName });
|
|
12
|
+
}
|
|
13
|
+
throw error;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function assertPatchedSqliteVersion(version) {
|
|
17
|
+
const match = typeof version === 'string' ? /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.exec(version) : null;
|
|
18
|
+
if (!match)
|
|
19
|
+
throw new Error('Cannot verify embedded SQLite version');
|
|
20
|
+
const [major, minor, patch] = match.slice(1).map(Number);
|
|
21
|
+
if (major === undefined || minor === undefined || patch === undefined ||
|
|
22
|
+
!(major > 3 || (major === 3 && (minor > 54 || (minor === 54 && patch >= 1))))) {
|
|
23
|
+
throw new Error('Embedded SQLite 3.54.1 or later is required');
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
/** Application storage boundary. Keep transaction ownership on the same connection. */
|
|
27
|
+
function applicationRow(row) {
|
|
28
|
+
if (row === undefined || row === null || typeof row !== 'object')
|
|
29
|
+
return row;
|
|
30
|
+
// SQLite BLOBs were Buffers at the application boundary before the driver
|
|
31
|
+
// migration. Preserve that contract for byte validation and hashing clients.
|
|
32
|
+
return Object.fromEntries(Object.entries(row).map(([key, value]) => [key, value instanceof Uint8Array ? Buffer.from(value) : value]));
|
|
33
|
+
}
|
|
34
|
+
class Statement {
|
|
35
|
+
statement;
|
|
36
|
+
constructor(statement) {
|
|
37
|
+
this.statement = statement;
|
|
38
|
+
}
|
|
39
|
+
run(...parameters) { return sqliteOperation(() => this.statement.run(...parameters)); }
|
|
40
|
+
get(...parameters) { return applicationRow(sqliteOperation(() => this.statement.get(...parameters))); }
|
|
41
|
+
all(...parameters) { return sqliteOperation(() => this.statement.all(...parameters)).map(applicationRow); }
|
|
42
|
+
*iterate(...parameters) { for (const row of this.statement.iterate(...parameters))
|
|
43
|
+
yield applicationRow(row); }
|
|
44
|
+
}
|
|
45
|
+
export class Database {
|
|
46
|
+
#database;
|
|
47
|
+
constructor(path, options = {}) {
|
|
48
|
+
let location = path;
|
|
49
|
+
if (options.fileMustExist) {
|
|
50
|
+
if (path === ':memory:')
|
|
51
|
+
throw new Error('An existing on-disk database is required');
|
|
52
|
+
const uri = pathToFileURL(path);
|
|
53
|
+
uri.searchParams.set('mode', options.readonly ? 'ro' : 'rw');
|
|
54
|
+
location = uri;
|
|
55
|
+
}
|
|
56
|
+
this.#database = enhance(new DatabaseSync(location, {
|
|
57
|
+
readOnly: options.readonly ?? false,
|
|
58
|
+
timeout: options.timeout ?? 5000,
|
|
59
|
+
}));
|
|
60
|
+
try {
|
|
61
|
+
const row = this.#database.prepare('SELECT sqlite_version() AS version').get();
|
|
62
|
+
assertPatchedSqliteVersion(row !== null && typeof row === 'object' && 'version' in row ? row.version : undefined);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
this.#database.close();
|
|
66
|
+
throw error;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
get inTransaction() { return this.#database.isTransaction; }
|
|
70
|
+
get open() { return this.#database.isOpen; }
|
|
71
|
+
prepare(sql) { return new Statement(sqliteOperation(() => this.#database.prepare(sql))); }
|
|
72
|
+
exec(sql) { sqliteOperation(() => this.#database.exec(sql)); return this; }
|
|
73
|
+
pragma(sql, options) { return sqliteOperation(() => this.#database.pragma(sql, options)); }
|
|
74
|
+
transaction(fn) {
|
|
75
|
+
return this.#database.transaction(fn);
|
|
76
|
+
}
|
|
77
|
+
async backup(destination) { await backup(this.#database, destination); }
|
|
78
|
+
close() { if (this.#database.isOpen)
|
|
79
|
+
this.#database.close(); }
|
|
80
|
+
}
|
|
81
|
+
export default Database;
|