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