@noetic-tools/acp 1.0.0 → 1.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.
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The server direction's permission gate: a context layer whose
3
+ * `beforeToolCall` hook evaluates the declarative policy and, for `ask`
4
+ * decisions, parks the pending call on a broker until the ACP client (or an
5
+ * embedding host) answers `session/request_permission`.
6
+ *
7
+ * The gate leans on the core contract from spec 31: the hook is async and
8
+ * awaited on every tool-executing path, receives the pending call's `callId`,
9
+ * and runs after `tool_call_started` — so a parked call is visible to the
10
+ * client as a pending `tool_call` rather than invisible until approved.
11
+ */
12
+ import type { AcpToolKind, ContextLayer } from '@noetic-tools/types';
13
+ import type { AcpServePermissionDecision, AcpServePermissionPolicy, AcpServePermissionPrompt, AcpServePermissionReply } from './serve-types.js';
14
+ /**
15
+ * First decisive rule wins, checked `deny` → `ask` → `allow`; the policy
16
+ * `default` (or `allow`) applies when nothing matches.
17
+ * @public
18
+ */
19
+ export declare function evaluateServePolicy(params: {
20
+ policy: AcpServePermissionPolicy;
21
+ toolName: string;
22
+ kind?: AcpToolKind;
23
+ }): AcpServePermissionDecision;
24
+ /**
25
+ * Holds `ask` parks and routes each to its answerer. The layer registers the
26
+ * park *before* invoking `forward`, so an answer racing back in the same tick
27
+ * still finds it; `cancelSession` unwinds every park for a session when the
28
+ * client sends `session/cancel`.
29
+ */
30
+ export declare class ServePermissionBroker {
31
+ private readonly forward;
32
+ private readonly pending;
33
+ constructor(forward: (prompt: AcpServePermissionPrompt) => Promise<AcpServePermissionReply>);
34
+ ask(prompt: AcpServePermissionPrompt, timeoutMs: number): Promise<AcpServePermissionReply>;
35
+ /** Resolve one park; later answers to the same request are dropped. */
36
+ answer(requestId: string, reply: AcpServePermissionReply): void;
37
+ /** Unwind every park belonging to a session — the `session/cancel` path. */
38
+ cancelSession(sessionId: string): void;
39
+ }
40
+ /** How a tool's name maps to its declared presentation, shared with the event pump. */
41
+ export interface ServeToolPresentation {
42
+ kindOf(toolName: string): AcpToolKind | undefined;
43
+ titleOf(toolName: string, args: unknown): string;
44
+ }
45
+ /**
46
+ * Build the per-session gate layer. Slot is far past the built-in layers so
47
+ * steering and other gates run first — a call another layer denies is never
48
+ * escalated to the client.
49
+ */
50
+ export declare function createServePermissionLayer(params: {
51
+ sessionId: string;
52
+ policy: AcpServePermissionPolicy;
53
+ broker: ServePermissionBroker;
54
+ presentation: ServeToolPresentation;
55
+ }): ContextLayer;
@@ -0,0 +1,180 @@
1
+ /**
2
+ * The server direction's permission gate: a context layer whose
3
+ * `beforeToolCall` hook evaluates the declarative policy and, for `ask`
4
+ * decisions, parks the pending call on a broker until the ACP client (or an
5
+ * embedding host) answers `session/request_permission`.
6
+ *
7
+ * The gate leans on the core contract from spec 31: the hook is async and
8
+ * awaited on every tool-executing path, receives the pending call's `callId`,
9
+ * and runs after `tool_call_started` — so a parked call is visible to the
10
+ * client as a pending `tool_call` rather than invisible until approved.
11
+ */
12
+ import { frameworkCast } from '@noetic-tools/types';
13
+ //#region Policy evaluation
14
+ const DEFAULT_ASK_TIMEOUT_MS = 5 * 60 * 1e3;
15
+ /**
16
+ * First decisive rule wins, checked `deny` → `ask` → `allow`; the policy
17
+ * `default` (or `allow`) applies when nothing matches.
18
+ * @public
19
+ */
20
+ export function evaluateServePolicy(params) {
21
+ const { policy, toolName, kind } = params;
22
+ const rules = policy.rules ?? [];
23
+ const tiers = [
24
+ 'deny',
25
+ 'ask',
26
+ 'allow',
27
+ ];
28
+ for (const tier of tiers) {
29
+ const matched = rules.some((rule) => rule.decision === tier &&
30
+ ((rule.tool !== undefined && rule.tool === toolName) ||
31
+ (rule.kind !== undefined && rule.kind === kind)));
32
+ if (matched) {
33
+ return tier;
34
+ }
35
+ }
36
+ return policy.default ?? 'allow';
37
+ }
38
+ /**
39
+ * Holds `ask` parks and routes each to its answerer. The layer registers the
40
+ * park *before* invoking `forward`, so an answer racing back in the same tick
41
+ * still finds it; `cancelSession` unwinds every park for a session when the
42
+ * client sends `session/cancel`.
43
+ */
44
+ export class ServePermissionBroker {
45
+ forward;
46
+ pending = new Map();
47
+ constructor(forward) {
48
+ this.forward = forward;
49
+ }
50
+ async ask(prompt, timeoutMs) {
51
+ let timer;
52
+ const parked = new Promise((resolve) => {
53
+ this.pending.set(prompt.requestId, {
54
+ sessionId: prompt.sessionId,
55
+ resolve,
56
+ });
57
+ timer = setTimeout(() => {
58
+ this.answer(prompt.requestId, {
59
+ decision: 'deny',
60
+ reason: 'permission request timed out',
61
+ });
62
+ }, timeoutMs);
63
+ });
64
+ // The forwarder answers through `answer()` so a session cancel, the
65
+ // deadline, and the client's reply all converge on the same park — first
66
+ // one wins, the rest are no-ops.
67
+ this.forward(prompt).then((reply) => {
68
+ this.answer(prompt.requestId, reply);
69
+ }, (error) => {
70
+ this.answer(prompt.requestId, {
71
+ decision: 'deny',
72
+ reason: error instanceof Error ? error.message : String(error),
73
+ });
74
+ });
75
+ try {
76
+ return await parked;
77
+ }
78
+ finally {
79
+ clearTimeout(timer);
80
+ this.pending.delete(prompt.requestId);
81
+ }
82
+ }
83
+ /** Resolve one park; later answers to the same request are dropped. */
84
+ answer(requestId, reply) {
85
+ const entry = this.pending.get(requestId);
86
+ if (!entry) {
87
+ return;
88
+ }
89
+ this.pending.delete(requestId);
90
+ entry.resolve(reply);
91
+ }
92
+ /** Unwind every park belonging to a session — the `session/cancel` path. */
93
+ cancelSession(sessionId) {
94
+ for (const [requestId, entry] of this.pending) {
95
+ if (entry.sessionId !== sessionId) {
96
+ continue;
97
+ }
98
+ this.pending.delete(requestId);
99
+ entry.resolve({
100
+ decision: 'cancel',
101
+ reason: 'turn cancelled',
102
+ });
103
+ }
104
+ }
105
+ }
106
+ /**
107
+ * Build the per-session gate layer. Slot is far past the built-in layers so
108
+ * steering and other gates run first — a call another layer denies is never
109
+ * escalated to the client.
110
+ */
111
+ export function createServePermissionLayer(params) {
112
+ const { sessionId, policy, broker, presentation } = params;
113
+ const askTimeoutMs = policy.askTimeoutMs ?? DEFAULT_ASK_TIMEOUT_MS;
114
+ const beforeToolCall = async (hookParams) => {
115
+ const { toolName, toolArgs, callId } = hookParams;
116
+ const kind = presentation.kindOf(toolName);
117
+ const decision = evaluateServePolicy({
118
+ policy,
119
+ toolName,
120
+ kind,
121
+ });
122
+ if (decision === 'allow') {
123
+ return {
124
+ decision: {
125
+ action: 'allow',
126
+ },
127
+ };
128
+ }
129
+ if (decision === 'deny') {
130
+ return {
131
+ decision: {
132
+ action: 'deny',
133
+ guidance: `tool '${toolName}' is denied by the ACP serve policy`,
134
+ },
135
+ };
136
+ }
137
+ const reply = await broker.ask({
138
+ requestId: crypto.randomUUID(),
139
+ sessionId,
140
+ toolName,
141
+ callId,
142
+ title: presentation.titleOf(toolName, toolArgs),
143
+ kind,
144
+ args: toolArgs,
145
+ }, askTimeoutMs);
146
+ if (reply.decision === 'allow') {
147
+ return {
148
+ decision: {
149
+ action: 'allow',
150
+ },
151
+ };
152
+ }
153
+ return {
154
+ decision: {
155
+ action: 'deny',
156
+ guidance: reply.reason ??
157
+ (reply.decision === 'cancel' ? 'turn cancelled' : 'the user rejected the tool call'),
158
+ },
159
+ };
160
+ };
161
+ return frameworkCast({
162
+ id: `acp-serve-permissions:${sessionId}`,
163
+ name: 'ACP serve permission gate',
164
+ slot: 1e6,
165
+ scope: 'execution',
166
+ hooks: {
167
+ beforeToolCall,
168
+ },
169
+ timeouts: {
170
+ // The broker owns the real deadline (askTimeoutMs → deny); this outer
171
+ // lifecycle timeout only backstops a wedged broker.
172
+ beforeToolCall: askTimeoutMs + 10e3,
173
+ },
174
+ // A gate fails CLOSED: if the hook ever throws or blows the backstop
175
+ // timeout, the lifecycle denies the call rather than abstaining into the
176
+ // silent approval `mostRestrictive([])` would produce.
177
+ onBeforeToolCallError: 'deny',
178
+ });
179
+ }
180
+ //#endregion
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Public types for the server direction: serving a Noetic harness *as* an ACP
3
+ * agent (spec 31). The adapter drives any harness through `AcpServeHarness`, a
4
+ * structural subset of `AgentHarnessContract` — the same pattern
5
+ * `@noetic-tools/chat-sdk` uses — so this package keeps depending only on
6
+ * `@noetic-tools/types`.
7
+ */
8
+ import type { AcpMcpServer, AcpToolKind, ExecuteInput, ExecuteOptions, FsAdapter, Item, SessionScope, ShellAdapter, StreamEvent, StreamingItem, ToolAcpDeclaration } from '@noetic-tools/types';
9
+ import type * as acp from '@zed-industries/agent-client-protocol';
10
+ /**
11
+ * The slice of `AgentHarnessContract` the ACP server drives. Any harness (or
12
+ * structural stand-in, in tests) satisfying this can be served.
13
+ * @public
14
+ */
15
+ export interface AcpServeHarness {
16
+ execute(input: ExecuteInput, options?: ExecuteOptions): Promise<void>;
17
+ getFullStream(scope?: SessionScope): AsyncIterable<StreamEvent>;
18
+ getItemStream(scope?: SessionScope): AsyncIterable<StreamingItem>;
19
+ seedSessionHistory(threadId: string, items: ReadonlyArray<Item>): void;
20
+ abort(scope?: SessionScope & {
21
+ reason?: string;
22
+ }): Promise<void>;
23
+ }
24
+ /**
25
+ * What a per-session harness factory receives when the client opens a session.
26
+ * @public
27
+ */
28
+ export interface AcpServeSessionInit {
29
+ /** The minted ACP session id — also the harness `threadId`. */
30
+ sessionId: string;
31
+ /** Absolute working directory the client established for the session. */
32
+ cwd: string;
33
+ /** MCP servers the client asked the agent to connect to (not yet mounted; see spec 31 Future Considerations). */
34
+ mcpServers: ReadonlyArray<AcpMcpServer>;
35
+ /**
36
+ * Adapters backed by the ACP client's own `fs/*` and `terminal/*` methods,
37
+ * built from the capabilities it advertised. Wire them into the harness's
38
+ * `environment` and the agent sees unsaved editor buffers instead of disk.
39
+ * Operations the client did not advertise (or the wire cannot express)
40
+ * reject with `AcpCapabilityError`.
41
+ */
42
+ client: {
43
+ fs: FsAdapter;
44
+ shell: ShellAdapter;
45
+ capabilities?: acp.ClientCapabilities;
46
+ };
47
+ }
48
+ /**
49
+ * A harness shared across sessions, or a factory called once per
50
+ * `session/new` for per-session cwd/adapters isolation.
51
+ * @public
52
+ */
53
+ export type AcpServeHarnessSource = AcpServeHarness | ((session: AcpServeSessionInit) => AcpServeHarness | Promise<AcpServeHarness>);
54
+ /** @public What the policy says about one first-party tool. */
55
+ export type AcpServePermissionDecision = 'allow' | 'ask' | 'deny';
56
+ /**
57
+ * One policy rule, matched on the tool's name or its declared ACP kind.
58
+ * A rule naming both matches when either does.
59
+ * @public
60
+ */
61
+ export interface AcpServePermissionRule {
62
+ tool?: string;
63
+ kind?: AcpToolKind;
64
+ decision: AcpServePermissionDecision;
65
+ }
66
+ /**
67
+ * Declarative gate over first-party tool calls. Decisions are checked in
68
+ * order `deny` → `ask` → `allow`, so an explicit refusal beats a required
69
+ * ask, which beats a broad grant. The default is **`allow`** — deliberately
70
+ * the opposite of the client direction's `deny`: the harness author curated
71
+ * every tool on the harness, and the editor user is supervising work they
72
+ * initiated, not sandboxing a stranger.
73
+ * @public
74
+ */
75
+ export interface AcpServePermissionPolicy {
76
+ default?: AcpServePermissionDecision;
77
+ rules?: ReadonlyArray<AcpServePermissionRule>;
78
+ /**
79
+ * How long an `ask` waits for the client's answer, in milliseconds.
80
+ * Defaults to 5 minutes. On expiry the call is denied — waiting must not
81
+ * become approval.
82
+ */
83
+ askTimeoutMs?: number;
84
+ }
85
+ /** @public A permission ask on its way to the client (or an embedding host). */
86
+ export interface AcpServePermissionPrompt {
87
+ /** Correlates the answer with this ask. */
88
+ requestId: string;
89
+ /** The ACP session (= harness thread) the call belongs to. */
90
+ sessionId: string;
91
+ /** The tool's machine name. */
92
+ toolName: string;
93
+ /** The pending call's id — the same id its `tool_call` notification carries. */
94
+ callId?: string;
95
+ /** Presentation title resolved from the tool's `acp` declaration. */
96
+ title: string;
97
+ /** Declared ACP kind, when the tool has one. */
98
+ kind?: AcpToolKind;
99
+ /** Parsed tool arguments. */
100
+ args?: unknown;
101
+ }
102
+ /** @public The answer to an {@link AcpServePermissionPrompt}. */
103
+ export interface AcpServePermissionReply {
104
+ decision: 'allow' | 'deny' | 'cancel';
105
+ reason?: string;
106
+ }
107
+ /** @public Session context handed to a slash command's `run`. */
108
+ export interface AcpServeCommandContext {
109
+ sessionId: string;
110
+ cwd: string;
111
+ }
112
+ /**
113
+ * A slash command advertised to the client as `availableCommands`. A prompt
114
+ * beginning with `/name` routes to `run`, whose return value becomes the
115
+ * turn's input; a command without `run` forwards its text unchanged.
116
+ * @public
117
+ */
118
+ export interface AcpServeCommand {
119
+ name: string;
120
+ description: string;
121
+ /** Hint shown by clients for the command's free-text argument. */
122
+ inputHint?: string;
123
+ run?(argsText: string, ctx: AcpServeCommandContext): string | Item[] | Promise<string | Item[]>;
124
+ }
125
+ /**
126
+ * Two-method persistence seam. Providing it advertises the `loadSession`
127
+ * capability: `session/load` seeds the harness from `load` and replays the
128
+ * conversation to the client, and every completed item is appended through
129
+ * `save` as it streams.
130
+ * @public
131
+ */
132
+ export interface AcpServeHistory {
133
+ load(sessionId: string): Promise<ReadonlyArray<Item> | null>;
134
+ save(sessionId: string, item: Item): Promise<void>;
135
+ }
136
+ /** @public A tool's name plus its ACP presentation, for `AcpServeOptions.tools`. */
137
+ export interface AcpPresentableTool {
138
+ name: string;
139
+ acp?: ToolAcpDeclaration;
140
+ }
141
+ /** @public Options for `toAcpAgent` / `serveAcp`. */
142
+ export interface AcpServeOptions {
143
+ /**
144
+ * The harness's tools (or any subset), read for their `acp` presentation
145
+ * declarations. Pass the same array the harness was built with; an
146
+ * undeclared or unlisted tool renders as kind `other` with its name as the
147
+ * title.
148
+ */
149
+ tools?: ReadonlyArray<AcpPresentableTool>;
150
+ /** Declarative gate over first-party tool calls. Absent: everything is allowed. */
151
+ permissions?: AcpServePermissionPolicy;
152
+ /**
153
+ * Answer permission asks in-process instead of forwarding them to the ACP
154
+ * client over the wire — the hatch for hosts that embed the server and own
155
+ * their own approval surface.
156
+ */
157
+ onPermissionRequest?(prompt: AcpServePermissionPrompt): Promise<AcpServePermissionReply>;
158
+ /** Persistence seam; presence advertises `loadSession`. */
159
+ history?: AcpServeHistory;
160
+ /** Slash commands advertised to the client. */
161
+ commands?: ReadonlyArray<AcpServeCommand>;
162
+ }
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Public types for the server direction: serving a Noetic harness *as* an ACP
3
+ * agent (spec 31). The adapter drives any harness through `AcpServeHarness`, a
4
+ * structural subset of `AgentHarnessContract` — the same pattern
5
+ * `@noetic-tools/chat-sdk` uses — so this package keeps depending only on
6
+ * `@noetic-tools/types`.
7
+ */
8
+ export {};
9
+ //#endregion
@@ -0,0 +1,28 @@
1
+ /**
2
+ * The server direction (spec 31): expose a Noetic harness *as* an ACP agent.
3
+ *
4
+ * `toAcpAgent(harness)` returns the `(conn) => acp.Agent` factory shape that
5
+ * `loopbackTransport()` accepts — so a served harness can be mounted as a
6
+ * sub-agent of another harness, driven by Noetic's own ACP client in tests,
7
+ * or bound to process stdio by `serveAcp()` (`@noetic-tools/acp/server`).
8
+ *
9
+ * The adapter maps the protocol onto the harness's existing public surface —
10
+ * `execute`, the streams, `seedSessionHistory`, `abort` — and nothing else.
11
+ */
12
+ import type * as acp from '@zed-industries/agent-client-protocol';
13
+ import type { AgentSideConnection } from '@zed-industries/agent-client-protocol';
14
+ import type { AcpServeHarnessSource, AcpServeOptions } from './serve-types.js';
15
+ /**
16
+ * The served agent: the protocol surface plus `dispose()`, which cancels
17
+ * every live session when the transport goes away.
18
+ * @public
19
+ */
20
+ export interface AcpServedAgent extends acp.Agent {
21
+ dispose(): Promise<void>;
22
+ }
23
+ /**
24
+ * Adapt a harness (or per-session factory) into an ACP `Agent` factory — the
25
+ * exact shape `loopbackTransport()` and `AgentSideConnection` accept.
26
+ * @public
27
+ */
28
+ export declare function toAcpAgent(source: AcpServeHarnessSource, options?: AcpServeOptions): (conn: AgentSideConnection) => AcpServedAgent;