@intended-inc/claude-code-hook 0.1.1 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -2
- package/dist/bin.js +272 -3
- package/dist/bin.mjs +274 -5
- package/dist/index.d.mts +45 -13
- package/dist/index.d.ts +45 -13
- package/dist/index.js +278 -2
- package/dist/index.mjs +275 -3
- package/package.json +1 -1
package/dist/index.d.mts
CHANGED
|
@@ -1,15 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure, testable core of the Intended Claude Code PreToolUse hook.
|
|
3
|
-
*
|
|
4
|
-
* Contract:
|
|
5
|
-
* - Unconfigured (no API key / tenant) → ALLOW (fail-open; never bricks a repo).
|
|
6
|
-
* - Configured:
|
|
7
|
-
* 200 APPROVED → allow
|
|
8
|
-
* 202 ESCALATED → ask (human)
|
|
9
|
-
* 403 DENIED → deny
|
|
10
|
-
* any other status (401/429/5xx/…), a network throw, or an unrecognized body
|
|
11
|
-
* → DENY (fail-closed). Never falls through to allow.
|
|
12
|
-
*/
|
|
13
1
|
interface HookEvent {
|
|
14
2
|
tool_name?: string;
|
|
15
3
|
tool_input?: Record<string, unknown>;
|
|
@@ -18,6 +6,10 @@ interface HookEnv {
|
|
|
18
6
|
INTENDED_API_KEY?: string;
|
|
19
7
|
INTENDED_TENANT_ID?: string;
|
|
20
8
|
INTENDED_API_URL?: string;
|
|
9
|
+
/** Seconds to wait for the approver on ESCALATED (default 45). */
|
|
10
|
+
INTENDED_HOOK_ESCALATION_WAIT_SECONDS?: string;
|
|
11
|
+
/** What to do when the decision is still pending after the wait: "deny" (default) or "ask". */
|
|
12
|
+
INTENDED_HOOK_ON_PENDING?: string;
|
|
21
13
|
}
|
|
22
14
|
interface HookDecision {
|
|
23
15
|
permissionDecision: "allow" | "deny" | "ask";
|
|
@@ -34,11 +26,51 @@ interface HookDecision {
|
|
|
34
26
|
type FetchLike = (url: string, init?: unknown) => Promise<{
|
|
35
27
|
status: number;
|
|
36
28
|
json: () => Promise<unknown>;
|
|
29
|
+
headers?: {
|
|
30
|
+
get(name: string): string | null;
|
|
31
|
+
};
|
|
37
32
|
}>;
|
|
33
|
+
/**
|
|
34
|
+
* Where escalations still waiting on an approver are remembered between hook
|
|
35
|
+
* runs (each run is a separate process). Keyed by toolCallKey(tool, args).
|
|
36
|
+
*/
|
|
37
|
+
interface PendingStore {
|
|
38
|
+
get(key: string): string | undefined;
|
|
39
|
+
set(key: string, intentId: string, expiresAt?: string | null): void;
|
|
40
|
+
delete(key: string): void;
|
|
41
|
+
}
|
|
42
|
+
/** Claude Code hooks time out at 60s by default; leave headroom. */
|
|
43
|
+
declare const DEFAULT_ESCALATION_WAIT_SECONDS = 45;
|
|
44
|
+
/**
|
|
45
|
+
* The action text Intended stores (and explain_decision returns): the tool name
|
|
46
|
+
* and argument KEYS, never values. Values (e.g. the Bash command) travel only in
|
|
47
|
+
* `arguments`, which the API evaluates in memory and stores as a sha256 digest.
|
|
48
|
+
*/
|
|
49
|
+
declare function describeToolCall(name: string, args: Record<string, unknown>): string;
|
|
50
|
+
/** INTENDED_HOOK_ESCALATION_WAIT_SECONDS → ms. Unset or invalid → 45s. */
|
|
51
|
+
declare function escalationWaitMs(env: HookEnv): number;
|
|
38
52
|
declare function evaluateHookDecision(input: {
|
|
39
53
|
event: HookEvent;
|
|
40
54
|
env: HookEnv;
|
|
41
55
|
fetchImpl?: FetchLike;
|
|
56
|
+
/** Remembers pending escalations across hook runs. Optional: without it, every call is a fresh intent. */
|
|
57
|
+
pendingStore?: PendingStore;
|
|
58
|
+
/** Clock + sleep overrides (tests). */
|
|
59
|
+
now?: () => number;
|
|
60
|
+
sleep?: (ms: number) => Promise<void>;
|
|
42
61
|
}): Promise<HookDecision>;
|
|
43
62
|
|
|
44
|
-
|
|
63
|
+
declare class FilePendingStore implements PendingStore {
|
|
64
|
+
private readonly path;
|
|
65
|
+
private readonly maxEntries;
|
|
66
|
+
private readonly now;
|
|
67
|
+
constructor(path: string, maxEntries?: number, now?: () => number);
|
|
68
|
+
get(key: string): string | undefined;
|
|
69
|
+
set(key: string, intentId: string, expiresAt?: string | null): void;
|
|
70
|
+
delete(key: string): void;
|
|
71
|
+
/** Read the file and drop expired entries. */
|
|
72
|
+
private load;
|
|
73
|
+
private save;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export { DEFAULT_ESCALATION_WAIT_SECONDS, type FetchLike, FilePendingStore, type HookDecision, type HookEnv, type HookEvent, type PendingStore, describeToolCall, escalationWaitMs, evaluateHookDecision };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,15 +1,3 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Pure, testable core of the Intended Claude Code PreToolUse hook.
|
|
3
|
-
*
|
|
4
|
-
* Contract:
|
|
5
|
-
* - Unconfigured (no API key / tenant) → ALLOW (fail-open; never bricks a repo).
|
|
6
|
-
* - Configured:
|
|
7
|
-
* 200 APPROVED → allow
|
|
8
|
-
* 202 ESCALATED → ask (human)
|
|
9
|
-
* 403 DENIED → deny
|
|
10
|
-
* any other status (401/429/5xx/…), a network throw, or an unrecognized body
|
|
11
|
-
* → DENY (fail-closed). Never falls through to allow.
|
|
12
|
-
*/
|
|
13
1
|
interface HookEvent {
|
|
14
2
|
tool_name?: string;
|
|
15
3
|
tool_input?: Record<string, unknown>;
|
|
@@ -18,6 +6,10 @@ interface HookEnv {
|
|
|
18
6
|
INTENDED_API_KEY?: string;
|
|
19
7
|
INTENDED_TENANT_ID?: string;
|
|
20
8
|
INTENDED_API_URL?: string;
|
|
9
|
+
/** Seconds to wait for the approver on ESCALATED (default 45). */
|
|
10
|
+
INTENDED_HOOK_ESCALATION_WAIT_SECONDS?: string;
|
|
11
|
+
/** What to do when the decision is still pending after the wait: "deny" (default) or "ask". */
|
|
12
|
+
INTENDED_HOOK_ON_PENDING?: string;
|
|
21
13
|
}
|
|
22
14
|
interface HookDecision {
|
|
23
15
|
permissionDecision: "allow" | "deny" | "ask";
|
|
@@ -34,11 +26,51 @@ interface HookDecision {
|
|
|
34
26
|
type FetchLike = (url: string, init?: unknown) => Promise<{
|
|
35
27
|
status: number;
|
|
36
28
|
json: () => Promise<unknown>;
|
|
29
|
+
headers?: {
|
|
30
|
+
get(name: string): string | null;
|
|
31
|
+
};
|
|
37
32
|
}>;
|
|
33
|
+
/**
|
|
34
|
+
* Where escalations still waiting on an approver are remembered between hook
|
|
35
|
+
* runs (each run is a separate process). Keyed by toolCallKey(tool, args).
|
|
36
|
+
*/
|
|
37
|
+
interface PendingStore {
|
|
38
|
+
get(key: string): string | undefined;
|
|
39
|
+
set(key: string, intentId: string, expiresAt?: string | null): void;
|
|
40
|
+
delete(key: string): void;
|
|
41
|
+
}
|
|
42
|
+
/** Claude Code hooks time out at 60s by default; leave headroom. */
|
|
43
|
+
declare const DEFAULT_ESCALATION_WAIT_SECONDS = 45;
|
|
44
|
+
/**
|
|
45
|
+
* The action text Intended stores (and explain_decision returns): the tool name
|
|
46
|
+
* and argument KEYS, never values. Values (e.g. the Bash command) travel only in
|
|
47
|
+
* `arguments`, which the API evaluates in memory and stores as a sha256 digest.
|
|
48
|
+
*/
|
|
49
|
+
declare function describeToolCall(name: string, args: Record<string, unknown>): string;
|
|
50
|
+
/** INTENDED_HOOK_ESCALATION_WAIT_SECONDS → ms. Unset or invalid → 45s. */
|
|
51
|
+
declare function escalationWaitMs(env: HookEnv): number;
|
|
38
52
|
declare function evaluateHookDecision(input: {
|
|
39
53
|
event: HookEvent;
|
|
40
54
|
env: HookEnv;
|
|
41
55
|
fetchImpl?: FetchLike;
|
|
56
|
+
/** Remembers pending escalations across hook runs. Optional: without it, every call is a fresh intent. */
|
|
57
|
+
pendingStore?: PendingStore;
|
|
58
|
+
/** Clock + sleep overrides (tests). */
|
|
59
|
+
now?: () => number;
|
|
60
|
+
sleep?: (ms: number) => Promise<void>;
|
|
42
61
|
}): Promise<HookDecision>;
|
|
43
62
|
|
|
44
|
-
|
|
63
|
+
declare class FilePendingStore implements PendingStore {
|
|
64
|
+
private readonly path;
|
|
65
|
+
private readonly maxEntries;
|
|
66
|
+
private readonly now;
|
|
67
|
+
constructor(path: string, maxEntries?: number, now?: () => number);
|
|
68
|
+
get(key: string): string | undefined;
|
|
69
|
+
set(key: string, intentId: string, expiresAt?: string | null): void;
|
|
70
|
+
delete(key: string): void;
|
|
71
|
+
/** Read the file and drop expired entries. */
|
|
72
|
+
private load;
|
|
73
|
+
private save;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export { DEFAULT_ESCALATION_WAIT_SECONDS, type FetchLike, FilePendingStore, type HookDecision, type HookEnv, type HookEvent, type PendingStore, describeToolCall, escalationWaitMs, evaluateHookDecision };
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,147 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
var crypto = require('crypto');
|
|
4
|
+
var fs = require('fs');
|
|
5
|
+
var path = require('path');
|
|
6
|
+
|
|
7
|
+
// src/wait.ts
|
|
8
|
+
var FINAL = /* @__PURE__ */ new Set(["ALLOW", "DENY", "EXPIRED"]);
|
|
9
|
+
var MAX_POLL_SECONDS = 50;
|
|
10
|
+
var MAX_BACKOFF_MS = 1e4;
|
|
11
|
+
var MIN_REPOLL_MS = 1e3;
|
|
12
|
+
var defaultSleep = (ms) => new Promise((r) => setTimeout(r, Math.max(0, ms)));
|
|
13
|
+
function str(v) {
|
|
14
|
+
return typeof v === "string" && v.length > 0 ? v : null;
|
|
15
|
+
}
|
|
16
|
+
function base(intentId, status, reason) {
|
|
17
|
+
return {
|
|
18
|
+
intentId,
|
|
19
|
+
status,
|
|
20
|
+
reason,
|
|
21
|
+
token: null,
|
|
22
|
+
decidedBy: null,
|
|
23
|
+
decidedAt: null,
|
|
24
|
+
escalationId: null,
|
|
25
|
+
expiresAt: null,
|
|
26
|
+
receiptUrl: null
|
|
27
|
+
};
|
|
28
|
+
}
|
|
29
|
+
function parseBody(intentId, body, apiUrl) {
|
|
30
|
+
const status = body.status;
|
|
31
|
+
if (status !== "ALLOW" && status !== "DENY" && status !== "PENDING" && status !== "EXPIRED") return null;
|
|
32
|
+
const receipt = str(body.receiptUrl);
|
|
33
|
+
return {
|
|
34
|
+
intentId: str(body.intentId) ?? intentId,
|
|
35
|
+
status,
|
|
36
|
+
reason: str(body.reason) ?? `Decision: ${status}`,
|
|
37
|
+
token: status === "ALLOW" ? str(body.token) : null,
|
|
38
|
+
decidedBy: body.decidedBy && typeof body.decidedBy === "object" ? body.decidedBy : null,
|
|
39
|
+
decidedAt: str(body.decidedAt),
|
|
40
|
+
escalationId: str(body.escalationId),
|
|
41
|
+
expiresAt: str(body.expiresAt),
|
|
42
|
+
receiptUrl: receipt ? /^https?:\/\//.test(receipt) ? receipt : `${apiUrl}${receipt.startsWith("/") ? "" : "/"}${receipt}` : null
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
function retryAfterHeaderMs(res) {
|
|
46
|
+
const raw = res.headers?.get?.("retry-after");
|
|
47
|
+
const n = raw == null ? NaN : Number(raw);
|
|
48
|
+
return Number.isFinite(n) && n > 0 ? n * 1e3 : 0;
|
|
49
|
+
}
|
|
50
|
+
async function waitForDecision(intentId, opts) {
|
|
51
|
+
const apiUrl = (opts.apiUrl ?? "https://api.intended.so").replace(/\/$/, "");
|
|
52
|
+
const fetchImpl = opts.fetchImpl ?? fetch;
|
|
53
|
+
const now = opts.now ?? Date.now;
|
|
54
|
+
const sleep = opts.sleep ?? defaultSleep;
|
|
55
|
+
const deadline = now() + Math.max(0, opts.timeoutMs);
|
|
56
|
+
const headers = {
|
|
57
|
+
authorization: `Bearer ${opts.apiKey}`,
|
|
58
|
+
"x-tenant-id": opts.tenantId
|
|
59
|
+
};
|
|
60
|
+
let backoffMs = 1e3;
|
|
61
|
+
for (; ; ) {
|
|
62
|
+
const remaining = deadline - now();
|
|
63
|
+
const timeoutSec = remaining <= 0 ? 0 : Math.min(MAX_POLL_SECONDS, Math.ceil(remaining / 1e3));
|
|
64
|
+
const url = `${apiUrl}/v1/decisions/${encodeURIComponent(intentId)}/wait?timeout=${timeoutSec}&tenantId=${encodeURIComponent(opts.tenantId)}`;
|
|
65
|
+
const startedAt = now();
|
|
66
|
+
let res = null;
|
|
67
|
+
try {
|
|
68
|
+
res = await fetchImpl(url, {
|
|
69
|
+
headers,
|
|
70
|
+
// The server holds at most timeoutSec; give the network some slack beyond that.
|
|
71
|
+
signal: AbortSignal.timeout(timeoutSec * 1e3 + 15e3)
|
|
72
|
+
});
|
|
73
|
+
} catch {
|
|
74
|
+
res = null;
|
|
75
|
+
}
|
|
76
|
+
let transientWaitMs = 0;
|
|
77
|
+
if (res) {
|
|
78
|
+
if (res.status === 401) {
|
|
79
|
+
return { ...base(intentId, "ERROR", "The Intended API rejected the API key (401). The action is not approved."), error: "unauthorized" };
|
|
80
|
+
}
|
|
81
|
+
if (res.status === 403) {
|
|
82
|
+
return {
|
|
83
|
+
...base(
|
|
84
|
+
intentId,
|
|
85
|
+
"ERROR",
|
|
86
|
+
"This API key cannot read decisions: it needs the intent:read scope. The action is not approved."
|
|
87
|
+
),
|
|
88
|
+
error: "forbidden"
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
if (res.status === 404) {
|
|
92
|
+
return { ...base(intentId, "ERROR", `Intended has no decision for intent ${intentId}. The action is not approved.`), error: "not_found" };
|
|
93
|
+
}
|
|
94
|
+
if (res.status === 429 || res.status >= 500) {
|
|
95
|
+
transientWaitMs = Math.max(backoffMs, retryAfterHeaderMs(res));
|
|
96
|
+
} else {
|
|
97
|
+
const body = await res.json().catch(() => null);
|
|
98
|
+
const parsed = res.status === 200 && body ? parseBody(intentId, body, apiUrl) : null;
|
|
99
|
+
if (!parsed) {
|
|
100
|
+
return {
|
|
101
|
+
...base(intentId, "ERROR", `Unrecognised decision response (HTTP ${res.status}). The action is not approved.`),
|
|
102
|
+
error: "bad_response"
|
|
103
|
+
};
|
|
104
|
+
}
|
|
105
|
+
if (FINAL.has(parsed.status)) return parsed;
|
|
106
|
+
if (now() >= deadline) return { ...parsed, timedOut: true };
|
|
107
|
+
const retryAfterMs = typeof body?.retryAfterMs === "number" && body.retryAfterMs > 0 ? body.retryAfterMs : 0;
|
|
108
|
+
const answeredFast = now() - startedAt < Math.min(timeoutSec * 1e3, MIN_REPOLL_MS) / 2;
|
|
109
|
+
const pause = retryAfterMs > 0 ? retryAfterMs : answeredFast ? MIN_REPOLL_MS : 0;
|
|
110
|
+
if (pause > 0) await sleep(Math.min(pause, Math.max(0, deadline - now())));
|
|
111
|
+
backoffMs = 1e3;
|
|
112
|
+
continue;
|
|
113
|
+
}
|
|
114
|
+
} else {
|
|
115
|
+
transientWaitMs = backoffMs;
|
|
116
|
+
}
|
|
117
|
+
if (now() >= deadline) {
|
|
118
|
+
return {
|
|
119
|
+
...base(
|
|
120
|
+
intentId,
|
|
121
|
+
"PENDING",
|
|
122
|
+
"The Intended decision service could not be reached before the wait ended. The action is still not approved."
|
|
123
|
+
),
|
|
124
|
+
timedOut: true
|
|
125
|
+
};
|
|
126
|
+
}
|
|
127
|
+
await sleep(Math.min(transientWaitMs, Math.max(0, deadline - now())));
|
|
128
|
+
backoffMs = Math.min(backoffMs * 2, MAX_BACKOFF_MS);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
function canonicalJson(value) {
|
|
132
|
+
if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null";
|
|
133
|
+
if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]`;
|
|
134
|
+
const obj = value;
|
|
135
|
+
return `{${Object.keys(obj).sort().filter((k) => obj[k] !== void 0).map((k) => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(",")}}`;
|
|
136
|
+
}
|
|
137
|
+
function toolCallKey(toolName, args) {
|
|
138
|
+
return crypto.createHash("sha256").update(`${toolName}
|
|
139
|
+
${canonicalJson(args ?? {})}`).digest("hex");
|
|
140
|
+
}
|
|
141
|
+
|
|
3
142
|
// src/evaluate.ts
|
|
4
143
|
var AUTHORITY_STATUSES = /* @__PURE__ */ new Set([200, 202, 403]);
|
|
144
|
+
var DEFAULT_ESCALATION_WAIT_SECONDS = 45;
|
|
5
145
|
var MAX_DESCRIBED_KEYS = 20;
|
|
6
146
|
var SAFE_KEY = /^[A-Za-z_][A-Za-z0-9_.-]{0,63}$/;
|
|
7
147
|
function describeToolCall(name, args) {
|
|
@@ -12,8 +152,17 @@ function describeToolCall(name, args) {
|
|
|
12
152
|
const list = [...named, ...unnamed > 0 ? [`+${unnamed} more`] : []].join(", ");
|
|
13
153
|
return `Call tool "${name}" with args: ${list}`;
|
|
14
154
|
}
|
|
155
|
+
function escalationWaitMs(env) {
|
|
156
|
+
const raw = env.INTENDED_HOOK_ESCALATION_WAIT_SECONDS;
|
|
157
|
+
if (raw === void 0 || raw.trim() === "") return DEFAULT_ESCALATION_WAIT_SECONDS * 1e3;
|
|
158
|
+
const n = Number(raw);
|
|
159
|
+
return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e3) : DEFAULT_ESCALATION_WAIT_SECONDS * 1e3;
|
|
160
|
+
}
|
|
161
|
+
function onPending(env) {
|
|
162
|
+
return env.INTENDED_HOOK_ON_PENDING?.trim().toLowerCase() === "ask" ? "ask" : "deny";
|
|
163
|
+
}
|
|
15
164
|
async function evaluateHookDecision(input) {
|
|
16
|
-
const { event, env } = input;
|
|
165
|
+
const { event, env, pendingStore } = input;
|
|
17
166
|
const fetchImpl = input.fetchImpl ?? globalThis.fetch;
|
|
18
167
|
const toolName = event.tool_name ?? "unknown";
|
|
19
168
|
const args = { ...event.tool_input ?? {} };
|
|
@@ -21,6 +170,21 @@ async function evaluateHookDecision(input) {
|
|
|
21
170
|
const tenantId = env.INTENDED_TENANT_ID;
|
|
22
171
|
const apiUrl = (env.INTENDED_API_URL ?? "https://api.intended.so").replace(/\/$/, "");
|
|
23
172
|
if (!apiKey || !tenantId) return { permissionDecision: "allow" };
|
|
173
|
+
const key = toolCallKey(toolName, args);
|
|
174
|
+
const wait = (intentId) => waitForDecision(intentId, {
|
|
175
|
+
apiUrl,
|
|
176
|
+
apiKey,
|
|
177
|
+
tenantId,
|
|
178
|
+
fetchImpl,
|
|
179
|
+
timeoutMs: escalationWaitMs(env),
|
|
180
|
+
now: input.now,
|
|
181
|
+
sleep: input.sleep
|
|
182
|
+
});
|
|
183
|
+
const pendingIntentId = safe(() => pendingStore?.get(key));
|
|
184
|
+
if (pendingIntentId) {
|
|
185
|
+
const outcome = await wait(pendingIntentId);
|
|
186
|
+
return settle(outcome, pendingIntentId, toolName, key, env, pendingStore);
|
|
187
|
+
}
|
|
24
188
|
let res;
|
|
25
189
|
try {
|
|
26
190
|
res = await fetchImpl(`${apiUrl}/v1/agent-intent`, {
|
|
@@ -51,8 +215,120 @@ async function evaluateHookDecision(input) {
|
|
|
51
215
|
tokenIssued: Boolean(data.authorityDecisionToken)
|
|
52
216
|
};
|
|
53
217
|
if (verdict === "APPROVED") return { permissionDecision: "allow", record };
|
|
54
|
-
if (verdict === "ESCALATED")
|
|
218
|
+
if (verdict === "ESCALATED") {
|
|
219
|
+
if (!data.intentId) {
|
|
220
|
+
return { permissionDecision: "deny", reason: "Intended: escalated without an intent id to wait on \u2014 fail-closed.", record };
|
|
221
|
+
}
|
|
222
|
+
const outcome = await wait(data.intentId);
|
|
223
|
+
return settle(outcome, data.intentId, toolName, key, env, pendingStore, reason);
|
|
224
|
+
}
|
|
55
225
|
return { permissionDecision: "deny", reason: `Intended: denied \u2014 ${reason || "fail-closed (unrecognized decision)"}`, record };
|
|
56
226
|
}
|
|
227
|
+
function settle(outcome, intentId, toolName, key, env, store, escalationReason = "") {
|
|
228
|
+
const record = {
|
|
229
|
+
tool: toolName,
|
|
230
|
+
verdict: outcome.status === "ALLOW" ? "APPROVED_AFTER_ESCALATION" : outcome.status === "PENDING" ? "ESCALATED" : outcome.status,
|
|
231
|
+
reason: outcome.reason || escalationReason,
|
|
232
|
+
intentId,
|
|
233
|
+
tokenIssued: Boolean(outcome.token)
|
|
234
|
+
};
|
|
235
|
+
if (outcome.status === "ALLOW") {
|
|
236
|
+
safe(() => store?.delete(key));
|
|
237
|
+
return { permissionDecision: "allow", record };
|
|
238
|
+
}
|
|
239
|
+
if (outcome.status === "PENDING") {
|
|
240
|
+
safe(() => store?.set(key, intentId, outcome.expiresAt));
|
|
241
|
+
const message = `Intended: awaiting human approval (intent ${intentId}). Ask an approver to approve it in the Intended console, then retry the same tool call; it will be allowed then.` + (outcome.timedOut && /could not be reached/.test(outcome.reason) ? ` (${outcome.reason})` : "");
|
|
242
|
+
return { permissionDecision: onPending(env), reason: message, record };
|
|
243
|
+
}
|
|
244
|
+
safe(() => store?.delete(key));
|
|
245
|
+
if (outcome.status === "EXPIRED") {
|
|
246
|
+
return {
|
|
247
|
+
permissionDecision: "deny",
|
|
248
|
+
reason: `Intended: denied \u2014 no approver decided before the approval request expired (intent ${intentId}).`,
|
|
249
|
+
record
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
if (outcome.status === "ERROR") {
|
|
253
|
+
return { permissionDecision: "deny", reason: `Intended: could not get the approval decision \u2014 ${outcome.reason}`, record };
|
|
254
|
+
}
|
|
255
|
+
return { permissionDecision: "deny", reason: `Intended: denied \u2014 ${outcome.reason}`, record };
|
|
256
|
+
}
|
|
257
|
+
function safe(fn) {
|
|
258
|
+
try {
|
|
259
|
+
return fn();
|
|
260
|
+
} catch {
|
|
261
|
+
return void 0;
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
var DEFAULT_TTL_MS = 24 * 60 * 60 * 1e3;
|
|
265
|
+
var FilePendingStore = class {
|
|
266
|
+
constructor(path, maxEntries = 200, now = Date.now) {
|
|
267
|
+
this.path = path;
|
|
268
|
+
this.maxEntries = maxEntries;
|
|
269
|
+
this.now = now;
|
|
270
|
+
}
|
|
271
|
+
path;
|
|
272
|
+
maxEntries;
|
|
273
|
+
now;
|
|
274
|
+
get(key) {
|
|
275
|
+
const entries = this.load();
|
|
276
|
+
const e = entries[key];
|
|
277
|
+
if (!e) return void 0;
|
|
278
|
+
if (e.expiresAt <= this.now()) {
|
|
279
|
+
delete entries[key];
|
|
280
|
+
this.save(entries);
|
|
281
|
+
return void 0;
|
|
282
|
+
}
|
|
283
|
+
return e.intentId;
|
|
284
|
+
}
|
|
285
|
+
set(key, intentId, expiresAt) {
|
|
286
|
+
const entries = this.load();
|
|
287
|
+
const parsed = expiresAt ? Date.parse(expiresAt) : NaN;
|
|
288
|
+
entries[key] = {
|
|
289
|
+
intentId,
|
|
290
|
+
expiresAt: Number.isFinite(parsed) ? parsed : this.now() + DEFAULT_TTL_MS,
|
|
291
|
+
savedAt: this.now()
|
|
292
|
+
};
|
|
293
|
+
const keys = Object.keys(entries).sort((a, b) => entries[a].savedAt - entries[b].savedAt);
|
|
294
|
+
for (const k of keys.slice(0, Math.max(0, keys.length - this.maxEntries))) delete entries[k];
|
|
295
|
+
this.save(entries);
|
|
296
|
+
}
|
|
297
|
+
delete(key) {
|
|
298
|
+
const entries = this.load();
|
|
299
|
+
if (!(key in entries)) return;
|
|
300
|
+
delete entries[key];
|
|
301
|
+
this.save(entries);
|
|
302
|
+
}
|
|
303
|
+
/** Read the file and drop expired entries. */
|
|
304
|
+
load() {
|
|
305
|
+
let raw;
|
|
306
|
+
try {
|
|
307
|
+
raw = JSON.parse(fs.readFileSync(this.path, "utf8"));
|
|
308
|
+
} catch {
|
|
309
|
+
return {};
|
|
310
|
+
}
|
|
311
|
+
const out = {};
|
|
312
|
+
if (!raw || typeof raw !== "object") return out;
|
|
313
|
+
const t = this.now();
|
|
314
|
+
for (const [k, v] of Object.entries(raw)) {
|
|
315
|
+
const e = v;
|
|
316
|
+
if (e && typeof e.intentId === "string" && typeof e.expiresAt === "number" && typeof e.savedAt === "number" && e.expiresAt > t) {
|
|
317
|
+
out[k] = { intentId: e.intentId, expiresAt: e.expiresAt, savedAt: e.savedAt };
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return out;
|
|
321
|
+
}
|
|
322
|
+
save(entries) {
|
|
323
|
+
fs.mkdirSync(path.dirname(this.path), { recursive: true });
|
|
324
|
+
const tmp = `${this.path}.${process.pid}.tmp`;
|
|
325
|
+
fs.writeFileSync(tmp, JSON.stringify(entries, null, 2), { mode: 384 });
|
|
326
|
+
fs.renameSync(tmp, this.path);
|
|
327
|
+
}
|
|
328
|
+
};
|
|
57
329
|
|
|
330
|
+
exports.DEFAULT_ESCALATION_WAIT_SECONDS = DEFAULT_ESCALATION_WAIT_SECONDS;
|
|
331
|
+
exports.FilePendingStore = FilePendingStore;
|
|
332
|
+
exports.describeToolCall = describeToolCall;
|
|
333
|
+
exports.escalationWaitMs = escalationWaitMs;
|
|
58
334
|
exports.evaluateHookDecision = evaluateHookDecision;
|