@nifrajs/agent 2.12.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 ADDED
@@ -0,0 +1,26 @@
1
+ # @nifrajs/agent
2
+
3
+ Provider-neutral, typed, resumable agent turns over Nifra tool contracts.
4
+
5
+ The package owns one bounded turn at a time. Model providers, state, approvals, budgets, idempotency,
6
+ and telemetry are ports. The package never imports a model vendor and its state adapter stores only
7
+ token-only turn evidence.
8
+
9
+ ```ts
10
+ import { createAgentState, runAgent } from "@nifrajs/agent"
11
+
12
+ const result = await runAgent(definition, { value: input }, ports, {
13
+ state: createAgentState("support-1"),
14
+ maxTurns: 8,
15
+ })
16
+ ```
17
+
18
+ The public in-memory adapters are for local development and tests. Durable state, provider
19
+ credentials, and operated policy remain adapter concerns.
20
+
21
+ Execution policies can be required by a tool contract. `createLocalProcessAdapter` applies cwd and
22
+ environment filtering, timeouts, and cancellation to child processes. The local adapter is NOT a
23
+ security boundary. Without OS-level sandboxing it contains crashes and accidents, not hostile code.
24
+
25
+ For the compact agent contract, see [`LLM.md`](./LLM.md). The full machine-readable corpus is
26
+ [`../../llms-full.txt`](../../llms-full.txt).
@@ -0,0 +1,23 @@
1
+ import type { AgentStepEvidence, AgentTelemetryPort } from "./index.js";
2
+ /** Options for the lifecycle evidence stream. */
3
+ export interface AgentEvidenceStreamOptions {
4
+ /** Maximum number of produced evidence items waiting for a consumer. Default 1024. */
5
+ readonly maxQueueSize?: number;
6
+ }
7
+ /**
8
+ * The existing step evidence as an async iterable. No second event vocabulary is introduced.
9
+ *
10
+ * Pass the stream as `ports.telemetry`, consume it with `for await`, and call `complete()` when the
11
+ * runner finishes. The stream keeps queued evidence until it has been consumed, then terminates.
12
+ */
13
+ export interface AgentEvidenceStream extends AgentTelemetryPort, AsyncIterableIterator<AgentStepEvidence> {
14
+ complete(): void;
15
+ /**
16
+ * How many evidence items the queue discarded because the consumer fell behind. Non-zero means the
17
+ * `seq` sequence has gaps; the turn result still carries the complete, authoritative evidence array.
18
+ */
19
+ readonly dropped: number;
20
+ }
21
+ /** Create an async iterable that yields the exact evidence values received by `step`. */
22
+ export declare function createAgentEvidenceStream(options?: AgentEvidenceStreamOptions): AgentEvidenceStream;
23
+ //# sourceMappingURL=events.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.d.ts","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,YAAY,CAAA;AAEvE,iDAAiD;AACjD,MAAM,WAAW,0BAA0B;IACzC,sFAAsF;IACtF,QAAQ,CAAC,YAAY,CAAC,EAAE,MAAM,CAAA;CAC/B;AAED;;;;;GAKG;AACH,MAAM,WAAW,mBACf,SAAQ,kBAAkB,EACxB,qBAAqB,CAAC,iBAAiB,CAAC;IAC1C,QAAQ,IAAI,IAAI,CAAA;IAChB;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;CACzB;AAED,yFAAyF;AACzF,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,0BAA+B,GACvC,mBAAmB,CAwDrB"}
package/dist/events.js ADDED
@@ -0,0 +1,61 @@
1
+ /** Create an async iterable that yields the exact evidence values received by `step`. */
2
+ export function createAgentEvidenceStream(options = {}) {
3
+ const maxQueueSize = options.maxQueueSize ?? 1024;
4
+ if (!Number.isSafeInteger(maxQueueSize) || maxQueueSize < 1)
5
+ throw new RangeError("agent evidence stream: maxQueueSize must be a positive safe integer");
6
+ const queue = [];
7
+ const waiters = [];
8
+ let completed = false;
9
+ let dropped = 0;
10
+ const finishWaiters = () => {
11
+ if (!completed || queue.length > 0)
12
+ return;
13
+ while (waiters.length > 0)
14
+ waiters.shift()?.({ done: true, value: undefined });
15
+ };
16
+ const stream = {
17
+ get dropped() {
18
+ return dropped;
19
+ },
20
+ step(evidence) {
21
+ if (completed)
22
+ return;
23
+ const waiter = waiters.shift();
24
+ if (waiter !== undefined) {
25
+ waiter({ done: false, value: evidence });
26
+ return;
27
+ }
28
+ // A consumer that stopped reading (a closed SSE connection is the common one) must never fail
29
+ // the turn it is observing. The queue is a live view; the authoritative evidence is returned by
30
+ // the runner either way, so the oldest item is discarded and counted instead of thrown.
31
+ if (queue.length >= maxQueueSize) {
32
+ queue.shift();
33
+ dropped += 1;
34
+ }
35
+ queue.push(evidence);
36
+ },
37
+ complete() {
38
+ completed = true;
39
+ finishWaiters();
40
+ },
41
+ next() {
42
+ const evidence = queue.shift();
43
+ if (evidence !== undefined)
44
+ return Promise.resolve({ done: false, value: evidence });
45
+ if (completed)
46
+ return Promise.resolve({ done: true, value: undefined });
47
+ return new Promise((resolve) => waiters.push(resolve));
48
+ },
49
+ return() {
50
+ queue.length = 0;
51
+ completed = true;
52
+ finishWaiters();
53
+ return Promise.resolve({ done: true, value: undefined });
54
+ },
55
+ [Symbol.asyncIterator]() {
56
+ return this;
57
+ },
58
+ };
59
+ return stream;
60
+ }
61
+ //# sourceMappingURL=events.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"events.js","sourceRoot":"","sources":["../src/events.ts"],"names":[],"mappings":"AAyBA,yFAAyF;AACzF,MAAM,UAAU,yBAAyB,CACvC,UAAsC,EAAE;IAExC,MAAM,YAAY,GAAG,OAAO,CAAC,YAAY,IAAI,IAAI,CAAA;IACjD,IAAI,CAAC,MAAM,CAAC,aAAa,CAAC,YAAY,CAAC,IAAI,YAAY,GAAG,CAAC;QACzD,MAAM,IAAI,UAAU,CAAC,qEAAqE,CAAC,CAAA;IAE7F,MAAM,KAAK,GAAwB,EAAE,CAAA;IACrC,MAAM,OAAO,GAA+D,EAAE,CAAA;IAC9E,IAAI,SAAS,GAAG,KAAK,CAAA;IACrB,IAAI,OAAO,GAAG,CAAC,CAAA;IAEf,MAAM,aAAa,GAAG,GAAS,EAAE;QAC/B,IAAI,CAAC,SAAS,IAAI,KAAK,CAAC,MAAM,GAAG,CAAC;YAAE,OAAM;QAC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,CAAC,CAAC,CAAA;QAC3F,CAAC;QACD,MAAM;YACJ,KAAK,CAAC,MAAM,GAAG,CAAC,CAAA;YAChB,SAAS,GAAG,IAAI,CAAA;YAChB,aAAa,EAAE,CAAA;YACf,OAAO,OAAO,CAAC,OAAO,CAAC,EAAE,IAAI,EAAE,IAAI,EAAE,KAAK,EAAE,SAAS,EAAE,CAAC,CAAA;QAC1D,CAAC;QACD,CAAC,MAAM,CAAC,aAAa,CAAC;YACpB,OAAO,IAAI,CAAA;QACb,CAAC;KACF,CAAA;IACD,OAAO,MAAM,CAAA;AACf,CAAC"}
@@ -0,0 +1,43 @@
1
+ import { defineExecutionPolicy, type ExecutionPolicy, type ExecutionPolicyAdapter } from "@nifrajs/core/execution-policy";
2
+ /** This statement is intentionally repeated in the API and runtime result. */
3
+ export declare const LOCAL_PROCESS_LIMITATION = "The local adapter is NOT a security boundary.";
4
+ export interface LocalProcessAdapterOptions {
5
+ readonly cwd?: string;
6
+ /** Only these inherited environment names are copied. Default: PATH, LANG, and LC_ALL. */
7
+ readonly envAllowlist?: readonly string[];
8
+ readonly maxOutputBytes?: number;
9
+ }
10
+ export interface LocalProcessRequest {
11
+ readonly command: string;
12
+ readonly args?: readonly string[];
13
+ readonly cwd?: string;
14
+ readonly env?: Readonly<Record<string, string | undefined>>;
15
+ readonly capability?: string;
16
+ readonly policy: ExecutionPolicy;
17
+ readonly signal?: AbortSignal;
18
+ }
19
+ export interface LocalProcessResult {
20
+ readonly ok: boolean;
21
+ readonly exitCode: number | null;
22
+ readonly signal?: string;
23
+ readonly stdout: string;
24
+ readonly stderr: string;
25
+ readonly timedOut: boolean;
26
+ readonly cancelled: boolean;
27
+ readonly limitations: readonly string[];
28
+ }
29
+ export declare class LocalProcessPolicyError extends Error {
30
+ readonly code: "policy_unsatisfied" | "invalid_request" | "cancelled";
31
+ constructor(code: "policy_unsatisfied" | "invalid_request" | "cancelled");
32
+ }
33
+ export interface LocalProcessAdapter extends ExecutionPolicyAdapter {
34
+ run(request: LocalProcessRequest): Promise<LocalProcessResult>;
35
+ }
36
+ /**
37
+ * Run a command with the host controls available to a normal child process. The local adapter is NOT
38
+ * a security boundary. Without OS-level sandboxing it contains crashes and accidents, not hostile code.
39
+ */
40
+ export declare function createLocalProcessAdapter(options?: LocalProcessAdapterOptions): LocalProcessAdapter;
41
+ export type { ExecutionPolicy, ExecutionPolicyAdapter };
42
+ export { defineExecutionPolicy };
43
+ //# sourceMappingURL=execution-policy.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution-policy.d.ts","sourceRoot":"","sources":["../src/execution-policy.ts"],"names":[],"mappings":"AAEA,OAAO,EACL,qBAAqB,EACrB,KAAK,eAAe,EACpB,KAAK,sBAAsB,EAC5B,MAAM,gCAAgC,CAAA;AAEvC,8EAA8E;AAC9E,eAAO,MAAM,wBAAwB,kDAAkD,CAAA;AAIvF,MAAM,WAAW,0BAA0B;IACzC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IACrB,0FAA0F;IAC1F,QAAQ,CAAC,YAAY,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;IACzC,QAAQ,CAAC,cAAc,CAAC,EAAE,MAAM,CAAA;CACjC;AAED,MAAM,WAAW,mBAAmB;IAClC,QAAQ,CAAC,OAAO,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,IAAI,CAAC,EAAE,SAAS,MAAM,EAAE,CAAA;IACjC,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IACrB,QAAQ,CAAC,GAAG,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,CAAC,CAAC,CAAA;IAC3D,QAAQ,CAAC,UAAU,CAAC,EAAE,MAAM,CAAA;IAC5B,QAAQ,CAAC,MAAM,EAAE,eAAe,CAAA;IAChC,QAAQ,CAAC,MAAM,CAAC,EAAE,WAAW,CAAA;CAC9B;AAED,MAAM,WAAW,kBAAkB;IACjC,QAAQ,CAAC,EAAE,EAAE,OAAO,CAAA;IACpB,QAAQ,CAAC,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAA;IAChC,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;IACvB,QAAQ,CAAC,QAAQ,EAAE,OAAO,CAAA;IAC1B,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;IAC3B,QAAQ,CAAC,WAAW,EAAE,SAAS,MAAM,EAAE,CAAA;CACxC;AAED,qBAAa,uBAAwB,SAAQ,KAAK;IACpC,QAAQ,CAAC,IAAI,EAAE,oBAAoB,GAAG,iBAAiB,GAAG,WAAW;gBAA5D,IAAI,EAAE,oBAAoB,GAAG,iBAAiB,GAAG,WAAW;CAIlF;AAED,MAAM,WAAW,mBAAoB,SAAQ,sBAAsB;IACjE,GAAG,CAAC,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAAA;CAC/D;AAED;;;GAGG;AACH,wBAAgB,yBAAyB,CACvC,OAAO,GAAE,0BAA+B,GACvC,mBAAmB,CAuErB;AA8GD,YAAY,EAAE,eAAe,EAAE,sBAAsB,EAAE,CAAA;AACvD,OAAO,EAAE,qBAAqB,EAAE,CAAA"}
@@ -0,0 +1,185 @@
1
+ import { spawn } from "node:child_process";
2
+ import { isAbsolute, relative, resolve, sep } from "node:path";
3
+ import { defineExecutionPolicy, } from "@nifrajs/core/execution-policy";
4
+ /** This statement is intentionally repeated in the API and runtime result. */
5
+ export const LOCAL_PROCESS_LIMITATION = "The local adapter is NOT a security boundary.";
6
+ const SIGKILL_GRACE_MS = 2000;
7
+ export class LocalProcessPolicyError extends Error {
8
+ code;
9
+ constructor(code) {
10
+ super(`local process: ${code}. ${LOCAL_PROCESS_LIMITATION}`);
11
+ this.code = code;
12
+ this.name = "LocalProcessPolicyError";
13
+ }
14
+ }
15
+ /**
16
+ * Run a command with the host controls available to a normal child process. The local adapter is NOT
17
+ * a security boundary. Without OS-level sandboxing it contains crashes and accidents, not hostile code.
18
+ */
19
+ export function createLocalProcessAdapter(options = {}) {
20
+ const cwd = options.cwd ?? process.cwd();
21
+ const allowlist = new Set(options.envAllowlist ?? ["PATH", "LANG", "LC_ALL"]);
22
+ const maxOutputBytes = options.maxOutputBytes ?? 1024 * 1024;
23
+ if (!Number.isSafeInteger(maxOutputBytes) || maxOutputBytes < 1) {
24
+ throw new RangeError("local process: maxOutputBytes must be a positive safe integer");
25
+ }
26
+ const adapter = {
27
+ name: "local-process",
28
+ canSatisfy(policyInput) {
29
+ const policy = defineExecutionPolicy(policyInput);
30
+ return (policy.filesystem === "cwd" &&
31
+ policy.network === "allow" &&
32
+ policy.capabilityCeiling.length > 0);
33
+ },
34
+ limitations(policyInput) {
35
+ const policy = defineExecutionPolicy(policyInput);
36
+ const limitations = [LOCAL_PROCESS_LIMITATION];
37
+ if (policy.filesystem !== "cwd")
38
+ limitations.push("filesystem-scope-not-enforced");
39
+ if (policy.network === "deny")
40
+ limitations.push("network-denial-not-enforced");
41
+ limitations.push("capability-ceiling-is-admission-only");
42
+ return Object.freeze(limitations);
43
+ },
44
+ async run(request) {
45
+ const policy = defineExecutionPolicy(request.policy);
46
+ if (typeof request.command !== "string" ||
47
+ request.command.trim() === "" ||
48
+ request.args?.some((arg) => typeof arg !== "string")) {
49
+ throw new LocalProcessPolicyError("invalid_request");
50
+ }
51
+ if (!(await adapter.canSatisfy(policy)))
52
+ throw new LocalProcessPolicyError("policy_unsatisfied");
53
+ if (request.capability !== undefined &&
54
+ !policy.capabilityCeiling.includes(request.capability)) {
55
+ throw new LocalProcessPolicyError("policy_unsatisfied");
56
+ }
57
+ if (request.signal?.aborted === true)
58
+ throw new LocalProcessPolicyError("cancelled");
59
+ const processCwd = resolve(cwd, request.cwd ?? ".");
60
+ if (policy.filesystem === "cwd" && !isWithin(processCwd, cwd))
61
+ throw new LocalProcessPolicyError("policy_unsatisfied");
62
+ const env = filteredEnv(request.env ?? {});
63
+ return spawnProcess({
64
+ command: request.command,
65
+ args: request.args ?? [],
66
+ cwd: processCwd,
67
+ env,
68
+ policy,
69
+ ...(request.signal === undefined ? {} : { signal: request.signal }),
70
+ maxOutputBytes,
71
+ limitations: adapter.limitations(policy),
72
+ });
73
+ },
74
+ };
75
+ return Object.freeze(adapter);
76
+ function filteredEnv(values) {
77
+ const result = {};
78
+ for (const name of allowlist) {
79
+ const value = values[name] ?? process.env[name];
80
+ if (value !== undefined)
81
+ result[name] = value;
82
+ }
83
+ return result;
84
+ }
85
+ }
86
+ function isWithin(path, root) {
87
+ const resolvedPath = resolve(path);
88
+ const resolvedRoot = resolve(root);
89
+ const distance = relative(resolvedRoot, resolvedPath);
90
+ return (distance === "" ||
91
+ (distance !== ".." && !distance.startsWith(`..${sep}`) && !isAbsolute(distance)));
92
+ }
93
+ function spawnProcess(input) {
94
+ return new Promise((resolve, reject) => {
95
+ let child;
96
+ try {
97
+ child = spawn(input.command, [...input.args], {
98
+ cwd: input.cwd,
99
+ env: input.env,
100
+ shell: false,
101
+ stdio: ["ignore", "pipe", "pipe"],
102
+ });
103
+ }
104
+ catch {
105
+ reject(new LocalProcessPolicyError("invalid_request"));
106
+ return;
107
+ }
108
+ const stdout = [];
109
+ const stderr = [];
110
+ let timedOut = false;
111
+ let cancelled = false;
112
+ let settled = false;
113
+ const outputUsed = { value: 0 };
114
+ const append = (target, chunk) => {
115
+ const remaining = input.maxOutputBytes - outputUsed.value;
116
+ if (remaining <= 0)
117
+ return;
118
+ const selected = chunk.byteLength <= remaining ? chunk : chunk.slice(0, remaining);
119
+ target.push(selected);
120
+ outputUsed.value += selected.byteLength;
121
+ };
122
+ if (child.stdout === null || child.stderr === null) {
123
+ child.kill();
124
+ reject(new LocalProcessPolicyError("invalid_request"));
125
+ return;
126
+ }
127
+ child.stdout.on("data", (chunk) => append(stdout, chunk));
128
+ child.stderr.on("data", (chunk) => append(stderr, chunk));
129
+ let killTimer;
130
+ const terminate = () => {
131
+ child.kill("SIGTERM");
132
+ // A child that ignores SIGTERM would otherwise leave this promise pending forever,
133
+ // making policy.timeMs advisory instead of a bound.
134
+ killTimer ??= setTimeout(() => child.kill("SIGKILL"), SIGKILL_GRACE_MS);
135
+ };
136
+ const timer = setTimeout(() => {
137
+ timedOut = true;
138
+ terminate();
139
+ }, input.policy.timeMs);
140
+ const cancel = () => {
141
+ cancelled = true;
142
+ terminate();
143
+ };
144
+ input.signal?.addEventListener("abort", cancel, { once: true });
145
+ child.once("error", () => {
146
+ if (settled)
147
+ return;
148
+ settled = true;
149
+ clearTimeout(timer);
150
+ if (killTimer !== undefined)
151
+ clearTimeout(killTimer);
152
+ reject(new LocalProcessPolicyError("invalid_request"));
153
+ });
154
+ child.once("close", (exitCode, signal) => {
155
+ if (settled)
156
+ return;
157
+ settled = true;
158
+ clearTimeout(timer);
159
+ if (killTimer !== undefined)
160
+ clearTimeout(killTimer);
161
+ resolve({
162
+ ok: !timedOut && !cancelled && exitCode === 0,
163
+ exitCode,
164
+ ...(signal === null ? {} : { signal }),
165
+ stdout: new TextDecoder().decode(concat(stdout)),
166
+ stderr: new TextDecoder().decode(concat(stderr)),
167
+ timedOut,
168
+ cancelled,
169
+ limitations: input.limitations,
170
+ });
171
+ });
172
+ });
173
+ }
174
+ function concat(chunks) {
175
+ const size = chunks.reduce((total, chunk) => total + chunk.byteLength, 0);
176
+ const result = new Uint8Array(size);
177
+ let offset = 0;
178
+ for (const chunk of chunks) {
179
+ result.set(chunk, offset);
180
+ offset += chunk.byteLength;
181
+ }
182
+ return result;
183
+ }
184
+ export { defineExecutionPolicy };
185
+ //# sourceMappingURL=execution-policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"execution-policy.js","sourceRoot":"","sources":["../src/execution-policy.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAC1C,OAAO,EAAE,UAAU,EAAE,QAAQ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,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,MAAM,CAAC,MAA6B;IAC3C,MAAM,IAAI,GAAG,MAAM,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,KAAK,EAAE,EAAE,CAAC,KAAK,GAAG,KAAK,CAAC,UAAU,EAAE,CAAC,CAAC,CAAA;IACzE,MAAM,MAAM,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,CAAA;IACnC,IAAI,MAAM,GAAG,CAAC,CAAA;IACd,KAAK,MAAM,KAAK,IAAI,MAAM,EAAE,CAAC;QAC3B,MAAM,CAAC,GAAG,CAAC,KAAK,EAAE,MAAM,CAAC,CAAA;QACzB,MAAM,IAAI,KAAK,CAAC,UAAU,CAAA;IAC5B,CAAC;IACD,OAAO,MAAM,CAAA;AACf,CAAC;AAGD,OAAO,EAAE,qBAAqB,EAAE,CAAA"}
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Provider-neutral agent turns.
3
+ *
4
+ * One turn makes one model decision and may execute one {@link ToolContract}. The multi-turn runner
5
+ * is intentionally bounded. The state adapter stores token-only evidence and cursor metadata; model
6
+ * input, tool input, and tool output remain transient caller data.
7
+ */
8
+ import { type RequestBudget } from "@nifrajs/core/budget";
9
+ import type { ExecutionPolicyAdapter } from "@nifrajs/core/execution-policy";
10
+ import type { EffectCost } from "@nifrajs/core/ledger";
11
+ import { type StandardIssue, type StandardSchemaV1 } from "@nifrajs/core/schema";
12
+ import { type ToolCatalogEntry } from "@nifrajs/core/tool-catalog";
13
+ import { type ToolApproval, type ToolBudget, type ToolContract, type ToolError, type ToolIdempotencyStore } from "@nifrajs/core/tool-contract";
14
+ export { createLocalProcessAdapter, type ExecutionPolicy, type ExecutionPolicyAdapter, LOCAL_PROCESS_LIMITATION, type LocalProcessAdapter, type LocalProcessAdapterOptions, LocalProcessPolicyError, type LocalProcessRequest, type LocalProcessResult, } from "./execution-policy.js";
15
+ export type AgentStatus = "continue" | "completed" | "suspended";
16
+ export type AgentPendingKind = "approval" | "budget" | "model" | "cancelled";
17
+ export interface AgentDefinition<InputSchema extends StandardSchemaV1, OutputSchema extends StandardSchemaV1> {
18
+ readonly name: string;
19
+ readonly instruction: string;
20
+ readonly input: InputSchema;
21
+ readonly output: OutputSchema;
22
+ readonly tools: readonly AgentToolContract[];
23
+ /** Dimensionless counters charged once per model decision. */
24
+ readonly modelCost?: EffectCost;
25
+ }
26
+ /** Heterogeneous tool collection used by an agent definition. Runtime schemas remain authoritative. */
27
+ export type AgentToolContract = ToolContract<any, any>;
28
+ /** The model-facing descriptor is the complete descriptive catalog entry. */
29
+ export type AgentToolDescriptor = ToolCatalogEntry;
30
+ export interface AgentTurnState {
31
+ readonly version: 1;
32
+ readonly turnId: string;
33
+ readonly step: number;
34
+ readonly status: "ready" | "suspended" | "completed";
35
+ readonly evidence: readonly AgentStepEvidence[];
36
+ readonly pending?: {
37
+ readonly kind: AgentPendingKind;
38
+ readonly tool?: string;
39
+ readonly effectId: string;
40
+ };
41
+ }
42
+ export interface AgentStepEvidence {
43
+ readonly seq: number;
44
+ readonly at: number;
45
+ readonly kind: "model" | "tool" | "approval" | "budget" | "state";
46
+ readonly outcome: "started" | "passed" | "failed" | "denied" | "suspended" | "committed";
47
+ readonly name?: string;
48
+ readonly effectId?: string;
49
+ readonly code?: string;
50
+ readonly ledgerHead?: string;
51
+ }
52
+ export interface AgentModelRequest {
53
+ readonly agent: string;
54
+ readonly instruction: string;
55
+ readonly input: unknown;
56
+ readonly state: AgentTurnState;
57
+ readonly tools: readonly AgentToolDescriptor[];
58
+ readonly toolResult?: AgentToolResult;
59
+ readonly previousOutput?: unknown;
60
+ readonly signal: AbortSignal;
61
+ /** Wall-clock budget shared with the parent request. Use withDeadlineHeader for outbound requests. */
62
+ readonly deadline?: RequestBudget;
63
+ }
64
+ export type AgentModelResponse = {
65
+ readonly kind: "output";
66
+ readonly value: unknown;
67
+ } | {
68
+ readonly kind: "tool";
69
+ readonly name: string;
70
+ readonly input: unknown;
71
+ };
72
+ export interface AgentModelPort {
73
+ /** Provider output is unknown until the response parser accepts it. */
74
+ complete(request: AgentModelRequest): unknown | PromiseLike<unknown>;
75
+ }
76
+ export interface AgentToolResult {
77
+ readonly name: string;
78
+ readonly ok: boolean;
79
+ readonly output?: unknown;
80
+ readonly error?: ToolError | {
81
+ readonly code: "unknown_tool" | "invalid_model_response";
82
+ readonly stage: "execution";
83
+ };
84
+ }
85
+ export interface AgentPendingContinuation {
86
+ readonly kind: AgentPendingKind;
87
+ readonly tool?: string;
88
+ readonly input?: unknown;
89
+ readonly effectId: string;
90
+ }
91
+ export type AgentApprovalResult = {
92
+ readonly status: "approved";
93
+ readonly approval: ToolApproval;
94
+ } | {
95
+ readonly status: "denied";
96
+ readonly reason?: string;
97
+ } | {
98
+ readonly status: "pending";
99
+ readonly effectId: string;
100
+ };
101
+ export interface AgentApprovalPort {
102
+ request(input: {
103
+ readonly turnId: string;
104
+ readonly effectId: string;
105
+ readonly tool: string;
106
+ readonly capability: string;
107
+ readonly signal: AbortSignal;
108
+ /** Wall-clock budget reserved for this approval hop and the following tool execution. */
109
+ readonly deadline?: RequestBudget;
110
+ }): AgentApprovalResult | PromiseLike<AgentApprovalResult>;
111
+ }
112
+ export interface AgentStateStore {
113
+ load(turnId: string): AgentTurnState | undefined | PromiseLike<AgentTurnState | undefined>;
114
+ save(state: AgentTurnState): void | PromiseLike<void>;
115
+ }
116
+ export declare class MemoryAgentStateStore implements AgentStateStore {
117
+ private readonly states;
118
+ load(turnId: string): AgentTurnState | undefined;
119
+ save(state: AgentTurnState): void;
120
+ }
121
+ export interface AgentTelemetryPort {
122
+ step(evidence: AgentStepEvidence): void | PromiseLike<void>;
123
+ }
124
+ export interface AgentPorts {
125
+ readonly model: AgentModelPort;
126
+ readonly capabilities: readonly string[];
127
+ readonly budget?: ToolBudget;
128
+ /** Wall-clock budget shared with the parent request. Distinct from `budget`, which is cost. */
129
+ readonly deadline?: RequestBudget;
130
+ readonly idempotency?: ToolIdempotencyStore;
131
+ readonly state?: AgentStateStore;
132
+ readonly approval?: AgentApprovalPort;
133
+ readonly telemetry?: AgentTelemetryPort;
134
+ readonly clock?: () => number;
135
+ /** Adapter used to satisfy execution policies declared by tool contracts. */
136
+ readonly executionPolicy?: ExecutionPolicyAdapter;
137
+ /** Injectable token generator for deterministic replay and tests. */
138
+ readonly idFactory?: () => string;
139
+ readonly signal?: AbortSignal;
140
+ /** Replay mode skips every tool executor and marks the call dry-run. */
141
+ readonly dryRun?: boolean;
142
+ }
143
+ export interface AgentTurnInput {
144
+ readonly value: unknown;
145
+ readonly toolResult?: AgentToolResult;
146
+ readonly previousOutput?: unknown;
147
+ readonly resume?: {
148
+ readonly continuation: AgentPendingContinuation;
149
+ readonly approval?: ToolApproval;
150
+ };
151
+ }
152
+ export interface AgentTurnBaseResult {
153
+ readonly state: AgentTurnState;
154
+ readonly evidence: readonly AgentStepEvidence[];
155
+ readonly transcript: AgentTranscript;
156
+ }
157
+ export interface AgentTurnError {
158
+ readonly code: "input_invalid" | "output_invalid" | "model_failed";
159
+ readonly issues?: readonly StandardIssue[];
160
+ }
161
+ export type AgentTurnResult<Output> = (AgentTurnBaseResult & {
162
+ readonly status: "completed";
163
+ readonly output: Output;
164
+ readonly error?: never;
165
+ }) | (AgentTurnBaseResult & {
166
+ readonly status: "completed";
167
+ readonly error: AgentTurnError;
168
+ readonly output?: never;
169
+ }) | (AgentTurnBaseResult & {
170
+ readonly status: "continue";
171
+ readonly toolResult: AgentToolResult;
172
+ }) | (AgentTurnBaseResult & {
173
+ readonly status: "suspended";
174
+ readonly pending: AgentPendingContinuation;
175
+ readonly reason: "approval" | "budget" | "model" | "cancelled";
176
+ });
177
+ export interface AgentTranscript {
178
+ readonly version: 1;
179
+ readonly turnId: string;
180
+ readonly responses: readonly AgentModelResponse[];
181
+ readonly evidence: readonly AgentStepEvidence[];
182
+ }
183
+ export interface RunAgentOptions {
184
+ readonly state: AgentTurnState;
185
+ readonly maxTurns?: number;
186
+ readonly goal?: (output: unknown) => boolean;
187
+ }
188
+ export type AgentRunResult<Output> = AgentTurnResult<Output> | (AgentTurnBaseResult & {
189
+ readonly status: "suspended";
190
+ readonly pending: AgentPendingContinuation;
191
+ readonly reason: "max_turns";
192
+ });
193
+ export declare function createAgentState(turnId: string): AgentTurnState;
194
+ export declare function turn<InputSchema extends StandardSchemaV1, OutputSchema extends StandardSchemaV1>(definition: AgentDefinition<InputSchema, OutputSchema>, state: AgentTurnState, input: AgentTurnInput, ports: AgentPorts): Promise<AgentTurnResult<NonNullable<OutputSchema["~standard"]["types"]>["output"]>>;
195
+ export declare function runAgent<InputSchema extends StandardSchemaV1, OutputSchema extends StandardSchemaV1>(definition: AgentDefinition<InputSchema, OutputSchema>, input: AgentTurnInput, ports: AgentPorts, options: RunAgentOptions): Promise<AgentRunResult<NonNullable<OutputSchema["~standard"]["types"]>["output"]>>;
196
+ /** Load a saved token-only state record and continue a bounded run. */
197
+ export declare function resumeAgent<InputSchema extends StandardSchemaV1, OutputSchema extends StandardSchemaV1>(definition: AgentDefinition<InputSchema, OutputSchema>, turnId: string, input: AgentTurnInput, ports: AgentPorts, options?: Omit<RunAgentOptions, "state">): Promise<AgentRunResult<NonNullable<OutputSchema["~standard"]["types"]>["output"]>>;
198
+ export declare function replayAgent<InputSchema extends StandardSchemaV1, OutputSchema extends StandardSchemaV1>(definition: AgentDefinition<InputSchema, OutputSchema>, input: AgentTurnInput, ports: Omit<AgentPorts, "model">, transcript: AgentTranscript, options: RunAgentOptions): Promise<AgentRunResult<NonNullable<OutputSchema["~standard"]["types"]>["output"]>>;
199
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAc,KAAK,aAAa,EAAE,MAAM,sBAAsB,CAAA;AACrE,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,gCAA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