@adjudicate/adapter-core 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +55 -0
- package/package.json +36 -0
- package/src/bridge.ts +111 -0
- package/src/decisions.ts +294 -0
- package/src/errors.ts +36 -0
- package/src/index.ts +98 -0
- package/src/loop.ts +569 -0
- package/src/persistence-redis.ts +158 -0
- package/src/persistence.ts +176 -0
- package/src/trace.ts +105 -0
- package/src/types.ts +236 -0
- package/tests/bridge.test.ts +112 -0
- package/tests/decisions.test.ts +194 -0
- package/tests/persistence-redis.test.ts +207 -0
- package/tests/persistence.test.ts +105 -0
- package/tests/trace.test.ts +223 -0
- package/tsconfig.json +7 -0
- package/vitest.config.ts +27 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bruno Rodolpho
|
|
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
|
|
13
|
+
all 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
|
|
21
|
+
THE SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
# @adjudicate/adapter-core
|
|
2
|
+
|
|
3
|
+
Provider-neutral orchestration for `adjudicate`-backed LLM agents.
|
|
4
|
+
|
|
5
|
+
The loop, bridge, decision translator, persistence shims, and error taxonomy live here. Provider adapters (`@adjudicate/anthropic`, `@adjudicate/openai`, …) each implement a `ProviderBridge<H>` against their SDK and re-export a thin `createAdjudicatedAgent` that wires it into this loop.
|
|
6
|
+
|
|
7
|
+
## Layout
|
|
8
|
+
|
|
9
|
+
```
|
|
10
|
+
src/
|
|
11
|
+
loop.ts ← runAdjudicatedLoop — send/resume/confirm orchestrator
|
|
12
|
+
bridge.ts ← classifyIncomingToolUse + buildEnvelopeFromToolUse
|
|
13
|
+
decisions.ts ← Decision → ToolResultBlock + LoopAction translator
|
|
14
|
+
persistence.ts ← DeferRedis, ParkRedis, ConfirmationStore (+ in-mem shims)
|
|
15
|
+
errors.ts ← AdapterError + AdapterErrorCode
|
|
16
|
+
types.ts ← ProviderBridge<H>, AssistantTurn, ToolResultBlock, …
|
|
17
|
+
index.ts ← barrel
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
## Invariants the loop preserves
|
|
21
|
+
|
|
22
|
+
These are the same load-bearing properties the kernel demands. Any provider adapter built on this loop inherits them:
|
|
23
|
+
|
|
24
|
+
1. **Every intent envelope crosses `adjudicateAndAudit()`.** No bypass, no taint elevation, no guard-ordering short-circuit.
|
|
25
|
+
2. **First non-continue Decision wins** per assistant turn. Subsequent `tool_use` blocks in the same turn are surfaced as `not_processed_due_to_pause`.
|
|
26
|
+
3. **REWRITE executes the rewritten envelope**, never the original.
|
|
27
|
+
4. **DEFER persists full envelope fields** (version/nonce/taint/actorPrincipal). The resume side re-derives `intentHash` and detects tampering.
|
|
28
|
+
5. **REQUEST_CONFIRMATION blobs are hash-verified** at `confirm()`. Tampered blobs refuse to resume.
|
|
29
|
+
6. **History `H` is opaque to the loop.** The bridge is the only thing that knows the SDK-specific conversation shape; the loop threads it.
|
|
30
|
+
|
|
31
|
+
## Provider adapters
|
|
32
|
+
|
|
33
|
+
Implement the `ProviderBridge<H>` contract:
|
|
34
|
+
|
|
35
|
+
```ts
|
|
36
|
+
interface ProviderBridge<H> {
|
|
37
|
+
emptyHistory(): H;
|
|
38
|
+
appendUserMessage(history: H, text: string): H;
|
|
39
|
+
send(
|
|
40
|
+
history: H,
|
|
41
|
+
request: { systemPrompt: string; maxTokens: number; toolSchemas: ReadonlyArray<ToolSchema> },
|
|
42
|
+
): Promise<{ history: H; turn: AssistantTurn }>;
|
|
43
|
+
appendToolResults(history: H, results: ReadonlyArray<ToolResultBlock>): H;
|
|
44
|
+
}
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Reference implementations:
|
|
48
|
+
- `@adjudicate/anthropic` — `H = ReadonlyArray<MessageParam>`
|
|
49
|
+
- `@adjudicate/openai` — `H = ReadonlyArray<OpenAIMessage>`
|
|
50
|
+
|
|
51
|
+
Adding a new provider is a < 200-line PR: a bridge module plus a renderer.
|
|
52
|
+
|
|
53
|
+
## Status
|
|
54
|
+
|
|
55
|
+
Shipped at adapter-core v0.6. Contracts stable. `ProviderBridge<H>` may gain optional methods for streaming / cancellation in future minor versions; existing implementations continue to compile.
|
package/package.json
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@adjudicate/adapter-core",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"publishConfig": {
|
|
5
|
+
"access": "public"
|
|
6
|
+
},
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/index.js",
|
|
9
|
+
"types": "./dist/index.d.ts",
|
|
10
|
+
"exports": {
|
|
11
|
+
".": {
|
|
12
|
+
"types": "./dist/index.d.ts",
|
|
13
|
+
"import": "./dist/index.js",
|
|
14
|
+
"default": "./dist/index.js"
|
|
15
|
+
}
|
|
16
|
+
},
|
|
17
|
+
"dependencies": {
|
|
18
|
+
"@adjudicate/core": "1.0.0",
|
|
19
|
+
"@adjudicate/audit": "1.0.0",
|
|
20
|
+
"@adjudicate/runtime": "0.1.0"
|
|
21
|
+
},
|
|
22
|
+
"devDependencies": {
|
|
23
|
+
"@eslint/eslintrc": "^3.0.0",
|
|
24
|
+
"@vitest/coverage-v8": "^3.2.0",
|
|
25
|
+
"eslint": "^9.0.0",
|
|
26
|
+
"typescript": "^5.9.0",
|
|
27
|
+
"vitest": "^3.2.0",
|
|
28
|
+
"@adjudicate/pack-payments-pix": "0.1.0",
|
|
29
|
+
"@adjudicate/eslint-config": "0.0.1"
|
|
30
|
+
},
|
|
31
|
+
"scripts": {
|
|
32
|
+
"build": "tsc --outDir dist",
|
|
33
|
+
"lint": "tsc --noEmit && eslint \"src/**/*.ts\"",
|
|
34
|
+
"test": "vitest run"
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/bridge.ts
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Bridge module — the boundary between provider tool-use blocks and
|
|
3
|
+
* adjudicate's `IntentEnvelope`s.
|
|
4
|
+
*
|
|
5
|
+
* Convention: intent-kind tool name (e.g. `pix.charge.create`) is
|
|
6
|
+
* translated to a wire-friendly form by replacing `.` with `_` (most
|
|
7
|
+
* provider APIs forbid dots in tool names). The renderer applies the
|
|
8
|
+
* translation outbound; `classifyIncomingToolUse` accepts either the
|
|
9
|
+
* translated form (live API path) or the raw dotted form (mocked-test
|
|
10
|
+
* path) so test harnesses that bypass the renderer continue to work.
|
|
11
|
+
*
|
|
12
|
+
* Taint is ALWAYS `"UNTRUSTED"` for envelopes derived from LLM tool_use
|
|
13
|
+
* blocks. There is no path from this module that raises taint upward;
|
|
14
|
+
* TRUSTED intents (e.g. webhook confirmations) come from elsewhere.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
import { buildEnvelope, type IntentEnvelope, type Taint } from "@adjudicate/core";
|
|
18
|
+
import type { Plan } from "@adjudicate/core/llm";
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Translate an intent-kind / READ-tool name to its wire-API form.
|
|
22
|
+
* Replaces `.` with `_` so names like `pix.charge.create` become
|
|
23
|
+
* `pix_charge_create`, matching the lowest-common-denominator tool-name
|
|
24
|
+
* pattern (`^[a-zA-Z0-9_-]+$`) that both Anthropic and OpenAI accept.
|
|
25
|
+
* No-op for names that already contain only API-allowed characters.
|
|
26
|
+
*
|
|
27
|
+
* Reversibility caveat: an intent kind `a.b` and a READ tool `a_b` both
|
|
28
|
+
* translate to `a_b` and become indistinguishable on the wire. Adopters
|
|
29
|
+
* who hit this collision should rename one of them; the Pack-conformance
|
|
30
|
+
* check (P2) surfaces the collision at install time.
|
|
31
|
+
*/
|
|
32
|
+
export function intentKindToApiName(name: string): string {
|
|
33
|
+
return name.replaceAll(".", "_");
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export type ToolUseClassification =
|
|
37
|
+
| { readonly kind: "read"; readonly name: string; readonly input: unknown }
|
|
38
|
+
| {
|
|
39
|
+
readonly kind: "intent";
|
|
40
|
+
readonly intentKind: string;
|
|
41
|
+
readonly payload: unknown;
|
|
42
|
+
}
|
|
43
|
+
| { readonly kind: "out_of_plan"; readonly name: string };
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Decide whether an incoming `tool_use` is a READ tool execution, an
|
|
47
|
+
* intent proposal, or a hallucinated tool the planner did not advertise.
|
|
48
|
+
*
|
|
49
|
+
* Out-of-plan tool_uses translate to `isError: true` tool-results so the
|
|
50
|
+
* loop never silently fails — the model gets a recoverable signal.
|
|
51
|
+
*
|
|
52
|
+
* The match is forgiving: the planner exposes the raw (dotted) intent
|
|
53
|
+
* kind, the renderer ships the translated (underscored) form to the
|
|
54
|
+
* provider API, and the model echoes back the translated form on
|
|
55
|
+
* `tool_use`. We compare both raw and translated against each candidate
|
|
56
|
+
* so mocked-test paths (which skip the renderer translation) and
|
|
57
|
+
* live-API paths (which round-trip through translation) both work.
|
|
58
|
+
*/
|
|
59
|
+
export function classifyIncomingToolUse(
|
|
60
|
+
toolUse: { readonly name: string; readonly input: unknown },
|
|
61
|
+
plan: Plan,
|
|
62
|
+
): ToolUseClassification {
|
|
63
|
+
const matchesName = (candidate: string): boolean =>
|
|
64
|
+
candidate === toolUse.name ||
|
|
65
|
+
intentKindToApiName(candidate) === toolUse.name;
|
|
66
|
+
|
|
67
|
+
const readMatch = plan.visibleReadTools.find(matchesName);
|
|
68
|
+
if (readMatch !== undefined) {
|
|
69
|
+
return { kind: "read", name: readMatch, input: toolUse.input };
|
|
70
|
+
}
|
|
71
|
+
const intentMatch = plan.allowedIntents.find(matchesName);
|
|
72
|
+
if (intentMatch !== undefined) {
|
|
73
|
+
return {
|
|
74
|
+
kind: "intent",
|
|
75
|
+
intentKind: intentMatch,
|
|
76
|
+
payload: toolUse.input,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
return { kind: "out_of_plan", name: toolUse.name };
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface BuildEnvelopeFromToolUseArgs {
|
|
83
|
+
readonly intentKind: string;
|
|
84
|
+
readonly payload: unknown;
|
|
85
|
+
readonly sessionId: string;
|
|
86
|
+
/**
|
|
87
|
+
* Taint of the proposing context. The loop pins this to `"UNTRUSTED"`
|
|
88
|
+
* for LLM-derived envelopes; this argument exists for symmetry with
|
|
89
|
+
* `buildEnvelope` and to keep the boundary explicit.
|
|
90
|
+
*/
|
|
91
|
+
readonly taint: Taint;
|
|
92
|
+
readonly nonce: string;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/**
|
|
96
|
+
* Construct an IntentEnvelope from a provider-neutral tool_use. Wraps
|
|
97
|
+
* `buildEnvelope` from @adjudicate/core with adapter-specific defaults:
|
|
98
|
+
* principal = `"llm"`, taint as supplied (always `"UNTRUSTED"` from the
|
|
99
|
+
* loop).
|
|
100
|
+
*/
|
|
101
|
+
export function buildEnvelopeFromToolUse(
|
|
102
|
+
args: BuildEnvelopeFromToolUseArgs,
|
|
103
|
+
): IntentEnvelope<string, unknown> {
|
|
104
|
+
return buildEnvelope({
|
|
105
|
+
kind: args.intentKind,
|
|
106
|
+
payload: args.payload,
|
|
107
|
+
actor: { principal: "llm", sessionId: args.sessionId },
|
|
108
|
+
taint: args.taint,
|
|
109
|
+
nonce: args.nonce,
|
|
110
|
+
});
|
|
111
|
+
}
|
package/src/decisions.ts
ADDED
|
@@ -0,0 +1,294 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Decision → provider-neutral tool-result + loop-action translator.
|
|
3
|
+
*
|
|
4
|
+
* One branch per `Decision.kind`. Returns:
|
|
5
|
+
* - `toolResult` — the provider-neutral `ToolResultBlock` that goes back
|
|
6
|
+
* to the model in the next user-role message (or `null` if no tool-
|
|
7
|
+
* result is sent).
|
|
8
|
+
* - `loopAction` — what the loop should do next: `continue` (next
|
|
9
|
+
* iteration), `pause_for_user_confirmation` / `pause_for_defer`
|
|
10
|
+
* (return outcome to adopter), or `complete_for_escalation`
|
|
11
|
+
* (terminate the turn).
|
|
12
|
+
* - `events` — `AgentEvent`s to push for audit / transcript display.
|
|
13
|
+
*
|
|
14
|
+
* **REWRITE** runs the executor against the *rewritten* envelope (NOT
|
|
15
|
+
* the original) and surfaces a human-readable note in the tool-result
|
|
16
|
+
* by default.
|
|
17
|
+
*
|
|
18
|
+
* **First non-continue Decision wins**: if multiple tool_use blocks fire
|
|
19
|
+
* in the same assistant turn, the loop processes them in order but
|
|
20
|
+
* stops translating the moment a non-continue Decision arrives. The
|
|
21
|
+
* remaining blocks are surfaced as `not_processed_due_to_pause`.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
import type { Decision, IntentEnvelope } from "@adjudicate/core";
|
|
25
|
+
import { parkDeferredIntent } from "@adjudicate/runtime";
|
|
26
|
+
import { AdapterError, AdapterErrorCode } from "./errors.js";
|
|
27
|
+
import type {
|
|
28
|
+
ConfirmationStore,
|
|
29
|
+
DeferRedis,
|
|
30
|
+
ParkRedis,
|
|
31
|
+
} from "./persistence.js";
|
|
32
|
+
import type {
|
|
33
|
+
AdopterExecutor,
|
|
34
|
+
AgentEvent,
|
|
35
|
+
AgentLogger,
|
|
36
|
+
ToolResultBlock,
|
|
37
|
+
} from "./types.js";
|
|
38
|
+
|
|
39
|
+
export interface DecisionTranslationContext<K extends string, P, S, H> {
|
|
40
|
+
readonly decision: Decision;
|
|
41
|
+
readonly envelope: IntentEnvelope<K, P>;
|
|
42
|
+
readonly toolUseId: string;
|
|
43
|
+
readonly sessionId: string;
|
|
44
|
+
readonly state: S;
|
|
45
|
+
readonly executor: AdopterExecutor<K, P, S>;
|
|
46
|
+
readonly deferStore: DeferRedis & ParkRedis;
|
|
47
|
+
readonly confirmationStore: ConfirmationStore<H>;
|
|
48
|
+
readonly historySnapshot: H;
|
|
49
|
+
readonly rk: (raw: string) => string;
|
|
50
|
+
readonly log?: AgentLogger;
|
|
51
|
+
/**
|
|
52
|
+
* Per-turn token generator. Adapter passes `crypto.randomUUID()` by
|
|
53
|
+
* default; tests can inject a deterministic generator.
|
|
54
|
+
*/
|
|
55
|
+
readonly generateToken: () => string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export type LoopAction =
|
|
59
|
+
| { readonly kind: "continue" }
|
|
60
|
+
| {
|
|
61
|
+
readonly kind: "pause_for_user_confirmation";
|
|
62
|
+
readonly prompt: string;
|
|
63
|
+
readonly token: string;
|
|
64
|
+
}
|
|
65
|
+
| {
|
|
66
|
+
readonly kind: "pause_for_defer";
|
|
67
|
+
readonly signal: string;
|
|
68
|
+
readonly intentHash: string;
|
|
69
|
+
}
|
|
70
|
+
| {
|
|
71
|
+
readonly kind: "complete_for_escalation";
|
|
72
|
+
readonly to: "human" | "supervisor";
|
|
73
|
+
readonly reason: string;
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
export interface DecisionTranslation {
|
|
77
|
+
readonly toolResult: ToolResultBlock | null;
|
|
78
|
+
readonly loopAction: LoopAction;
|
|
79
|
+
readonly extraEvents: ReadonlyArray<AgentEvent>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Translate a `Decision` into a provider-neutral `ToolResultBlock` plus
|
|
84
|
+
* the next loop action. The caller (the send loop) appends the tool-
|
|
85
|
+
* result to the next user-role message and either continues or pauses
|
|
86
|
+
* based on `loopAction.kind`.
|
|
87
|
+
*/
|
|
88
|
+
export async function translateDecision<K extends string, P, S, H>(
|
|
89
|
+
ctx: DecisionTranslationContext<K, P, S, H>,
|
|
90
|
+
): Promise<DecisionTranslation> {
|
|
91
|
+
switch (ctx.decision.kind) {
|
|
92
|
+
case "EXECUTE":
|
|
93
|
+
return runExecute(ctx, ctx.envelope, null);
|
|
94
|
+
case "REWRITE":
|
|
95
|
+
return runExecute(
|
|
96
|
+
ctx,
|
|
97
|
+
ctx.decision.rewritten as IntentEnvelope<K, P>,
|
|
98
|
+
ctx.decision.reason,
|
|
99
|
+
);
|
|
100
|
+
case "REFUSE": {
|
|
101
|
+
const text = ctx.decision.refusal.userFacing;
|
|
102
|
+
const result: ToolResultBlock = {
|
|
103
|
+
toolUseId: ctx.toolUseId,
|
|
104
|
+
content: text,
|
|
105
|
+
isError: true,
|
|
106
|
+
};
|
|
107
|
+
return {
|
|
108
|
+
toolResult: result,
|
|
109
|
+
loopAction: { kind: "continue" },
|
|
110
|
+
extraEvents: [
|
|
111
|
+
{ kind: "tool_result", toolUseId: ctx.toolUseId, payload: result },
|
|
112
|
+
],
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
case "REQUEST_CONFIRMATION": {
|
|
116
|
+
const token = ctx.generateToken();
|
|
117
|
+
await ctx.confirmationStore.put(
|
|
118
|
+
token,
|
|
119
|
+
{
|
|
120
|
+
envelope: ctx.envelope,
|
|
121
|
+
sessionId: ctx.sessionId,
|
|
122
|
+
assistantHistorySnapshot: ctx.historySnapshot,
|
|
123
|
+
toolUseId: ctx.toolUseId,
|
|
124
|
+
prompt: ctx.decision.prompt,
|
|
125
|
+
},
|
|
126
|
+
24 * 60 * 60,
|
|
127
|
+
);
|
|
128
|
+
const result: ToolResultBlock = {
|
|
129
|
+
toolUseId: ctx.toolUseId,
|
|
130
|
+
content: `Confirmation required: ${ctx.decision.prompt}`,
|
|
131
|
+
};
|
|
132
|
+
return {
|
|
133
|
+
toolResult: result,
|
|
134
|
+
loopAction: {
|
|
135
|
+
kind: "pause_for_user_confirmation",
|
|
136
|
+
prompt: ctx.decision.prompt,
|
|
137
|
+
token,
|
|
138
|
+
},
|
|
139
|
+
extraEvents: [
|
|
140
|
+
{ kind: "tool_result", toolUseId: ctx.toolUseId, payload: result },
|
|
141
|
+
],
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
case "ESCALATE": {
|
|
145
|
+
const result: ToolResultBlock = {
|
|
146
|
+
toolUseId: ctx.toolUseId,
|
|
147
|
+
content: `Escalated to ${ctx.decision.to}: ${ctx.decision.reason}`,
|
|
148
|
+
};
|
|
149
|
+
return {
|
|
150
|
+
toolResult: result,
|
|
151
|
+
loopAction: {
|
|
152
|
+
kind: "complete_for_escalation",
|
|
153
|
+
to: ctx.decision.to,
|
|
154
|
+
reason: ctx.decision.reason,
|
|
155
|
+
},
|
|
156
|
+
extraEvents: [
|
|
157
|
+
{ kind: "tool_result", toolUseId: ctx.toolUseId, payload: result },
|
|
158
|
+
],
|
|
159
|
+
};
|
|
160
|
+
}
|
|
161
|
+
case "DEFER": {
|
|
162
|
+
const ttlSeconds = Math.max(ctx.decision.timeoutMs, 1000) / 1000 + 60;
|
|
163
|
+
const parkResult = await parkDeferredIntent({
|
|
164
|
+
envelope: {
|
|
165
|
+
intentHash: ctx.envelope.intentHash,
|
|
166
|
+
kind: ctx.envelope.kind,
|
|
167
|
+
actor: { sessionId: ctx.envelope.actor.sessionId },
|
|
168
|
+
payload: ctx.envelope.payload,
|
|
169
|
+
// Hash-verification fields. The resume path re-derives intentHash
|
|
170
|
+
// via sha256Canonical and asserts byte-equality with the stored
|
|
171
|
+
// value — detects blob tampering between park and resume.
|
|
172
|
+
version: ctx.envelope.version,
|
|
173
|
+
nonce: ctx.envelope.nonce,
|
|
174
|
+
taint: ctx.envelope.taint,
|
|
175
|
+
actorPrincipal: ctx.envelope.actor.principal,
|
|
176
|
+
},
|
|
177
|
+
signal: ctx.decision.signal,
|
|
178
|
+
ttlSeconds,
|
|
179
|
+
redis: ctx.deferStore,
|
|
180
|
+
rk: ctx.rk,
|
|
181
|
+
log: ctx.log,
|
|
182
|
+
});
|
|
183
|
+
if (!parkResult.parked) {
|
|
184
|
+
const result: ToolResultBlock = {
|
|
185
|
+
toolUseId: ctx.toolUseId,
|
|
186
|
+
content: `This action could not be queued (per-session quota exceeded; ${parkResult.observed}/${parkResult.limit}).`,
|
|
187
|
+
isError: true,
|
|
188
|
+
};
|
|
189
|
+
return {
|
|
190
|
+
toolResult: result,
|
|
191
|
+
loopAction: { kind: "continue" },
|
|
192
|
+
extraEvents: [
|
|
193
|
+
{ kind: "tool_result", toolUseId: ctx.toolUseId, payload: result },
|
|
194
|
+
],
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
const result: ToolResultBlock = {
|
|
198
|
+
toolUseId: ctx.toolUseId,
|
|
199
|
+
content: `Action queued. Waiting for signal "${ctx.decision.signal}" (timeout ${ctx.decision.timeoutMs}ms).`,
|
|
200
|
+
};
|
|
201
|
+
return {
|
|
202
|
+
toolResult: result,
|
|
203
|
+
loopAction: {
|
|
204
|
+
kind: "pause_for_defer",
|
|
205
|
+
signal: ctx.decision.signal,
|
|
206
|
+
intentHash: ctx.envelope.intentHash,
|
|
207
|
+
},
|
|
208
|
+
extraEvents: [
|
|
209
|
+
{ kind: "tool_result", toolUseId: ctx.toolUseId, payload: result },
|
|
210
|
+
],
|
|
211
|
+
};
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Shared EXECUTE / REWRITE path. Runs the adopter's executor against the
|
|
218
|
+
* envelope passed in (the original for EXECUTE, the rewritten one for
|
|
219
|
+
* REWRITE), serializes the result, and returns a continue-loop translation.
|
|
220
|
+
*/
|
|
221
|
+
async function runExecute<K extends string, P, S, H>(
|
|
222
|
+
ctx: DecisionTranslationContext<K, P, S, H>,
|
|
223
|
+
effectiveEnvelope: IntentEnvelope<K, P>,
|
|
224
|
+
rewriteReason: string | null,
|
|
225
|
+
): Promise<DecisionTranslation> {
|
|
226
|
+
let executorResult: unknown;
|
|
227
|
+
try {
|
|
228
|
+
executorResult = await ctx.executor.invokeIntent(
|
|
229
|
+
effectiveEnvelope,
|
|
230
|
+
ctx.state,
|
|
231
|
+
);
|
|
232
|
+
} catch (err) {
|
|
233
|
+
const message =
|
|
234
|
+
err instanceof Error ? err.message : "executor threw a non-Error value";
|
|
235
|
+
const errResult: ToolResultBlock = {
|
|
236
|
+
toolUseId: ctx.toolUseId,
|
|
237
|
+
content: `Executor failed: ${message}`,
|
|
238
|
+
isError: true,
|
|
239
|
+
};
|
|
240
|
+
return {
|
|
241
|
+
toolResult: errResult,
|
|
242
|
+
loopAction: { kind: "continue" },
|
|
243
|
+
extraEvents: [
|
|
244
|
+
{ kind: "tool_result", toolUseId: ctx.toolUseId, payload: errResult },
|
|
245
|
+
],
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
const handlerEvent: AgentEvent = {
|
|
250
|
+
kind: "handler_result",
|
|
251
|
+
toolUseId: ctx.toolUseId,
|
|
252
|
+
result: executorResult,
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
const body =
|
|
256
|
+
rewriteReason === null
|
|
257
|
+
? { ok: true, result: executorResult }
|
|
258
|
+
: {
|
|
259
|
+
ok: true,
|
|
260
|
+
result: executorResult,
|
|
261
|
+
note: `Note: kernel rewrote your proposal — ${rewriteReason}`,
|
|
262
|
+
};
|
|
263
|
+
|
|
264
|
+
const result: ToolResultBlock = {
|
|
265
|
+
toolUseId: ctx.toolUseId,
|
|
266
|
+
content: JSON.stringify(body),
|
|
267
|
+
};
|
|
268
|
+
return {
|
|
269
|
+
toolResult: result,
|
|
270
|
+
loopAction: { kind: "continue" },
|
|
271
|
+
extraEvents: [
|
|
272
|
+
handlerEvent,
|
|
273
|
+
{ kind: "tool_result", toolUseId: ctx.toolUseId, payload: result },
|
|
274
|
+
],
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* Build the provider-neutral `ToolResultBlock` for an out-of-plan tool
|
|
280
|
+
* call. Re-exported so tests + adopters can construct one from outside
|
|
281
|
+
* the loop.
|
|
282
|
+
*/
|
|
283
|
+
export function makeOutOfPlanToolResult(
|
|
284
|
+
toolUseId: string,
|
|
285
|
+
toolName: string,
|
|
286
|
+
): ToolResultBlock {
|
|
287
|
+
return {
|
|
288
|
+
toolUseId,
|
|
289
|
+
content: `Tool "${toolName}" is not available in the current plan.`,
|
|
290
|
+
isError: true,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
export { AdapterError, AdapterErrorCode };
|
package/src/errors.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Error taxonomy for the provider-neutral adapter loop.
|
|
3
|
+
*
|
|
4
|
+
* Most failures inside the loop become `isError: true` tool-results
|
|
5
|
+
* surfaced back to the model (so it can recover gracefully). Errors
|
|
6
|
+
* thrown out of the adapter are reserved for adopter-visible
|
|
7
|
+
* misconfiguration or contract violations.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
export const AdapterErrorCode = {
|
|
11
|
+
OUT_OF_PLAN_TOOL_USE: "OUT_OF_PLAN_TOOL_USE",
|
|
12
|
+
EXECUTOR_FAILED: "EXECUTOR_FAILED",
|
|
13
|
+
INVALID_PAYLOAD: "INVALID_PAYLOAD",
|
|
14
|
+
MAX_ITERATIONS_EXCEEDED: "MAX_ITERATIONS_EXCEEDED",
|
|
15
|
+
CONFIRMATION_TOKEN_INVALID: "CONFIRMATION_TOKEN_INVALID",
|
|
16
|
+
RESUME_NO_PARKED: "RESUME_NO_PARKED",
|
|
17
|
+
} as const;
|
|
18
|
+
|
|
19
|
+
export type AdapterErrorCode =
|
|
20
|
+
(typeof AdapterErrorCode)[keyof typeof AdapterErrorCode];
|
|
21
|
+
|
|
22
|
+
export class AdapterError extends Error {
|
|
23
|
+
readonly code: AdapterErrorCode;
|
|
24
|
+
readonly details?: Record<string, unknown>;
|
|
25
|
+
|
|
26
|
+
constructor(
|
|
27
|
+
code: AdapterErrorCode,
|
|
28
|
+
message: string,
|
|
29
|
+
details?: Record<string, unknown>,
|
|
30
|
+
) {
|
|
31
|
+
super(message);
|
|
32
|
+
this.name = "AdapterError";
|
|
33
|
+
this.code = code;
|
|
34
|
+
this.details = details;
|
|
35
|
+
}
|
|
36
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@adjudicate/adapter-core` — provider-neutral orchestration for
|
|
3
|
+
* adjudicate-backed LLM agents.
|
|
4
|
+
*
|
|
5
|
+
* The loop, bridge, decision translator, persistence shims, and error
|
|
6
|
+
* taxonomy live here. Provider adapters (`@adjudicate/anthropic`,
|
|
7
|
+
* `@adjudicate/openai`, …) implement a `ProviderBridge<H>` against
|
|
8
|
+
* their SDK and re-export a thin `createAdjudicatedAgent` that wires
|
|
9
|
+
* it into this loop.
|
|
10
|
+
*
|
|
11
|
+
* Invariants the loop preserves:
|
|
12
|
+
* - Every intent envelope crosses `adjudicateAndAudit()`. No bypass,
|
|
13
|
+
* no taint elevation, no guard-ordering short-circuit.
|
|
14
|
+
* - First non-continue Decision wins per assistant turn.
|
|
15
|
+
* - History `H` is opaque to the loop; the bridge owns its shape.
|
|
16
|
+
* - REWRITE executes the rewritten envelope, never the original.
|
|
17
|
+
* - DEFER persists full envelope fields so resume can re-derive the
|
|
18
|
+
* intentHash and detect tampering.
|
|
19
|
+
*
|
|
20
|
+
* Provider adapters MUST NOT bypass this loop. The kernel-side audit
|
|
21
|
+
* + ledger guarantees only hold when every adjudication flows here.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
export { createAdjudicatedAgent } from "./loop.js";
|
|
25
|
+
export type {
|
|
26
|
+
AdjudicatedAgent,
|
|
27
|
+
AdjudicatedAgentOptions,
|
|
28
|
+
AdopterExecutor,
|
|
29
|
+
AgentEvent,
|
|
30
|
+
AgentLogger,
|
|
31
|
+
AgentOutcome,
|
|
32
|
+
AgentTurnResult,
|
|
33
|
+
AssistantTurn,
|
|
34
|
+
ConfirmArgs,
|
|
35
|
+
ProviderBridge,
|
|
36
|
+
ProviderRequest,
|
|
37
|
+
ResumeArgs,
|
|
38
|
+
SendInput,
|
|
39
|
+
ToolResultBlock,
|
|
40
|
+
ToolUseRequest,
|
|
41
|
+
} from "./types.js";
|
|
42
|
+
|
|
43
|
+
export {
|
|
44
|
+
buildEnvelopeFromToolUse,
|
|
45
|
+
classifyIncomingToolUse,
|
|
46
|
+
intentKindToApiName,
|
|
47
|
+
} from "./bridge.js";
|
|
48
|
+
export type {
|
|
49
|
+
BuildEnvelopeFromToolUseArgs,
|
|
50
|
+
ToolUseClassification,
|
|
51
|
+
} from "./bridge.js";
|
|
52
|
+
|
|
53
|
+
export {
|
|
54
|
+
makeOutOfPlanToolResult,
|
|
55
|
+
translateDecision,
|
|
56
|
+
} from "./decisions.js";
|
|
57
|
+
export type {
|
|
58
|
+
DecisionTranslation,
|
|
59
|
+
DecisionTranslationContext,
|
|
60
|
+
LoopAction,
|
|
61
|
+
} from "./decisions.js";
|
|
62
|
+
|
|
63
|
+
export {
|
|
64
|
+
createInMemoryConfirmationStore,
|
|
65
|
+
createInMemoryDeferStore,
|
|
66
|
+
} from "./persistence.js";
|
|
67
|
+
export type {
|
|
68
|
+
ConfirmationStore,
|
|
69
|
+
DeferRedis,
|
|
70
|
+
ParkRedis,
|
|
71
|
+
PendingConfirmation,
|
|
72
|
+
} from "./persistence.js";
|
|
73
|
+
export {
|
|
74
|
+
createRedisConfirmationStore,
|
|
75
|
+
type ConfirmationRedisClient,
|
|
76
|
+
type CreateRedisConfirmationStoreOptions,
|
|
77
|
+
} from "./persistence-redis.js";
|
|
78
|
+
|
|
79
|
+
export {
|
|
80
|
+
noopTraceSink,
|
|
81
|
+
createInMemoryTraceSink,
|
|
82
|
+
type AdapterPauseReason,
|
|
83
|
+
type AdapterTraceEvent,
|
|
84
|
+
type AdapterTracePhase,
|
|
85
|
+
type TraceSink,
|
|
86
|
+
} from "./trace.js";
|
|
87
|
+
|
|
88
|
+
export { AdapterError, AdapterErrorCode } from "./errors.js";
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* In-memory Execution Ledger — re-export from `@adjudicate/audit` for
|
|
92
|
+
* zero-import-friction in tests, quickstarts, and local development.
|
|
93
|
+
*
|
|
94
|
+
* NOT for distributed or persistent production deployments. Production
|
|
95
|
+
* adopters wire `createRedisLedger` (or any backing store with SET-NX,
|
|
96
|
+
* EX, INCR, DECR) from `@adjudicate/audit`.
|
|
97
|
+
*/
|
|
98
|
+
export { createMemoryLedger } from "@adjudicate/audit";
|