@hivemagnus/ardent 3.1.3 → 3.2.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.
Files changed (79) hide show
  1. package/README.md +504 -16
  2. package/dist/a2a-client.d.ts +26 -4
  3. package/dist/a2a-client.js +91 -23
  4. package/dist/a2a-push-inbox.d.ts +2 -0
  5. package/dist/a2a-push-inbox.js +7 -0
  6. package/dist/a2a-push.d.ts +1 -1
  7. package/dist/a2a-push.js +26 -18
  8. package/dist/a2a-server.d.ts +17 -0
  9. package/dist/a2a-server.js +91 -14
  10. package/dist/a2a.d.ts +19 -1
  11. package/dist/a2a.js +197 -27
  12. package/dist/api.d.ts +2 -0
  13. package/dist/api.js +160 -22
  14. package/dist/artifact-manifests.d.ts +344 -5
  15. package/dist/artifact-manifests.js +413 -20
  16. package/dist/artifact-transfer.d.ts +113 -0
  17. package/dist/artifact-transfer.js +517 -0
  18. package/dist/artifacts.d.ts +86 -0
  19. package/dist/artifacts.js +249 -1
  20. package/dist/backend-events.d.ts +2 -1
  21. package/dist/backend-events.js +1 -1
  22. package/dist/channel-catchup.d.ts +67 -0
  23. package/dist/channel-catchup.js +108 -0
  24. package/dist/channels.d.ts +35 -0
  25. package/dist/channels.js +152 -4
  26. package/dist/cli.js +28 -3
  27. package/dist/codex-protocol.d.ts +22 -0
  28. package/dist/codex-protocol.js +19 -0
  29. package/dist/codex.d.ts +32 -3
  30. package/dist/codex.js +91 -17
  31. package/dist/config.d.ts +25 -2
  32. package/dist/config.js +41 -4
  33. package/dist/development.d.ts +6 -6
  34. package/dist/execution-state.d.ts +245 -0
  35. package/dist/execution-state.js +236 -0
  36. package/dist/execution.d.ts +135 -0
  37. package/dist/execution.js +178 -0
  38. package/dist/index.d.ts +7 -4
  39. package/dist/index.js +5 -3
  40. package/dist/job-engine.d.ts +2 -1
  41. package/dist/job-engine.js +33 -4
  42. package/dist/lineage.d.ts +106 -0
  43. package/dist/lineage.js +145 -0
  44. package/dist/llamacpp.d.ts +32 -2
  45. package/dist/llamacpp.js +69 -33
  46. package/dist/mattermost.d.ts +8 -0
  47. package/dist/mattermost.js +250 -36
  48. package/dist/mission-tools.js +41 -5
  49. package/dist/missions.d.ts +5 -1
  50. package/dist/missions.js +10 -5
  51. package/dist/plugin-evidence.js +2 -1
  52. package/dist/plugin-sdk.d.ts +3 -0
  53. package/dist/plugin-sdk.js +3 -0
  54. package/dist/plugins.d.ts +108 -2
  55. package/dist/plugins.js +131 -1
  56. package/dist/preview.d.ts +1 -0
  57. package/dist/preview.js +4 -1
  58. package/dist/recovery.d.ts +155 -0
  59. package/dist/recovery.js +216 -0
  60. package/dist/research.d.ts +1 -1
  61. package/dist/retry.d.ts +143 -0
  62. package/dist/retry.js +127 -0
  63. package/dist/runtime.d.ts +56 -4
  64. package/dist/runtime.js +727 -125
  65. package/dist/store.d.ts +62 -7
  66. package/dist/store.js +86 -15
  67. package/dist/team-artifacts.d.ts +130 -112
  68. package/dist/team-artifacts.js +123 -151
  69. package/dist/team-child.d.ts +4 -1
  70. package/dist/team-child.js +21 -2
  71. package/dist/team-contract.d.ts +1 -1
  72. package/dist/telegram.d.ts +2 -0
  73. package/dist/telegram.js +83 -47
  74. package/dist/tool-scheduler.d.ts +84 -0
  75. package/dist/tool-scheduler.js +226 -0
  76. package/dist/tools.d.ts +78 -4
  77. package/dist/tools.js +34 -7
  78. package/package.json +16 -9
  79. package/profiles/assistant/config.yaml +2 -1
@@ -0,0 +1,84 @@
1
+ import { type ArdentPlugin, type ArdentTaskPluginContext } from './plugins.js';
2
+ import type { TaskEvidence } from './runtime.js';
3
+ import { type ExecutionContext, type Tool, type ToolContext, type ToolRegistry, type ToolResult } from './tools.js';
4
+ /** One model tool call, bound to the id the model gave it. */
5
+ export type ScheduledToolCall = {
6
+ id: string;
7
+ name: string;
8
+ arguments: unknown;
9
+ };
10
+ export type ScheduledToolOutcome = {
11
+ call: ScheduledToolCall;
12
+ result: ToolResult;
13
+ };
14
+ export type NotDispatchedReason = 'cancelled' | 'tool_call_limit' | 'batch_failed' | 'task_settled';
15
+ export type ToolSchedulerOptions = {
16
+ taskId: string;
17
+ context: ToolContext;
18
+ tools: ToolRegistry;
19
+ /** Parallel-eligible calls in flight at once (`execution.max_parallel_tool_calls`). */
20
+ limit: number;
21
+ /** Dispatches allowed for the whole task (`execution.max_tool_calls`). */
22
+ maxToolCalls: number;
23
+ signal: AbortSignal;
24
+ /**
25
+ * Append a task journal event. For `tool_attempt`, `tool_result` and
26
+ * `tool_not_dispatched` the call is passed too, so the runtime writes its
27
+ * execution checkpoint (`tool_invocations`, `execution_state`) in the same
28
+ * transaction as the event.
29
+ */
30
+ journal(kind: string, detail: unknown, boundary?: ToolBoundary): void;
31
+ /** Operator pause: resolves when the task may dispatch, rejects on abort. */
32
+ pauseGate(signal: AbortSignal): Promise<void>;
33
+ /** Team admission boundary, after the attempt is journaled and before invocation. */
34
+ admissionGate(signal: AbortSignal): Promise<void>;
35
+ /** The journal shape of the arguments (`compactToolArguments`). */
36
+ journalArguments?(name: string, args: unknown): unknown;
37
+ /** Runtime evidence recording, before plugin observers. */
38
+ recordEvidence?(name: string, result: ToolResult): void;
39
+ /** False once the task's terminal state is recorded; later results are not journaled. */
40
+ accepting?(): boolean;
41
+ plugins?: readonly ArdentPlugin[];
42
+ pluginContext?: ArdentTaskPluginContext;
43
+ evidence?: TaskEvidence;
44
+ execution?: ExecutionContext;
45
+ /** Dispatches already counted toward `maxToolCalls` (a resumed task's recorded tool count). */
46
+ initialDispatched?: number;
47
+ /** The idempotency key of a call carried over from an earlier attempt; default `toolIdempotencyKey(taskId, id)`. */
48
+ idempotencyKeyFor?(callId: string): string | undefined;
49
+ /** A recorded outcome to return instead of dispatching (a settled call reused on resume). It is never dispatched again. */
50
+ reuse?(call: ScheduledToolCall): ToolResult | undefined;
51
+ };
52
+ /** The call a boundary journal event belongs to. `arguments` are the full (uncompacted) arguments. */
53
+ export type ToolBoundary = {
54
+ call: ScheduledToolCall;
55
+ effect: Tool['effect'] | undefined;
56
+ idempotencyKey: string;
57
+ result?: ToolResult;
58
+ };
59
+ /** The idempotency key a tool receives: `sha256("<taskId>:<callId>")`, stable for one model call. */
60
+ export declare function toolIdempotencyKey(taskId: string, callId: string): string;
61
+ /**
62
+ * Dispatches one task's tool calls under a single policy for every backend.
63
+ *
64
+ * Calls are admitted strictly in arrival (emitted) order. A parallel-eligible
65
+ * call (a `read` tool, or one declaring `concurrency: 'parallel'`) shares a
66
+ * slot with the calls around it, at most `limit` at once. Any other call is a
67
+ * barrier: it starts after every earlier call settled, and later calls wait for
68
+ * it. Each dispatch pauses, checks the tool-call limit, journals the attempt,
69
+ * passes team admission, asks plugins, invokes, journals the result and tells
70
+ * observers, in that order. On abort, queued calls settle without dispatch;
71
+ * calls already started keep their uncertainty.
72
+ */
73
+ export declare class ToolScheduler {
74
+ #private;
75
+ constructor(options: ToolSchedulerOptions);
76
+ /** Calls journaled as attempted so far. */
77
+ get dispatched(): number;
78
+ /** Run one model turn's calls; results come back in emitted order. */
79
+ runBatch(calls: readonly ScheduledToolCall[]): Promise<ScheduledToolOutcome[]>;
80
+ /** Dispatch one call. Admission order is the order of `dispatch` calls. */
81
+ dispatch(call: ScheduledToolCall): Promise<ToolResult>;
82
+ /** Wait for cancellation callbacks already started; call before per-task cleanup. */
83
+ quiesce(): Promise<void>;
84
+ }
@@ -0,0 +1,226 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { frozenCopy, observePluginToolResult, pluginBeforeToolCall, runPluginObservers } from './plugins.js';
3
+ import { ToolCallLimitError, toolRunsInParallel } from './tools.js';
4
+ /** The idempotency key a tool receives: `sha256("<taskId>:<callId>")`, stable for one model call. */
5
+ export function toolIdempotencyKey(taskId, callId) {
6
+ return createHash('sha256').update(`${taskId}:${callId}`).digest('hex');
7
+ }
8
+ /**
9
+ * Dispatches one task's tool calls under a single policy for every backend.
10
+ *
11
+ * Calls are admitted strictly in arrival (emitted) order. A parallel-eligible
12
+ * call (a `read` tool, or one declaring `concurrency: 'parallel'`) shares a
13
+ * slot with the calls around it, at most `limit` at once. Any other call is a
14
+ * barrier: it starts after every earlier call settled, and later calls wait for
15
+ * it. Each dispatch pauses, checks the tool-call limit, journals the attempt,
16
+ * passes team admission, asks plugins, invokes, journals the result and tells
17
+ * observers, in that order. On abort, queued calls settle without dispatch;
18
+ * calls already started keep their uncertainty.
19
+ */
20
+ export class ToolScheduler {
21
+ #options;
22
+ #limit;
23
+ #queue = [];
24
+ #inFlight = new Set();
25
+ #hooks = new Set();
26
+ #hookChain = Promise.resolve();
27
+ #shared = 0;
28
+ #exclusive = false;
29
+ #dispatched = 0;
30
+ #closed;
31
+ constructor(options) {
32
+ this.#options = options;
33
+ this.#limit = Math.max(1, Math.min(16, Math.floor(options.limit)));
34
+ this.#dispatched = Math.max(0, Math.floor(options.initialDispatched ?? 0));
35
+ if (options.signal.aborted)
36
+ this.#closed = 'cancelled';
37
+ else
38
+ options.signal.addEventListener('abort', () => this.#abort(), { once: true });
39
+ }
40
+ /** Calls journaled as attempted so far. */
41
+ get dispatched() { return this.#dispatched; }
42
+ /** Run one model turn's calls; results come back in emitted order. */
43
+ async runBatch(calls) {
44
+ const settled = await Promise.allSettled(calls.map(call => this.dispatch(call)));
45
+ return settled.map((item, index) => {
46
+ if (item.status === 'rejected')
47
+ throw settled.find(entry => entry.status === 'rejected')?.reason ?? item.reason;
48
+ return { call: calls[index], result: item.value };
49
+ });
50
+ }
51
+ /** Dispatch one call. Admission order is the order of `dispatch` calls. */
52
+ dispatch(call) {
53
+ // A settled call is reused, never dispatched again; it takes no slot and no tool-call budget.
54
+ const reused = this.#options.reuse?.(call);
55
+ if (reused)
56
+ return Promise.resolve(reused);
57
+ const tool = this.#options.tools.get(call.name, this.#options.context);
58
+ // A question to the user ends the turn, so it never overlaps another call.
59
+ const parallel = call.name !== 'team_ask_user' && toolRunsInParallel(tool);
60
+ const admitted = this.#acquire(parallel);
61
+ return this.#run(call, tool, parallel, admitted);
62
+ }
63
+ /** Wait for cancellation callbacks already started; call before per-task cleanup. */
64
+ async quiesce() {
65
+ while (this.#hooks.size)
66
+ await Promise.allSettled([...this.#hooks]);
67
+ }
68
+ #key(callId) {
69
+ return this.#options.idempotencyKeyFor?.(callId) ?? toolIdempotencyKey(this.#options.taskId, callId);
70
+ }
71
+ async #run(call, tool, parallel, admitted) {
72
+ const options = this.#options;
73
+ try {
74
+ await admitted;
75
+ }
76
+ catch (reason) {
77
+ return this.#notDispatched(call, tool, this.#closed ?? (reason === 'tool_call_limit' || reason === 'batch_failed' || reason === 'task_settled' ? reason : 'cancelled'));
78
+ }
79
+ let entry;
80
+ try {
81
+ try {
82
+ await options.pauseGate(options.signal);
83
+ }
84
+ catch (error) {
85
+ if (options.signal.aborted)
86
+ return this.#notDispatched(call, tool, 'cancelled');
87
+ throw error;
88
+ }
89
+ if (this.#closed)
90
+ return this.#notDispatched(call, tool, this.#closed);
91
+ if (options.accepting && !options.accepting())
92
+ return this.#notDispatched(call, tool, 'task_settled');
93
+ if (this.#dispatched >= options.maxToolCalls) {
94
+ this.#close('tool_call_limit');
95
+ this.#notDispatched(call, tool, 'tool_call_limit');
96
+ throw new ToolCallLimitError();
97
+ }
98
+ this.#dispatched++;
99
+ const idempotencyKey = this.#key(call.id);
100
+ options.journal('tool_attempt', { id: call.id, name: call.name, args: options.journalArguments ? options.journalArguments(call.name, call.arguments) : call.arguments,
101
+ ...(tool ? { effect: tool.effect } : {}) }, { call, effect: tool?.effect, idempotencyKey });
102
+ entry = { call: this.#hookCall(call, tool, call.arguments, idempotencyKey), tool };
103
+ this.#inFlight.add(entry);
104
+ await options.admissionGate(options.signal);
105
+ const prepared = options.tools.prepare(call.name, call.arguments, options.context);
106
+ let result;
107
+ if ('result' in prepared)
108
+ result = prepared.result;
109
+ else {
110
+ entry.call = this.#hookCall(call, prepared.tool, prepared.input, idempotencyKey);
111
+ const denial = options.plugins && options.pluginContext
112
+ ? await pluginBeforeToolCall(options.plugins, options.pluginContext, entry.call, this.#failure) : undefined;
113
+ if (denial) {
114
+ options.journal('tool_denied_by_plugin', { id: call.id, name: call.name, plugin: denial.plugin, code: denial.code });
115
+ result = { ok: false, code: denial.code, message: denial.message, effect: 'none' };
116
+ }
117
+ else
118
+ result = await options.tools.invokePrepared(prepared, options.signal, { idempotencyKey, ...(options.execution ? { execution: options.execution } : {}) });
119
+ }
120
+ this.#inFlight.delete(entry);
121
+ // Never append a late result to a task whose terminal state is recorded.
122
+ if (options.accepting && !options.accepting())
123
+ return result;
124
+ options.journal('tool_result', { id: call.id, name: call.name, result }, { call, effect: tool?.effect, idempotencyKey, result });
125
+ options.recordEvidence?.(call.name, result);
126
+ if (options.plugins && options.pluginContext) {
127
+ if (options.evidence)
128
+ observePluginToolResult(options.plugins, options.pluginContext, call.name, result, options.evidence, this.#failure);
129
+ const view = entry.call;
130
+ const context = options.pluginContext;
131
+ await runPluginObservers(options.plugins, 'afterToolCall', plugin => plugin.afterToolCall?.(context, view, frozenCopy(result)), this.#failure);
132
+ }
133
+ return result;
134
+ }
135
+ catch (error) {
136
+ if (entry)
137
+ this.#inFlight.delete(entry);
138
+ // A failed dispatch fails the turn: nothing queued behind it may start.
139
+ if (!(error instanceof ToolCallLimitError))
140
+ this.#close(options.signal.aborted ? 'cancelled' : 'batch_failed');
141
+ throw error;
142
+ }
143
+ finally {
144
+ this.#release(parallel);
145
+ }
146
+ }
147
+ #hookCall(call, tool, args, idempotencyKey) {
148
+ let copied;
149
+ try {
150
+ copied = structuredClone(args);
151
+ }
152
+ catch {
153
+ copied = null;
154
+ }
155
+ return frozenCopy({ task_id: this.#options.taskId, call_id: call.id, name: call.name, arguments: copied,
156
+ effect: tool?.effect ?? 'read', idempotency_key: idempotencyKey, ...(this.#options.execution ? { execution: this.#options.execution } : {}) });
157
+ }
158
+ #failure = (plugin, hook) => {
159
+ if (this.#options.accepting && !this.#options.accepting())
160
+ return;
161
+ this.#options.journal('plugin_hook_failed', { plugin, hook });
162
+ };
163
+ #notDispatched(call, tool, reason) {
164
+ const result = { ok: false, code: 'CANCELLED',
165
+ message: reason === 'tool_call_limit' ? 'Tool-call limit reached before this call was dispatched'
166
+ : reason === 'batch_failed' ? 'An earlier call in this turn failed; this call was not dispatched'
167
+ : 'Task stopped before this call was dispatched', effect: 'none' };
168
+ if (!this.#options.accepting || this.#options.accepting())
169
+ this.#options.journal('tool_not_dispatched', { id: call.id, name: call.name, reason, effect: 'none' }, { call, effect: tool?.effect, idempotencyKey: this.#key(call.id), result });
170
+ if (reason === 'cancelled')
171
+ this.#cancelled(this.#hookCall(call, tool, call.arguments, this.#key(call.id)), { dispatched: false, effect: 'none' });
172
+ return result;
173
+ }
174
+ #cancelled(call, outcome) {
175
+ const { plugins, pluginContext } = this.#options;
176
+ if (!plugins?.some(plugin => plugin.toolCallCancelled) || !pluginContext)
177
+ return;
178
+ // One call's callbacks finish before the next call's start, in the order calls were stopped.
179
+ const done = this.#hookChain.then(() => runPluginObservers(plugins, 'toolCallCancelled', plugin => plugin.toolCallCancelled?.(pluginContext, call, frozenCopy(outcome)), this.#failure, { reverse: true }));
180
+ this.#hookChain = done;
181
+ this.#hooks.add(done);
182
+ void done.finally(() => this.#hooks.delete(done));
183
+ }
184
+ #abort() {
185
+ this.#close('cancelled');
186
+ // A started call keeps its uncertainty: only a read is known to have no effect.
187
+ for (const entry of this.#inFlight)
188
+ this.#cancelled(entry.call, { dispatched: true, effect: entry.tool?.effect === 'read' ? 'none' : 'unknown' });
189
+ }
190
+ #close(reason) {
191
+ this.#closed ??= reason;
192
+ for (const waiter of this.#queue.splice(0))
193
+ waiter.reject(this.#closed);
194
+ }
195
+ #acquire(parallel) {
196
+ if (this.#closed)
197
+ return Promise.reject(this.#closed);
198
+ return new Promise((resolve, reject) => { this.#queue.push({ parallel, resolve, reject }); this.#drain(); });
199
+ }
200
+ #drain() {
201
+ for (;;) {
202
+ const next = this.#queue[0];
203
+ if (!next || this.#exclusive)
204
+ return;
205
+ if (next.parallel) {
206
+ if (this.#shared >= this.#limit)
207
+ return;
208
+ this.#shared++;
209
+ }
210
+ else {
211
+ if (this.#shared > 0)
212
+ return;
213
+ this.#exclusive = true;
214
+ }
215
+ this.#queue.shift();
216
+ next.resolve();
217
+ }
218
+ }
219
+ #release(parallel) {
220
+ if (parallel)
221
+ this.#shared--;
222
+ else
223
+ this.#exclusive = false;
224
+ this.#drain();
225
+ }
226
+ }
package/dist/tools.d.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { z } from 'zod';
2
+ import type { ExecutionContext } from '@hivemagnus/hive-common/execution';
2
3
  import type { TaskContext } from './store.js';
4
+ export type { ExecutionContext } from '@hivemagnus/hive-common/execution';
3
5
  /** A task context in which a tool may run. Mission tools run only in `mission`. */
4
6
  export type ToolContext = TaskContext;
5
7
  export type ToolEffect = 'read' | 'artifact-write' | 'memory-write' | 'external-write';
@@ -8,6 +10,10 @@ export declare class ProvenNoEffectError extends Error {
8
10
  readonly code: string;
9
11
  constructor(message: string, code: string);
10
12
  }
13
+ /** The task reached `execution.max_tool_calls`; the call was not dispatched. */
14
+ export declare class ToolCallLimitError extends Error {
15
+ constructor(message?: string);
16
+ }
11
17
  export declare const ToolResultSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
12
18
  ok: z.ZodLiteral<true>;
13
19
  value: z.ZodOptional<z.ZodUnknown>;
@@ -16,11 +22,39 @@ export declare const ToolResultSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
16
22
  code: z.ZodString;
17
23
  message: z.ZodString;
18
24
  effect: z.ZodEnum<{
19
- none: "none";
20
25
  unknown: "unknown";
26
+ none: "none";
21
27
  }>;
22
28
  }, z.core.$strict>], "ok">;
23
29
  export type ToolResult = z.infer<typeof ToolResultSchema>;
30
+ /**
31
+ * Per-invocation identity passed to a tool. `idempotencyKey` is
32
+ * `sha256("<taskId>:<callId>")` (hex): stable for one model call, so a tool
33
+ * that forwards it to its service can make a repeated dispatch harmless.
34
+ * `execution` is attribution only and never grants access.
35
+ */
36
+ export type ToolInvocationContext = {
37
+ idempotencyKey: string;
38
+ execution?: ExecutionContext;
39
+ };
40
+ /** Identity a reconciliation hook receives for a call interrupted after dispatch. */
41
+ export type ToolReconcileContext = {
42
+ taskId: string;
43
+ callId: string;
44
+ idempotencyKey: string;
45
+ dispatchedMs: number;
46
+ execution?: ExecutionContext;
47
+ };
48
+ /** What a tool's own service proves about an interrupted call. `unknown` keeps the call held. */
49
+ export type ToolReconcileResult = {
50
+ status: 'applied';
51
+ value: unknown;
52
+ } | {
53
+ status: 'not_applied';
54
+ } | {
55
+ status: 'unknown';
56
+ };
57
+ export type ToolConcurrency = 'parallel' | 'serial';
24
58
  export interface Tool {
25
59
  name: string;
26
60
  description: string;
@@ -29,7 +63,29 @@ export interface Tool {
29
63
  effect: ToolEffect;
30
64
  contexts: readonly ToolContext[];
31
65
  timeoutMs: number;
32
- invoke(input: unknown, signal: AbortSignal): Promise<unknown>;
66
+ /**
67
+ * Repeating the call with identical arguments and idempotency key is safe.
68
+ * Execution recovery re-dispatches an interrupted idempotent call (with the
69
+ * same key) instead of holding it; declare it only when that is true.
70
+ */
71
+ idempotent?: boolean;
72
+ /**
73
+ * Scheduling within one model turn. By default a `read` tool may overlap
74
+ * other parallel-eligible calls and every other effect is serial (a barrier).
75
+ * `parallel` opts a non-read tool in; `serial` keeps a read tool exclusive.
76
+ */
77
+ concurrency?: ToolConcurrency;
78
+ /**
79
+ * Ask the tool's own service what happened to a call interrupted after
80
+ * dispatch (a crash or restart before its result was recorded). Only an
81
+ * outcome the service proves may be `applied` (its `value` must match
82
+ * `output`; it becomes the call's result) or `not_applied` (the model is
83
+ * told, and the call is not retried); anything else, a throw included, is
84
+ * `unknown` and holds the task for an operator. Execution recovery calls it
85
+ * before the task resumes, for a non-idempotent tool with a possible effect.
86
+ */
87
+ reconcile?(input: unknown, ctx: ToolReconcileContext, signal: AbortSignal): Promise<ToolReconcileResult>;
88
+ invoke(input: unknown, signal: AbortSignal, ctx?: ToolInvocationContext): Promise<unknown>;
33
89
  }
34
90
  export declare function defineTool<I extends z.ZodTypeAny, O extends z.ZodTypeAny>(definition: {
35
91
  name: string;
@@ -39,12 +95,30 @@ export declare function defineTool<I extends z.ZodTypeAny, O extends z.ZodTypeAn
39
95
  effect: ToolEffect;
40
96
  contexts: readonly ToolContext[];
41
97
  timeoutMs: number;
42
- handler: (input: z.infer<I>, signal: AbortSignal) => Promise<z.infer<O>>;
98
+ idempotent?: boolean;
99
+ concurrency?: ToolConcurrency;
100
+ reconcile?: (input: z.infer<I>, ctx: ToolReconcileContext, signal: AbortSignal) => Promise<ToolReconcileResult>;
101
+ handler: (input: z.infer<I>, signal: AbortSignal, ctx?: ToolInvocationContext) => Promise<z.infer<O>>;
43
102
  }): Tool;
103
+ /** Whether a tool may overlap other parallel-eligible calls in one model turn. */
104
+ export declare function toolRunsInParallel(tool: Pick<Tool, 'effect' | 'concurrency'> | undefined): boolean;
105
+ /** A call that passed context scoping and argument validation, ready to invoke. */
106
+ export type PreparedToolCall = {
107
+ readonly tool: Tool;
108
+ readonly input: unknown;
109
+ };
44
110
  export declare class ToolRegistry {
45
111
  #private;
46
112
  register(tool: Tool): void;
113
+ /** The tool callable in this context, if any. */
114
+ get(name: string, context: ToolContext): Tool | undefined;
47
115
  list(context: ToolContext): Tool[];
48
116
  schemas(context: ToolContext): object[];
49
- call(name: string, args: unknown, context: ToolContext, signal: AbortSignal): Promise<ToolResult>;
117
+ /** Scope and validate a call without invoking it. A refusal is a no-effect result. */
118
+ prepare(name: string, args: unknown, context: ToolContext): PreparedToolCall | {
119
+ result: ToolResult;
120
+ };
121
+ call(name: string, args: unknown, context: ToolContext, signal: AbortSignal, ctx?: ToolInvocationContext): Promise<ToolResult>;
122
+ /** Invoke a call returned by `prepare`, bounded by the tool's timeout and the caller's signal. */
123
+ invokePrepared({ tool, input }: PreparedToolCall, signal: AbortSignal, ctx?: ToolInvocationContext): Promise<ToolResult>;
50
124
  }
package/dist/tools.js CHANGED
@@ -8,12 +8,25 @@ export class ProvenNoEffectError extends Error {
8
8
  this.code = code;
9
9
  }
10
10
  }
11
+ /** The task reached `execution.max_tool_calls`; the call was not dispatched. */
12
+ export class ToolCallLimitError extends Error {
13
+ constructor(message = 'Tool-call limit reached') { super(message); }
14
+ }
11
15
  export const ToolResultSchema = z.discriminatedUnion('ok', [
12
16
  z.object({ ok: z.literal(true), value: z.unknown().optional() }).strict(),
13
17
  z.object({ ok: z.literal(false), code: z.string(), message: z.string(), effect: z.enum(['none', 'unknown']) }).strict()
14
18
  ]);
15
19
  export function defineTool(definition) {
16
- return { ...definition, invoke: async (input, signal) => definition.handler(definition.input.parse(input), signal) };
20
+ const { handler, reconcile, ...rest } = definition;
21
+ return { ...rest,
22
+ ...(reconcile ? { reconcile: async (input, ctx, signal) => reconcile(definition.input.parse(input), ctx, signal) } : {}),
23
+ invoke: async (input, signal, ctx) => handler(definition.input.parse(input), signal, ctx) };
24
+ }
25
+ /** Whether a tool may overlap other parallel-eligible calls in one model turn. */
26
+ export function toolRunsInParallel(tool) {
27
+ if (!tool)
28
+ return false;
29
+ return (tool.effect === 'read' && tool.concurrency !== 'serial') || tool.concurrency === 'parallel';
17
30
  }
18
31
  export class ToolRegistry {
19
32
  #tools = new Map();
@@ -22,17 +35,31 @@ export class ToolRegistry {
22
35
  throw new Error(`Duplicate tool: ${tool.name}`);
23
36
  this.#tools.set(tool.name, tool);
24
37
  }
38
+ /** The tool callable in this context, if any. */
39
+ get(name, context) {
40
+ const tool = this.#tools.get(name);
41
+ return tool?.contexts.includes(context) ? tool : undefined;
42
+ }
25
43
  list(context) { return [...this.#tools.values()].filter(tool => tool.contexts.includes(context)); }
26
44
  schemas(context) {
27
45
  return this.list(context).map(tool => ({ type: 'function', function: { name: tool.name, description: tool.description, parameters: toJsonSchema(tool.input, 'openapi-3.0') } }));
28
46
  }
29
- async call(name, args, context, signal) {
30
- const tool = this.#tools.get(name);
31
- if (!tool || !tool.contexts.includes(context))
32
- return { ok: false, code: 'TOOL_DENIED', message: 'Tool is unavailable in this context', effect: 'none' };
47
+ /** Scope and validate a call without invoking it. A refusal is a no-effect result. */
48
+ prepare(name, args, context) {
49
+ const tool = this.get(name, context);
50
+ if (!tool)
51
+ return { result: { ok: false, code: 'TOOL_DENIED', message: 'Tool is unavailable in this context', effect: 'none' } };
33
52
  const parsed = tool.input.safeParse(args);
34
53
  if (!parsed.success)
35
- return { ok: false, code: 'INVALID_ARGUMENT', message: parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; '), effect: 'none' };
54
+ return { result: { ok: false, code: 'INVALID_ARGUMENT', message: parsed.error.issues.map(issue => `${issue.path.join('.')}: ${issue.message}`).join('; '), effect: 'none' } };
55
+ return { tool, input: parsed.data };
56
+ }
57
+ async call(name, args, context, signal, ctx) {
58
+ const prepared = this.prepare(name, args, context);
59
+ return 'result' in prepared ? prepared.result : this.invokePrepared(prepared, signal, ctx);
60
+ }
61
+ /** Invoke a call returned by `prepare`, bounded by the tool's timeout and the caller's signal. */
62
+ async invokePrepared({ tool, input }, signal, ctx) {
36
63
  const controller = new AbortController();
37
64
  const timeout = setTimeout(() => controller.abort(), tool.timeoutMs);
38
65
  const cancel = () => controller.abort();
@@ -40,7 +67,7 @@ export class ToolRegistry {
40
67
  try {
41
68
  if (signal.aborted)
42
69
  controller.abort();
43
- const value = await tool.invoke(parsed.data, controller.signal);
70
+ const value = await (ctx ? tool.invoke(input, controller.signal, ctx) : tool.invoke(input, controller.signal));
44
71
  return { ok: true, value: tool.output.parse(value) };
45
72
  }
46
73
  catch (error) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hivemagnus/ardent",
3
- "version": "3.1.3",
3
+ "version": "3.2.0",
4
4
  "description": "Headless TypeScript agent runtime with A2A, scheduled jobs, skills, chat channels, and a plugin API",
5
5
  "keywords": [
6
6
  "agent",
@@ -52,13 +52,16 @@
52
52
  "README.md",
53
53
  "LICENSE"
54
54
  ],
55
+ "workspaces": [
56
+ "client"
57
+ ],
55
58
  "scripts": {
56
59
  "build": "node -e \"require('node:fs').rmSync('dist',{recursive:true,force:true})\" && tsc --build",
57
- "typecheck": "tsc --noEmit",
60
+ "typecheck": "tsc --noEmit && tsc -p client --noEmit",
58
61
  "test": "vitest run --exclude 'test/interop/**'",
59
62
  "interop:test": "vitest run test/interop",
60
63
  "interop": "node scripts/run-interop.mjs",
61
- "lint": "eslint src test",
64
+ "lint": "eslint src test client",
62
65
  "protocol:check": "node scripts/verify-protocol.mjs",
63
66
  "openapi:check": "npm run build && node scripts/check-openapi.mjs",
64
67
  "openapi:write": "npm run build && node scripts/check-openapi.mjs --write",
@@ -69,9 +72,12 @@
69
72
  "native:check": "npm run build && node scripts/check-native.mjs",
70
73
  "scan:secrets": "bash scripts/scan-secrets.sh",
71
74
  "check:private": "bash scripts/check-private-data.sh",
72
- "privacy:test": "node --test scripts/test-privacy-policy.mjs scripts/test-publish-environment.mjs scripts/test-publish-package.mjs",
75
+ "privacy:test": "node --test scripts/test-privacy-policy.mjs scripts/test-publish-environment.mjs scripts/test-publish-package.mjs scripts/test-client-version.mjs",
73
76
  "hooks:install": "git config core.hooksPath .githooks",
74
- "verify": "npm run privacy:test && npm run scan:secrets && npm run check:private && npm run protocol:check && npm run typecheck && npm run lint && npm test && npm run build && npm run openapi:check && npm run pack:check"
77
+ "verify": "npm run privacy:test && npm run scan:secrets && npm run check:private && npm run version:check && npm run protocol:check && npm run typecheck && npm run lint && npm test && npm run build && npm run client:build && npm run openapi:check && npm run pack:check",
78
+ "client:build": "npm run build --workspace @hivemagnus/ardent-client",
79
+ "version:check": "node scripts/check-client-version.mjs",
80
+ "release:version": "npm version --no-git-tag-version --workspaces --include-workspace-root"
75
81
  },
76
82
  "dependencies": {
77
83
  "@a2a-js/sdk": "1.3.0",
@@ -79,7 +85,9 @@
79
85
  "@grpc/grpc-js": "1.14.7",
80
86
  "@hivemagnus/canvas-word-codec": "1.1.0",
81
87
  "@hivemagnus/emberfold": "0.1.0",
82
- "@hono/node-server": "^2.1.5",
88
+ "@hivemagnus/hive-common": "0.6.0",
89
+ "@hono/node-server": "^2.1.6",
90
+ "@photostructure/sqlite": "3.3.1",
83
91
  "dotenv": "^18.0.9",
84
92
  "express": "5.3.0",
85
93
  "hono": "^4.13.18",
@@ -88,8 +96,7 @@
88
96
  "pdfmake": "0.3.13",
89
97
  "ws": "^8.22.0",
90
98
  "yaml": "2.9.1",
91
- "zod": "^4.6.7",
92
- "@photostructure/sqlite": "3.3.1"
99
+ "zod": "^4.6.7"
93
100
  },
94
101
  "devDependencies": {
95
102
  "@apidevtools/swagger-parser": "^13.1.0",
@@ -97,8 +104,8 @@
97
104
  "@types/node": "^24.19.2",
98
105
  "@types/pdfmake": "0.3.3",
99
106
  "@types/ws": "^8.18.2",
107
+ "esbuild": "0.28.2",
100
108
  "eslint": "10.14.0",
101
- "openapi-fetch": "0.17.0",
102
109
  "openapi-typescript": "^7.13.0",
103
110
  "tsx": "^4.23.15",
104
111
  "typescript": "^6.0.3",
@@ -14,7 +14,8 @@ execution:
14
14
  backend: llamacpp # llamacpp | codex
15
15
  max_model_steps: 40
16
16
  max_tool_calls: 80
17
- max_parallel_tools: 3
17
+ max_parallel_tasks: 3 # tasks running at once (the runtime runs at most 4)
18
+ max_parallel_tool_calls: 4 # independent read calls overlapping in one model turn
18
19
  deadline_seconds: 3600
19
20
  max_delegation_depth: 2
20
21
  providers: