@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.
package/LICENSE ADDED
@@ -0,0 +1,149 @@
1
+ License text copyright © 2017 MariaDB Corporation Ab, All Rights Reserved.
2
+ "Business Source License" is a trademark of MariaDB Corporation Ab.
3
+
4
+ Parameters
5
+
6
+ Licensor: Agimon Pty Ltd
7
+ Licensed Work: Po, the software in the Po source repository and the
8
+ packages released from it, in each version released by
9
+ the Licensor.
10
+ The Licensed Work is (c) 2026 Agimon Pty Ltd.
11
+ Material identified as third-party in the "Third-party
12
+ components" section at the end of this file or in a
13
+ NOTICE file, and any package or directory whose own
14
+ license file grants a different license, is not part of
15
+ the Licensed Work and remains under its own license.
16
+ Additional Use Grant: You may make production use of the Licensed Work if
17
+ your use is Eligible Use. "Eligible Use" is production use that falls
18
+ within at least one of the following:
19
+
20
+ (a) Personal Use. Use by an individual for their own personal purposes,
21
+ and not on behalf of, or for the benefit of, an employer, client, or
22
+ other Organization. Use by an individual in the course of employment
23
+ or engagement by an Organization is use by that Organization.
24
+
25
+ (b) Small Organization Use. Use by or on behalf of an Organization whose
26
+ Annual Revenue is less than USD 1,000,000.
27
+
28
+ (c) Non-profit, Education and Research Use. Use, regardless of Annual
29
+ Revenue, by (i) an Organization registered or recognized as a
30
+ non-profit or charitable organization under the laws of its
31
+ jurisdiction, for its non-profit purposes; (ii) an accredited school,
32
+ college, or university, for teaching, learning, or academic research;
33
+ or (iii) a publicly funded research institution, for its research.
34
+
35
+ (d) Service Provider Use. Use by a consultant, contractor, agency, or other
36
+ service provider, regardless of its own Annual Revenue, solely to
37
+ build, deploy, host, operate, or support the Licensed Work for a client
38
+ whose own use would be Eligible Use under (a), (b), or (c). A service
39
+ provider's use for its own purposes is Eligible Use only if the service
40
+ provider itself qualifies under (b) or (c).
41
+
42
+
43
+ Hosted services. Offering the Licensed Work to third parties as a hosted
44
+ or managed service whose primary value is the Licensed Work is Eligible
45
+ Use only if each such third party's own use would be Eligible Use.
46
+
47
+ Definitions. "Organization" means any company, partnership, sole
48
+ proprietorship, trust, association, government body, or other entity, and
49
+ includes an individual acting in a business or professional capacity.
50
+ "Affiliate" means any entity that directly or indirectly controls, is
51
+ controlled by, or is under common control with an Organization, where
52
+ "control" means ownership of more than 50% of the voting interests of an
53
+ entity or the power to direct its management and policies by contract or
54
+ otherwise. "Annual Revenue" means the total gross revenue of an
55
+ Organization and all of its Affiliates combined, from all sources and
56
+ whether or not related to the Licensed Work, for its most recently
57
+ completed fiscal year, or, if it has not completed a fiscal year, for the
58
+ twelve months before the use (or since its formation, if shorter),
59
+ converted into US dollars at the average exchange rate for that period.
60
+ Proceeds of equity or debt financing are not revenue.
61
+
62
+ Threshold. If an Organization stops qualifying under (b), its existing
63
+ production use remains Eligible Use for 90 days after it stops
64
+ qualifying, after which it must obtain a commercial license or stop
65
+ production use. Use that was Eligible Use when it occurred never requires
66
+ a commercial license after the fact.
67
+ Change Date: Four years from the date a version of the Licensed Work
68
+ is first publicly released by the Licensor.
69
+ Change License: Apache License, Version 2.0
70
+
71
+ For information about alternative licensing arrangements for the Licensed
72
+ Work, please visit: https://agimon.ai/licensing
73
+
74
+ Notice
75
+
76
+ The Business Source License (this document, or the "License") is not an Open
77
+ Source license. However, the Licensed Work will eventually be made available
78
+ under an Open Source License, as stated in this License.
79
+
80
+ -----------------------------------------------------------------------------
81
+
82
+ Business Source License 1.1
83
+
84
+ Terms
85
+
86
+ The Licensor hereby grants you the right to copy, modify, create derivative
87
+ works, redistribute, and make non-production use of the Licensed Work. The
88
+ Licensor may make an Additional Use Grant, above, permitting limited
89
+ production use.
90
+
91
+ Effective on the Change Date, or the fourth anniversary of the first publicly
92
+ available distribution of a specific version of the Licensed Work under this
93
+ License, whichever comes first, the Licensor hereby grants you rights under
94
+ the terms of the Change License, and the rights granted in the paragraph
95
+ above terminate.
96
+
97
+ If your use of the Licensed Work does not comply with the requirements
98
+ currently in effect as described in this License, you must purchase a
99
+ commercial license from the Licensor, its affiliated entities, or authorized
100
+ resellers, or you must refrain from using the Licensed Work.
101
+
102
+ All copies of the original and modified Licensed Work, and derivative works
103
+ of the Licensed Work, are subject to this License. This License applies
104
+ separately for each version of the Licensed Work and the Change Date may vary
105
+ for each version of the Licensed Work released by Licensor.
106
+
107
+ You must conspicuously display this License on each original or modified copy
108
+ of the Licensed Work. If you receive the Licensed Work in original or
109
+ modified form from a third party, the terms and conditions set forth in this
110
+ License apply to your use of that work.
111
+
112
+ Any use of the Licensed Work in violation of this License will automatically
113
+ terminate your rights under this License for the current and all other
114
+ versions of the Licensed Work.
115
+
116
+ This License does not grant you any right in any trademark or logo of
117
+ Licensor or its affiliates (provided that you may use a trademark or logo of
118
+ Licensor as expressly required by this License).
119
+
120
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED ON
121
+ AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS,
122
+ EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION) WARRANTIES OF
123
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT, AND
124
+ TITLE.
125
+
126
+ MariaDB hereby grants you permission to use this License’s text to license
127
+ your works, and to refer to it using the trademark “Business Source License”,
128
+ as long as you comply with the Covenants of Licensor below.
129
+
130
+ Covenants of Licensor
131
+
132
+ In consideration of the right to use this License’s text and the “Business
133
+ Source License” name and trademark, Licensor covenants to MariaDB, and to all
134
+ other recipients of the licensed work to be provided by Licensor:
135
+
136
+ 1. To specify as the Change License the GPL Version 2.0 or any later version,
137
+ or a license that is compatible with GPL Version 2.0 or a later version,
138
+ where “compatible” means that software provided under the Change License can
139
+ be included in a program with software provided under GPL Version 2.0 or a
140
+ later version. Licensor may specify additional Change Licenses without
141
+ limitation.
142
+
143
+ 2. To either: (a) specify an additional grant of rights to use that does not
144
+ impose any additional restriction on the right granted in this License, as
145
+ the Additional Use Grant; or (b) insert the text “None”.
146
+
147
+ 3. To specify a Change Date.
148
+
149
+ 4. Not to modify this License in any other way.
package/README.md ADDED
@@ -0,0 +1,67 @@
1
+ # Po Approval
2
+
3
+ Asks the person before a tool or code-mode method that declares approval runs in a Po session.
4
+
5
+ ## What it binds
6
+
7
+ The session service `po/approval` (`PO_APPROVAL_CONTRACT` from `@agimon-ai/po-core/approval`). Po core's gate calls it for any
8
+ direct tool or code-mode namespace member that declares `approval: { requirement, describe }`. Without this package
9
+ bound, `ask` calls run without asking and `human` calls are refused.
10
+
11
+ Consumers declare approval through the generic core contract. The shared tool/code-mode gate consumes the Cordis
12
+ `po/approval` service on their behalf; this provider does not inspect plugin names or provenance to admit requests.
13
+
14
+ ## How a call is asked
15
+
16
+ Asking does not block the agent. A gated call is queued and returns at once with `pending approval` and its approval id
17
+ (code mode throws `ApprovalPendingError`; do not retry it). The agent keeps working and can take its own request back with
18
+ `approval_withdraw` while it is still pending.
19
+
20
+ The person answers in the session's Activity rail, under the Approval card (web and native). Each card carries the
21
+ bounded text the package's `describe` returned (title, summary, up to 12 details), never the call's arguments. The
22
+ session list shows that the session is waiting for the person's approval while any request is pending.
23
+
24
+ Requests never expire. They live in one machine-wide queue (`~/.po/approval/approval.sqlite`), so they survive restarts:
25
+
26
+ - `pending`: waiting for Approve or Deny. Each answer names the card's revision; a stale or duplicate answer is refused,
27
+ and a session can only answer its own requests.
28
+ - `approved`: the call runs once, as the main agent, as soon as its session is mounted (Approve revives a dormant
29
+ session).
30
+ - `succeeded` / `failed`: the outcome reaches the agent as a steering message.
31
+ - `denied`: the agent is told not to retry unless asked.
32
+ - `withdrawn`: the agent took back its own pending call; nothing runs.
33
+ - `interrupted`: the server stopped while the call was running. It is reported, never replayed.
34
+
35
+ When a session is no longer live or dormant, its pending or approved cards offer Dismiss to cancel without running.
36
+ A code-mode call replays only if its namespace member still declares approval when it runs.
37
+
38
+ Execution is at most once. An interrupted call is never automatically replayed. Delivery is at least once: a crash
39
+ between message admission and saving `deliveredAt` may repeat the steering message.
40
+
41
+ Existing JSON-backed queues migrate to the column-based schema in one transaction when opened. A failed migration
42
+ leaves the original queue intact. Older Approval builds cannot read the migrated schema.
43
+
44
+ ## Voice
45
+
46
+ When a session has exactly one pending request and it is `ask`, Live Voice can read it out and accept a spoken
47
+ `approve` or `deny`. `human` requests are answered in the app only.
48
+
49
+ ## Unattended sessions
50
+
51
+ Host-set `interaction: 'unattended'` does not prevent a foreground main-agent call from queuing a `human` request
52
+ through the approval service. This includes workflow and scheduled sessions. The person answers in the originating
53
+ session's Approval card; an approved call executes in that same session and its outcome arrives there as a message.
54
+ Approval replays only the saved operation, not the original script or its continuation. Chat permission does not replace
55
+ the app decision for the queued request.
56
+
57
+ Subagents and background `exec` scripts still cannot request `human` approval. Their approved replay would run as the
58
+ main agent, so those calls remain hidden or refused. `ask` calls still run without asking in all unattended contexts.
59
+ Without a bound approval service, a `human` call is refused and nothing runs.
60
+
61
+ Absent `interaction` means interactive. Provenance labels stay opaque, and tool arguments cannot change presence.
62
+ Queuing approval does not change the session's interaction setting or relax the operation's own safety checks.
63
+
64
+ ## Limits
65
+
66
+ `ask` is a courtesy, not a security boundary: it is skipped where nobody can answer. Pi tools, Bash and raw code are not
67
+ gated.
@@ -0,0 +1,58 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ let _agimon_ai_po_core_apiContracts = require("@agimon-ai/po-core/apiContracts");
6
+ let _agimon_ai_po_core_approval = require("@agimon-ai/po-core/approval");
7
+ let typebox = require("typebox");
8
+ //#region src/schemas/apiContracts.ts
9
+ const VoiceApprovalAnswerSchema = typebox.Type.Object({
10
+ approvalId: typebox.Type.String({
11
+ minLength: 1,
12
+ maxLength: 200
13
+ }),
14
+ decision: typebox.Type.Union([typebox.Type.Literal("approved"), typebox.Type.Literal("denied")]),
15
+ channel: typebox.Type.Literal("voice")
16
+ });
17
+ typebox.Type.Object({ id: typebox.Type.String({
18
+ minLength: 1,
19
+ maxLength: 200,
20
+ description: "The approval id from the pending receipt."
21
+ }) });
22
+ const apiContracts = (0, _agimon_ai_po_core_apiContracts.defineApiContract)({
23
+ version: 1,
24
+ http: [{
25
+ id: "approval.current",
26
+ scope: "session",
27
+ basePath: "approval",
28
+ path: "/current",
29
+ method: "GET",
30
+ authentication: "owner",
31
+ description: "Read the one pending ask approval of this session, or null when there is none or more than one.",
32
+ responses: (0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Union([_agimon_ai_po_core_approval.PoApprovalPromptSchema, typebox.Type.Null()]))
33
+ }, {
34
+ id: "approval.answer",
35
+ scope: "session",
36
+ basePath: "approval",
37
+ path: "/current",
38
+ method: "POST",
39
+ authentication: "owner",
40
+ description: "Answer the current ask approval through Voice. Human approvals are app-only.",
41
+ body: {
42
+ required: true,
43
+ contentType: "application/json",
44
+ schema: VoiceApprovalAnswerSchema
45
+ },
46
+ responses: {
47
+ ...(0, _agimon_ai_po_core_apiContracts.jsonApiResponses)(typebox.Type.Object({ answered: typebox.Type.Boolean() })),
48
+ "400": { description: "Invalid approval answer." }
49
+ }
50
+ }],
51
+ sockets: [],
52
+ dynamic: []
53
+ });
54
+ //#endregion
55
+ exports.apiContracts = apiContracts;
56
+ exports.default = apiContracts;
57
+
58
+ //# sourceMappingURL=apiContracts.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.cjs","names":["Type","defineApiContract","jsonApiResponses","PoApprovalPromptSchema"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses } from '@agimon-ai/po-core/apiContracts';\nimport { PoApprovalPromptSchema } from '@agimon-ai/po-core/approval';\nimport { Type } from 'typebox';\n\nexport const VoiceApprovalAnswerSchema = Type.Object({\n approvalId: Type.String({ minLength: 1, maxLength: 200 }),\n decision: Type.Union([Type.Literal('approved'), Type.Literal('denied')]),\n channel: Type.Literal('voice'),\n});\n\n/** `approval_withdraw` input. */\nexport const ApprovalWithdrawParametersSchema = Type.Object({\n id: Type.String({ minLength: 1, maxLength: 200, description: 'The approval id from the pending receipt.' }),\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n http: [\n {\n id: 'approval.current',\n scope: 'session',\n basePath: 'approval',\n path: '/current',\n method: 'GET',\n authentication: 'owner',\n description: 'Read the one pending ask approval of this session, or null when there is none or more than one.',\n responses: jsonApiResponses(Type.Union([PoApprovalPromptSchema, Type.Null()])),\n },\n {\n id: 'approval.answer',\n scope: 'session',\n basePath: 'approval',\n path: '/current',\n method: 'POST',\n authentication: 'owner',\n description: 'Answer the current ask approval through Voice. Human approvals are app-only.',\n body: { required: true, contentType: 'application/json', schema: VoiceApprovalAnswerSchema },\n responses: {\n ...jsonApiResponses(Type.Object({ answered: Type.Boolean() })),\n '400': { description: 'Invalid approval answer.' },\n },\n },\n ],\n sockets: [],\n dynamic: [],\n});\nexport default apiContracts;\n"],"mappings":";;;;;;;;AAIA,MAAa,4BAA4BA,QAAAA,KAAK,OAAO;CACnD,YAAYA,QAAAA,KAAK,OAAO;EAAE,WAAW;EAAG,WAAW;CAAI,CAAC;CACxD,UAAUA,QAAAA,KAAK,MAAM,CAACA,QAAAA,KAAK,QAAQ,UAAU,GAAGA,QAAAA,KAAK,QAAQ,QAAQ,CAAC,CAAC;CACvE,SAASA,QAAAA,KAAK,QAAQ,OAAO;AAC/B,CAAC;AAG+CA,QAAAA,KAAK,OAAO,EAC1D,IAAIA,QAAAA,KAAK,OAAO;CAAE,WAAW;CAAG,WAAW;CAAK,aAAa;AAA4C,CAAC,EAC5G,CAAC;AACD,MAAa,gBAAA,GAAeC,gCAAAA,kBAAAA,CAAkB;CAC5C,SAAS;CACT,MAAM,CACJ;EACE,IAAI;EACJ,OAAO;EACP,UAAU;EACV,MAAM;EACN,QAAQ;EACR,gBAAgB;EAChB,aAAa;EACb,YAAA,GAAWC,gCAAAA,iBAAAA,CAAiBF,QAAAA,KAAK,MAAM,CAACG,4BAAAA,wBAAwBH,QAAAA,KAAK,KAAK,CAAC,CAAC,CAAC;CAC/E,GACA;EACE,IAAI;EACJ,OAAO;EACP,UAAU;EACV,MAAM;EACN,QAAQ;EACR,gBAAgB;EAChB,aAAa;EACb,MAAM;GAAE,UAAU;GAAM,aAAa;GAAoB,QAAQ;EAA0B;EAC3F,WAAW;GACT,IAAA,GAAGE,gCAAAA,iBAAAA,CAAiBF,QAAAA,KAAK,OAAO,EAAE,UAAUA,QAAAA,KAAK,QAAQ,EAAE,CAAC,CAAC;GAC7D,OAAO,EAAE,aAAa,2BAA2B;EACnD;CACF,CACF;CACA,SAAS,CAAC;CACV,SAAS,CAAC;AACZ,CAAC"}
@@ -0,0 +1,53 @@
1
+ import { Type } from "typebox";
2
+ //#region src/schemas/apiContracts.d.ts
3
+ export declare const apiContracts: {
4
+ version: 1;
5
+ protocols?: Record<string, string> | undefined;
6
+ schemas?: Record<string, boolean | object> | undefined;
7
+ http: {
8
+ id: string;
9
+ scope: "global" | "session" | "workspace";
10
+ basePath?: string | undefined;
11
+ path: string;
12
+ method: "DELETE" | "GET" | "HEAD" | "OPTIONS" | "PATCH" | "POST" | "PUT";
13
+ description: string;
14
+ availability?: string | undefined;
15
+ authentication: "device" | "none" | "owner";
16
+ parameters?: {
17
+ name: string;
18
+ in: "header" | "path" | "query";
19
+ required: boolean;
20
+ schema: boolean | object;
21
+ }[] | undefined;
22
+ body?: {
23
+ contentType: string;
24
+ contentTypes?: string[] | undefined;
25
+ required: boolean;
26
+ schema: boolean | object;
27
+ } | undefined;
28
+ responses: Record<string, {
29
+ description: string;
30
+ contentType?: string | undefined;
31
+ schema?: boolean | object | undefined;
32
+ events?: Record<string, boolean | object> | undefined;
33
+ }>;
34
+ }[];
35
+ sockets: {
36
+ id: string;
37
+ scope: "global" | "session" | "workspace";
38
+ description: string;
39
+ availability?: string | undefined;
40
+ service: string;
41
+ member: string;
42
+ direction: "client-to-server" | "server-to-client";
43
+ kind: "channel" | "method" | "state";
44
+ input: boolean | object;
45
+ output?: boolean | object | undefined;
46
+ errors?: boolean | object | undefined;
47
+ }[];
48
+ dynamic: string[];
49
+ gaps?: string[] | undefined;
50
+ };
51
+ //#endregion
52
+ export { apiContracts as default };
53
+ //# sourceMappingURL=apiContracts.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.d.mts","names":[],"sources":["../src/schemas/apiContracts.ts"],"mappings":";;qBAca"}
@@ -0,0 +1,53 @@
1
+ import { defineApiContract, jsonApiResponses } from "@agimon-ai/po-core/apiContracts";
2
+ import { PoApprovalPromptSchema } from "@agimon-ai/po-core/approval";
3
+ import { Type } from "typebox";
4
+ //#region src/schemas/apiContracts.ts
5
+ const VoiceApprovalAnswerSchema = Type.Object({
6
+ approvalId: Type.String({
7
+ minLength: 1,
8
+ maxLength: 200
9
+ }),
10
+ decision: Type.Union([Type.Literal("approved"), Type.Literal("denied")]),
11
+ channel: Type.Literal("voice")
12
+ });
13
+ Type.Object({ id: Type.String({
14
+ minLength: 1,
15
+ maxLength: 200,
16
+ description: "The approval id from the pending receipt."
17
+ }) });
18
+ const apiContracts = defineApiContract({
19
+ version: 1,
20
+ http: [{
21
+ id: "approval.current",
22
+ scope: "session",
23
+ basePath: "approval",
24
+ path: "/current",
25
+ method: "GET",
26
+ authentication: "owner",
27
+ description: "Read the one pending ask approval of this session, or null when there is none or more than one.",
28
+ responses: jsonApiResponses(Type.Union([PoApprovalPromptSchema, Type.Null()]))
29
+ }, {
30
+ id: "approval.answer",
31
+ scope: "session",
32
+ basePath: "approval",
33
+ path: "/current",
34
+ method: "POST",
35
+ authentication: "owner",
36
+ description: "Answer the current ask approval through Voice. Human approvals are app-only.",
37
+ body: {
38
+ required: true,
39
+ contentType: "application/json",
40
+ schema: VoiceApprovalAnswerSchema
41
+ },
42
+ responses: {
43
+ ...jsonApiResponses(Type.Object({ answered: Type.Boolean() })),
44
+ "400": { description: "Invalid approval answer." }
45
+ }
46
+ }],
47
+ sockets: [],
48
+ dynamic: []
49
+ });
50
+ //#endregion
51
+ export { apiContracts, apiContracts as default };
52
+
53
+ //# sourceMappingURL=apiContracts.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract, jsonApiResponses } from '@agimon-ai/po-core/apiContracts';\nimport { PoApprovalPromptSchema } from '@agimon-ai/po-core/approval';\nimport { Type } from 'typebox';\n\nexport const VoiceApprovalAnswerSchema = Type.Object({\n approvalId: Type.String({ minLength: 1, maxLength: 200 }),\n decision: Type.Union([Type.Literal('approved'), Type.Literal('denied')]),\n channel: Type.Literal('voice'),\n});\n\n/** `approval_withdraw` input. */\nexport const ApprovalWithdrawParametersSchema = Type.Object({\n id: Type.String({ minLength: 1, maxLength: 200, description: 'The approval id from the pending receipt.' }),\n});\nexport const apiContracts = defineApiContract({\n version: 1,\n http: [\n {\n id: 'approval.current',\n scope: 'session',\n basePath: 'approval',\n path: '/current',\n method: 'GET',\n authentication: 'owner',\n description: 'Read the one pending ask approval of this session, or null when there is none or more than one.',\n responses: jsonApiResponses(Type.Union([PoApprovalPromptSchema, Type.Null()])),\n },\n {\n id: 'approval.answer',\n scope: 'session',\n basePath: 'approval',\n path: '/current',\n method: 'POST',\n authentication: 'owner',\n description: 'Answer the current ask approval through Voice. Human approvals are app-only.',\n body: { required: true, contentType: 'application/json', schema: VoiceApprovalAnswerSchema },\n responses: {\n ...jsonApiResponses(Type.Object({ answered: Type.Boolean() })),\n '400': { description: 'Invalid approval answer.' },\n },\n },\n ],\n sockets: [],\n dynamic: [],\n});\nexport default apiContracts;\n"],"mappings":";;;;AAIA,MAAa,4BAA4B,KAAK,OAAO;CACnD,YAAY,KAAK,OAAO;EAAE,WAAW;EAAG,WAAW;CAAI,CAAC;CACxD,UAAU,KAAK,MAAM,CAAC,KAAK,QAAQ,UAAU,GAAG,KAAK,QAAQ,QAAQ,CAAC,CAAC;CACvE,SAAS,KAAK,QAAQ,OAAO;AAC/B,CAAC;AAG+C,KAAK,OAAO,EAC1D,IAAI,KAAK,OAAO;CAAE,WAAW;CAAG,WAAW;CAAK,aAAa;AAA4C,CAAC,EAC5G,CAAC;AACD,MAAa,eAAe,kBAAkB;CAC5C,SAAS;CACT,MAAM,CACJ;EACE,IAAI;EACJ,OAAO;EACP,UAAU;EACV,MAAM;EACN,QAAQ;EACR,gBAAgB;EAChB,aAAa;EACb,WAAW,iBAAiB,KAAK,MAAM,CAAC,wBAAwB,KAAK,KAAK,CAAC,CAAC,CAAC;CAC/E,GACA;EACE,IAAI;EACJ,OAAO;EACP,UAAU;EACV,MAAM;EACN,QAAQ;EACR,gBAAgB;EAChB,aAAa;EACb,MAAM;GAAE,UAAU;GAAM,aAAa;GAAoB,QAAQ;EAA0B;EAC3F,WAAW;GACT,GAAG,iBAAiB,KAAK,OAAO,EAAE,UAAU,KAAK,QAAQ,EAAE,CAAC,CAAC;GAC7D,OAAO,EAAE,aAAa,2BAA2B;EACnD;CACF,CACF;CACA,SAAS,CAAC;CACV,SAAS,CAAC;AACZ,CAAC"}
@@ -0,0 +1,144 @@
1
+ let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
2
+ //#region src/services/approvalRoot/type.ts
3
+ var ApprovalRequestError = class extends Error {
4
+ status;
5
+ constructor(message, status = 409) {
6
+ super(message);
7
+ this.status = status;
8
+ this.name = "ApprovalRequestError";
9
+ }
10
+ };
11
+ const APPROVAL_ROOT_SERVICE = (0, _agimon_ai_po_core_serverPlugin.defineServiceContract)("po/approval-root", { scope: "global" });
12
+ //#endregion
13
+ //#region src/services/approvalSession/index.ts
14
+ const OUTCOME_MESSAGE_TYPE = "approval-outcome";
15
+ function prompt(record) {
16
+ const { title, summary, details } = record.description;
17
+ return {
18
+ id: record.id,
19
+ toolCallId: record.toolCallId,
20
+ operation: record.operation,
21
+ requirement: record.requirement,
22
+ title,
23
+ summary,
24
+ ...details === void 0 ? {} : { details }
25
+ };
26
+ }
27
+ /** One session's view of the global queue: it submits only its own calls and runs only its own approved ones. */
28
+ function createApprovalSession(options) {
29
+ const { root, sessionId } = options;
30
+ const executors = /* @__PURE__ */ new Map();
31
+ const lifetime = new AbortController();
32
+ const binding = {
33
+ signal: lifetime.signal,
34
+ ready: (kind) => executors.has(kind),
35
+ run: (record, signal) => {
36
+ const executor = executors.get(record.operation.kind);
37
+ if (executor === void 0) throw new Error(`Nothing in this session can run ${record.operation.name}.`);
38
+ return executor({
39
+ approvalId: record.id,
40
+ operation: record.operation,
41
+ input: record.input,
42
+ ...record.argumentFormat === void 0 ? {} : { argumentFormat: record.argumentFormat }
43
+ }, signal);
44
+ },
45
+ deliver: async (record, text) => {
46
+ if (options.session?.admitMessage === void 0) throw new Error("This session cannot receive messages.");
47
+ await options.session.admitMessage({
48
+ type: OUTCOME_MESSAGE_TYPE,
49
+ text,
50
+ details: {
51
+ approvalId: record.id,
52
+ state: record.state
53
+ }
54
+ }, "steer", `approval:${record.id}:${record.state}`);
55
+ }
56
+ };
57
+ let detach;
58
+ const voiceTarget = async () => {
59
+ const pending = (await root.open(sessionId)).filter((record) => record.state === "pending");
60
+ return pending.length === 1 && pending[0].requirement === "ask" ? pending[0] : void 0;
61
+ };
62
+ return {
63
+ start() {
64
+ if (!lifetime.signal.aborted && detach === void 0) detach = root.attach(sessionId, binding);
65
+ },
66
+ service: {
67
+ async submit(request) {
68
+ if (request.sessionId !== sessionId) throw new Error("A session can only ask about its own calls.");
69
+ return root.submit(request);
70
+ },
71
+ registerExecutor(kind, run) {
72
+ executors.set(kind, run);
73
+ root.drain(sessionId);
74
+ return () => {
75
+ if (executors.get(kind) === run) executors.delete(kind);
76
+ };
77
+ }
78
+ },
79
+ async voiceCurrent() {
80
+ const record = await voiceTarget();
81
+ return record === void 0 ? void 0 : prompt(record);
82
+ },
83
+ async voiceAnswer(approvalId, decision) {
84
+ const record = await voiceTarget();
85
+ if (record?.id !== approvalId) return false;
86
+ try {
87
+ await root.decide(record.id, record.revision, decision === "approved" ? "approve" : "deny");
88
+ return true;
89
+ } catch {
90
+ return false;
91
+ }
92
+ },
93
+ withdraw: (id) => root.withdraw(sessionId, id),
94
+ async cards() {
95
+ return (await root.open(sessionId)).map((record) => ({
96
+ ...prompt(record),
97
+ revision: record.revision,
98
+ state: record.state,
99
+ ...record.sessionGone === true ? { sessionGone: true } : {},
100
+ ...record.sessionName === void 0 ? {} : { sessionName: record.sessionName.slice(0, 200) },
101
+ ...record.workspaceName === void 0 ? {} : { workspaceName: record.workspaceName.slice(0, 200) },
102
+ ...record.reason === void 0 ? {} : { reason: record.reason }
103
+ }));
104
+ },
105
+ onChanged(listener) {
106
+ return root.onChanged((changed) => {
107
+ if (changed === sessionId) listener();
108
+ });
109
+ },
110
+ async decide(id, revision, decision) {
111
+ if (!(await root.open(sessionId)).some((record) => record.id === id)) throw new ApprovalRequestError("This approval is no longer here.", 404);
112
+ await root.decide(id, revision, decision);
113
+ },
114
+ async dismiss(id) {
115
+ if (!(await root.open(sessionId)).some((record) => record.id === id)) throw new ApprovalRequestError("This approval is no longer here.", 404);
116
+ await root.dismiss(id);
117
+ },
118
+ dispose() {
119
+ lifetime.abort();
120
+ detach?.();
121
+ }
122
+ };
123
+ }
124
+ //#endregion
125
+ Object.defineProperty(exports, "APPROVAL_ROOT_SERVICE", {
126
+ enumerable: true,
127
+ get: function() {
128
+ return APPROVAL_ROOT_SERVICE;
129
+ }
130
+ });
131
+ Object.defineProperty(exports, "ApprovalRequestError", {
132
+ enumerable: true,
133
+ get: function() {
134
+ return ApprovalRequestError;
135
+ }
136
+ });
137
+ Object.defineProperty(exports, "createApprovalSession", {
138
+ enumerable: true,
139
+ get: function() {
140
+ return createApprovalSession;
141
+ }
142
+ });
143
+
144
+ //# sourceMappingURL=approvalSession-BAbRvyI-.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"approvalSession-BAbRvyI-.cjs","names":["defineServiceContract"],"sources":["../src/services/approvalRoot/type.ts","../src/services/approvalSession/index.ts"],"sourcesContent":["import type { PoApprovalOperation, PoApprovalRequest } from '@agimon-ai/po-core/approval';\nimport type { PoHubSessionService } from '@agimon-ai/po-core/hubChannel';\nimport { defineServiceContract } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { ApprovalRecord, ApprovalStore } from '../approvalStore/type';\n\n/** What a mounted session lends the root so approved calls run there and outcomes reach its agent. */\nexport interface ApprovalSessionBinding {\n /** True once an executor for this kind is registered; approved calls of other kinds wait. */\n ready(kind: PoApprovalOperation['kind']): boolean;\n run(record: ApprovalRecord, signal: AbortSignal): Promise<unknown>;\n /** Tells the agent the outcome. Resolves once the message is admitted. */\n deliver(record: ApprovalRecord, text: string): Promise<void>;\n /** Ends with the session, aborting a running call. */\n readonly signal: AbortSignal;\n}\n\nexport type ApprovalDecision = 'approve' | 'deny';\nexport type ApprovalOpenRecord = ApprovalRecord & {\n state: 'pending' | 'approved' | 'running' | 'interrupted';\n /** Derived from the host's session catalogue, never persisted or supplied by the client. */\n sessionGone?: true;\n /** The owning session's name and workspace folder, from the same catalogue, for Home. */\n sessionName?: string;\n workspaceName?: string;\n};\n\nexport class ApprovalRequestError extends Error {\n constructor(\n message: string,\n readonly status: 404 | 409 = 409,\n ) {\n super(message);\n this.name = 'ApprovalRequestError';\n }\n}\n\nexport interface ApprovalRootOptions {\n store: ApprovalStore;\n sessions?: Pick<PoHubSessionService, 'isLive' | 'dormant' | 'revive' | 'scopes'>;\n setPendingCount?(sessionId: string, count: number): void;\n onError: (error: unknown) => void;\n}\n\nexport interface ApprovalRoot {\n submit(request: PoApprovalRequest): Promise<{ readonly id: string }>;\n /** A mounted session attaches; its approved calls run and undelivered outcomes reach its agent. */\n attach(sessionId: string, binding: ApprovalSessionBinding): () => void;\n /** Runs what an attached session can run now, for example after an executor registers. */\n drain(sessionId: string): Promise<void>;\n /** The person's answer. Refuses a stale revision or an already decided request. */\n decide(id: string, revision: number, decision: ApprovalDecision): Promise<ApprovalRecord>;\n /** The agent takes back its own pending request. */\n withdraw(sessionId: string, id: string): Promise<ApprovalRecord | undefined>;\n /** The person clears a pending or approved call only when its session is gone. */\n dismiss(id: string, revision?: number): Promise<ApprovalRecord>;\n /** Pending, approved, running and not-yet-reported uncertain outcomes, oldest first, for Activity. */\n open(sessionId?: string): Promise<ApprovalOpenRecord[]>;\n onChanged(listener: (sessionId: string) => void): () => void;\n dispose(): void;\n}\n\nexport const APPROVAL_ROOT_SERVICE = defineServiceContract<ApprovalRoot>('po/approval-root', { scope: 'global' });\n","import type { PoApprovalExecutor, PoApprovalOperation, PoApprovalPrompt } from '@agimon-ai/po-core/approval';\n\nimport { ApprovalRequestError, type ApprovalSessionBinding } from '../approvalRoot/type';\nimport type { ApprovalRecord } from '../approvalStore/type';\nimport type { ApprovalSession, ApprovalSessionOptions } from './type';\n\nconst OUTCOME_MESSAGE_TYPE = 'approval-outcome';\n\nfunction prompt(record: ApprovalRecord): PoApprovalPrompt {\n const { title, summary, details } = record.description;\n return {\n id: record.id,\n toolCallId: record.toolCallId,\n operation: record.operation,\n requirement: record.requirement,\n title,\n summary,\n ...(details === undefined ? {} : { details }),\n };\n}\n\n/** One session's view of the global queue: it submits only its own calls and runs only its own approved ones. */\nexport function createApprovalSession(options: ApprovalSessionOptions): ApprovalSession {\n const { root, sessionId } = options;\n const executors = new Map<PoApprovalOperation['kind'], PoApprovalExecutor>();\n const lifetime = new AbortController();\n const binding: ApprovalSessionBinding = {\n signal: lifetime.signal,\n ready: (kind) => executors.has(kind),\n run: (record, signal) => {\n const executor = executors.get(record.operation.kind);\n if (executor === undefined) throw new Error(`Nothing in this session can run ${record.operation.name}.`);\n return executor(\n {\n approvalId: record.id,\n operation: record.operation,\n input: record.input,\n ...(record.argumentFormat === undefined ? {} : { argumentFormat: record.argumentFormat }),\n },\n signal,\n );\n },\n deliver: async (record, text) => {\n if (options.session?.admitMessage === undefined) throw new Error('This session cannot receive messages.');\n await options.session.admitMessage(\n { type: OUTCOME_MESSAGE_TYPE, text, details: { approvalId: record.id, state: record.state } },\n 'steer',\n `approval:${record.id}:${record.state}`,\n );\n },\n };\n let detach: (() => void) | undefined;\n const voiceTarget = async (): Promise<ApprovalRecord | undefined> => {\n const pending = (await root.open(sessionId)).filter((record) => record.state === 'pending');\n return pending.length === 1 && pending[0]!.requirement === 'ask' ? pending[0] : undefined;\n };\n return {\n start() {\n if (!lifetime.signal.aborted && detach === undefined) detach = root.attach(sessionId, binding);\n },\n service: {\n async submit(request) {\n if (request.sessionId !== sessionId) throw new Error('A session can only ask about its own calls.');\n return root.submit(request);\n },\n registerExecutor(kind, run) {\n executors.set(kind, run);\n void root.drain(sessionId);\n return () => {\n if (executors.get(kind) === run) executors.delete(kind);\n };\n },\n },\n async voiceCurrent() {\n const record = await voiceTarget();\n return record === undefined ? undefined : prompt(record);\n },\n async voiceAnswer(approvalId, decision) {\n const record = await voiceTarget();\n if (record?.id !== approvalId) return false;\n try {\n await root.decide(record.id, record.revision, decision === 'approved' ? 'approve' : 'deny');\n return true;\n } catch {\n // Answered elsewhere first, or changed meanwhile: this answer did nothing.\n return false;\n }\n },\n withdraw: (id) => root.withdraw(sessionId, id),\n async cards() {\n return (await root.open(sessionId)).map((record) => ({\n ...prompt(record),\n revision: record.revision,\n state: record.state,\n ...(record.sessionGone === true ? { sessionGone: true as const } : {}),\n // Home reads the same store, so live frames keep the names snapshots carry.\n ...(record.sessionName === undefined ? {} : { sessionName: record.sessionName.slice(0, 200) }),\n ...(record.workspaceName === undefined ? {} : { workspaceName: record.workspaceName.slice(0, 200) }),\n ...(record.reason === undefined ? {} : { reason: record.reason }),\n }));\n },\n onChanged(listener) {\n return root.onChanged((changed) => {\n if (changed === sessionId) listener();\n });\n },\n async decide(id, revision, decision) {\n // Only this session's own requests; an id from another session reads as gone.\n if (!(await root.open(sessionId)).some((record) => record.id === id))\n throw new ApprovalRequestError('This approval is no longer here.', 404);\n await root.decide(id, revision, decision);\n },\n async dismiss(id) {\n if (!(await root.open(sessionId)).some((record) => record.id === id))\n throw new ApprovalRequestError('This approval is no longer here.', 404);\n await root.dismiss(id);\n },\n dispose() {\n lifetime.abort();\n detach?.();\n },\n };\n}\n"],"mappings":"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"}