@graphorin/agent 0.5.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 (72) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/LICENSE +21 -0
  3. package/README.md +159 -0
  4. package/dist/errors/index.d.ts +170 -0
  5. package/dist/errors/index.d.ts.map +1 -0
  6. package/dist/errors/index.js +204 -0
  7. package/dist/errors/index.js.map +1 -0
  8. package/dist/evaluator-optimizer/index.d.ts +91 -0
  9. package/dist/evaluator-optimizer/index.d.ts.map +1 -0
  10. package/dist/evaluator-optimizer/index.js +85 -0
  11. package/dist/evaluator-optimizer/index.js.map +1 -0
  12. package/dist/factory.d.ts +13 -0
  13. package/dist/factory.d.ts.map +1 -0
  14. package/dist/factory.js +1853 -0
  15. package/dist/factory.js.map +1 -0
  16. package/dist/fallback/index.d.ts +52 -0
  17. package/dist/fallback/index.d.ts.map +1 -0
  18. package/dist/fallback/index.js +53 -0
  19. package/dist/fallback/index.js.map +1 -0
  20. package/dist/fanout/index.d.ts +142 -0
  21. package/dist/fanout/index.d.ts.map +1 -0
  22. package/dist/fanout/index.js +252 -0
  23. package/dist/fanout/index.js.map +1 -0
  24. package/dist/filters/index.d.ts +137 -0
  25. package/dist/filters/index.d.ts.map +1 -0
  26. package/dist/filters/index.js +273 -0
  27. package/dist/filters/index.js.map +1 -0
  28. package/dist/index.d.ts +51 -0
  29. package/dist/index.d.ts.map +1 -0
  30. package/dist/index.js +49 -0
  31. package/dist/index.js.map +1 -0
  32. package/dist/internal/ids.js +46 -0
  33. package/dist/internal/ids.js.map +1 -0
  34. package/dist/internal/usage-accumulator.js +62 -0
  35. package/dist/internal/usage-accumulator.js.map +1 -0
  36. package/dist/lateral-leak/causality-monitor.d.ts +97 -0
  37. package/dist/lateral-leak/causality-monitor.d.ts.map +1 -0
  38. package/dist/lateral-leak/causality-monitor.js +139 -0
  39. package/dist/lateral-leak/causality-monitor.js.map +1 -0
  40. package/dist/lateral-leak/index.d.ts +4 -0
  41. package/dist/lateral-leak/index.js +5 -0
  42. package/dist/lateral-leak/merge-guard.d.ts +89 -0
  43. package/dist/lateral-leak/merge-guard.d.ts.map +1 -0
  44. package/dist/lateral-leak/merge-guard.js +65 -0
  45. package/dist/lateral-leak/merge-guard.js.map +1 -0
  46. package/dist/lateral-leak/protocol-guard.d.ts +76 -0
  47. package/dist/lateral-leak/protocol-guard.d.ts.map +1 -0
  48. package/dist/lateral-leak/protocol-guard.js +147 -0
  49. package/dist/lateral-leak/protocol-guard.js.map +1 -0
  50. package/dist/preferred-model/index.d.ts +53 -0
  51. package/dist/preferred-model/index.d.ts.map +1 -0
  52. package/dist/preferred-model/index.js +141 -0
  53. package/dist/preferred-model/index.js.map +1 -0
  54. package/dist/progress/index.d.ts +62 -0
  55. package/dist/progress/index.d.ts.map +1 -0
  56. package/dist/progress/index.js +150 -0
  57. package/dist/progress/index.js.map +1 -0
  58. package/dist/run-state/index.d.ts +152 -0
  59. package/dist/run-state/index.d.ts.map +1 -0
  60. package/dist/run-state/index.js +311 -0
  61. package/dist/run-state/index.js.map +1 -0
  62. package/dist/tooling/adapters.js +154 -0
  63. package/dist/tooling/adapters.js.map +1 -0
  64. package/dist/tooling/catalogue.js +37 -0
  65. package/dist/tooling/catalogue.js.map +1 -0
  66. package/dist/tooling/dataflow.js +99 -0
  67. package/dist/tooling/dataflow.js.map +1 -0
  68. package/dist/tooling/registry-build.js +85 -0
  69. package/dist/tooling/registry-build.js.map +1 -0
  70. package/dist/types.d.ts +413 -0
  71. package/dist/types.d.ts.map +1 -0
  72. package/package.json +115 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,7 @@
1
+ # @graphorin/agent
2
+
3
+ ## 0.1.0
4
+
5
+ Initial release. See the workspace root `CHANGELOG.md` for the full
6
+ release notes; the per-package changelog is generated by Changesets
7
+ and tracks subsequent updates.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oleksiy Stepurenko
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,159 @@
1
+ # @graphorin/agent
2
+
3
+ > Agent runtime for the Graphorin framework.
4
+
5
+ `@graphorin/agent` is the agent layer of the Graphorin framework. It
6
+ owns the typed `model -> tool calls -> model` loop, the streaming
7
+ event surface, durable HITL approvals, multi-agent handoffs, and
8
+ the cross-cutting safety mechanisms (intra-loop reasoning
9
+ preservation, agent-level model fallback, post-compaction hooks,
10
+ per-tool model-tier hints, lateral-leak defenses).
11
+
12
+ The package is **library-mode-first**: every primitive that can be
13
+ useful from a script (`createAgent`, `RunState.toJSON / fromJSON`,
14
+ the filter library, `evaluatorOptimizer`, `Agent.fanOut`,
15
+ `agent.progress.write / read`) ships from the npm package without
16
+ the optional standalone server.
17
+
18
+ ## Dependencies
19
+
20
+ - `@graphorin/core` — typed contracts (`AgentEvent`, `RunState`,
21
+ `RunContext`, `Provider`, `Tool`, `StopCondition`, `HandoffFilter`,
22
+ `Sensitivity`, …).
23
+ - `@graphorin/provider` — middleware composer assertion + token
24
+ counter dispatcher + per-provider model-tier auto-classifier.
25
+ - `@graphorin/tools` — `ToolRegistry` + `ToolExecutor` (parallel /
26
+ sequential dispatch, approval flow, sandbox enforcement, inbound
27
+ sanitization).
28
+ - `@graphorin/skills` — skill metadata cards, lazy body loading.
29
+ - `@graphorin/memory` — `Memory` facade + `ContextEngine` for
30
+ per-step prompt assembly + auto-compaction trigger.
31
+ - `@graphorin/sessions` — multi-agent attribution, handoff records,
32
+ `AgentRegistry`, audit trail.
33
+ - `@graphorin/observability` — `Tracer`, span attributes, counter
34
+ receivers.
35
+ - `@graphorin/security` — `SecretsAccessScope` for sub-agent
36
+ inheritance, audit chain, lateral-leak guard primitives.
37
+
38
+ ## Quick start
39
+
40
+ ```ts
41
+ import { createAgent } from '@graphorin/agent';
42
+ import { createProvider } from '@graphorin/provider';
43
+
44
+ const agent = createAgent({
45
+ name: 'helpful-assistant',
46
+ instructions: 'You are a helpful, concise assistant.',
47
+ provider: createProvider({ /* ... */ }),
48
+ });
49
+
50
+ for await (const event of agent.stream('Plan a trip to Mars')) {
51
+ if (event.type === 'text.delta') process.stdout.write(event.delta);
52
+ }
53
+ ```
54
+
55
+ ## Highlights
56
+
57
+ - **Streaming-first.** Every operation returns
58
+ `AsyncIterable<AgentEvent<TOutput>>`. `agent.run(...)` is a thin
59
+ collect helper.
60
+ - **Typed events.** The `AgentEvent<TOutput>` discriminated union
61
+ covers every event the runtime emits (text deltas, tool calls,
62
+ approvals, handoffs, compaction, fan-out, evaluator iterations,
63
+ progress artifacts, lateral-leak detections, model fallback
64
+ transitions, …). `assertNever(...)` exhaustiveness is verified at
65
+ compile time.
66
+ - **Durable HITL.** `RunState.toJSON()` /
67
+ `RunState.fromJSON(serialized, agent)` round-trip the full run
68
+ state through any storage the caller picks (file, SQLite, KV, S3).
69
+ - **Multi-agent.** `Agent.toTool({ exposeTurns, inputFilter })`
70
+ wraps an agent as a tool the parent agent can call. The parent's
71
+ abort signal, deps, and sessionId propagate into the sub-run;
72
+ without an `inputFilter` the sub-agent sees only the input string
73
+ (no parent conversation crosses the boundary), and there is no
74
+ secret-inheritance mechanism at this boundary at all — least
75
+ authority by construction.
76
+ - **Filter library.** `filters.lastN(n)`, `filters.lastUser`,
77
+ `filters.summary({...})`, `filters.bySensitivity({...})`,
78
+ `filters.stripReasoning()`, `filters.stripSensitiveOutputs()`,
79
+ `filters.stripToolCalls()`, `filters.compose(...)`. Every filter
80
+ returns a serializable `HandoffInputFilterDescriptor` so the
81
+ JSONL session export can replay it byte-equal.
82
+ - **Cancellation.** `agent.abort({ drain, onPendingApprovals })` —
83
+ the default hard-kills the in-flight provider stream mid-event;
84
+ `drain: true` lets the current step's stream finish (reach its step
85
+ boundary) before stopping. A mid-stream abort ends the run as
86
+ `'aborted'` (a cancellation), never a failed run. Pending approvals
87
+ can be auto-denied (`'deny'` default), held (`'hold'`), or raised as
88
+ an error (`'fail'`).
89
+ - **Reasoning preservation.** Anthropic Claude tool-use loops
90
+ round-trip `reasoning` content parts (with opaque `meta` such as
91
+ `signature` / `data`) into the next provider call when the
92
+ effective `reasoningRetention` is not `'strip'`. The handoff
93
+ boundary is independent: `filters.stripReasoning()` is always
94
+ applied to messages forwarded to a sub-agent regardless of the
95
+ intra-loop policy.
96
+ - **Agent-level model fallback.** `Agent.fallbackModels: ModelSpec[]`
97
+ retries the whole step against the next model on rate-limit /
98
+ capacity / context-length errors; `agent.model.fellback` event
99
+ fires per transition; per-model usage attribution lives in
100
+ `RunState.usage.byModel`.
101
+ - **Post-compaction hook lifecycle.** When
102
+ `@graphorin/memory.contextEngine` auto-compacts the buffer, the
103
+ runtime fires every registered `postCompactionHooks[i]` between
104
+ the trim and the next `provider.stream(...)` call. Failed hooks
105
+ are isolated; the harness continues with the survivors.
106
+ - **Agent-step-level fan-out.** `Agent.fanOut({ subagents,
107
+ mergeStrategy, perBudget, ... })` spawns N sub-agents under a
108
+ bounded-fanout cap (default `maxConcurrentChildren: 4`) with
109
+ per-child token / tool-call / duration budgets and four built-in
110
+ merge strategies (`'concat'`, `'first-success'`, `'judge-merge'`,
111
+ `'custom'`).
112
+ - **`evaluatorOptimizer({...})`.** Generator → Evaluator iteration
113
+ loop with three rubric kinds (`'free-form'`, `'zod'`,
114
+ `'llm-judge'`) + REQUIRED iteration cap.
115
+ - **Progress artifacts.** `agent.progress.write(content, { role,
116
+ seq, sensitivity, tags })` and `agent.progress.read({ runId,
117
+ role, sinceSeq, maxArtifacts })` persist UTF-8 text artifacts to
118
+ the artifact root via atomic-write `.tmp + rename` discipline for
119
+ cross-session continuity.
120
+ - **Per-tool model-tier hints.** `tool({ ..., preferredModel:
121
+ 'fast' | 'balanced' | 'smart' | ModelSpec })` declares a hint;
122
+ `Agent.modelTierMap` resolves the cost-tier vocabulary to
123
+ concrete `Provider` instances at agent warm-up; the per-step
124
+ planner walks the precedence ladder
125
+ `'prepare-step' > 'tier-map' | 'spec' > 'agent-preferred' >
126
+ 'fallthrough-default'` once per step.
127
+ - **Lateral-leak defense layer.** `Agent.causalityMonitor`
128
+ (Agentic Reference Monitor pattern), `Agent.mergeGuard` (per-child
129
+ trust scoring + bias detection on `'judge-merge'`; `detect-and-block`
130
+ refuses the merge with `MergeBlockedError`), the protocol
131
+ injection guard (`guardOutboundContent` — an exported helper for
132
+ the server boundary, not an `AgentConfig` knob), and
133
+ commentary-phase trace sanitization at the session-output
134
+ boundary compose orthogonally with the other security layers
135
+ (handoff input filter, outbound redaction, inbound sanitization).
136
+ - **Inbound sanitization preamble.** Part of the context-engine
137
+ assemble path: with `autoAssembleContext: true` **and** memory
138
+ wired, when the assembled message list contains any non-trusted
139
+ `MessageContent` part the engine appends the locale-resolved
140
+ preamble fragment to the system prompt **after** the cache
141
+ breakpoint so the trusted-only cache prefix is not invalidated.
142
+ Without that opt-in the preamble (like the rest of `assemble()`)
143
+ does not run; the context engine is configured on the memory
144
+ facade (`createMemory({ contextEngine })`), not on `AgentConfig`.
145
+
146
+ ## Documentation
147
+
148
+ The full architecture lives in the framework docs (the agent loop
149
+ reference). The package's `CHANGELOG.md` records every change.
150
+
151
+ ## License
152
+
153
+ MIT © Oleksiy Stepurenko. See [LICENSE](./LICENSE) for the full
154
+ text.
155
+
156
+ ---
157
+
158
+ **Project Graphorin** · v0.5.0 · MIT License · © 2026 Oleksiy
159
+ Stepurenko · <https://github.com/o-stepper/graphorin>
@@ -0,0 +1,170 @@
1
+ //#region src/errors/index.d.ts
2
+ /**
3
+ * Typed error surface for `@graphorin/agent`.
4
+ *
5
+ * Every error class extends the base {@link AgentRuntimeError} which is
6
+ * a thin wrapper around `Error` with a stable `code` discriminator so
7
+ * callers can `switch` on it without parsing messages.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+ /**
12
+ * Stable code discriminator surfaced on every {@link AgentRuntimeError}.
13
+ *
14
+ * @stable
15
+ */
16
+ type AgentRuntimeErrorCode = 'invalid-config' | 'invalid-preferred-model' | 'invalid-fallback-policy' | 'invalid-evaluator-optimizer-config' | 'agent-resolution-failed' | 'tool-not-found' | 'handoff-target-not-found' | 'multiple-handoffs-in-step' | 'run-aborted' | 'middleware-order-violation' | 'progress-write-failed' | 'merge-blocked' | 'protocol-injection-rejected' | 'run-state-version-unsupported' | 'run-state-malformed' | 'concurrent-run';
17
+ /**
18
+ * Base class for every error thrown from `@graphorin/agent`.
19
+ *
20
+ * @stable
21
+ */
22
+ declare class AgentRuntimeError extends Error {
23
+ readonly code: AgentRuntimeErrorCode;
24
+ constructor(code: AgentRuntimeErrorCode, message: string, name?: string);
25
+ }
26
+ /**
27
+ * Thrown by `createAgent({...})` when the supplied options fail
28
+ * structural validation (missing `provider`, empty `name`, an
29
+ * `outputType` of kind `'text'` carrying a `schema`, ...).
30
+ *
31
+ * @stable
32
+ */
33
+ declare class InvalidAgentConfigError extends AgentRuntimeError {
34
+ constructor(reason: string);
35
+ }
36
+ /**
37
+ * Thrown by `createAgent({...})` when `preferredModel` carries an
38
+ * unknown literal (any value outside the `'fast' | 'balanced' |
39
+ * 'smart'` cost-tier vocabulary AND not a valid `ModelSpec`).
40
+ *
41
+ * @stable
42
+ */
43
+ declare class InvalidPreferredModelError extends AgentRuntimeError {
44
+ readonly value: unknown;
45
+ constructor(value: unknown);
46
+ }
47
+ /**
48
+ * Thrown by `evaluatorOptimizer({...})` when `maxIterations < 1` at
49
+ * construction time. The helper purposely surfaces the misuse early
50
+ * rather than failing on the first run.
51
+ *
52
+ * @stable
53
+ */
54
+ declare class EvaluatorOptimizerConfigError extends AgentRuntimeError {
55
+ constructor(reason: string);
56
+ }
57
+ /**
58
+ * Thrown by `runStateFromJSON(...)` when the agent name in the
59
+ * serialized state cannot be resolved against the supplied agent
60
+ * graph (renamed agent / removed handoff).
61
+ *
62
+ * @stable
63
+ */
64
+ declare class AgentResolutionError extends AgentRuntimeError {
65
+ readonly agentId: string;
66
+ constructor(agentId: string);
67
+ }
68
+ /**
69
+ * Thrown by the agent loop when the model emits a tool call referring
70
+ * to an unregistered tool (the model hallucinated a name).
71
+ *
72
+ * @stable
73
+ */
74
+ declare class ToolNotFoundError extends AgentRuntimeError {
75
+ readonly toolName: string;
76
+ constructor(toolName: string);
77
+ }
78
+ /**
79
+ * Thrown when the model invokes more than one handoff (`transfer_to_*`)
80
+ * tool in a single response. Per the agent-loop documentation this is
81
+ * an error rather than a silent drop.
82
+ *
83
+ * @stable
84
+ */
85
+ /**
86
+ * Thrown when a second `run()` / `stream()` starts while another run is
87
+ * in flight on the same `Agent` instance (AG-11). The public surface
88
+ * (`steer` / `followUp` / `abort` / `compact`) addresses "the run"
89
+ * without a run handle, so overlapping runs would share the abort
90
+ * controller, steer queue, and executor bridge — start the second run
91
+ * on its own `createAgent(...)` instance instead.
92
+ *
93
+ * @stable
94
+ */
95
+ declare class ConcurrentRunError extends AgentRuntimeError {
96
+ constructor();
97
+ }
98
+ declare class MultipleHandoffsInStepError extends AgentRuntimeError {
99
+ readonly handoffNames: ReadonlyArray<string>;
100
+ constructor(handoffNames: ReadonlyArray<string>);
101
+ }
102
+ /**
103
+ * Thrown by `runStateFromJSON(...)` when the version field in the
104
+ * serialized state is from a future major version of the framework.
105
+ *
106
+ * @stable
107
+ */
108
+ declare class RunStateVersionUnsupportedError extends AgentRuntimeError {
109
+ readonly version: string;
110
+ readonly readerVersion: string;
111
+ constructor(version: string, readerVersion: string);
112
+ }
113
+ /**
114
+ * Thrown by `runStateFromJSON(...)` when the supplied JSON does not
115
+ * shape-match the documented {@link SerializedRunState}.
116
+ *
117
+ * @stable
118
+ */
119
+ declare class RunStateMalformedError extends AgentRuntimeError {
120
+ constructor(reason: string);
121
+ }
122
+ /**
123
+ * Thrown by `Agent.fanOut(...)` when the configured
124
+ * {@link MergeAgentSidewaysInjectionGuard} fires with strictness
125
+ * `'detect-and-block'`.
126
+ *
127
+ * @stable
128
+ */
129
+ declare class MergeBlockedError extends AgentRuntimeError {
130
+ readonly fanOutId: string;
131
+ readonly reason: string;
132
+ constructor(fanOutId: string, reason: string);
133
+ }
134
+ /**
135
+ * Thrown by the protocol-injection guard when the operator selected
136
+ * the strictest deployment posture (`escapePolicy: 'reject'`) and a
137
+ * tool result body carries control characters at the corresponding
138
+ * outbound boundary.
139
+ *
140
+ * @stable
141
+ */
142
+ declare class ProtocolInjectionRejectError extends AgentRuntimeError {
143
+ readonly boundary: string;
144
+ readonly matchedPattern: string;
145
+ constructor(boundary: string, matchedPattern: string);
146
+ }
147
+ /**
148
+ * Thrown by `agent.progress.write(...)` when the atomic write fails
149
+ * (disk full, permission denied, ...). The partial `.tmp` file is
150
+ * unlinked before the error propagates.
151
+ *
152
+ * @stable
153
+ */
154
+ declare class ProgressWriteError extends AgentRuntimeError {
155
+ readonly path: string;
156
+ constructor(path: string, cause: unknown);
157
+ }
158
+ /**
159
+ * Thrown by `createAgent({...})` when the supplied
160
+ * `composeProviderMiddleware` chain violates the canonical inside-out
161
+ * ordering (DEC-145 / ADR-039).
162
+ *
163
+ * @stable
164
+ */
165
+ declare class ProviderMiddlewareOrderError extends AgentRuntimeError {
166
+ constructor(reason: string);
167
+ }
168
+ //#endregion
169
+ export { AgentResolutionError, AgentRuntimeError, AgentRuntimeErrorCode, ConcurrentRunError, EvaluatorOptimizerConfigError, InvalidAgentConfigError, InvalidPreferredModelError, MergeBlockedError, MultipleHandoffsInStepError, ProgressWriteError, ProtocolInjectionRejectError, ProviderMiddlewareOrderError, RunStateMalformedError, RunStateVersionUnsupportedError, ToolNotFoundError };
170
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/errors/index.ts"],"sourcesContent":[],"mappings":";;AAeA;AAuBA;;;;;AAgBA;AAiBA;AAoBA;AAiBA;AAkBA;AA6BA;AAUA;AACyB,KAvJb,qBAAA,GAuJa,gBAAA,GAAA,yBAAA,GAAA,yBAAA,GAAA,oCAAA,GAAA,yBAAA,GAAA,gBAAA,GAAA,0BAAA,GAAA,2BAAA,GAAA,aAAA,GAAA,4BAAA,GAAA,uBAAA,GAAA,eAAA,GAAA,6BAAA,GAAA,+BAAA,GAAA,qBAAA,GAAA,gBAAA;;;;AAiBzB;AAqBA;AAaa,cAnLA,iBAAA,SAA0B,KAAA,CAmLA;EAsB1B,SAAA,IAAA,EAxMI,qBAwMyB;EAqB7B,WAAA,CAAA,IAAA,EA5NO,qBA4NoB,EAAA,OAAA,EAAA,MAAiB,EAAA,IAAA,CAAA,EAAA,MAAA;AA6BzD;;;;;;;;cA3Oa,uBAAA,SAAgC,iBAAA;;;;;;;;;;cAiBhC,0BAAA,SAAmC,iBAAA;;;;;;;;;;;cAoBnC,6BAAA,SAAsC,iBAAA;;;;;;;;;;cAiBtC,oBAAA,SAA6B,iBAAA;;;;;;;;;;cAkB7B,iBAAA,SAA0B,iBAAA;;;;;;;;;;;;;;;;;;;;;cA6B1B,kBAAA,SAA2B,iBAAA;;;cAU3B,2BAAA,SAAoC,iBAAA;yBACxB;4BACG;;;;;;;;cAgBf,+BAAA,SAAwC,iBAAA;;;;;;;;;;;cAqBxC,sBAAA,SAA+B,iBAAA;;;;;;;;;;cAa/B,iBAAA,SAA0B,iBAAA;;;;;;;;;;;;;cAsB1B,4BAAA,SAAqC,iBAAA;;;;;;;;;;;;cAqBrC,kBAAA,SAA2B,iBAAA;;;;;;;;;;;cA6B3B,4BAAA,SAAqC,iBAAA"}
@@ -0,0 +1,204 @@
1
+ //#region src/errors/index.ts
2
+ /**
3
+ * Base class for every error thrown from `@graphorin/agent`.
4
+ *
5
+ * @stable
6
+ */
7
+ var AgentRuntimeError = class extends Error {
8
+ code;
9
+ constructor(code, message, name = "AgentRuntimeError") {
10
+ super(message);
11
+ this.name = name;
12
+ this.code = code;
13
+ }
14
+ };
15
+ /**
16
+ * Thrown by `createAgent({...})` when the supplied options fail
17
+ * structural validation (missing `provider`, empty `name`, an
18
+ * `outputType` of kind `'text'` carrying a `schema`, ...).
19
+ *
20
+ * @stable
21
+ */
22
+ var InvalidAgentConfigError = class extends AgentRuntimeError {
23
+ constructor(reason) {
24
+ super("invalid-config", `Invalid createAgent({...}) options: ${reason}.`, "InvalidAgentConfigError");
25
+ }
26
+ };
27
+ /**
28
+ * Thrown by `createAgent({...})` when `preferredModel` carries an
29
+ * unknown literal (any value outside the `'fast' | 'balanced' |
30
+ * 'smart'` cost-tier vocabulary AND not a valid `ModelSpec`).
31
+ *
32
+ * @stable
33
+ */
34
+ var InvalidPreferredModelError = class extends AgentRuntimeError {
35
+ value;
36
+ constructor(value) {
37
+ super("invalid-preferred-model", `Invalid Agent.preferredModel: ${JSON.stringify(value)}. Expected 'fast' | 'balanced' | 'smart' | ModelSpec.`, "InvalidPreferredModelError");
38
+ this.value = value;
39
+ }
40
+ };
41
+ /**
42
+ * Thrown by `evaluatorOptimizer({...})` when `maxIterations < 1` at
43
+ * construction time. The helper purposely surfaces the misuse early
44
+ * rather than failing on the first run.
45
+ *
46
+ * @stable
47
+ */
48
+ var EvaluatorOptimizerConfigError = class extends AgentRuntimeError {
49
+ constructor(reason) {
50
+ super("invalid-evaluator-optimizer-config", `Invalid evaluatorOptimizer({...}) options: ${reason}.`, "EvaluatorOptimizerConfigError");
51
+ }
52
+ };
53
+ /**
54
+ * Thrown by `runStateFromJSON(...)` when the agent name in the
55
+ * serialized state cannot be resolved against the supplied agent
56
+ * graph (renamed agent / removed handoff).
57
+ *
58
+ * @stable
59
+ */
60
+ var AgentResolutionError = class extends AgentRuntimeError {
61
+ agentId;
62
+ constructor(agentId) {
63
+ super("agent-resolution-failed", `runStateFromJSON: agent '${agentId}' is not registered in the supplied graph.`, "AgentResolutionError");
64
+ this.agentId = agentId;
65
+ }
66
+ };
67
+ /**
68
+ * Thrown by the agent loop when the model emits a tool call referring
69
+ * to an unregistered tool (the model hallucinated a name).
70
+ *
71
+ * @stable
72
+ */
73
+ var ToolNotFoundError = class extends AgentRuntimeError {
74
+ toolName;
75
+ constructor(toolName) {
76
+ super("tool-not-found", `Tool '${toolName}' is not registered on this agent.`, "ToolNotFoundError");
77
+ this.toolName = toolName;
78
+ }
79
+ };
80
+ /**
81
+ * Thrown when the model invokes more than one handoff (`transfer_to_*`)
82
+ * tool in a single response. Per the agent-loop documentation this is
83
+ * an error rather than a silent drop.
84
+ *
85
+ * @stable
86
+ */
87
+ /**
88
+ * Thrown when a second `run()` / `stream()` starts while another run is
89
+ * in flight on the same `Agent` instance (AG-11). The public surface
90
+ * (`steer` / `followUp` / `abort` / `compact`) addresses "the run"
91
+ * without a run handle, so overlapping runs would share the abort
92
+ * controller, steer queue, and executor bridge — start the second run
93
+ * on its own `createAgent(...)` instance instead.
94
+ *
95
+ * @stable
96
+ */
97
+ var ConcurrentRunError = class extends AgentRuntimeError {
98
+ constructor() {
99
+ super("concurrent-run", "This Agent instance already has a run in flight. One run per instance: await the active run (or abort it), or create a separate agent instance for parallel work.", "ConcurrentRunError");
100
+ }
101
+ };
102
+ var MultipleHandoffsInStepError = class extends AgentRuntimeError {
103
+ handoffNames;
104
+ constructor(handoffNames) {
105
+ super("multiple-handoffs-in-step", `The model invoked multiple handoff tools in one step: ${handoffNames.join(", ")}.`, "MultipleHandoffsInStepError");
106
+ this.handoffNames = handoffNames;
107
+ }
108
+ };
109
+ /**
110
+ * Thrown by `runStateFromJSON(...)` when the version field in the
111
+ * serialized state is from a future major version of the framework.
112
+ *
113
+ * @stable
114
+ */
115
+ var RunStateVersionUnsupportedError = class extends AgentRuntimeError {
116
+ version;
117
+ readerVersion;
118
+ constructor(version, readerVersion) {
119
+ super("run-state-version-unsupported", `RunState version '${version}' is newer than reader '${readerVersion}'. Upgrade @graphorin/agent to load this state.`, "RunStateVersionUnsupportedError");
120
+ this.version = version;
121
+ this.readerVersion = readerVersion;
122
+ }
123
+ };
124
+ /**
125
+ * Thrown by `runStateFromJSON(...)` when the supplied JSON does not
126
+ * shape-match the documented {@link SerializedRunState}.
127
+ *
128
+ * @stable
129
+ */
130
+ var RunStateMalformedError = class extends AgentRuntimeError {
131
+ constructor(reason) {
132
+ super("run-state-malformed", `Malformed RunState JSON: ${reason}.`, "RunStateMalformedError");
133
+ }
134
+ };
135
+ /**
136
+ * Thrown by `Agent.fanOut(...)` when the configured
137
+ * {@link MergeAgentSidewaysInjectionGuard} fires with strictness
138
+ * `'detect-and-block'`.
139
+ *
140
+ * @stable
141
+ */
142
+ var MergeBlockedError = class extends AgentRuntimeError {
143
+ fanOutId;
144
+ reason;
145
+ constructor(fanOutId, reason) {
146
+ super("merge-blocked", `Agent.fanOut('${fanOutId}') merge blocked by MergeAgentSidewaysInjectionGuard: ${reason}.`, "MergeBlockedError");
147
+ this.fanOutId = fanOutId;
148
+ this.reason = reason;
149
+ }
150
+ };
151
+ /**
152
+ * Thrown by the protocol-injection guard when the operator selected
153
+ * the strictest deployment posture (`escapePolicy: 'reject'`) and a
154
+ * tool result body carries control characters at the corresponding
155
+ * outbound boundary.
156
+ *
157
+ * @stable
158
+ */
159
+ var ProtocolInjectionRejectError = class extends AgentRuntimeError {
160
+ boundary;
161
+ matchedPattern;
162
+ constructor(boundary, matchedPattern) {
163
+ super("protocol-injection-rejected", `Protocol injection guard rejected output at the '${boundary}' boundary (matched ${matchedPattern}).`, "ProtocolInjectionRejectError");
164
+ this.boundary = boundary;
165
+ this.matchedPattern = matchedPattern;
166
+ }
167
+ };
168
+ /**
169
+ * Thrown by `agent.progress.write(...)` when the atomic write fails
170
+ * (disk full, permission denied, ...). The partial `.tmp` file is
171
+ * unlinked before the error propagates.
172
+ *
173
+ * @stable
174
+ */
175
+ var ProgressWriteError = class extends AgentRuntimeError {
176
+ path;
177
+ constructor(path, cause) {
178
+ const message = cause instanceof Error ? cause.message : String(cause);
179
+ super("progress-write-failed", `agent.progress.write('${path}') failed: ${message}.`, "ProgressWriteError");
180
+ this.path = path;
181
+ if (cause !== void 0) Object.defineProperty(this, "cause", {
182
+ value: cause,
183
+ enumerable: false,
184
+ configurable: true,
185
+ writable: true
186
+ });
187
+ }
188
+ };
189
+ /**
190
+ * Thrown by `createAgent({...})` when the supplied
191
+ * `composeProviderMiddleware` chain violates the canonical inside-out
192
+ * ordering (DEC-145 / ADR-039).
193
+ *
194
+ * @stable
195
+ */
196
+ var ProviderMiddlewareOrderError = class extends AgentRuntimeError {
197
+ constructor(reason) {
198
+ super("middleware-order-violation", `Provider middleware composition violated the inside-out ordering: ${reason}.`, "ProviderMiddlewareOrderError");
199
+ }
200
+ };
201
+
202
+ //#endregion
203
+ export { AgentResolutionError, AgentRuntimeError, ConcurrentRunError, EvaluatorOptimizerConfigError, InvalidAgentConfigError, InvalidPreferredModelError, MergeBlockedError, MultipleHandoffsInStepError, ProgressWriteError, ProtocolInjectionRejectError, ProviderMiddlewareOrderError, RunStateMalformedError, RunStateVersionUnsupportedError, ToolNotFoundError };
204
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/errors/index.ts"],"sourcesContent":["/**\n * Typed error surface for `@graphorin/agent`.\n *\n * Every error class extends the base {@link AgentRuntimeError} which is\n * a thin wrapper around `Error` with a stable `code` discriminator so\n * callers can `switch` on it without parsing messages.\n *\n * @packageDocumentation\n */\n\n/**\n * Stable code discriminator surfaced on every {@link AgentRuntimeError}.\n *\n * @stable\n */\nexport type AgentRuntimeErrorCode =\n | 'invalid-config'\n | 'invalid-preferred-model'\n | 'invalid-fallback-policy'\n | 'invalid-evaluator-optimizer-config'\n | 'agent-resolution-failed'\n | 'tool-not-found'\n | 'handoff-target-not-found'\n | 'multiple-handoffs-in-step'\n | 'run-aborted'\n | 'middleware-order-violation'\n | 'progress-write-failed'\n | 'merge-blocked'\n | 'protocol-injection-rejected'\n | 'run-state-version-unsupported'\n | 'run-state-malformed'\n | 'concurrent-run';\n\n/**\n * Base class for every error thrown from `@graphorin/agent`.\n *\n * @stable\n */\nexport class AgentRuntimeError extends Error {\n readonly code: AgentRuntimeErrorCode;\n constructor(code: AgentRuntimeErrorCode, message: string, name = 'AgentRuntimeError') {\n super(message);\n this.name = name;\n this.code = code;\n }\n}\n\n/**\n * Thrown by `createAgent({...})` when the supplied options fail\n * structural validation (missing `provider`, empty `name`, an\n * `outputType` of kind `'text'` carrying a `schema`, ...).\n *\n * @stable\n */\nexport class InvalidAgentConfigError extends AgentRuntimeError {\n constructor(reason: string) {\n super(\n 'invalid-config',\n `Invalid createAgent({...}) options: ${reason}.`,\n 'InvalidAgentConfigError',\n );\n }\n}\n\n/**\n * Thrown by `createAgent({...})` when `preferredModel` carries an\n * unknown literal (any value outside the `'fast' | 'balanced' |\n * 'smart'` cost-tier vocabulary AND not a valid `ModelSpec`).\n *\n * @stable\n */\nexport class InvalidPreferredModelError extends AgentRuntimeError {\n readonly value: unknown;\n constructor(value: unknown) {\n super(\n 'invalid-preferred-model',\n `Invalid Agent.preferredModel: ${JSON.stringify(value)}. ` +\n \"Expected 'fast' | 'balanced' | 'smart' | ModelSpec.\",\n 'InvalidPreferredModelError',\n );\n this.value = value;\n }\n}\n\n/**\n * Thrown by `evaluatorOptimizer({...})` when `maxIterations < 1` at\n * construction time. The helper purposely surfaces the misuse early\n * rather than failing on the first run.\n *\n * @stable\n */\nexport class EvaluatorOptimizerConfigError extends AgentRuntimeError {\n constructor(reason: string) {\n super(\n 'invalid-evaluator-optimizer-config',\n `Invalid evaluatorOptimizer({...}) options: ${reason}.`,\n 'EvaluatorOptimizerConfigError',\n );\n }\n}\n\n/**\n * Thrown by `runStateFromJSON(...)` when the agent name in the\n * serialized state cannot be resolved against the supplied agent\n * graph (renamed agent / removed handoff).\n *\n * @stable\n */\nexport class AgentResolutionError extends AgentRuntimeError {\n readonly agentId: string;\n constructor(agentId: string) {\n super(\n 'agent-resolution-failed',\n `runStateFromJSON: agent '${agentId}' is not registered in the supplied graph.`,\n 'AgentResolutionError',\n );\n this.agentId = agentId;\n }\n}\n\n/**\n * Thrown by the agent loop when the model emits a tool call referring\n * to an unregistered tool (the model hallucinated a name).\n *\n * @stable\n */\nexport class ToolNotFoundError extends AgentRuntimeError {\n readonly toolName: string;\n constructor(toolName: string) {\n super(\n 'tool-not-found',\n `Tool '${toolName}' is not registered on this agent.`,\n 'ToolNotFoundError',\n );\n this.toolName = toolName;\n }\n}\n\n/**\n * Thrown when the model invokes more than one handoff (`transfer_to_*`)\n * tool in a single response. Per the agent-loop documentation this is\n * an error rather than a silent drop.\n *\n * @stable\n */\n/**\n * Thrown when a second `run()` / `stream()` starts while another run is\n * in flight on the same `Agent` instance (AG-11). The public surface\n * (`steer` / `followUp` / `abort` / `compact`) addresses \"the run\"\n * without a run handle, so overlapping runs would share the abort\n * controller, steer queue, and executor bridge — start the second run\n * on its own `createAgent(...)` instance instead.\n *\n * @stable\n */\nexport class ConcurrentRunError extends AgentRuntimeError {\n constructor() {\n super(\n 'concurrent-run',\n 'This Agent instance already has a run in flight. One run per instance: await the active run (or abort it), or create a separate agent instance for parallel work.',\n 'ConcurrentRunError',\n );\n }\n}\n\nexport class MultipleHandoffsInStepError extends AgentRuntimeError {\n readonly handoffNames: ReadonlyArray<string>;\n constructor(handoffNames: ReadonlyArray<string>) {\n super(\n 'multiple-handoffs-in-step',\n `The model invoked multiple handoff tools in one step: ${handoffNames.join(', ')}.`,\n 'MultipleHandoffsInStepError',\n );\n this.handoffNames = handoffNames;\n }\n}\n\n/**\n * Thrown by `runStateFromJSON(...)` when the version field in the\n * serialized state is from a future major version of the framework.\n *\n * @stable\n */\nexport class RunStateVersionUnsupportedError extends AgentRuntimeError {\n readonly version: string;\n readonly readerVersion: string;\n constructor(version: string, readerVersion: string) {\n super(\n 'run-state-version-unsupported',\n `RunState version '${version}' is newer than reader '${readerVersion}'. ` +\n 'Upgrade @graphorin/agent to load this state.',\n 'RunStateVersionUnsupportedError',\n );\n this.version = version;\n this.readerVersion = readerVersion;\n }\n}\n\n/**\n * Thrown by `runStateFromJSON(...)` when the supplied JSON does not\n * shape-match the documented {@link SerializedRunState}.\n *\n * @stable\n */\nexport class RunStateMalformedError extends AgentRuntimeError {\n constructor(reason: string) {\n super('run-state-malformed', `Malformed RunState JSON: ${reason}.`, 'RunStateMalformedError');\n }\n}\n\n/**\n * Thrown by `Agent.fanOut(...)` when the configured\n * {@link MergeAgentSidewaysInjectionGuard} fires with strictness\n * `'detect-and-block'`.\n *\n * @stable\n */\nexport class MergeBlockedError extends AgentRuntimeError {\n readonly fanOutId: string;\n readonly reason: string;\n constructor(fanOutId: string, reason: string) {\n super(\n 'merge-blocked',\n `Agent.fanOut('${fanOutId}') merge blocked by MergeAgentSidewaysInjectionGuard: ${reason}.`,\n 'MergeBlockedError',\n );\n this.fanOutId = fanOutId;\n this.reason = reason;\n }\n}\n\n/**\n * Thrown by the protocol-injection guard when the operator selected\n * the strictest deployment posture (`escapePolicy: 'reject'`) and a\n * tool result body carries control characters at the corresponding\n * outbound boundary.\n *\n * @stable\n */\nexport class ProtocolInjectionRejectError extends AgentRuntimeError {\n readonly boundary: string;\n readonly matchedPattern: string;\n constructor(boundary: string, matchedPattern: string) {\n super(\n 'protocol-injection-rejected',\n `Protocol injection guard rejected output at the '${boundary}' boundary (matched ${matchedPattern}).`,\n 'ProtocolInjectionRejectError',\n );\n this.boundary = boundary;\n this.matchedPattern = matchedPattern;\n }\n}\n\n/**\n * Thrown by `agent.progress.write(...)` when the atomic write fails\n * (disk full, permission denied, ...). The partial `.tmp` file is\n * unlinked before the error propagates.\n *\n * @stable\n */\nexport class ProgressWriteError extends AgentRuntimeError {\n readonly path: string;\n constructor(path: string, cause: unknown) {\n const message = cause instanceof Error ? cause.message : String(cause);\n super(\n 'progress-write-failed',\n `agent.progress.write('${path}') failed: ${message}.`,\n 'ProgressWriteError',\n );\n this.path = path;\n if (cause !== undefined) {\n // Preserve the underlying cause for diagnostics.\n Object.defineProperty(this, 'cause', {\n value: cause,\n enumerable: false,\n configurable: true,\n writable: true,\n });\n }\n }\n}\n\n/**\n * Thrown by `createAgent({...})` when the supplied\n * `composeProviderMiddleware` chain violates the canonical inside-out\n * ordering (DEC-145 / ADR-039).\n *\n * @stable\n */\nexport class ProviderMiddlewareOrderError extends AgentRuntimeError {\n constructor(reason: string) {\n super(\n 'middleware-order-violation',\n `Provider middleware composition violated the inside-out ordering: ${reason}.`,\n 'ProviderMiddlewareOrderError',\n );\n }\n}\n"],"mappings":";;;;;;AAsCA,IAAa,oBAAb,cAAuC,MAAM;CAC3C,AAAS;CACT,YAAY,MAA6B,SAAiB,OAAO,qBAAqB;AACpF,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,OAAO;;;;;;;;;;AAWhB,IAAa,0BAAb,cAA6C,kBAAkB;CAC7D,YAAY,QAAgB;AAC1B,QACE,kBACA,uCAAuC,OAAO,IAC9C,0BACD;;;;;;;;;;AAWL,IAAa,6BAAb,cAAgD,kBAAkB;CAChE,AAAS;CACT,YAAY,OAAgB;AAC1B,QACE,2BACA,iCAAiC,KAAK,UAAU,MAAM,CAAC,wDAEvD,6BACD;AACD,OAAK,QAAQ;;;;;;;;;;AAWjB,IAAa,gCAAb,cAAmD,kBAAkB;CACnE,YAAY,QAAgB;AAC1B,QACE,sCACA,8CAA8C,OAAO,IACrD,gCACD;;;;;;;;;;AAWL,IAAa,uBAAb,cAA0C,kBAAkB;CAC1D,AAAS;CACT,YAAY,SAAiB;AAC3B,QACE,2BACA,4BAA4B,QAAQ,6CACpC,uBACD;AACD,OAAK,UAAU;;;;;;;;;AAUnB,IAAa,oBAAb,cAAuC,kBAAkB;CACvD,AAAS;CACT,YAAY,UAAkB;AAC5B,QACE,kBACA,SAAS,SAAS,qCAClB,oBACD;AACD,OAAK,WAAW;;;;;;;;;;;;;;;;;;;;AAqBpB,IAAa,qBAAb,cAAwC,kBAAkB;CACxD,cAAc;AACZ,QACE,kBACA,qKACA,qBACD;;;AAIL,IAAa,8BAAb,cAAiD,kBAAkB;CACjE,AAAS;CACT,YAAY,cAAqC;AAC/C,QACE,6BACA,yDAAyD,aAAa,KAAK,KAAK,CAAC,IACjF,8BACD;AACD,OAAK,eAAe;;;;;;;;;AAUxB,IAAa,kCAAb,cAAqD,kBAAkB;CACrE,AAAS;CACT,AAAS;CACT,YAAY,SAAiB,eAAuB;AAClD,QACE,iCACA,qBAAqB,QAAQ,0BAA0B,cAAc,kDAErE,kCACD;AACD,OAAK,UAAU;AACf,OAAK,gBAAgB;;;;;;;;;AAUzB,IAAa,yBAAb,cAA4C,kBAAkB;CAC5D,YAAY,QAAgB;AAC1B,QAAM,uBAAuB,4BAA4B,OAAO,IAAI,yBAAyB;;;;;;;;;;AAWjG,IAAa,oBAAb,cAAuC,kBAAkB;CACvD,AAAS;CACT,AAAS;CACT,YAAY,UAAkB,QAAgB;AAC5C,QACE,iBACA,iBAAiB,SAAS,wDAAwD,OAAO,IACzF,oBACD;AACD,OAAK,WAAW;AAChB,OAAK,SAAS;;;;;;;;;;;AAYlB,IAAa,+BAAb,cAAkD,kBAAkB;CAClE,AAAS;CACT,AAAS;CACT,YAAY,UAAkB,gBAAwB;AACpD,QACE,+BACA,oDAAoD,SAAS,sBAAsB,eAAe,KAClG,+BACD;AACD,OAAK,WAAW;AAChB,OAAK,iBAAiB;;;;;;;;;;AAW1B,IAAa,qBAAb,cAAwC,kBAAkB;CACxD,AAAS;CACT,YAAY,MAAc,OAAgB;EACxC,MAAM,UAAU,iBAAiB,QAAQ,MAAM,UAAU,OAAO,MAAM;AACtE,QACE,yBACA,yBAAyB,KAAK,aAAa,QAAQ,IACnD,qBACD;AACD,OAAK,OAAO;AACZ,MAAI,UAAU,OAEZ,QAAO,eAAe,MAAM,SAAS;GACnC,OAAO;GACP,YAAY;GACZ,cAAc;GACd,UAAU;GACX,CAAC;;;;;;;;;;AAYR,IAAa,+BAAb,cAAkD,kBAAkB;CAClE,YAAY,QAAgB;AAC1B,QACE,8BACA,qEAAqE,OAAO,IAC5E,+BACD"}