airlock-bot 0.3.1 → 0.3.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. package/dist/airlock/tools.d.ts +10 -2
  2. package/dist/airlock/tools.d.ts.map +1 -1
  3. package/dist/airlock/tools.js +17 -0
  4. package/dist/airlock/tools.js.map +1 -1
  5. package/dist/allowlist/engine.d.ts.map +1 -1
  6. package/dist/allowlist/engine.js +15 -0
  7. package/dist/allowlist/engine.js.map +1 -1
  8. package/dist/audit/db.d.ts +22 -0
  9. package/dist/audit/db.d.ts.map +1 -1
  10. package/dist/audit/db.js +68 -3
  11. package/dist/audit/db.js.map +1 -1
  12. package/dist/audit/logger.d.ts +7 -1
  13. package/dist/audit/logger.d.ts.map +1 -1
  14. package/dist/audit/logger.js +18 -0
  15. package/dist/audit/logger.js.map +1 -1
  16. package/dist/backend/airlock-adapter.d.ts +10 -1
  17. package/dist/backend/airlock-adapter.d.ts.map +1 -1
  18. package/dist/backend/airlock-adapter.js +230 -10
  19. package/dist/backend/airlock-adapter.js.map +1 -1
  20. package/dist/backend/factory.d.ts.map +1 -1
  21. package/dist/backend/factory.js +6 -0
  22. package/dist/backend/factory.js.map +1 -1
  23. package/dist/config/schema.d.ts +168 -0
  24. package/dist/config/schema.d.ts.map +1 -1
  25. package/dist/config/schema.js +44 -1
  26. package/dist/config/schema.js.map +1 -1
  27. package/dist/gateway.d.ts.map +1 -1
  28. package/dist/gateway.js +11 -9
  29. package/dist/gateway.js.map +1 -1
  30. package/dist/hitl/api.d.ts.map +1 -1
  31. package/dist/hitl/api.js +9 -2
  32. package/dist/hitl/api.js.map +1 -1
  33. package/dist/hitl/approval-dashboard.d.ts +1 -0
  34. package/dist/hitl/approval-dashboard.d.ts.map +1 -1
  35. package/dist/hitl/approval-dashboard.js +51 -5
  36. package/dist/hitl/approval-dashboard.js.map +1 -1
  37. package/dist/hitl/approval-stream.d.ts.map +1 -1
  38. package/dist/hitl/approval-stream.js +1 -0
  39. package/dist/hitl/approval-stream.js.map +1 -1
  40. package/dist/hitl/engine.d.ts +136 -4
  41. package/dist/hitl/engine.d.ts.map +1 -1
  42. package/dist/hitl/engine.js +556 -93
  43. package/dist/hitl/engine.js.map +1 -1
  44. package/dist/hitl/formatter.d.ts.map +1 -1
  45. package/dist/hitl/formatter.js +55 -9
  46. package/dist/hitl/formatter.js.map +1 -1
  47. package/dist/hitl/grant-api.d.ts +32 -0
  48. package/dist/hitl/grant-api.d.ts.map +1 -0
  49. package/dist/hitl/grant-api.js +249 -0
  50. package/dist/hitl/grant-api.js.map +1 -0
  51. package/dist/hitl/grants.d.ts +146 -0
  52. package/dist/hitl/grants.d.ts.map +1 -0
  53. package/dist/hitl/grants.js +252 -0
  54. package/dist/hitl/grants.js.map +1 -0
  55. package/dist/hitl/parser.d.ts +9 -0
  56. package/dist/hitl/parser.d.ts.map +1 -1
  57. package/dist/hitl/parser.js +56 -4
  58. package/dist/hitl/parser.js.map +1 -1
  59. package/dist/hitl/providers/ios.d.ts.map +1 -1
  60. package/dist/hitl/providers/ios.js +80 -12
  61. package/dist/hitl/providers/ios.js.map +1 -1
  62. package/dist/hitl/providers/macos.d.ts +2 -0
  63. package/dist/hitl/providers/macos.d.ts.map +1 -1
  64. package/dist/hitl/providers/macos.js +85 -3
  65. package/dist/hitl/providers/macos.js.map +1 -1
  66. package/dist/hitl/providers/openclaw.js +3 -9
  67. package/dist/hitl/providers/openclaw.js.map +1 -1
  68. package/dist/hitl/providers/stdio.js +3 -9
  69. package/dist/hitl/providers/stdio.js.map +1 -1
  70. package/dist/hitl/providers/telegram.js +3 -9
  71. package/dist/hitl/providers/telegram.js.map +1 -1
  72. package/dist/hitl/providers/tui.d.ts.map +1 -1
  73. package/dist/hitl/providers/tui.js +35 -2
  74. package/dist/hitl/providers/tui.js.map +1 -1
  75. package/dist/hitl/providers/types.d.ts +28 -2
  76. package/dist/hitl/providers/types.d.ts.map +1 -1
  77. package/dist/hitl/runtime.d.ts +18 -0
  78. package/dist/hitl/runtime.d.ts.map +1 -0
  79. package/dist/hitl/runtime.js +60 -0
  80. package/dist/hitl/runtime.js.map +1 -0
  81. package/dist/hook/api.d.ts +6 -1
  82. package/dist/hook/api.d.ts.map +1 -1
  83. package/dist/hook/api.js +50 -12
  84. package/dist/hook/api.js.map +1 -1
  85. package/dist/middleware/core/allowlist.d.ts.map +1 -1
  86. package/dist/middleware/core/allowlist.js +4 -1
  87. package/dist/middleware/core/allowlist.js.map +1 -1
  88. package/dist/middleware/core/hitl-gate.d.ts +4 -1
  89. package/dist/middleware/core/hitl-gate.d.ts.map +1 -1
  90. package/dist/middleware/core/hitl-gate.js +125 -35
  91. package/dist/middleware/core/hitl-gate.js.map +1 -1
  92. package/dist/middleware/types.d.ts +2 -0
  93. package/dist/middleware/types.d.ts.map +1 -1
  94. package/dist/mobile/api.d.ts.map +1 -1
  95. package/dist/mobile/api.js +32 -2
  96. package/dist/mobile/api.js.map +1 -1
  97. package/dist/mobile/apns.d.ts +37 -0
  98. package/dist/mobile/apns.d.ts.map +1 -1
  99. package/dist/mobile/apns.js +71 -23
  100. package/dist/mobile/apns.js.map +1 -1
  101. package/dist/registry/airlock-policy.js +1 -1
  102. package/dist/registry/airlock-policy.js.map +1 -1
  103. package/dist/registry/registry.d.ts +3 -0
  104. package/dist/registry/registry.d.ts.map +1 -1
  105. package/dist/registry/registry.js +15 -13
  106. package/dist/registry/registry.js.map +1 -1
  107. package/dist/stdio-mode.d.ts.map +1 -1
  108. package/dist/stdio-mode.js +10 -8
  109. package/dist/stdio-mode.js.map +1 -1
  110. package/dist/transport/agent-server.d.ts.map +1 -1
  111. package/dist/transport/agent-server.js +24 -10
  112. package/dist/transport/agent-server.js.map +1 -1
  113. package/dist/transport/http-server.d.ts +2 -0
  114. package/dist/transport/http-server.d.ts.map +1 -1
  115. package/dist/transport/http-server.js +67 -7
  116. package/dist/transport/http-server.js.map +1 -1
  117. package/dist/transport/session-limiter.d.ts +2 -0
  118. package/dist/transport/session-limiter.d.ts.map +1 -1
  119. package/dist/transport/session-limiter.js +5 -3
  120. package/dist/transport/session-limiter.js.map +1 -1
  121. package/dist/util/stable-json.d.ts +3 -0
  122. package/dist/util/stable-json.d.ts.map +1 -0
  123. package/dist/util/stable-json.js +10 -0
  124. package/dist/util/stable-json.js.map +1 -0
  125. package/dist/util/tool-name.d.ts +9 -0
  126. package/dist/util/tool-name.d.ts.map +1 -0
  127. package/dist/util/tool-name.js +14 -0
  128. package/dist/util/tool-name.js.map +1 -0
  129. package/package.json +1 -1
  130. package/schema.json +59 -1
@@ -1,6 +1,16 @@
1
1
  import { generateId, generateApprovalCode } from '../util/id.js';
2
+ import { GrantStore, describeScope, formatDuration, } from './grants.js';
2
3
  import { childLogger } from '../util/logger.js';
3
4
  const log = childLogger('hitl-engine');
5
+ export class GrantSpecError extends Error {
6
+ }
7
+ const DEFAULTS = {
8
+ asyncGrantTtlMs: 30 * 60_000,
9
+ planGrantTtlMs: 30 * 60_000,
10
+ defaultGrantDurationMs: 15 * 60_000,
11
+ maxGrantDurationMs: 24 * 60 * 60_000,
12
+ denialMemoryMs: 5 * 60_000,
13
+ };
4
14
  function redactApprovalArgs(auditLogger, args) {
5
15
  return (auditLogger.redactArgs?.(args) ?? args);
6
16
  }
@@ -10,10 +20,25 @@ export class HitlEngine {
10
20
  _timeoutMs;
11
21
  pending = new Map(); // id → request
12
22
  byCode = new Map(); // code → id
13
- constructor(auditLogger, provider, _timeoutMs) {
23
+ batches = new Map(); // batchId → batch
24
+ batchByCode = new Map(); // batch code → batchId
25
+ recentDenials = new Map(); // agentId\0fingerprint → expiry ms
26
+ grants;
27
+ opts;
28
+ constructor(auditLogger, provider, _timeoutMs, options = {}) {
14
29
  this.auditLogger = auditLogger;
15
30
  this.provider = provider;
16
31
  this._timeoutMs = _timeoutMs;
32
+ this.grants = options.grants ?? new GrantStore(undefined);
33
+ this.opts = {
34
+ defaultMode: options.defaultMode ?? 'sync',
35
+ asyncGrantTtlMs: options.asyncGrantTtlMs ?? DEFAULTS.asyncGrantTtlMs,
36
+ planGrantTtlMs: options.planGrantTtlMs ?? DEFAULTS.planGrantTtlMs,
37
+ defaultGrantDurationMs: options.defaultGrantDurationMs ?? DEFAULTS.defaultGrantDurationMs,
38
+ maxGrantDurationMs: options.maxGrantDurationMs ?? DEFAULTS.maxGrantDurationMs,
39
+ denialMemoryMs: options.denialMemoryMs ?? DEFAULTS.denialMemoryMs,
40
+ profilesForTool: options.profilesForTool,
41
+ };
17
42
  }
18
43
  get timeoutMs() {
19
44
  return this._timeoutMs;
@@ -21,10 +46,28 @@ export class HitlEngine {
21
46
  setTimeoutMs(timeoutMs) {
22
47
  this._timeoutMs = timeoutMs;
23
48
  }
49
+ get defaultMode() {
50
+ return this.opts.defaultMode;
51
+ }
52
+ configure(options) {
53
+ for (const [key, value] of Object.entries(options)) {
54
+ if (value !== undefined)
55
+ this.opts[key] = value;
56
+ }
57
+ }
24
58
  create(params) {
25
59
  const id = generateId();
26
60
  const code = generateApprovalCode();
27
61
  const approvalArgs = redactApprovalArgs(this.auditLogger, params.args);
62
+ const createdAt = new Date().toISOString();
63
+ const kind = params.kind ?? 'call';
64
+ const mode = params.mode ?? 'sync';
65
+ const meta = {
66
+ kind,
67
+ mode,
68
+ ...(params.subject ? { subject: params.subject } : {}),
69
+ ...(params.plan ? { plan: params.plan } : {}),
70
+ };
28
71
  // Persist to DB synchronously before returning
29
72
  this.auditLogger.insertHitl({
30
73
  id,
@@ -33,57 +76,72 @@ export class HitlEngine {
33
76
  tool: params.tool,
34
77
  args: JSON.stringify(withContext(approvalArgs, params.context)),
35
78
  status: 'pending',
36
- created_at: new Date().toISOString(),
37
- });
38
- const result = new Promise((resolve) => {
39
- const req = { id, code, ...params, args: approvalArgs, resolve };
40
- this.pending.set(id, req);
41
- this.byCode.set(code, id);
42
- if (this.timeoutMs > 0) {
43
- const timer = setTimeout(() => {
44
- this.pending.delete(id);
45
- this.byCode.delete(code);
46
- this.auditLogger.updateHitlStatus(id, 'timeout');
47
- log.warn({ id, code, tool: params.tool }, 'HITL request timed out');
48
- this.updateApprovalStatus(req, 'timeout');
49
- resolve('timeout');
50
- }, this.timeoutMs);
51
- timer.unref();
52
- req.timer = timer;
53
- }
79
+ created_at: createdAt,
80
+ meta: JSON.stringify(meta),
54
81
  });
55
- log.info({ id, code, agent: params.agentId, tool: params.tool }, 'HITL request created');
82
+ let resolve;
83
+ const result = new Promise((r) => (resolve = r));
84
+ const req = {
85
+ id,
86
+ code,
87
+ agentId: params.agentId,
88
+ tool: params.tool,
89
+ args: approvalArgs,
90
+ ...(params.context ? { context: params.context } : {}),
91
+ ...(params.sandbox ? { sandbox: params.sandbox } : {}),
92
+ kind,
93
+ mode,
94
+ ...(params.subject ? { subject: params.subject } : {}),
95
+ ...(params.plan ? { plan: params.plan } : {}),
96
+ createdAt,
97
+ result,
98
+ resolve,
99
+ };
100
+ this.track(req, this.timeoutMs);
101
+ log.info({ id, code, agent: params.agentId, tool: params.tool, kind, mode }, 'HITL request created');
56
102
  return { id, code, result };
57
103
  }
58
- approve(id) {
104
+ /** Redact args the same way approval requests are redacted before display. */
105
+ redact(args) {
106
+ return redactApprovalArgs(this.auditLogger, args);
107
+ }
108
+ /** The notification payload for a request just created, ready for the batcher. */
109
+ buildNotification(id) {
110
+ const req = this.pending.get(id);
111
+ if (!req)
112
+ return undefined;
113
+ return this.toNotification(req, this.timeoutMs);
114
+ }
115
+ approve(id, options) {
59
116
  const req = this.pending.get(id);
60
117
  if (!req) {
61
118
  log.warn({ id }, 'No pending HITL request found');
62
- return;
119
+ return undefined;
63
120
  }
64
- this.approveRequest(req);
121
+ return this.approveWithOptions(req, options);
65
122
  }
66
- approveByCode(code) {
123
+ approveByCode(code, options) {
124
+ const batchId = this.batchByCode.get(code);
125
+ if (batchId) {
126
+ if (options?.grant) {
127
+ throw new GrantSpecError('A grant needs a single request: approve one request with a duration, not the batch');
128
+ }
129
+ return this.approveBatch(batchId);
130
+ }
67
131
  const req = this.resolveRequestByCode(code);
68
132
  if (!req) {
69
133
  log.warn({ code }, 'No pending HITL request found for approval code');
70
- return;
134
+ return undefined;
71
135
  }
72
- this.approveRequest(req);
136
+ return this.approveWithOptions(req, options);
73
137
  }
74
138
  /** Cancel a pending request (e.g. transport disconnected). */
75
139
  cancel(id) {
76
140
  const req = this.pending.get(id);
77
141
  if (!req)
78
142
  return;
79
- if (req.timer)
80
- clearTimeout(req.timer);
81
- this.pending.delete(req.id);
82
- this.byCode.delete(req.code);
83
- this.auditLogger.updateHitlStatus(req.id, 'cancelled');
143
+ this.finish(req, 'cancelled');
84
144
  log.info({ id: req.id, code: req.code }, 'HITL cancelled (session disconnected)');
85
- this.updateApprovalStatus(req, 'cancelled');
86
- req.resolve('cancelled');
87
145
  }
88
146
  deny(id, reason) {
89
147
  const req = this.pending.get(id);
@@ -94,6 +152,11 @@ export class HitlEngine {
94
152
  this.denyRequest(req, reason);
95
153
  }
96
154
  denyByCode(code, reason) {
155
+ const batchId = this.batchByCode.get(code);
156
+ if (batchId) {
157
+ this.denyBatch(batchId, reason);
158
+ return;
159
+ }
97
160
  const req = this.resolveRequestByCode(code);
98
161
  if (!req) {
99
162
  log.warn({ code }, 'No pending HITL request found for approval code');
@@ -101,16 +164,97 @@ export class HitlEngine {
101
164
  }
102
165
  this.denyRequest(req, reason);
103
166
  }
167
+ /**
168
+ * Approve an explicit list of requests in one decision. Bulk approval is for routine tool calls:
169
+ * escalated calls (flagged by a detector or command policy) are skipped unless
170
+ * `includeEscalated` is set, and plans and ask_user questions are always skipped — a plan mints
171
+ * grants and a question needs reading, so each deserves its own look.
172
+ */
173
+ approveMany(ids, opts = {}) {
174
+ const approved = [];
175
+ const skipped = [];
176
+ for (const id of ids) {
177
+ const req = this.pending.get(id);
178
+ if (!req || req.kind !== 'call' || (req.subject?.escalated && !opts.includeEscalated)) {
179
+ skipped.push(id);
180
+ continue;
181
+ }
182
+ this.approveRequest(req);
183
+ approved.push(id);
184
+ }
185
+ log.info({ approved: approved.length, skipped: skipped.length }, 'HITL bulk approve');
186
+ return { approved, skipped };
187
+ }
188
+ denyMany(ids, reason) {
189
+ const denied = [];
190
+ for (const id of ids) {
191
+ const req = this.pending.get(id);
192
+ if (!req)
193
+ continue;
194
+ this.denyRequest(req, reason);
195
+ denied.push(id);
196
+ }
197
+ return denied;
198
+ }
199
+ /** Approve every still-pending, non-escalated member of a notification batch. */
200
+ approveBatch(batchIdOrCode) {
201
+ const batch = this.getBatch(batchIdOrCode);
202
+ if (!batch)
203
+ return undefined;
204
+ return this.approveMany(batch.ids);
205
+ }
206
+ denyBatch(batchIdOrCode, reason) {
207
+ const batch = this.getBatch(batchIdOrCode);
208
+ if (!batch)
209
+ return undefined;
210
+ return this.denyMany(batch.ids, reason);
211
+ }
212
+ /**
213
+ * Snapshot a set of requests notified together. Returns undefined for a single request — a
214
+ * batch of one is just a request. "Approve all" only ever covers this snapshot, never requests
215
+ * that arrived after the operator was shown the batch.
216
+ */
217
+ registerBatch(ids) {
218
+ const members = ids.filter((id) => this.pending.has(id));
219
+ if (members.length < 2)
220
+ return undefined;
221
+ const batch = {
222
+ id: generateId(),
223
+ code: generateApprovalCode(),
224
+ agentId: this.pending.get(members[0]).agentId,
225
+ ids: members,
226
+ };
227
+ this.batches.set(batch.id, batch);
228
+ this.batchByCode.set(batch.code, batch.id);
229
+ for (const id of members)
230
+ this.pending.get(id).batchId = batch.id;
231
+ return { batchId: batch.id, batchCode: batch.code };
232
+ }
233
+ hasBatch(batchIdOrCode) {
234
+ return this.getBatch(batchIdOrCode) !== undefined;
235
+ }
104
236
  getPending() {
105
- return Array.from(this.pending.values()).map((r) => ({
106
- id: r.id,
107
- code: r.code,
108
- agentId: r.agentId,
109
- tool: r.tool,
110
- args: r.args,
111
- ...(r.context ? { context: r.context } : {}),
112
- ...(r.sandbox ? { sandbox: r.sandbox } : {}),
113
- }));
237
+ return Array.from(this.pending.values()).map((r) => {
238
+ const batch = r.batchId ? this.batches.get(r.batchId) : undefined;
239
+ const grantOptions = this.grantOptionsFor(r);
240
+ return {
241
+ id: r.id,
242
+ code: r.code,
243
+ agentId: r.agentId,
244
+ tool: r.tool,
245
+ args: r.args,
246
+ ...(r.context ? { context: r.context } : {}),
247
+ ...(r.sandbox ? { sandbox: r.sandbox } : {}),
248
+ kind: r.kind,
249
+ mode: r.mode,
250
+ ...(r.subject
251
+ ? { tier: r.subject.tier, provider: r.subject.provider, escalated: r.subject.escalated }
252
+ : {}),
253
+ ...(r.plan ? { plan: r.plan } : {}),
254
+ ...(batch ? { batchId: batch.id, batchCode: batch.code } : {}),
255
+ ...(grantOptions.length > 0 ? { grantOptions } : {}),
256
+ };
257
+ });
114
258
  }
115
259
  hasPending(id) {
116
260
  return this.pending.has(id);
@@ -118,35 +262,343 @@ export class HitlEngine {
118
262
  getPreviewRequest(id) {
119
263
  return this.pending.get(id);
120
264
  }
265
+ // ── Grants ────────────────────────────────────────────────────────────────
266
+ /** Consume a grant covering this call, if one exists. */
267
+ consumeGrant(subject) {
268
+ return this.grants.consume(subject);
269
+ }
270
+ /** Create a grant directly (operator pre-approval, not tied to a request). */
271
+ createOperatorGrant(params) {
272
+ if (params.scope.kind === 'call') {
273
+ throw new GrantSpecError('call grants are created by plans and async approvals only');
274
+ }
275
+ if (params.maxUses !== undefined && (!Number.isInteger(params.maxUses) || params.maxUses < 1)) {
276
+ throw new GrantSpecError('maxUses must be a whole number of at least 1');
277
+ }
278
+ const durationMs = this.clampDuration(params.durationMs);
279
+ const grant = this.grants.create({
280
+ agentId: params.agentId,
281
+ scope: params.scope,
282
+ source: 'operator',
283
+ label: `${describeScope(params.scope)} for ${formatDuration(durationMs)}`,
284
+ expiresAt: new Date(Date.now() + durationMs).toISOString(),
285
+ ...(params.maxUses !== undefined ? { usesRemaining: params.maxUses } : {}),
286
+ });
287
+ this.sweepPending(grant);
288
+ return grant;
289
+ }
290
+ listGrants(agentId) {
291
+ return this.grants.list(agentId);
292
+ }
293
+ revokeGrant(id) {
294
+ return this.grants.revoke(id);
295
+ }
296
+ // ── Async support ─────────────────────────────────────────────────────────
297
+ /** A pending async request for the same exact call, so retries don't create duplicates. */
298
+ findPendingCall(agentId, fingerprint) {
299
+ for (const req of this.pending.values()) {
300
+ if (req.agentId === agentId &&
301
+ req.subject?.fingerprint === fingerprint &&
302
+ req.kind === 'call') {
303
+ return { id: req.id, code: req.code };
304
+ }
305
+ }
306
+ return undefined;
307
+ }
308
+ wasRecentlyDenied(agentId, fingerprint) {
309
+ const key = `${agentId}\0${fingerprint}`;
310
+ const expiry = this.recentDenials.get(key);
311
+ if (expiry === undefined)
312
+ return false;
313
+ if (expiry <= Date.now()) {
314
+ this.recentDenials.delete(key);
315
+ return false;
316
+ }
317
+ return true;
318
+ }
319
+ /** Status of an approval the given agent owns, or undefined if it isn't theirs / doesn't exist. */
320
+ getStatus(id, agentId) {
321
+ const req = this.pending.get(id);
322
+ if (req) {
323
+ if (req.agentId !== agentId)
324
+ return undefined;
325
+ return { id, code: req.code, agentId, tool: req.tool, kind: req.kind, status: 'pending' };
326
+ }
327
+ const row = this.auditLogger.getHitlById?.(id);
328
+ if (!row || row.agent_id !== agentId)
329
+ return undefined;
330
+ const meta = parseMeta(row.meta);
331
+ return {
332
+ id,
333
+ code: row.code,
334
+ agentId,
335
+ tool: row.tool,
336
+ kind: meta.kind ?? 'call',
337
+ status: row.status,
338
+ };
339
+ }
340
+ /** Wait up to `waitMs` for an approval to resolve. */
341
+ async waitFor(id, agentId, waitMs) {
342
+ const req = this.pending.get(id);
343
+ if (req && req.agentId === agentId && waitMs > 0) {
344
+ let timer;
345
+ await Promise.race([
346
+ req.result,
347
+ new Promise((resolve) => {
348
+ timer = setTimeout(resolve, waitMs);
349
+ timer.unref();
350
+ }),
351
+ ]);
352
+ clearTimeout(timer);
353
+ }
354
+ return this.getStatus(id, agentId);
355
+ }
356
+ // ── Internals ─────────────────────────────────────────────────────────────
357
+ getBatch(batchIdOrCode) {
358
+ const batchId = this.batchByCode.get(batchIdOrCode) ?? batchIdOrCode;
359
+ return this.batches.get(batchId);
360
+ }
121
361
  resolveRequestByCode(code) {
122
362
  const id = this.byCode.get(code);
123
363
  if (id)
124
364
  return this.pending.get(id);
125
365
  return undefined;
126
366
  }
367
+ track(req, timeoutMs) {
368
+ this.pending.set(req.id, req);
369
+ this.byCode.set(req.code, req.id);
370
+ if (timeoutMs > 0) {
371
+ const timer = setTimeout(() => {
372
+ log.warn({ id: req.id, code: req.code, tool: req.tool }, 'HITL request timed out');
373
+ this.finish(req, 'timeout');
374
+ }, timeoutMs);
375
+ timer.unref();
376
+ req.timer = timer;
377
+ }
378
+ }
379
+ approveWithOptions(req, options) {
380
+ // Validate the grant before approving so a bad spec rejects the whole decision.
381
+ const spec = options?.grant;
382
+ const scope = spec ? this.scopeFromSpec(req, spec) : undefined;
383
+ if (spec?.maxUses !== undefined && (!Number.isInteger(spec.maxUses) || spec.maxUses < 1)) {
384
+ throw new GrantSpecError('maxUses must be a whole number of at least 1');
385
+ }
386
+ if (spec?.sessionOnly && !req.subject?.sessionId) {
387
+ // Never silently widen a session-only grant to every session of the agent.
388
+ throw new GrantSpecError('This request has no session to bind a session-only grant to');
389
+ }
390
+ this.approveRequest(req);
391
+ if (!scope || !spec)
392
+ return { approved: [req.id], skipped: [] };
393
+ // The approval that creates the grant counts as its first use.
394
+ const usesRemaining = spec.maxUses !== undefined ? spec.maxUses - 1 : undefined;
395
+ if (usesRemaining === 0)
396
+ return { approved: [req.id], skipped: [] };
397
+ const durationMs = this.clampDuration(spec.durationMs);
398
+ const grant = this.grants.create({
399
+ agentId: req.agentId,
400
+ ...(spec.sessionOnly ? { sessionId: req.subject.sessionId } : {}),
401
+ scope,
402
+ source: 'approval',
403
+ approvalId: req.id,
404
+ label: `${describeScope(scope)} for ${formatDuration(durationMs)}`,
405
+ expiresAt: new Date(Date.now() + durationMs).toISOString(),
406
+ ...(usesRemaining !== undefined ? { usesRemaining } : {}),
407
+ });
408
+ const alsoApproved = this.sweepPending(grant);
409
+ return { approved: [req.id, ...alsoApproved], skipped: [], grant };
410
+ }
411
+ /** Resolve every other pending call the new grant covers — e.g. the 9 queued email reads. */
412
+ sweepPending(grant) {
413
+ const approved = [];
414
+ const only = new Set([grant.id]);
415
+ for (const other of [...this.pending.values()]) {
416
+ if (other.kind !== 'call' || !other.subject)
417
+ continue;
418
+ if (!this.grants.covers(grant, other.subject))
419
+ continue;
420
+ // Every auto-approval spends a use, so maxUses holds. (An async request then also gets its
421
+ // own single-use call grant, which its retry consumes first.)
422
+ if (!this.grants.consume(other.subject, only))
423
+ break;
424
+ this.approveRequest(other);
425
+ approved.push(other.id);
426
+ }
427
+ if (approved.length > 0) {
428
+ log.info({ grantId: grant.id, count: approved.length }, 'Grant auto-approved pending calls');
429
+ }
430
+ return approved;
431
+ }
432
+ scopeFromSpec(req, spec) {
433
+ const subject = req.subject;
434
+ if (!subject || req.kind !== 'call') {
435
+ throw new GrantSpecError('Only tool-call approvals can be turned into a grant');
436
+ }
437
+ if (subject.escalated) {
438
+ throw new GrantSpecError('This call was flagged for review by a security check; it cannot be widened into a grant');
439
+ }
440
+ switch (spec.scope) {
441
+ case 'tool':
442
+ return { kind: 'tool', tool: subject.tool };
443
+ case 'tier': {
444
+ const tier = spec.tier ?? (subject.tier === 'read' ? 'read' : 'write');
445
+ return {
446
+ kind: 'tier',
447
+ tier,
448
+ ...(spec.sameProvider === false ? {} : { provider: subject.provider }),
449
+ };
450
+ }
451
+ case 'provider':
452
+ return { kind: 'provider', provider: subject.provider };
453
+ case 'profile': {
454
+ if (!spec.profile)
455
+ throw new GrantSpecError('profile is required for a profile grant');
456
+ const known = this.opts.profilesForTool?.(subject.tool) ?? [];
457
+ if (!known.includes(spec.profile)) {
458
+ throw new GrantSpecError(`Profile ${spec.profile} does not cover ${subject.tool}`);
459
+ }
460
+ return { kind: 'profile', profile: spec.profile };
461
+ }
462
+ default:
463
+ throw new GrantSpecError(`Unknown grant scope: ${String(spec.scope)}`);
464
+ }
465
+ }
466
+ grantOptionsFor(req) {
467
+ const subject = req.subject;
468
+ if (req.kind !== 'call' || !subject || subject.escalated)
469
+ return [];
470
+ const options = [{ scope: 'tool', label: `Allow ${subject.tool}` }];
471
+ if (subject.tier === 'read') {
472
+ options.push({
473
+ scope: 'tier',
474
+ tier: 'read',
475
+ label: `Allow read-only ${subject.provider} tools`,
476
+ });
477
+ }
478
+ else if (subject.tier === 'write') {
479
+ options.push({
480
+ scope: 'tier',
481
+ tier: 'write',
482
+ label: `Allow non-destructive ${subject.provider} tools`,
483
+ });
484
+ }
485
+ options.push({ scope: 'provider', label: `Allow all ${subject.provider} tools` });
486
+ for (const profile of this.opts.profilesForTool?.(subject.tool) ?? []) {
487
+ options.push({ scope: 'profile', profile, label: `Allow profile ${profile}` });
488
+ }
489
+ return options;
490
+ }
491
+ clampDuration(durationMs) {
492
+ const requested = durationMs && durationMs > 0 ? durationMs : this.opts.defaultGrantDurationMs;
493
+ return Math.min(requested, this.opts.maxGrantDurationMs);
494
+ }
127
495
  approveRequest(req) {
128
- if (req.timer)
129
- clearTimeout(req.timer);
130
- this.pending.delete(req.id);
131
- this.byCode.delete(req.code);
132
- this.auditLogger.updateHitlStatus(req.id, 'approved');
496
+ this.finish(req, 'approved');
133
497
  log.info({ id: req.id, code: req.code }, 'HITL approved');
134
- this.updateApprovalStatus(req, 'approved');
135
- req.resolve('approved');
498
+ if (req.kind === 'call' && req.mode === 'async' && req.subject) {
499
+ // The agent got an immediate "pending" answer; leave a single-use grant so its retry of the
500
+ // exact same call goes through.
501
+ this.grants.create({
502
+ agentId: req.agentId,
503
+ scope: { kind: 'call', tool: req.subject.tool, fingerprint: req.subject.fingerprint },
504
+ source: 'async',
505
+ approvalId: req.id,
506
+ label: `retry of ${req.subject.tool}`,
507
+ expiresAt: new Date(Date.now() + this.opts.asyncGrantTtlMs).toISOString(),
508
+ usesRemaining: 1,
509
+ });
510
+ }
511
+ if (req.kind === 'plan' && req.plan) {
512
+ const counts = new Map();
513
+ for (const entry of req.plan) {
514
+ const existing = counts.get(entry.fingerprint);
515
+ if (existing)
516
+ existing.count += 1;
517
+ else
518
+ counts.set(entry.fingerprint, { entry, count: 1 });
519
+ }
520
+ const expiresAt = new Date(Date.now() + this.opts.planGrantTtlMs).toISOString();
521
+ for (const [fingerprint, { entry, count }] of counts) {
522
+ const tool = entry.tool;
523
+ const summary = argsSummary(entry.args);
524
+ this.grants.create({
525
+ agentId: req.agentId,
526
+ scope: { kind: 'call', tool, fingerprint },
527
+ source: 'plan',
528
+ approvalId: req.id,
529
+ label: summary ? `planned ${tool} (${summary})` : `planned ${tool}`,
530
+ expiresAt,
531
+ usesRemaining: count,
532
+ });
533
+ }
534
+ }
136
535
  }
137
536
  denyRequest(req, reason) {
537
+ this.finish(req, 'denied', reason);
538
+ log.info({ id: req.id, code: req.code, reason }, 'HITL denied');
539
+ if (req.mode === 'async' && req.subject) {
540
+ const now = Date.now();
541
+ for (const [key, expiry] of this.recentDenials) {
542
+ if (expiry <= now)
543
+ this.recentDenials.delete(key);
544
+ }
545
+ this.recentDenials.set(`${req.agentId}\0${req.subject.fingerprint}`, Date.now() + this.opts.denialMemoryMs);
546
+ }
547
+ }
548
+ finish(req, result, reason) {
138
549
  if (req.timer)
139
550
  clearTimeout(req.timer);
140
551
  this.pending.delete(req.id);
141
552
  this.byCode.delete(req.code);
142
- this.auditLogger.updateHitlStatus(req.id, 'denied', reason);
143
- log.info({ id: req.id, code: req.code, reason }, 'HITL denied');
144
- this.updateApprovalStatus(req, 'denied');
145
- req.resolve('denied');
553
+ if (reason === undefined)
554
+ this.auditLogger.updateHitlStatus(req.id, result);
555
+ else
556
+ this.auditLogger.updateHitlStatus(req.id, result, reason);
557
+ this.updateApprovalStatus(req, result);
558
+ this.releaseBatch(req.batchId);
559
+ req.resolve(result);
560
+ }
561
+ /** Pending members left in a batch; forgets the batch once none are. */
562
+ releaseBatch(batchId) {
563
+ if (!batchId)
564
+ return undefined;
565
+ const batch = this.batches.get(batchId);
566
+ if (!batch)
567
+ return undefined;
568
+ const remaining = batch.ids.filter((id) => this.pending.has(id)).length;
569
+ if (remaining === 0) {
570
+ this.batches.delete(batch.id);
571
+ this.batchByCode.delete(batch.code);
572
+ }
573
+ return remaining;
574
+ }
575
+ toNotification(req, timeoutMs) {
576
+ const grantOptions = this.grantOptionsFor(req);
577
+ return {
578
+ id: req.id,
579
+ code: req.code,
580
+ agentId: req.agentId,
581
+ tool: req.tool,
582
+ args: req.args,
583
+ ...(req.context ? { context: req.context } : {}),
584
+ ...(req.sandbox ? { sandbox: req.sandbox } : {}),
585
+ timeoutMs,
586
+ kind: req.kind,
587
+ ...(req.subject
588
+ ? {
589
+ tier: req.subject.tier,
590
+ provider: req.subject.provider,
591
+ escalated: req.subject.escalated,
592
+ }
593
+ : {}),
594
+ ...(req.plan ? { plan: req.plan } : {}),
595
+ ...(grantOptions.length > 0 ? { grantOptions } : {}),
596
+ };
146
597
  }
147
598
  /** Recover pending requests from DB on startup */
148
599
  // eslint-disable-next-line @typescript-eslint/require-await
149
600
  async recoverPending() {
601
+ this.grants.load();
150
602
  const rows = this.auditLogger.getPendingHitl();
151
603
  if (rows.length === 0)
152
604
  return;
@@ -174,55 +626,48 @@ export class HitlEngine {
174
626
  }
175
627
  const context = readContext(args);
176
628
  const cleanArgs = stripStoredContext(args);
629
+ const meta = parseMeta(row.meta);
177
630
  // Re-arm without re-notifying (provider may not be ready yet)
178
- const promise = new Promise((resolve) => {
179
- const req = {
180
- id: row.id,
181
- code: row.code,
182
- agentId: row.agent_id,
183
- tool: row.tool,
184
- args: cleanArgs,
185
- ...(context ? { context } : {}),
186
- resolve,
187
- };
188
- this.pending.set(row.id, req);
189
- this.byCode.set(row.code, row.id);
190
- if (remaining > 0) {
191
- const timer = setTimeout(() => {
192
- this.pending.delete(row.id);
193
- this.byCode.delete(row.code);
194
- this.auditLogger.updateHitlStatus(row.id, 'timeout');
195
- this.updateApprovalStatus(req, 'timeout');
196
- resolve('timeout');
197
- }, remaining);
198
- timer.unref();
199
- req.timer = timer;
200
- }
201
- });
631
+ let resolve;
632
+ const result = new Promise((r) => (resolve = r));
633
+ const req = {
634
+ id: row.id,
635
+ code: row.code,
636
+ agentId: row.agent_id,
637
+ tool: row.tool,
638
+ args: cleanArgs,
639
+ ...(context ? { context } : {}),
640
+ kind: meta.kind ?? 'call',
641
+ // A sync caller's held-open call died with the old process; only async requests (whose
642
+ // agent will retry) and plans are still worth resolving.
643
+ mode: meta.mode ?? 'sync',
644
+ ...(meta.subject ? { subject: meta.subject } : {}),
645
+ ...(meta.plan ? { plan: meta.plan } : {}),
646
+ createdAt: row.created_at,
647
+ result,
648
+ resolve,
649
+ };
650
+ this.track(req, remaining);
202
651
  // Notify again so operator sees recovered requests
203
652
  void this.provider
204
- .notify([
205
- {
206
- id: row.id,
207
- code: row.code,
208
- agentId: row.agent_id,
209
- tool: row.tool,
210
- args: cleanArgs,
211
- ...(context ? { context } : {}),
212
- sandbox: undefined,
213
- timeoutMs: remaining,
214
- badgeCount: this.getPending().length,
215
- },
216
- ])
653
+ .notify([{ ...this.toNotification(req, remaining), badgeCount: this.pending.size }])
217
654
  .catch((err) => log.warn({ err }, 'Failed to re-notify recovered HITL request'));
218
- void promise; // tracked in pending map
219
655
  }
220
656
  }
221
657
  updateApprovalStatus(req, result) {
222
- const badgeCount = this.getPending().length;
658
+ const badgeCount = this.pending.size;
659
+ const batchPending = this.releaseBatch(req.batchId);
223
660
  if (this.provider.updateApprovalStatus) {
224
661
  void this.provider
225
- .updateApprovalStatus({ id: req.id, code: req.code, result, badgeCount })
662
+ .updateApprovalStatus({
663
+ id: req.id,
664
+ code: req.code,
665
+ result,
666
+ badgeCount,
667
+ ...(req.batchId && batchPending !== undefined
668
+ ? { batchId: req.batchId, batchPending }
669
+ : {}),
670
+ })
226
671
  .catch((err) => log.warn({ err }, 'Failed to update approval status'));
227
672
  return;
228
673
  }
@@ -231,6 +676,24 @@ export class HitlEngine {
231
676
  .catch((err) => log.warn({ err }, 'Failed to update approval badge count'));
232
677
  }
233
678
  }
679
+ /** Short "key: value" summary so several planned calls to one tool are distinguishable. */
680
+ function argsSummary(args) {
681
+ const text = Object.entries(args)
682
+ .slice(0, 2)
683
+ .map(([key, value]) => `${key}: ${typeof value === 'string' ? value : JSON.stringify(value)}`)
684
+ .join(', ');
685
+ return text.length > 60 ? `${text.slice(0, 57)}...` : text;
686
+ }
687
+ function parseMeta(raw) {
688
+ if (!raw)
689
+ return {};
690
+ try {
691
+ return JSON.parse(raw);
692
+ }
693
+ catch {
694
+ return {};
695
+ }
696
+ }
234
697
  function withContext(args, context) {
235
698
  if (!context)
236
699
  return args;