@agentic-kit/harness 0.11.0 → 0.13.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,47 @@
1
+ /**
2
+ * The declared half of the run gate: which tool calls run, which are refused,
3
+ * and which need a human. A policy is data — an ordered rule list evaluated with
4
+ * no I/O — so the same policy can be asserted in a test, stored on a run row,
5
+ * and shown in a UI.
6
+ *
7
+ * This is the *run's* policy, decided wherever the run is configured and
8
+ * enforceable without a UI, as opposed to `ConfirmGatePolicy` in
9
+ * `./policy`, which is a host's interactive confirm surface. Harness-neutral:
10
+ * an adapter maps its own tool-call event onto `RunGateRequest`.
11
+ */
12
+ export type RunGateDecision = 'allow' | 'deny' | 'ask';
13
+ export interface RunGateRequest {
14
+ toolName: string;
15
+ input: Record<string, unknown>;
16
+ }
17
+ export interface RunGateRule {
18
+ /** Tool name, or `*` for every tool. */
19
+ tool: string;
20
+ decision: RunGateDecision;
21
+ /** Narrow the rule to particular arguments (e.g. a bash command pattern). */
22
+ match?: (request: RunGateRequest) => boolean;
23
+ /** Shown to the model when denied, and to the human when asked. */
24
+ reason?: string;
25
+ }
26
+ export interface RunGateVerdict {
27
+ decision: RunGateDecision;
28
+ reason?: string;
29
+ /** The rule that decided, or `undefined` when the default applied. */
30
+ rule?: RunGateRule;
31
+ }
32
+ export interface RunGatePolicyOptions {
33
+ rules?: readonly RunGateRule[];
34
+ /** Verdict when no rule matches. Defaults to `ask` — an undeclared tool is
35
+ * not implicitly trusted, and denying outright would strand the run. */
36
+ defaultDecision?: RunGateDecision;
37
+ defaultReason?: string;
38
+ }
39
+ export declare class RunGatePolicy {
40
+ readonly rules: readonly RunGateRule[];
41
+ readonly defaultDecision: RunGateDecision;
42
+ private readonly defaultReason;
43
+ constructor(options?: RunGatePolicyOptions);
44
+ /** First matching rule wins, so order the list most specific first. */
45
+ evaluate(request: RunGateRequest): RunGateVerdict;
46
+ }
47
+ export declare function runGatePolicy(options?: RunGatePolicyOptions): RunGatePolicy;
@@ -0,0 +1,43 @@
1
+ /**
2
+ * The declared half of the run gate: which tool calls run, which are refused,
3
+ * and which need a human. A policy is data — an ordered rule list evaluated with
4
+ * no I/O — so the same policy can be asserted in a test, stored on a run row,
5
+ * and shown in a UI.
6
+ *
7
+ * This is the *run's* policy, decided wherever the run is configured and
8
+ * enforceable without a UI, as opposed to `ConfirmGatePolicy` in
9
+ * `./policy`, which is a host's interactive confirm surface. Harness-neutral:
10
+ * an adapter maps its own tool-call event onto `RunGateRequest`.
11
+ */
12
+ export class RunGatePolicy {
13
+ rules;
14
+ defaultDecision;
15
+ defaultReason;
16
+ constructor(options = {}) {
17
+ this.rules = options.rules ?? [];
18
+ this.defaultDecision = options.defaultDecision ?? 'ask';
19
+ this.defaultReason = options.defaultReason;
20
+ for (const rule of this.rules) {
21
+ if (!rule.tool)
22
+ throw new Error('gate: every rule needs a tool name (or "*")');
23
+ }
24
+ }
25
+ /** First matching rule wins, so order the list most specific first. */
26
+ evaluate(request) {
27
+ for (const rule of this.rules) {
28
+ if (rule.tool !== '*' && rule.tool !== request.toolName)
29
+ continue;
30
+ if (rule.match && !rule.match(request))
31
+ continue;
32
+ return rule.reason === undefined
33
+ ? { decision: rule.decision, rule }
34
+ : { decision: rule.decision, reason: rule.reason, rule };
35
+ }
36
+ return this.defaultReason === undefined
37
+ ? { decision: this.defaultDecision }
38
+ : { decision: this.defaultDecision, reason: this.defaultReason };
39
+ }
40
+ }
41
+ export function runGatePolicy(options = {}) {
42
+ return new RunGatePolicy(options);
43
+ }
package/esm/index.d.ts CHANGED
@@ -1,12 +1,18 @@
1
+ export * from './adapter';
1
2
  export * from './blueprint/blueprint-defaults';
2
3
  export * from './blueprint/blueprint-schema';
3
4
  export * from './blueprint/field-type';
4
5
  export * from './blueprint/internal-policies';
5
6
  export * from './blueprint/policy-provisioning';
7
+ export * from './gating/approvals';
6
8
  export * from './gating/confirm-gate';
9
+ export * from './gating/constructive-policy';
7
10
  export * from './gating/decline-guard';
11
+ export * from './gating/policy';
8
12
  export * from './gating/preview';
9
13
  export * from './gating/prompts';
14
+ export * from './gating/run-gate';
15
+ export * from './gating/run-policy';
10
16
  export * from './skills/default-source';
11
17
  export * from './skills/fetch';
12
18
  export * from './skills/frontmatter';
package/esm/index.js CHANGED
@@ -1,12 +1,18 @@
1
+ export * from './adapter';
1
2
  export * from './blueprint/blueprint-defaults';
2
3
  export * from './blueprint/blueprint-schema';
3
4
  export * from './blueprint/field-type';
4
5
  export * from './blueprint/internal-policies';
5
6
  export * from './blueprint/policy-provisioning';
7
+ export * from './gating/approvals';
6
8
  export * from './gating/confirm-gate';
9
+ export * from './gating/constructive-policy';
7
10
  export * from './gating/decline-guard';
11
+ export * from './gating/policy';
8
12
  export * from './gating/preview';
9
13
  export * from './gating/prompts';
14
+ export * from './gating/run-gate';
15
+ export * from './gating/run-policy';
10
16
  export * from './skills/default-source';
11
17
  export * from './skills/fetch';
12
18
  export * from './skills/frontmatter';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * The asynchronous half of the gate: an `ask` verdict has to reach a human who
3
+ * may be on another machine, so approval is an interface rather than a prompt.
4
+ *
5
+ * `pollingApprovalChannel` is the baseline implementation of the platform's
6
+ * rendezvous model — the request is submitted (a row), and the decision is
7
+ * polled for (another row). No socket back into the agent's process, which is
8
+ * what lets a cloud run be approved from a browser.
9
+ */
10
+ export interface ApprovalRequest {
11
+ runId: string;
12
+ toolCallId: string;
13
+ toolName: string;
14
+ input: Record<string, unknown>;
15
+ /** The policy's reason for asking. */
16
+ reason?: string;
17
+ requestedAt: string;
18
+ }
19
+ export interface ApprovalOutcome {
20
+ decision: 'allow' | 'deny';
21
+ reason?: string;
22
+ /** Who decided, when the channel knows. */
23
+ actorId?: string;
24
+ }
25
+ export interface ApprovalChannel {
26
+ /** Resolves once a decision exists; may take as long as a human takes. */
27
+ request(request: ApprovalRequest): Promise<ApprovalOutcome>;
28
+ }
29
+ export interface PollingApprovalChannelOptions {
30
+ /** Publish the request (insert the row, post to the API). */
31
+ submit: (request: ApprovalRequest) => Promise<void>;
32
+ /** Read the decision, or `undefined` while it is still outstanding. */
33
+ poll: (request: ApprovalRequest) => Promise<ApprovalOutcome | undefined>;
34
+ intervalMs?: number;
35
+ /** Give up after this long. Omit to wait indefinitely. */
36
+ timeoutMs?: number;
37
+ /** Verdict on timeout. Defaults to `deny`: an unattended run must not take an
38
+ * action nobody approved just because nobody was watching. */
39
+ onTimeout?: 'deny' | 'allow';
40
+ /** Injectable clock/sleep for tests. */
41
+ sleep?: (ms: number) => Promise<void>;
42
+ now?: () => number;
43
+ }
44
+ export declare function pollingApprovalChannel(options: PollingApprovalChannelOptions): ApprovalChannel;
45
+ /** Decide every request the same way — for tests, and for a headless run that is
46
+ * explicitly configured to auto-approve. */
47
+ export declare function staticApprovalChannel(outcome: ApprovalOutcome): ApprovalChannel;
@@ -0,0 +1,42 @@
1
+ "use strict";
2
+ /**
3
+ * The asynchronous half of the gate: an `ask` verdict has to reach a human who
4
+ * may be on another machine, so approval is an interface rather than a prompt.
5
+ *
6
+ * `pollingApprovalChannel` is the baseline implementation of the platform's
7
+ * rendezvous model — the request is submitted (a row), and the decision is
8
+ * polled for (another row). No socket back into the agent's process, which is
9
+ * what lets a cloud run be approved from a browser.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.pollingApprovalChannel = pollingApprovalChannel;
13
+ exports.staticApprovalChannel = staticApprovalChannel;
14
+ function pollingApprovalChannel(options) {
15
+ const intervalMs = options.intervalMs ?? 1000;
16
+ const onTimeout = options.onTimeout ?? 'deny';
17
+ const sleep = options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
18
+ const now = options.now ?? (() => Date.now());
19
+ return {
20
+ async request(request) {
21
+ await options.submit(request);
22
+ const startedAt = now();
23
+ for (;;) {
24
+ const outcome = await options.poll(request);
25
+ if (outcome)
26
+ return outcome;
27
+ if (options.timeoutMs !== undefined && now() - startedAt >= options.timeoutMs) {
28
+ return {
29
+ decision: onTimeout,
30
+ reason: `gate: no decision within ${options.timeoutMs}ms`
31
+ };
32
+ }
33
+ await sleep(intervalMs);
34
+ }
35
+ }
36
+ };
37
+ }
38
+ /** Decide every request the same way — for tests, and for a headless run that is
39
+ * explicitly configured to auto-approve. */
40
+ function staticApprovalChannel(outcome) {
41
+ return { request: () => Promise.resolve(outcome) };
42
+ }
@@ -1,15 +1,14 @@
1
+ import type { ConstructiveGateDeps } from './constructive-policy';
2
+ import type { GatePolicy, GateToolCallEvent } from './policy';
1
3
  import type { ConfirmPreview } from './preview';
2
4
  /**
3
- * Host-neutral confirm gate for mutating db tools. Structurally mirrors the
4
- * pi extension `tool_call` hook so a pi adapter is a thin mapping, but takes
5
- * every host capability (confirm UI, skip notification, context/token/preview
6
- * resolvers) as injected deps — no Electron, no pi imports.
5
+ * Host-neutral confirm gate. It owns the mechanics of asking a human —
6
+ * decline memory, auto-skipping a declined retry, refusing gated calls on a
7
+ * headless host — and takes both the host's capabilities (confirm UI, skip
8
+ * notification) and its policy (which calls are gated, what the prompt says)
9
+ * as injected dependencies. Structurally mirrors the pi extension `tool_call`
10
+ * hook so a pi adapter is a thin mapping: no Electron, no pi imports.
7
11
  */
8
- export type GateToolCallEvent = {
9
- toolName: string;
10
- toolCallId: string;
11
- input?: Record<string, unknown>;
12
- };
13
12
  /** `block: true` stops the tool call; `reason` is surfaced to the agent. */
14
13
  export type GateResult = {
15
14
  block: true;
@@ -23,31 +22,21 @@ export type GateHost = {
23
22
  /** A retry of an already-declined call was auto-skipped without prompting. */
24
23
  notifyToolSkipped(toolCallId: string): void;
25
24
  };
26
- export type ConfirmGateDeps = {
27
- /**
28
- * Whether the project is provisioned/runnable at `cwd`. Unrunnable calls
29
- * skip the confirm so the tool can return its clean "provision first"
30
- * message instead of making the user approve something that fails.
31
- */
32
- isProjectRunnable(cwd: string): Promise<boolean>;
33
- /** Whether a data-plane token is available (gates `add_records`). */
34
- hasDataToken(cwd: string): Promise<boolean>;
35
- /**
36
- * Resolve the preview for `create_template` (its tables live in the
37
- * blueprint it copies, not in the tool input). Return undefined when a
38
- * preview can't be built.
39
- */
40
- resolveTemplatePreview(cwd: string, blueprintName: string | undefined, displayName: string): Promise<ConfirmPreview | undefined>;
41
- /**
42
- * Tool names that require a human decision. The policy belongs to the host,
43
- * not the harness: Desktop/CLI gate Constructive's mutating db tools, a
44
- * remote coding host gates a different set. Defaults to
45
- * `MUTATING_DB_TOOLS`.
46
- */
47
- gatedTools?: ReadonlySet<string>;
25
+ /**
26
+ * The Constructive database deps, from which the gate derives the default
27
+ * `GatePolicy`. Kept as the name every existing host passes.
28
+ */
29
+ export type ConfirmGateDeps = ConstructiveGateDeps;
30
+ /**
31
+ * Either hand the gate the Constructive deps and get its database policy, or
32
+ * hand it a policy of your own — a remote coding host gating `bash` has no
33
+ * project context or data token to speak of.
34
+ */
35
+ export type ConfirmGateOptions = ConfirmGateDeps | {
36
+ policy: GatePolicy;
48
37
  };
49
38
  export type ConfirmGate = {
50
39
  onAgentStart: () => void;
51
40
  onToolCall: (event: GateToolCallEvent, host: GateHost, cwd: string) => Promise<GateResult>;
52
41
  };
53
- export declare function createConfirmGate(deps: ConfirmGateDeps): ConfirmGate;
42
+ export declare function createConfirmGate(options: ConfirmGateOptions): ConfirmGate;
@@ -1,34 +1,17 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.createConfirmGate = createConfirmGate;
4
+ const constructive_policy_1 = require("./constructive-policy");
4
5
  const decline_guard_1 = require("./decline-guard");
5
- const prompts_1 = require("./prompts");
6
- function createConfirmGate(deps) {
6
+ function createConfirmGate(options) {
7
7
  const declineGuard = (0, decline_guard_1.createDeclineGuard)();
8
- const gatedTools = deps.gatedTools ?? prompts_1.MUTATING_DB_TOOLS;
9
- async function confirmOrDecline(event, host, input, preview) {
10
- const { title, message, preview: basePreview } = (0, prompts_1.buildConfirmPrompt)(event.toolName, input);
11
- const approved = await host.confirmTool(event.toolCallId, title, message, preview ?? basePreview);
12
- if (!approved) {
13
- declineGuard.recordDecline(event.toolName, input);
14
- return { block: true, reason: (0, decline_guard_1.buildDeclineReason)(event.toolName) };
15
- }
16
- // An approved mutation changes database state, so earlier declines may no
17
- // longer describe the same effect (e.g. a create_template preview derives
18
- // from the blueprint, not the input) — let them re-prompt with fresh eyes.
19
- declineGuard.clear();
20
- return undefined;
21
- }
8
+ const policy = 'policy' in options ? options.policy : (0, constructive_policy_1.createConstructiveGatePolicy)(options);
22
9
  return {
23
10
  onAgentStart: () => declineGuard.clear(),
24
11
  onToolCall: async (event, host, cwd) => {
25
- if (!gatedTools.has(event.toolName))
12
+ if (!policy.isGated(event))
26
13
  return;
27
14
  const input = event.input;
28
- // manage_entity_types multiplexes read + write actions behind one tool
29
- // name; its read action is not a mutation, so it skips the gate.
30
- if (event.toolName === 'manage_entity_types' && input?.action === 'list')
31
- return;
32
15
  const retryBlock = declineGuard.checkRetry(event.toolName, input);
33
16
  if (retryBlock) {
34
17
  if (host.hasUI) {
@@ -42,27 +25,19 @@ function createConfirmGate(deps) {
42
25
  reason: `Cannot confirm "${event.toolName}" — no confirmation UI is available.`,
43
26
  };
44
27
  }
45
- // provision_database is the tool that CREATES the project context, so it
46
- // can't gate on an existing one — confirm it directly.
47
- if (event.toolName === 'provision_database') {
48
- return confirmOrDecline(event, host, input);
49
- }
50
- if (!(await deps.isProjectRunnable(cwd)))
28
+ const prompt = await policy.resolvePrompt(event, cwd);
29
+ if (!prompt)
51
30
  return;
52
- // Tools that need an app sign-in skip the confirm when no data token
53
- // exists — the tool returns its sign-in prompt instead of making the
54
- // user approve something that fails.
55
- if ((event.toolName === 'add_records' || event.toolName === 'create_api_key') &&
56
- !(await deps.hasDataToken(cwd))) {
57
- return;
58
- }
59
- let resolvedPreview;
60
- if (event.toolName === 'create_template') {
61
- const blueprintName = typeof input?.blueprintName === 'string' ? input.blueprintName : undefined;
62
- const displayName = typeof input?.displayName === 'string' ? input.displayName : '';
63
- resolvedPreview = await deps.resolveTemplatePreview(cwd, blueprintName, displayName);
31
+ const approved = await host.confirmTool(event.toolCallId, prompt.title, prompt.message, prompt.preview);
32
+ if (!approved) {
33
+ declineGuard.recordDecline(event.toolName, input);
34
+ return { block: true, reason: (0, decline_guard_1.buildDeclineReason)(event.toolName) };
64
35
  }
65
- return confirmOrDecline(event, host, input, resolvedPreview);
36
+ // An approved mutation changes state, so earlier declines may no longer
37
+ // describe the same effect (e.g. a create_template preview derives from
38
+ // the blueprint, not the input) — let them re-prompt with fresh eyes.
39
+ declineGuard.clear();
40
+ return undefined;
66
41
  },
67
42
  };
68
43
  }
@@ -0,0 +1,35 @@
1
+ import type { GatePolicy } from './policy';
2
+ import type { ConfirmPreview } from './preview';
3
+ /**
4
+ * Host capabilities the Constructive database policy needs. These are
5
+ * Constructive-specific — a policy for another host asks for whatever *its*
6
+ * rules depend on instead.
7
+ */
8
+ export type ConstructiveGateDeps = {
9
+ /**
10
+ * Whether the project is provisioned/runnable at `cwd`. Unrunnable calls
11
+ * skip the confirm so the tool can return its clean "provision first"
12
+ * message instead of making the user approve something that fails.
13
+ */
14
+ isProjectRunnable(cwd: string): Promise<boolean>;
15
+ /** Whether a data-plane token is available (gates `add_records`). */
16
+ hasDataToken(cwd: string): Promise<boolean>;
17
+ /**
18
+ * Resolve the preview for `create_template` (its tables live in the
19
+ * blueprint it copies, not in the tool input). Return undefined when a
20
+ * preview can't be built.
21
+ */
22
+ resolveTemplatePreview(cwd: string, blueprintName: string | undefined, displayName: string): Promise<ConfirmPreview | undefined>;
23
+ /**
24
+ * Tool names that require a human decision. Defaults to
25
+ * `MUTATING_DB_TOOLS`; a host that wants a different set entirely is better
26
+ * served by its own `GatePolicy`.
27
+ */
28
+ gatedTools?: ReadonlySet<string>;
29
+ };
30
+ /**
31
+ * The gate policy for Constructive's database tools, as the Desktop and CLI
32
+ * hosts want it: gate every mutating db tool, and skip the confirm when the
33
+ * call is going to bounce off a missing project or a missing sign-in anyway.
34
+ */
35
+ export declare function createConstructiveGatePolicy(deps: ConstructiveGateDeps): GatePolicy;
@@ -0,0 +1,48 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.createConstructiveGatePolicy = createConstructiveGatePolicy;
4
+ const prompts_1 = require("./prompts");
5
+ /**
6
+ * The gate policy for Constructive's database tools, as the Desktop and CLI
7
+ * hosts want it: gate every mutating db tool, and skip the confirm when the
8
+ * call is going to bounce off a missing project or a missing sign-in anyway.
9
+ */
10
+ function createConstructiveGatePolicy(deps) {
11
+ const gatedTools = deps.gatedTools ?? prompts_1.MUTATING_DB_TOOLS;
12
+ return {
13
+ isGated: (event) => {
14
+ if (!gatedTools.has(event.toolName))
15
+ return false;
16
+ // manage_entity_types multiplexes read + write actions behind one tool
17
+ // name; its read action is not a mutation, so it skips the gate.
18
+ if (event.toolName === 'manage_entity_types' && event.input?.action === 'list')
19
+ return false;
20
+ return true;
21
+ },
22
+ resolvePrompt: async (event, cwd) => {
23
+ const input = event.input;
24
+ const prompt = (0, prompts_1.buildConfirmPrompt)(event.toolName, input);
25
+ // provision_database is the tool that CREATES the project context, so it
26
+ // can't gate on an existing one — confirm it directly.
27
+ if (event.toolName === 'provision_database')
28
+ return prompt;
29
+ if (!(await deps.isProjectRunnable(cwd)))
30
+ return null;
31
+ // Tools that need an app sign-in skip the confirm when no data token
32
+ // exists — the tool returns its sign-in prompt instead of making the
33
+ // user approve something that fails.
34
+ if ((event.toolName === 'add_records' || event.toolName === 'create_api_key') &&
35
+ !(await deps.hasDataToken(cwd))) {
36
+ return null;
37
+ }
38
+ if (event.toolName === 'create_template') {
39
+ const blueprintName = typeof input?.blueprintName === 'string' ? input.blueprintName : undefined;
40
+ const displayName = typeof input?.displayName === 'string' ? input.displayName : '';
41
+ const preview = await deps.resolveTemplatePreview(cwd, blueprintName, displayName);
42
+ if (preview)
43
+ return { ...prompt, preview };
44
+ }
45
+ return prompt;
46
+ },
47
+ };
48
+ }
@@ -0,0 +1,36 @@
1
+ import type { ConfirmPrompt } from './preview';
2
+ /**
3
+ * What the gate knows about a tool call. Hosts map their agent's event shape
4
+ * onto this (pi's `ToolCallEvent`, an MCP request, …).
5
+ */
6
+ export type GateToolCallEvent = {
7
+ toolName: string;
8
+ toolCallId: string;
9
+ input?: Record<string, unknown>;
10
+ };
11
+ /**
12
+ * The host's answer to "which calls need a human decision, and what do we show
13
+ * the human?". Everything tool-specific lives here — which tool names are
14
+ * gated, which arguments turn a gated name into a harmless read, and the
15
+ * wording of the confirmation — so the gate itself stays host-neutral and only
16
+ * owns the mechanics (decline memory, headless blocking, prompting).
17
+ *
18
+ * `createConstructiveGatePolicy` is the Constructive database policy the
19
+ * Desktop/CLI hosts use; a remote coding host supplies its own.
20
+ */
21
+ export type GatePolicy = {
22
+ /**
23
+ * Whether this call needs a human decision at all. Cheap and synchronous:
24
+ * it runs before the decline memory and the headless block, so it must
25
+ * decide from the tool name and arguments alone — no I/O.
26
+ */
27
+ isGated(event: GateToolCallEvent): boolean;
28
+ /**
29
+ * The prompt to put in front of the user, or `null` to let an already-gated
30
+ * call through without one. Runs only for gated calls on a host with a
31
+ * confirm surface, so it may do I/O to build a richer preview or to check a
32
+ * precondition that makes the confirm pointless (e.g. the call is going to
33
+ * fail with "sign in first" anyway).
34
+ */
35
+ resolvePrompt(event: GateToolCallEvent, cwd: string): Promise<ConfirmPrompt | null>;
36
+ };
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -35,3 +35,9 @@ export type ConfirmPreview = {
35
35
  tableName: string;
36
36
  field: ConfirmPreviewField;
37
37
  };
38
+ /** What a host puts in front of the user for one gated call. */
39
+ export type ConfirmPrompt = {
40
+ title: string;
41
+ message: string;
42
+ preview?: ConfirmPreview;
43
+ };
@@ -1,8 +1,3 @@
1
1
  export declare const MUTATING_DB_TOOLS: Set<string>;
2
- import type { ConfirmPreview } from './preview';
3
- export type ConfirmPrompt = {
4
- title: string;
5
- message: string;
6
- preview?: ConfirmPreview;
7
- };
2
+ import type { ConfirmPrompt } from './preview';
8
3
  export declare function buildConfirmPrompt(toolName: string, input: Record<string, unknown> | undefined): ConfirmPrompt;
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The run gate: evaluate the run's policy for one tool call and, when the policy
3
+ * will not decide alone, wait for a human through the approval channel.
4
+ *
5
+ * Harness-neutral on purpose. An adapter owns one line of glue — map its
6
+ * harness's tool-call event onto `decide()` and turn the outcome into whatever
7
+ * that harness expects from a blocked call — so the policy, the approval
8
+ * rendezvous and the audit record are the same for every harness.
9
+ */
10
+ import { type ApprovalChannel, type ApprovalRequest } from './approvals';
11
+ import { RunGatePolicy, type RunGatePolicyOptions, type RunGateVerdict } from './run-policy';
12
+ export interface RunGateDecisionRecord {
13
+ runId: string;
14
+ toolCallId: string;
15
+ toolName: string;
16
+ input: Record<string, unknown>;
17
+ /** What the policy said. */
18
+ verdict: RunGateVerdict;
19
+ /** How the request was finally settled. */
20
+ decision: 'allow' | 'deny';
21
+ reason?: string;
22
+ actorId?: string;
23
+ decidedAt: string;
24
+ }
25
+ export interface RunGateOptions {
26
+ runId: string;
27
+ /** A policy, or the options to build one. */
28
+ policy: RunGatePolicy | RunGatePolicyOptions;
29
+ /** Required only if the policy can produce `ask`. */
30
+ approvals?: ApprovalChannel;
31
+ /** Every settled decision, for the run log / audit trail. */
32
+ onDecision?: (record: RunGateDecisionRecord) => void;
33
+ now?: () => Date;
34
+ }
35
+ export interface RunGateToolCall {
36
+ toolCallId: string;
37
+ toolName: string;
38
+ input?: Record<string, unknown>;
39
+ }
40
+ export interface RunGateOutcome {
41
+ /** `false` means the harness must not run the call. */
42
+ allowed: boolean;
43
+ /** The model's only explanation for a refusal, so policies should be specific. */
44
+ reason?: string;
45
+ }
46
+ export declare class RunGate {
47
+ readonly policy: RunGatePolicy;
48
+ /** Requests currently waiting on a human. */
49
+ readonly pending: ReadonlyMap<string, ApprovalRequest>;
50
+ private readonly options;
51
+ private readonly now;
52
+ private readonly waiting;
53
+ constructor(options: RunGateOptions);
54
+ decide(call: RunGateToolCall): Promise<RunGateOutcome>;
55
+ private ask;
56
+ }
57
+ export declare function createRunGate(options: RunGateOptions): RunGate;
@@ -0,0 +1,77 @@
1
+ "use strict";
2
+ /**
3
+ * The run gate: evaluate the run's policy for one tool call and, when the policy
4
+ * will not decide alone, wait for a human through the approval channel.
5
+ *
6
+ * Harness-neutral on purpose. An adapter owns one line of glue — map its
7
+ * harness's tool-call event onto `decide()` and turn the outcome into whatever
8
+ * that harness expects from a blocked call — so the policy, the approval
9
+ * rendezvous and the audit record are the same for every harness.
10
+ */
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.RunGate = void 0;
13
+ exports.createRunGate = createRunGate;
14
+ const run_policy_1 = require("./run-policy");
15
+ class RunGate {
16
+ policy;
17
+ /** Requests currently waiting on a human. */
18
+ pending;
19
+ options;
20
+ now;
21
+ waiting = new Map();
22
+ constructor(options) {
23
+ this.options = options;
24
+ this.now = options.now ?? (() => new Date());
25
+ this.policy = options.policy instanceof run_policy_1.RunGatePolicy ? options.policy : new run_policy_1.RunGatePolicy(options.policy);
26
+ this.pending = this.waiting;
27
+ if (canAsk(this.policy) && !options.approvals) {
28
+ throw new Error('gate: the policy can produce "ask", so an approvals channel is required');
29
+ }
30
+ }
31
+ async decide(call) {
32
+ const input = call.input ?? {};
33
+ const verdict = this.policy.evaluate({ toolName: call.toolName, input });
34
+ const settled = verdict.decision === 'ask'
35
+ ? await this.ask(call.toolCallId, call.toolName, input, verdict)
36
+ : { decision: verdict.decision, ...(verdict.reason === undefined ? {} : { reason: verdict.reason }) };
37
+ this.options.onDecision?.({
38
+ runId: this.options.runId,
39
+ toolCallId: call.toolCallId,
40
+ toolName: call.toolName,
41
+ input,
42
+ verdict,
43
+ decision: settled.decision,
44
+ ...(settled.reason === undefined ? {} : { reason: settled.reason }),
45
+ ...(settled.actorId === undefined ? {} : { actorId: settled.actorId }),
46
+ decidedAt: this.now().toISOString()
47
+ });
48
+ if (settled.decision === 'allow')
49
+ return { allowed: true };
50
+ return { allowed: false, reason: settled.reason ?? `gate: ${call.toolName} is not permitted in this run` };
51
+ }
52
+ async ask(toolCallId, toolName, input, verdict) {
53
+ const request = {
54
+ runId: this.options.runId,
55
+ toolCallId,
56
+ toolName,
57
+ input,
58
+ ...(verdict.reason === undefined ? {} : { reason: verdict.reason }),
59
+ requestedAt: this.now().toISOString()
60
+ };
61
+ this.waiting.set(toolCallId, request);
62
+ try {
63
+ return await this.options.approvals.request(request);
64
+ }
65
+ finally {
66
+ this.waiting.delete(toolCallId);
67
+ }
68
+ }
69
+ }
70
+ exports.RunGate = RunGate;
71
+ function createRunGate(options) {
72
+ return new RunGate(options);
73
+ }
74
+ function canAsk(policy) {
75
+ const decisions = [policy.defaultDecision, ...policy.rules.map((rule) => rule.decision)];
76
+ return decisions.includes('ask');
77
+ }