@agimon-ai/po-approval 0.0.0-alpha.100

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,909 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region \0rolldown/runtime.js
6
+ var __create = Object.create;
7
+ var __defProp = Object.defineProperty;
8
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
9
+ var __getOwnPropNames = Object.getOwnPropertyNames;
10
+ var __getProtoOf = Object.getPrototypeOf;
11
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
14
+ key = keys[i];
15
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
16
+ get: ((k) => from[k]).bind(null, key),
17
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
18
+ });
19
+ }
20
+ return to;
21
+ };
22
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule || !__hasOwnProp.call(mod, "default") ? __defProp(target, "default", {
23
+ value: mod,
24
+ enumerable: true
25
+ }) : target, mod));
26
+ //#endregion
27
+ const require_approvalSession = require("../approvalSession-BAbRvyI-.cjs");
28
+ let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
29
+ let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
30
+ let node_path = require("node:path");
31
+ node_path = __toESM(node_path, 1);
32
+ let _agimon_ai_po_core_piSettings = require("@agimon-ai/po-core/piSettings");
33
+ let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
34
+ let _agimon_ai_po_core_approval = require("@agimon-ai/po-core/approval");
35
+ let _agimon_ai_po_core_pluginProtocol = require("@agimon-ai/po-core/pluginProtocol");
36
+ let typebox = require("typebox");
37
+ let typebox_value = require("typebox/value");
38
+ let _agimon_ai_po_core_apiContracts = require("@agimon-ai/po-core/apiContracts");
39
+ //#region src/services/approvalRoot/index.ts
40
+ /** Outcomes the agent hears about once; withdrawn requests are its own doing and stay quiet. */
41
+ const REPORTED = [
42
+ "succeeded",
43
+ "failed",
44
+ "denied",
45
+ "cancelled",
46
+ "interrupted"
47
+ ];
48
+ const OPEN = [
49
+ "pending",
50
+ "approved",
51
+ "running",
52
+ "interrupted"
53
+ ];
54
+ /** A result is reported to the agent as text; anything longer is cut. */
55
+ const RESULT_TEXT_LIMIT = 8e3;
56
+ function message(error) {
57
+ return error instanceof Error ? error.message : String(error);
58
+ }
59
+ /** The last segment of a POSIX or Windows path; services take no `node:path`. */
60
+ function folderName(root) {
61
+ return root?.split(/[\\/]/).filter(Boolean).pop();
62
+ }
63
+ /** Text content of a tool result, else its JSON. */
64
+ function resultText(result) {
65
+ const content = result?.content;
66
+ let text;
67
+ if (Array.isArray(content) && content.every((part) => typeof part?.text === "string")) text = content.map((part) => part.text).join("\n");
68
+ else try {
69
+ text = JSON.stringify(result ?? null) ?? "null";
70
+ } catch {
71
+ text = String(result);
72
+ }
73
+ return text.length > RESULT_TEXT_LIMIT ? `${text.slice(0, RESULT_TEXT_LIMIT)}…` : text;
74
+ }
75
+ function outcomeText(record) {
76
+ const call = `${record.operation.name} (approval ${record.id})`;
77
+ switch (record.state) {
78
+ case "succeeded": return `The person approved ${call} and it ran. Result:\n${typeof record.result === "string" ? record.result : ""}`;
79
+ case "failed": return `The person approved ${call}, but it did not complete: ${record.reason ?? "it failed."}`;
80
+ case "denied": return `The person denied ${call}. Nothing ran.`;
81
+ case "cancelled": return `The person dismissed ${call}. Nothing ran.`;
82
+ case "interrupted": return `${call}: Outcome uncertain. ${record.reason ?? "It may have partly run."} Check before retrying.`;
83
+ default: return `${call}: ${record.reason ?? record.state}`;
84
+ }
85
+ }
86
+ /**
87
+ * The machine-wide approval queue. Requests survive restarts; an approved call runs in its session once that
88
+ * session is mounted (Approve revives a dormant one), and its outcome is admitted with a stable delivery key.
89
+ */
90
+ function createApprovalRoot(options) {
91
+ const { store } = options;
92
+ const bindings = /* @__PURE__ */ new Map();
93
+ const draining = /* @__PURE__ */ new Map();
94
+ const listeners = /* @__PURE__ */ new Set();
95
+ let disposed = false;
96
+ const sessionGone = (sessionId) => options.sessions?.dormant !== void 0 && !bindings.has(sessionId) && !options.sessions.isLive(sessionId) && !options.sessions.dormant().some((entry) => entry.sessionId === sessionId);
97
+ const changed = async (sessionId) => {
98
+ if (disposed) return;
99
+ for (const listener of listeners) listener(sessionId);
100
+ if (options.setPendingCount === void 0) return;
101
+ const pending = await store.list({
102
+ sessionId,
103
+ states: ["pending"]
104
+ });
105
+ if (!disposed) options.setPendingCount(sessionId, pending.length);
106
+ };
107
+ const note = (promise) => {
108
+ promise.catch(options.onError);
109
+ };
110
+ const drainOnce = async (sessionId) => {
111
+ const binding = bindings.get(sessionId);
112
+ if (binding === void 0 || disposed) return;
113
+ for (const approved of await store.list({
114
+ sessionId,
115
+ states: ["approved"]
116
+ })) {
117
+ if (binding.signal.aborted || disposed) return;
118
+ if (!binding.ready(approved.operation.kind)) continue;
119
+ const running = await store.update(approved.id, ["approved"], {
120
+ state: "running",
121
+ reason: void 0
122
+ });
123
+ if (running === void 0) continue;
124
+ await changed(sessionId);
125
+ try {
126
+ const result = await binding.run(running, binding.signal);
127
+ await store.update(running.id, ["running"], {
128
+ state: "succeeded",
129
+ result: resultText(result),
130
+ finishedAt: Date.now()
131
+ });
132
+ } catch (error) {
133
+ await store.update(running.id, ["running"], {
134
+ state: "failed",
135
+ reason: message(error),
136
+ finishedAt: Date.now()
137
+ });
138
+ }
139
+ await changed(sessionId);
140
+ }
141
+ for (const record of await store.list({
142
+ sessionId,
143
+ states: REPORTED
144
+ })) {
145
+ if (record.deliveredAt !== void 0 || binding.signal.aborted || disposed) continue;
146
+ await binding.deliver(record, outcomeText(record));
147
+ await store.update(record.id, [record.state], { deliveredAt: Date.now() });
148
+ await changed(sessionId);
149
+ }
150
+ };
151
+ const drain = (sessionId) => {
152
+ const next = (draining.get(sessionId) ?? Promise.resolve()).then(() => drainOnce(sessionId)).catch(options.onError);
153
+ draining.set(sessionId, next);
154
+ next.then(() => {
155
+ if (draining.get(sessionId) === next) draining.delete(sessionId);
156
+ });
157
+ return next;
158
+ };
159
+ /** Brings an approved call's session up so it can run; records why when it cannot. */
160
+ const wake = async (record) => {
161
+ const sessions = options.sessions;
162
+ const waiting = async (reason) => {
163
+ if (await store.update(record.id, ["approved"], { reason })) await changed(record.sessionId);
164
+ };
165
+ if (sessions?.isLive(record.sessionId)) return waiting("Waiting for the session to finish opening.");
166
+ if (!sessions?.dormant?.().some((entry) => entry.sessionId === record.sessionId) || !sessions.revive) return waiting("The session is gone, so this cannot run. Dismiss it to clear it.");
167
+ const outcome = await sessions.revive(record.sessionId, { automatic: true });
168
+ if (outcome === "paused") return waiting("The session is paused. It runs once the session opens again.");
169
+ if (outcome === "not_found") return waiting("The session is gone, so this cannot run. Dismiss it to clear it.");
170
+ };
171
+ store.list({ states: ["pending"] }).then((pending) => {
172
+ for (const sessionId of new Set(pending.map((record) => record.sessionId))) note(changed(sessionId));
173
+ }, options.onError);
174
+ return {
175
+ async submit(request) {
176
+ if (disposed) throw new Error("Approvals are closed.");
177
+ const record = await store.insert(request);
178
+ await changed(record.sessionId);
179
+ return { id: record.id };
180
+ },
181
+ attach(sessionId, binding) {
182
+ bindings.set(sessionId, binding);
183
+ note(changed(sessionId));
184
+ drain(sessionId);
185
+ return () => {
186
+ if (bindings.get(sessionId) === binding) bindings.delete(sessionId);
187
+ };
188
+ },
189
+ drain,
190
+ async decide(id, revision, decision) {
191
+ if (await store.get(id) === void 0) throw new require_approvalSession.ApprovalRequestError("This approval is no longer here.", 404);
192
+ const now = Date.now();
193
+ const next = await store.update(id, ["pending"], decision === "approve" ? {
194
+ state: "approved",
195
+ decidedAt: now
196
+ } : {
197
+ state: "denied",
198
+ decidedAt: now,
199
+ finishedAt: now
200
+ }, revision);
201
+ if (next === void 0) throw new require_approvalSession.ApprovalRequestError("This approval already changed. Its card shows where it is now.");
202
+ await changed(next.sessionId);
203
+ if (bindings.has(next.sessionId)) drain(next.sessionId);
204
+ else if (decision === "approve") note(wake(next));
205
+ return next;
206
+ },
207
+ async withdraw(sessionId, id) {
208
+ if ((await store.get(id))?.sessionId !== sessionId) return void 0;
209
+ const now = Date.now();
210
+ const next = await store.update(id, ["pending"], {
211
+ state: "withdrawn",
212
+ finishedAt: now,
213
+ deliveredAt: now
214
+ });
215
+ if (next !== void 0) await changed(sessionId);
216
+ return next;
217
+ },
218
+ async dismiss(id, revision) {
219
+ const record = await store.get(id);
220
+ if (record === void 0) throw new require_approvalSession.ApprovalRequestError("This approval is no longer here.", 404);
221
+ if (!sessionGone(record.sessionId)) throw new require_approvalSession.ApprovalRequestError("Only a call whose session is gone can be dismissed.");
222
+ const next = await store.update(id, ["pending", "approved"], {
223
+ state: "cancelled",
224
+ finishedAt: Date.now()
225
+ }, revision ?? record.revision);
226
+ if (next === void 0) throw new require_approvalSession.ApprovalRequestError("This approval already changed. Its card shows where it is now.");
227
+ await changed(next.sessionId);
228
+ return next;
229
+ },
230
+ open: async (sessionId) => {
231
+ const records = (await store.list({
232
+ ...sessionId === void 0 ? {} : { sessionId },
233
+ states: OPEN
234
+ })).filter((record) => record.state !== "interrupted" || record.deliveredAt === void 0);
235
+ const live = new Map((options.sessions?.scopes?.() ?? []).map((scope) => [scope.sessionId, scope]));
236
+ const dormant = new Map((options.sessions?.dormant?.() ?? []).map((entry) => [entry.sessionId, entry]));
237
+ return records.map((record) => {
238
+ const scope = live.get(record.sessionId);
239
+ const sessionName = scope?.name ?? dormant.get(record.sessionId)?.name;
240
+ const workspaceName = folderName(scope?.sessionContext?.workspaceRoot ?? scope?.cwd);
241
+ return {
242
+ ...record,
243
+ ...(record.state === "pending" || record.state === "approved") && sessionGone(record.sessionId) ? { sessionGone: true } : {},
244
+ ...sessionName ? { sessionName } : {},
245
+ ...workspaceName ? { workspaceName } : {}
246
+ };
247
+ });
248
+ },
249
+ onChanged(listener) {
250
+ listeners.add(listener);
251
+ return () => listeners.delete(listener);
252
+ },
253
+ dispose() {
254
+ disposed = true;
255
+ bindings.clear();
256
+ listeners.clear();
257
+ }
258
+ };
259
+ }
260
+ //#endregion
261
+ //#region src/services/approvalStore/index.ts
262
+ const INTERRUPTED_REASON = "Po stopped while this was running. It may have partly run, and it was not retried.";
263
+ const GET_BY_ID = "SELECT * FROM approvals WHERE id = ?";
264
+ const SCHEMA = `CREATE TABLE IF NOT EXISTS approvals (
265
+ id TEXT PRIMARY KEY NOT NULL,
266
+ session_id TEXT NOT NULL,
267
+ tool_call_id TEXT NOT NULL,
268
+ kind TEXT NOT NULL CHECK (kind IN ('tool', 'member')),
269
+ name TEXT NOT NULL,
270
+ requirement TEXT NOT NULL CHECK (requirement IN ('ask', 'human')),
271
+ description_json TEXT NOT NULL,
272
+ input_json TEXT,
273
+ argument_format TEXT CHECK (argument_format = 'positional'),
274
+ state TEXT NOT NULL CHECK (state IN ('pending', 'approved', 'running', 'succeeded', 'failed', 'denied', 'withdrawn', 'cancelled', 'interrupted')),
275
+ reason TEXT,
276
+ result_json TEXT,
277
+ revision INTEGER NOT NULL,
278
+ created_at INTEGER NOT NULL,
279
+ decided_at INTEGER,
280
+ finished_at INTEGER,
281
+ delivered_at INTEGER
282
+ )`;
283
+ function read(row) {
284
+ if (row === void 0) return void 0;
285
+ return {
286
+ id: row.id,
287
+ sessionId: row.session_id,
288
+ toolCallId: row.tool_call_id,
289
+ operation: {
290
+ kind: row.kind === "member" ? "codemode" : "tool",
291
+ name: row.name
292
+ },
293
+ requirement: row.requirement,
294
+ description: JSON.parse(row.description_json),
295
+ input: row.input_json === null ? void 0 : JSON.parse(row.input_json),
296
+ ...row.argument_format === null ? {} : { argumentFormat: row.argument_format },
297
+ state: row.state,
298
+ revision: row.revision,
299
+ createdAt: row.created_at,
300
+ ...row.reason === null ? {} : { reason: row.reason },
301
+ ...row.result_json === null ? {} : { result: JSON.parse(row.result_json) },
302
+ ...row.decided_at === null ? {} : { decidedAt: row.decided_at },
303
+ ...row.finished_at === null ? {} : { finishedAt: row.finished_at },
304
+ ...row.delivered_at === null ? {} : { deliveredAt: row.delivered_at }
305
+ };
306
+ }
307
+ /** Opens the approval file and marks calls a previous process left running as interrupted, never replayed. */
308
+ async function createApprovalStore(options) {
309
+ const now = options.now ?? Date.now;
310
+ const id = options.id ?? (() => crypto.randomUUID());
311
+ const db = options.database ?? await (async () => {
312
+ if (!options.fs || !options.sqlite || !options.directory || !options.context) throw new Error("Approvals require a database or filesystem and sqlite ports.");
313
+ const created = await options.fs.createDir(options.directory, { recursive: true }, options.context);
314
+ if (!created.ok) throw created.error;
315
+ const file = await options.fs.joinPath([options.directory, "approval.sqlite"], options.context);
316
+ if (!file.ok) throw file.error;
317
+ return options.sqlite.open(file.value, options.context);
318
+ })();
319
+ const insert = (tx, record) => tx.run(`INSERT INTO approvals (
320
+ id, session_id, tool_call_id, kind, name, requirement, description_json, input_json,
321
+ argument_format, state, reason, result_json, revision, created_at, decided_at, finished_at, delivered_at
322
+ ) VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)`, record.id, record.sessionId, record.toolCallId, record.operation.kind === "codemode" ? "member" : record.operation.kind, record.operation.name, record.requirement, JSON.stringify(record.description), JSON.stringify(record.input) ?? null, record.argumentFormat ?? null, record.state, record.reason ?? null, JSON.stringify(record.result) ?? null, record.revision, record.createdAt, record.decidedAt ?? null, record.finishedAt ?? null, record.deliveredAt ?? null);
323
+ try {
324
+ await db.transaction(async (tx) => {
325
+ const legacy = (await tx.all("PRAGMA table_info(approvals)")).some((column) => column.name === "data");
326
+ if (legacy) await tx.exec("ALTER TABLE approvals RENAME TO approvals_legacy");
327
+ await tx.exec(SCHEMA);
328
+ if (legacy) {
329
+ for (const row of await tx.all("SELECT id, session_id, state, data FROM approvals_legacy ORDER BY rowid")) {
330
+ const record = JSON.parse(row.data);
331
+ if (record.id !== row.id || record.sessionId !== row.session_id || record.state !== row.state) throw new Error(`Legacy approval ${row.id} does not match its indexed identity or state.`);
332
+ await insert(tx, record);
333
+ }
334
+ await tx.exec("DROP TABLE approvals_legacy");
335
+ }
336
+ await tx.exec("CREATE INDEX IF NOT EXISTS approvals_session_state ON approvals(session_id, state)");
337
+ await tx.run("UPDATE approvals SET state = 'interrupted', reason = ?, revision = revision + 1, finished_at = ? WHERE state = 'running'", INTERRUPTED_REASON, now());
338
+ });
339
+ } catch (error) {
340
+ await db.close();
341
+ throw error;
342
+ }
343
+ return {
344
+ async insert(request) {
345
+ const record = {
346
+ id: id(),
347
+ sessionId: request.sessionId,
348
+ toolCallId: request.toolCallId,
349
+ operation: {
350
+ kind: request.operation.kind,
351
+ name: request.operation.name
352
+ },
353
+ requirement: request.requirement,
354
+ description: request.description,
355
+ input: request.input,
356
+ ...request.argumentFormat === void 0 ? {} : { argumentFormat: request.argumentFormat },
357
+ state: "pending",
358
+ revision: 1,
359
+ createdAt: now()
360
+ };
361
+ await insert(db, record);
362
+ return record;
363
+ },
364
+ async get(recordId) {
365
+ return read(await db.get(GET_BY_ID, recordId));
366
+ },
367
+ async list(filter = {}) {
368
+ const where = [];
369
+ const params = [];
370
+ if (filter.sessionId !== void 0) {
371
+ where.push("session_id = ?");
372
+ params.push(filter.sessionId);
373
+ }
374
+ if (filter.states !== void 0) {
375
+ if (filter.states.length === 0) return [];
376
+ where.push(`state IN (${filter.states.map(() => "?").join(",")})`);
377
+ params.push(...filter.states);
378
+ }
379
+ return (await db.all(`SELECT * FROM approvals${where.length === 0 ? "" : ` WHERE ${where.join(" AND ")}`} ORDER BY rowid`, ...params)).map((row) => read(row));
380
+ },
381
+ async update(recordId, from, patch, revision) {
382
+ return db.transaction(async (tx) => {
383
+ const current = read(await tx.get(GET_BY_ID, recordId));
384
+ if (current === void 0 || !from.includes(current.state)) return void 0;
385
+ if (revision !== void 0 && current.revision !== revision) return void 0;
386
+ const next = {
387
+ ...current,
388
+ ...patch
389
+ };
390
+ return read(await tx.get(`UPDATE approvals SET state = ?, reason = ?, result_json = ?, revision = revision + 1,
391
+ decided_at = ?, finished_at = ?, delivered_at = ?
392
+ WHERE id = ? AND state = ? AND revision = ? RETURNING *`, next.state, next.reason ?? null, JSON.stringify(next.result) ?? null, next.decidedAt ?? null, next.finishedAt ?? null, next.deliveredAt ?? null, recordId, current.state, current.revision));
393
+ });
394
+ },
395
+ close: () => db.close()
396
+ };
397
+ }
398
+ //#endregion
399
+ //#region src/extensions/(backend)/_lib/root.server.ts
400
+ /**
401
+ * The machine-wide approval queue, kept in `<po home>/approval`. Only a Node host with a home and sqlite serves it;
402
+ * elsewhere sessions find no root, and the gate refuses `human` calls as it always has.
403
+ */
404
+ async function createApprovalGlobalRoot(plugin) {
405
+ const host = plugin.host.context;
406
+ let root;
407
+ let close;
408
+ const provider = plugin.context.inject([
409
+ _agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE,
410
+ _agimon_ai_po_core_platform.PO_FS_SERVICE,
411
+ _agimon_ai_po_core_platform.PO_SQLITE_SERVICE
412
+ ], async (injected) => {
413
+ if (root !== void 0) return (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(injected).provide(require_approvalSession.APPROVAL_ROOT_SERVICE, root);
414
+ if (host.homeDirectory === void 0) return;
415
+ const store = await createApprovalStore({
416
+ fs: (0, _agimon_ai_po_core_platform.requirePoFs)(injected),
417
+ sqlite: (0, _agimon_ai_po_core_platform.requirePoSqlite)(injected),
418
+ directory: node_path.default.join((0, _agimon_ai_po_core_piSettings.poHomeDirectory)(host.homeDirectory, host.environment ?? {}), "approval"),
419
+ context: _agimon_ai_po_core_platform.BACKGROUND_CONTEXT
420
+ });
421
+ const created = createApprovalRoot({
422
+ store,
423
+ ...host.sessionService === void 0 ? {} : { sessions: host.sessionService },
424
+ ...host.setSessionPendingApprovals === void 0 ? {} : { setPendingCount: host.setSessionPendingApprovals.bind(host) },
425
+ onError: (error) => host.onNotice(`Approval: ${error instanceof Error ? error.message : String(error)}`)
426
+ });
427
+ root = created;
428
+ close = async () => {
429
+ created.dispose();
430
+ await store.close();
431
+ };
432
+ return (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(injected).provide(require_approvalSession.APPROVAL_ROOT_SERVICE, created);
433
+ });
434
+ await provider.await();
435
+ return {
436
+ value: root,
437
+ onDispose: async () => {
438
+ await provider.dispose();
439
+ await close?.();
440
+ }
441
+ };
442
+ }
443
+ //#endregion
444
+ //#region src/extensions/(backend)/root.server.ts
445
+ var root_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineRoot)(createApprovalGlobalRoot);
446
+ //#endregion
447
+ //#region src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts
448
+ /**
449
+ * Binds approvals where an agent session runs on a host that keeps the global queue. Elsewhere nothing is bound,
450
+ * so the gate refuses `human` calls as before.
451
+ */
452
+ async function createApprovalSession({ context, agent, host }) {
453
+ const execution = agent?.context;
454
+ const sessionId = host.context.sessionId;
455
+ let session;
456
+ await context.inject([_agimon_ai_po_core_serverPlugin.PO_SERVER_SCOPE_SERVICE], async (scoped) => {
457
+ const scope = (0, _agimon_ai_po_core_serverPlugin.requirePoServerScope)(scoped);
458
+ const root = scope.resolve(require_approvalSession.APPROVAL_ROOT_SERVICE);
459
+ if (execution === void 0 || agent === void 0 || sessionId === void 0 || root === void 0) return;
460
+ const created = require_approvalSession.createApprovalSession({
461
+ root,
462
+ sessionId,
463
+ session: execution.session
464
+ });
465
+ session = created;
466
+ const start = agent.registerHook({
467
+ event: "session_start",
468
+ handle: () => created.start()
469
+ });
470
+ const withdraw = await scope.provide(_agimon_ai_po_core_approval.PO_APPROVAL_CONTRACT, created.service);
471
+ return async () => {
472
+ start.dispose();
473
+ await withdraw();
474
+ created.dispose();
475
+ if (session === created) session = void 0;
476
+ };
477
+ }).await();
478
+ return { value: { current: () => session } };
479
+ }
480
+ //#endregion
481
+ //#region src/extensions/workspaces/sessions/(backend)/root.server.ts
482
+ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(createApprovalSession);
483
+ //#endregion
484
+ //#region src/extensions/workspaces/sessions/(backend)/contract/approval.server.ts
485
+ var approval_server_default = (0, _agimon_ai_po_core_extensionFile.defineServiceContract)(_agimon_ai_po_core_approval.PO_APPROVAL_SERVICE, { scope: "session" });
486
+ //#endregion
487
+ //#region src/types/approvalActivity.ts
488
+ /** The session channel the Activity card reads. */
489
+ const approvalActivityChannelType = "approval_activity";
490
+ //#endregion
491
+ //#region src/schemas/approvalMethods.ts
492
+ const Address = {
493
+ service: "approval",
494
+ scope: "session",
495
+ direction: "client-to-server"
496
+ };
497
+ const Id = typebox.Type.String({
498
+ minLength: 1,
499
+ maxLength: 200
500
+ });
501
+ const GlobalAddress = {
502
+ ...Address,
503
+ scope: "global"
504
+ };
505
+ const Reply = typebox.Type.Union([typebox.Type.Object({ ok: typebox.Type.Literal(true) }), typebox.Type.Object({
506
+ ok: typebox.Type.Literal(false),
507
+ message: typebox.Type.String()
508
+ })]);
509
+ /** Owner-client recovery reads bounded pages without mounting or waking any session. */
510
+ const approvalSnapshotMethod = (0, _agimon_ai_po_core_pluginProtocol.definePoPluginMethod)({
511
+ ...GlobalAddress,
512
+ method: "snapshot",
513
+ input: typebox.Type.Object({ offset: typebox.Type.Integer({ minimum: 0 }) }, { additionalProperties: false }),
514
+ output: typebox.Type.Object({
515
+ cards: typebox.Type.Array(typebox.Type.Intersect([_agimon_ai_po_core_approval.PoApprovalPromptSchema, typebox.Type.Object({
516
+ sessionId: Id,
517
+ revision: typebox.Type.Integer({ minimum: 1 }),
518
+ state: typebox.Type.Union([
519
+ typebox.Type.Literal("pending"),
520
+ typebox.Type.Literal("approved"),
521
+ typebox.Type.Literal("running"),
522
+ typebox.Type.Literal("interrupted")
523
+ ]),
524
+ reason: typebox.Type.Optional(typebox.Type.String()),
525
+ sessionGone: typebox.Type.Optional(typebox.Type.Literal(true)),
526
+ sessionName: typebox.Type.Optional(typebox.Type.String({ maxLength: 200 })),
527
+ workspaceName: typebox.Type.Optional(typebox.Type.String({ maxLength: 200 }))
528
+ })]), { maxItems: 50 }),
529
+ nextOffset: typebox.Type.Union([typebox.Type.Integer({ minimum: 1 }), typebox.Type.Null()])
530
+ })
531
+ });
532
+ const approvalGlobalDecideMethod = (0, _agimon_ai_po_core_pluginProtocol.definePoPluginMethod)({
533
+ ...GlobalAddress,
534
+ method: "decide",
535
+ input: typebox.Type.Object({
536
+ sessionId: Id,
537
+ id: Id,
538
+ revision: typebox.Type.Integer({ minimum: 1 }),
539
+ decision: typebox.Type.Union([typebox.Type.Literal("approve"), typebox.Type.Literal("deny")])
540
+ }, { additionalProperties: false }),
541
+ output: Reply
542
+ });
543
+ const approvalGlobalDismissMethod = (0, _agimon_ai_po_core_pluginProtocol.definePoPluginMethod)({
544
+ ...GlobalAddress,
545
+ method: "dismiss",
546
+ input: typebox.Type.Object({
547
+ sessionId: Id,
548
+ id: Id,
549
+ revision: typebox.Type.Integer({ minimum: 1 })
550
+ }, { additionalProperties: false }),
551
+ output: Reply
552
+ });
553
+ /** The person's Approve or Deny for one pending request, naming the revision the card showed. */
554
+ const approvalDecideMethod = (0, _agimon_ai_po_core_pluginProtocol.definePoPluginMethod)({
555
+ ...Address,
556
+ method: "decide",
557
+ input: typebox.Type.Object({
558
+ id: Id,
559
+ revision: typebox.Type.Integer({ minimum: 1 }),
560
+ decision: typebox.Type.Union([typebox.Type.Literal("approve"), typebox.Type.Literal("deny")])
561
+ }, { additionalProperties: false }),
562
+ output: Reply
563
+ });
564
+ /** Clears an approved call its session can no longer run. Nothing runs. */
565
+ const approvalDismissMethod = (0, _agimon_ai_po_core_pluginProtocol.definePoPluginMethod)({
566
+ ...Address,
567
+ method: "dismiss",
568
+ input: typebox.Type.Object({ id: Id }, { additionalProperties: false }),
569
+ output: Reply
570
+ });
571
+ //#endregion
572
+ //#region src/extensions/(backend)/_lib/approval-methods.server.ts
573
+ const PAGE_SIZE = 50;
574
+ /** Typed plugin methods are served only over the host's owner-authenticated client connection. */
575
+ function createApprovalSnapshotMethod(root) {
576
+ return (0, _agimon_ai_po_core_serverPlugin.defineServerMethod)(approvalSnapshotMethod, async ({ offset }) => {
577
+ const records = await root?.open() ?? [];
578
+ return {
579
+ cards: records.slice(offset, offset + PAGE_SIZE).map((record) => ({
580
+ sessionId: record.sessionId,
581
+ id: record.id,
582
+ toolCallId: record.toolCallId,
583
+ operation: record.operation,
584
+ requirement: record.requirement,
585
+ title: record.description.title,
586
+ summary: record.description.summary ?? "",
587
+ ...record.description.details === void 0 ? {} : { details: record.description.details.map((detail) => ({ ...detail })) },
588
+ revision: record.revision,
589
+ state: record.state,
590
+ ...record.sessionGone === true ? { sessionGone: true } : {},
591
+ ...record.sessionName === void 0 ? {} : { sessionName: record.sessionName.slice(0, 200) },
592
+ ...record.workspaceName === void 0 ? {} : { workspaceName: record.workspaceName.slice(0, 200) },
593
+ ...record.reason === void 0 ? {} : { reason: record.reason }
594
+ })),
595
+ nextOffset: offset + PAGE_SIZE < records.length ? offset + PAGE_SIZE : null
596
+ };
597
+ });
598
+ }
599
+ async function answer$1(root, sessionId, id, work) {
600
+ try {
601
+ if (root === void 0) throw new Error("Approvals are not available on this host.");
602
+ if (!(await root.open(sessionId)).some((record) => record.id === id)) throw new require_approvalSession.ApprovalRequestError("This approval is no longer here.", 404);
603
+ await work(root);
604
+ return { ok: true };
605
+ } catch (error) {
606
+ return {
607
+ ok: false,
608
+ message: error instanceof Error ? error.message : String(error)
609
+ };
610
+ }
611
+ }
612
+ function createApprovalGlobalDecideMethod(root) {
613
+ return (0, _agimon_ai_po_core_serverPlugin.defineServerMethod)(approvalGlobalDecideMethod, ({ sessionId, id, revision, decision }) => answer$1(root, sessionId, id, (queue) => queue.decide(id, revision, decision)));
614
+ }
615
+ function createApprovalGlobalDismissMethod(root) {
616
+ return (0, _agimon_ai_po_core_serverPlugin.defineServerMethod)(approvalGlobalDismissMethod, ({ sessionId, id, revision }) => answer$1(root, sessionId, id, (queue) => queue.dismiss(id, revision)));
617
+ }
618
+ //#endregion
619
+ //#region src/extensions/(backend)/method/decide.server.ts
620
+ var decide_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineMethod)(({ root }) => createApprovalGlobalDecideMethod(root));
621
+ //#endregion
622
+ //#region src/extensions/(backend)/method/dismiss.server.ts
623
+ var dismiss_server_default$1 = (0, _agimon_ai_po_core_extensionFile.defineMethod)(({ root }) => createApprovalGlobalDismissMethod(root));
624
+ //#endregion
625
+ //#region src/extensions/(backend)/method/snapshot.server.ts
626
+ var snapshot_server_default = (0, _agimon_ai_po_core_extensionFile.defineMethod)(({ root }) => createApprovalSnapshotMethod(root));
627
+ //#endregion
628
+ //#region src/schemas/apiContracts.ts
629
+ const VoiceApprovalAnswerSchema = typebox.Type.Object({
630
+ approvalId: typebox.Type.String({
631
+ minLength: 1,
632
+ maxLength: 200
633
+ }),
634
+ decision: typebox.Type.Union([typebox.Type.Literal("approved"), typebox.Type.Literal("denied")]),
635
+ channel: typebox.Type.Literal("voice")
636
+ });
637
+ /** `approval_withdraw` input. */
638
+ const ApprovalWithdrawParametersSchema = typebox.Type.Object({ id: typebox.Type.String({
639
+ minLength: 1,
640
+ maxLength: 200,
641
+ description: "The approval id from the pending receipt."
642
+ }) });
643
+ (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
644
+ version: 1,
645
+ http: [{
646
+ id: "approval.current",
647
+ scope: "session",
648
+ basePath: "approval",
649
+ path: "/current",
650
+ method: "GET",
651
+ authentication: "owner",
652
+ description: "Read the one pending ask approval of this session, or null when there is none or more than one.",
653
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Union([_agimon_ai_po_core_approval.PoApprovalPromptSchema, typebox.Type.Null()]))
654
+ }, {
655
+ id: "approval.answer",
656
+ scope: "session",
657
+ basePath: "approval",
658
+ path: "/current",
659
+ method: "POST",
660
+ authentication: "owner",
661
+ description: "Answer the current ask approval through Voice. Human approvals are app-only.",
662
+ body: {
663
+ required: true,
664
+ contentType: "application/json",
665
+ schema: VoiceApprovalAnswerSchema
666
+ },
667
+ responses: {
668
+ ...(0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({ answered: typebox.Type.Boolean() })),
669
+ "400": { description: "Invalid approval answer." }
670
+ }
671
+ }],
672
+ sockets: [],
673
+ dynamic: []
674
+ });
675
+ //#endregion
676
+ //#region src/extensions/workspaces/sessions/(backend)/api/approval/route.server.ts
677
+ var route_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoute)(({ root }) => ({
678
+ basePath: "approval",
679
+ start: () => ({
680
+ async fetch(request) {
681
+ if (new URL(request.url).pathname !== "/current") return new Response(null, { status: 404 });
682
+ const session = root.current();
683
+ if (request.method === "GET") return Response.json(await session?.voiceCurrent() ?? null);
684
+ if (request.method !== "POST") return new Response(null, { status: 405 });
685
+ let body;
686
+ try {
687
+ body = await request.json();
688
+ } catch {
689
+ return Response.json({ error: "Invalid approval answer" }, { status: 400 });
690
+ }
691
+ if (!(0, typebox_value.Check)(VoiceApprovalAnswerSchema, body)) return new Response(null, { status: 400 });
692
+ return Response.json({ answered: await session?.voiceAnswer(body.approvalId, body.decision) === true });
693
+ },
694
+ close() {}
695
+ })
696
+ }));
697
+ //#endregion
698
+ //#region src/extensions/workspaces/sessions/(backend)/channel/_lib/approval-activity.server.ts
699
+ /**
700
+ * This session's open approvals, for the Activity card. The list comes from the global queue and
701
+ * carries the bounded description only, never a call's saved arguments.
702
+ */
703
+ function createApprovalActivityChannel({ root }) {
704
+ return {
705
+ frameType: approvalActivityChannelType,
706
+ start(host) {
707
+ const cards = /* @__PURE__ */ new Map();
708
+ const stops = /* @__PURE__ */ new Map();
709
+ const refresh = async (sessionId) => {
710
+ const next = await root.current()?.cards() ?? [];
711
+ if (!stops.has(sessionId)) return;
712
+ if (JSON.stringify(cards.get(sessionId)) === JSON.stringify(next)) return;
713
+ cards.set(sessionId, next);
714
+ host.publish(sessionId, { approvals: next });
715
+ const pending = next.filter((card) => card.state === "pending");
716
+ const { revision: _revision, state: _state, reason: _reason, ...voice } = pending[0] ?? {};
717
+ host.directEvents.publish(_agimon_ai_po_core_approval.PO_APPROVAL_VOICE_EVENT, sessionId, pending.length === 1 ? voice : null);
718
+ };
719
+ const report = (sessionId) => (error) => host.onNotice(`approval activity for ${sessionId} failed (${error instanceof Error ? error.message : String(error)})`);
720
+ return {
721
+ payloadFor(scope) {
722
+ const approvals = cards.get(scope.sessionId);
723
+ return approvals === void 0 ? void 0 : { approvals };
724
+ },
725
+ sessionAdded(scope) {
726
+ const session = root.current();
727
+ if (session === void 0 || stops.has(scope.sessionId)) return;
728
+ stops.set(scope.sessionId, session.onChanged(() => void refresh(scope.sessionId).catch(report(scope.sessionId))));
729
+ refresh(scope.sessionId).catch(report(scope.sessionId));
730
+ },
731
+ sessionRemoved(sessionId) {
732
+ stops.get(sessionId)?.();
733
+ stops.delete(sessionId);
734
+ cards.delete(sessionId);
735
+ },
736
+ close() {
737
+ for (const stop of stops.values()) stop();
738
+ stops.clear();
739
+ cards.clear();
740
+ }
741
+ };
742
+ }
743
+ };
744
+ }
745
+ //#endregion
746
+ //#region src/extensions/workspaces/sessions/(backend)/channel/approval-activity.server.ts
747
+ var approval_activity_server_default = (0, _agimon_ai_po_core_extensionFile.defineChannel)(createApprovalActivityChannel, { context: true });
748
+ //#endregion
749
+ //#region src/extensions/workspaces/sessions/(backend)/method/_lib/approval-methods.server.ts
750
+ /**
751
+ * The person's answers from the Activity card. They run in the session's own server and reach only
752
+ * that session's requests; Voice answers through its own route, and only `ask` requests.
753
+ */
754
+ const UNAVAILABLE = "Approvals are not kept in this session.";
755
+ async function answer(work) {
756
+ try {
757
+ await work();
758
+ return { ok: true };
759
+ } catch (error) {
760
+ return {
761
+ ok: false,
762
+ message: error instanceof Error ? error.message : String(error)
763
+ };
764
+ }
765
+ }
766
+ function createApprovalDecideMethod(root) {
767
+ return (0, _agimon_ai_po_core_serverPlugin.defineServerMethod)(approvalDecideMethod, ({ id, revision, decision }) => {
768
+ const session = root.current();
769
+ return session === void 0 ? {
770
+ ok: false,
771
+ message: UNAVAILABLE
772
+ } : answer(() => session.decide(id, revision, decision));
773
+ });
774
+ }
775
+ function createApprovalDismissMethod(root) {
776
+ return (0, _agimon_ai_po_core_serverPlugin.defineServerMethod)(approvalDismissMethod, ({ id }) => {
777
+ const session = root.current();
778
+ return session === void 0 ? {
779
+ ok: false,
780
+ message: UNAVAILABLE
781
+ } : answer(() => session.dismiss(id));
782
+ });
783
+ }
784
+ //#endregion
785
+ //#region src/extensions/workspaces/sessions/(backend)/method/decide.server.ts
786
+ var decide_server_default = (0, _agimon_ai_po_core_extensionFile.defineMethod)(({ root }) => createApprovalDecideMethod(root));
787
+ //#endregion
788
+ //#region src/extensions/workspaces/sessions/(backend)/method/dismiss.server.ts
789
+ var dismiss_server_default = (0, _agimon_ai_po_core_extensionFile.defineMethod)(({ root }) => createApprovalDismissMethod(root));
790
+ //#endregion
791
+ //#region src/extensions/workspaces/sessions/(backend)/tool/approval-withdraw.server.ts
792
+ var approval_withdraw_server_default = (0, _agimon_ai_po_core_extensionFile.defineServerTool)((context) => ({
793
+ name: "approval_withdraw",
794
+ label: "Withdraw approval request",
795
+ description: "Take back a tool call you sent for the person’s approval and no longer need. Only pending requests can be withdrawn.",
796
+ parameters: ApprovalWithdrawParametersSchema,
797
+ mainAgentOnly: true,
798
+ async execute(_toolCallId, { id }) {
799
+ const session = context.root.current();
800
+ const withdrawn = await session?.withdraw(id);
801
+ return {
802
+ content: [{
803
+ type: "text",
804
+ text: session === void 0 ? "Approvals are not kept in this session." : withdrawn === void 0 ? `Approval ${id} is not pending in this session, so there was nothing to withdraw.` : `Withdrew approval ${id}. ${withdrawn.operation.name} will not run.`
805
+ }],
806
+ details: {
807
+ approvalId: id,
808
+ withdrawn: withdrawn !== void 0
809
+ }
810
+ };
811
+ }
812
+ }));
813
+ //#endregion
814
+ //#region generated/server.ts
815
+ const at = (value, context) => typeof value === "function" ? value(context) : value;
816
+ /* v8 ignore next -- generated normalization branch */
817
+ const defined = (values) => values.filter((value) => value !== void 0);
818
+ const via = (identity, value) => value === void 0 ? void 0 : {
819
+ ...identity,
820
+ ...value
821
+ };
822
+ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
823
+ name: "@agimon-ai/po-approval",
824
+ providerOverrides: (0, _agimon_ai_po_core_serverPlugin.composeServerProviderOverrides)(root_server_default$1, root_server_default),
825
+ provides: { session: [approval_server_default] },
826
+ injects: (0, _agimon_ai_po_core_extensionFile.composeRootInjects)({
827
+ global: [root_server_default$1],
828
+ workspace: [root_server_default$1],
829
+ session: [root_server_default$1, root_server_default]
830
+ }),
831
+ global: async (context) => {
832
+ const scopeGlobal = await context.scopeRoot("global", root_server_default$1, context);
833
+ const contextGlobal = {
834
+ ...context,
835
+ root: scopeGlobal.value
836
+ };
837
+ return {
838
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeGlobal),
839
+ get methods() {
840
+ return [
841
+ at(decide_server_default$1, contextGlobal),
842
+ at(dismiss_server_default$1, contextGlobal),
843
+ at(snapshot_server_default, contextGlobal)
844
+ ];
845
+ },
846
+ services: [...scopeGlobal.services ?? []]
847
+ };
848
+ },
849
+ workspace: async (context) => {
850
+ const scopeGlobal = await context.scopeRoot("global", root_server_default$1, context);
851
+ const contextGlobal = {
852
+ ...context,
853
+ root: scopeGlobal.value
854
+ };
855
+ return {
856
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeGlobal),
857
+ get methods() {
858
+ return defined([
859
+ context.hosted("global") ? void 0 : at(decide_server_default$1, contextGlobal),
860
+ context.hosted("global") ? void 0 : at(dismiss_server_default$1, contextGlobal),
861
+ context.hosted("global") ? void 0 : at(snapshot_server_default, contextGlobal)
862
+ ]);
863
+ },
864
+ services: [...scopeGlobal.services ?? []]
865
+ };
866
+ },
867
+ session: async (context) => {
868
+ const scopeGlobal = await context.scopeRoot("global", root_server_default$1, context);
869
+ const contextGlobal = {
870
+ ...context,
871
+ root: scopeGlobal.value
872
+ };
873
+ const scopeSession = await context.scopeRoot("session", root_server_default, contextGlobal);
874
+ const contextSession = {
875
+ ...contextGlobal,
876
+ root: scopeSession.value
877
+ };
878
+ return {
879
+ ...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeGlobal, scopeSession),
880
+ get api() {
881
+ return [at(route_server_default, contextSession)];
882
+ },
883
+ get channels() {
884
+ return [() => via({ frameType: "approval_activity" }, at(approval_activity_server_default, contextSession))];
885
+ },
886
+ get methods() {
887
+ return defined([
888
+ context.hosted("global") ? void 0 : at(decide_server_default$1, contextGlobal),
889
+ context.hosted("global") ? void 0 : at(dismiss_server_default$1, contextGlobal),
890
+ context.hosted("global") ? void 0 : at(snapshot_server_default, contextGlobal),
891
+ at(decide_server_default, contextSession),
892
+ at(dismiss_server_default, contextSession)
893
+ ]);
894
+ },
895
+ get tools() {
896
+ return [via({ name: "approval_withdraw" }, at(approval_withdraw_server_default, contextSession))];
897
+ },
898
+ services: [...scopeGlobal.services ?? [], ...scopeSession.services ?? []],
899
+ get activities() {
900
+ return [...scopeGlobal.activities ?? [], ...scopeSession.activities ?? []];
901
+ }
902
+ };
903
+ }
904
+ });
905
+ //#endregion
906
+ exports.default = serverPlugin;
907
+ exports.serverPlugin = serverPlugin;
908
+
909
+ //# sourceMappingURL=server.cjs.map