@agimon-ai/po-codemode 0.0.0-stage → 0.0.1-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 CHANGED
@@ -1,3 +1,83 @@
1
- # Temporary Holding Version
1
+ # @agimon-ai/po-codemode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Code mode for Po sessions: discover and exec over namespaces other packages contribute
4
+
5
+ This package is a composable [Po](https://www.npmjs.com/package/@agimon-ai/po) subsystem. Use it through native server composition in the distribution.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js 24 or newer
10
+ - `@earendil-works/pi-coding-agent` 1.3.0
11
+
12
+ ## Install
13
+
14
+ ```bash
15
+ pnpm add @agimon-ai/po-codemode
16
+ ```
17
+
18
+ The package declares poServer metadata for native server discovery. Include it through normal profile and domain composition.
19
+
20
+ ## Use
21
+
22
+ Run the registered command in the cockpit:
23
+
24
+ ```text
25
+ /po-codemode
26
+ ```
27
+
28
+ Show code mode namespaces
29
+
30
+ ## Package behavior
31
+
32
+ > Before publishing, replace this paragraph with one concrete, copy-pasteable example of the package-specific input, output, configuration, or workflow that is not already demonstrated by the generated command.
33
+
34
+ ## Help
35
+
36
+ The published package includes `llms.txt` and `src/prompts/po-use-codemode/SKILL.md`. Link additional prompts from `llms.txt` and declare them through named `resource/*.server.ts` routes using `defineResource`. Server lifecycle registration owns their disposal. Publish prompts under `src/prompts`, never export Markdown or copy it into `dist`.
37
+
38
+ ## Public API
39
+
40
+ ```ts
41
+ import { DefaultCodemodeExtensionService } from '@agimon-ai/po-codemode';
42
+ ```
43
+
44
+ The native server entry is also available at:
45
+
46
+ ```text
47
+ @agimon-ai/po-codemode/extensions/server
48
+ ```
49
+
50
+ The build generates host entrypoints in `generated/` from named `src/extensions` routes. Pure re-export modules in `src/exports` expose selected public capabilities. Keep typed authoring helpers in a dedicated subpath with no host/runtime imports so repository modules can bundle them cheaply.
51
+
52
+ ## Structure and lifecycle
53
+
54
+ - `extensions/`: path-routed host contracts. Every scanned file default-exports one typed `define*` declaration.
55
+ - `services/{serviceName}/`: package logic, with `index.ts` and `type.ts`.
56
+ - `models/`: host-neutral state and transitions.
57
+ - `constants/`, `schemas/`, and `types/`: shared metadata, validation, and contracts.
58
+ - Private `_lib/` and `_components/` folders beside routes hold surface-private implementation and are not scanned.
59
+
60
+ Use scoped `root.server.ts` `defineRoot` factories for shared dependencies, Cordis services and lifecycle. Put each tool, command, hook, method, API, resource, and presentation contribution in its own named routed file. Do not use catch-all entries, named exports in routes, or freeform route implementation.
61
+
62
+ Give each event one owner. Server plugins own session hooks and shared runtime services.
63
+
64
+ The lifecycle is construct, register, `onStart`, run, `onStop`, unregister, `onDispose`. All hooks are optional and receive one typed context. The helper awaits startup before readiness. Shutdown aborts the context signal, stops work, removes registrations in reverse order, and performs final cleanup. Failed startup awaits rollback. Optional provider replacement rebinds contributions without restarting the plugin. Minor-mode actions are independent of mounting.
65
+
66
+ Factories construct state; `onStart` begins external work. `onStop` runs when the start stage was reached, including a failed `onStart`. Use `onDispose` only for remaining instance resources. Do not add empty hooks or manual registration cleanup.
67
+
68
+ ## Development
69
+
70
+ ```bash
71
+ pnpm build
72
+ pnpm typecheck
73
+ pnpm test
74
+ pnpm lint
75
+ pnpm exec vibe-lint check .
76
+ npm pack --dry-run
77
+ ```
78
+
79
+ Maintained by [Agimon](https://agimon.ai/about).
80
+
81
+ ## License
82
+
83
+ Business Source License 1.1: free for personal use, organisations under USD 1M revenue, non-profits and education. See [LICENSE](LICENSE) and https://agimon.ai/licensing.
@@ -0,0 +1,17 @@
1
+ Object.defineProperties(exports, {
2
+ __esModule: { value: true },
3
+ [Symbol.toStringTag]: { value: "Module" }
4
+ });
5
+ //#region src/schemas/apiContracts.ts
6
+ /** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
7
+ const apiContracts = (0, require("@agimon-ai/po-core/apiContracts").defineApiContract)({
8
+ version: 1,
9
+ http: [],
10
+ sockets: [],
11
+ dynamic: []
12
+ });
13
+ //#endregion
14
+ exports.apiContracts = apiContracts;
15
+ exports.default = apiContracts;
16
+
17
+ //# sourceMappingURL=apiContracts.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.cjs","names":["defineApiContract"],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;;;;AAGA,MAAa,gBAAA,4CAAeA,CAAAA,CAAAA,kBAAAA,CAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
@@ -0,0 +1,53 @@
1
+ //#region src/schemas/apiContracts.d.ts
2
+ /** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
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":";;qBAGa"}
@@ -0,0 +1,13 @@
1
+ import { defineApiContract } from "@agimon-ai/po-core/apiContracts";
2
+ //#region src/schemas/apiContracts.ts
3
+ /** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */
4
+ const apiContracts = defineApiContract({
5
+ version: 1,
6
+ http: [],
7
+ sockets: [],
8
+ dynamic: []
9
+ });
10
+ //#endregion
11
+ export { apiContracts, apiContracts as default };
12
+
13
+ //# sourceMappingURL=apiContracts.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiContracts.mjs","names":[],"sources":["../src/schemas/apiContracts.ts"],"sourcesContent":["import { defineApiContract } from '@agimon-ai/po-core/apiContracts';\n\n/** This server plugin contributes agent tools, commands or lifecycle only, with no separate HTTP or socket surface. */\nexport const apiContracts = defineApiContract({ version: 1, http: [], sockets: [], dynamic: [] });\nexport default apiContracts;\n"],"mappings":";;;AAGA,MAAa,eAAe,kBAAkB;CAAE,SAAS;CAAG,MAAM,CAAC;CAAG,SAAS,CAAC;CAAG,SAAS,CAAC;AAAE,CAAC"}
@@ -0,0 +1,349 @@
1
+ let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
2
+ let typebox = require("typebox");
3
+ //#region src/services/codemodeRegistry/index.ts
4
+ /** The session's namespaces and script folders, in registration order. One name per session. */
5
+ function createCodemodeRegistry() {
6
+ const entries = /* @__PURE__ */ new Map();
7
+ const scripts = /* @__PURE__ */ new Set();
8
+ const listeners = /* @__PURE__ */ new Set();
9
+ const notify = () => {
10
+ for (const listener of listeners) listener();
11
+ };
12
+ return {
13
+ register(source, namespace) {
14
+ (0, _agimon_ai_po_core_codemode.assertCodemodeNamespaceName)(namespace.name);
15
+ const taken = entries.get(namespace.name);
16
+ if (taken) throw new Error(`Code-mode namespace "${namespace.name}" from ${source} is already registered by ${taken.source}.`);
17
+ const entry = {
18
+ source,
19
+ namespace
20
+ };
21
+ entries.set(namespace.name, entry);
22
+ notify();
23
+ return { dispose: () => {
24
+ if (entries.get(namespace.name) !== entry) return;
25
+ entries.delete(namespace.name);
26
+ notify();
27
+ } };
28
+ },
29
+ list: () => [...entries.values()].map((entry) => entry.namespace),
30
+ registerScripts(_source, entry) {
31
+ const owned = {
32
+ domain: entry.domain,
33
+ directory: entry.directory
34
+ };
35
+ scripts.add(owned);
36
+ notify();
37
+ return { dispose: () => void (scripts.delete(owned) && notify()) };
38
+ },
39
+ listScripts: () => [...scripts],
40
+ subscribe(listener) {
41
+ listeners.add(listener);
42
+ return () => listeners.delete(listener);
43
+ }
44
+ };
45
+ }
46
+ //#endregion
47
+ //#region src/schemas/codemodeTools.ts
48
+ const DiscoverToolSchema = typebox.Type.Object({
49
+ namespace: typebox.Type.Optional(typebox.Type.String({ description: "Show the full TypeScript declarations of one namespace." })),
50
+ query: typebox.Type.Optional(typebox.Type.String({ description: "Find matching members across every namespace." }))
51
+ });
52
+ const ExecToolSchema = typebox.Type.Object({
53
+ code: typebox.Type.String({ description: "TypeScript body of an async function. Top-level await and return work. The returned value, console output and image() calls come back." }),
54
+ timeoutMs: typebox.Type.Optional(typebox.Type.Integer({
55
+ minimum: 1e3,
56
+ maximum: 12e4,
57
+ description: "Deadline in milliseconds. Default 30000."
58
+ }))
59
+ });
60
+ //#endregion
61
+ //#region src/services/codemodeTools/index.ts
62
+ const DEFAULT_TIMEOUT_MS = 3e4;
63
+ const MAX_TIMEOUT_MS = 12e4;
64
+ const MIN_TIMEOUT_MS = 1e3;
65
+ const MAX_LOG_CHARS = 1e4;
66
+ const MAX_VALUE_CHARS = 65536;
67
+ const MAX_DECLARATION_CHARS = 12e3;
68
+ const MAX_QUERY_LINES = 40;
69
+ const MAX_LISTED_SCRIPTS = 20;
70
+ const MAX_IMAGES = 4;
71
+ const MAX_IMAGE_BYTES = 5242880;
72
+ const DEFAULT_IMAGE_MIME = "image/png";
73
+ const MEMBER_LINE = /^\s{2}(?:readonly\s+)?(\w+)\s*[(?:<]/u;
74
+ const GLOBALS_HELP = "Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). Return a value with `return`.";
75
+ const SCRIPTS_HELP = "Every exec run is saved. Call a saved script with `await (await import(specifier))(args)`; inside it, `args` is the argument and its `return` is the result.";
76
+ function text(value, isError = false) {
77
+ return {
78
+ content: [{
79
+ type: "text",
80
+ text: value
81
+ }],
82
+ ...isError ? { isError: true } : {}
83
+ };
84
+ }
85
+ function truncate(value, limit) {
86
+ return value.length <= limit ? value : `${value.slice(0, limit)}\n[truncated ${value.length - limit} chars]`;
87
+ }
88
+ function format(value) {
89
+ if (typeof value === "string") return value;
90
+ try {
91
+ const json = JSON.stringify(value, null, 2);
92
+ if (json !== void 0) return json;
93
+ } catch {}
94
+ return String(value);
95
+ }
96
+ function memberNames(namespace) {
97
+ const names = /* @__PURE__ */ new Set();
98
+ for (const line of namespace.declarations.split("\n")) {
99
+ const name = MEMBER_LINE.exec(line)?.[1];
100
+ if (name) names.add(name);
101
+ }
102
+ return [...names];
103
+ }
104
+ function bytesToBase64(bytes) {
105
+ let binary = "";
106
+ for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
107
+ return btoa(binary);
108
+ }
109
+ /** Collects what a script prints and the images it returns, within the output caps. */
110
+ function createOutput() {
111
+ const lines = [];
112
+ const images = [];
113
+ let imageBytes = 0;
114
+ const log = (level) => (...args) => {
115
+ const line = args.map(format).join(" ");
116
+ lines.push(level === "log" || level === "info" ? line : `[${level}] ${line}`);
117
+ };
118
+ const note = (message) => void lines.push(`[note] ${message}`);
119
+ const addImage = (input, mimeType) => {
120
+ if (typeof input === "object" && input !== null && "images" in input && Array.isArray(input.images)) {
121
+ for (const image of input.images) addImage(image);
122
+ return;
123
+ }
124
+ let data;
125
+ let mime = typeof mimeType === "string" ? mimeType : DEFAULT_IMAGE_MIME;
126
+ if (typeof input === "string") data = input.replace(/^data:([^;]+);base64,/u, (_match, type) => (mime = type, ""));
127
+ else if (ArrayBuffer.isView(input)) data = bytesToBase64(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));
128
+ else if (typeof input === "object" && input !== null && "data" in input && typeof input.data === "string") {
129
+ data = input.data;
130
+ if ("mimeType" in input && typeof input.mimeType === "string") mime = input.mimeType;
131
+ } else throw new TypeError("image() takes base64 text, bytes, or { data, mimeType }.");
132
+ if (images.length >= MAX_IMAGES) throw new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);
133
+ imageBytes += Math.ceil(data.length * 3 / 4);
134
+ if (imageBytes > MAX_IMAGE_BYTES) throw new RangeError("Images from one exec run exceed 5 MB.");
135
+ images.push({
136
+ data,
137
+ mimeType: mime
138
+ });
139
+ };
140
+ return {
141
+ console: {
142
+ log: log("log"),
143
+ info: log("info"),
144
+ warn: log("warn"),
145
+ error: log("error"),
146
+ debug: log("debug")
147
+ },
148
+ note,
149
+ addImage,
150
+ lines,
151
+ images
152
+ };
153
+ }
154
+ /** The session's active domains; every registered domain when the host reports none. */
155
+ function activeDomains(execution) {
156
+ return execution?.selection?.domains;
157
+ }
158
+ function toResult(result, output, saved) {
159
+ const content = [];
160
+ if (output.lines.length > 0) content.push({
161
+ type: "text",
162
+ text: truncate(output.lines.join("\n"), MAX_LOG_CHARS)
163
+ });
164
+ if (result.ok) {
165
+ if (ArrayBuffer.isView(result.value)) content.push({
166
+ type: "text",
167
+ text: "The script returned bytes. Pass them to image(data, mimeType) instead."
168
+ });
169
+ else if (result.value !== void 0) content.push({
170
+ type: "text",
171
+ text: truncate(format(result.value), MAX_VALUE_CHARS)
172
+ });
173
+ } else {
174
+ const { kind, name, message } = result.error;
175
+ const hint = kind === "timeout" ? " Raise timeoutMs or split the work into smaller exec calls." : "";
176
+ content.push({
177
+ type: "text",
178
+ text: `${name}: ${message}${hint}`
179
+ });
180
+ }
181
+ if (content.length === 0) content.push({
182
+ type: "text",
183
+ text: "(no return value)"
184
+ });
185
+ if (saved !== void 0) content.push({
186
+ type: "text",
187
+ text: saved
188
+ });
189
+ for (const image of output.images) content.push({
190
+ type: "image",
191
+ data: image.data,
192
+ mimeType: image.mimeType
193
+ });
194
+ return {
195
+ content,
196
+ ...result.ok ? {} : { isError: true }
197
+ };
198
+ }
199
+ function sleep(ms, signal) {
200
+ return new Promise((resolve, reject) => {
201
+ if (signal.aborted) return reject(/* @__PURE__ */ new Error("Run ended."));
202
+ const timer = setTimeout(resolve, Math.max(0, ms));
203
+ signal.addEventListener("abort", () => {
204
+ clearTimeout(timer);
205
+ reject(/* @__PURE__ */ new Error("Run ended."));
206
+ }, { once: true });
207
+ });
208
+ }
209
+ /** `discover` and `exec` for one session, over the namespaces its packages contributed. */
210
+ function createCodemodeTools({ registry, isolate, scripts }) {
211
+ let busy = false;
212
+ const visible = (service) => registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);
213
+ return {
214
+ discover: {
215
+ name: "discover",
216
+ label: "Discover",
217
+ description: "List the code-mode namespaces and reusable scripts you can use from `exec`, show one namespace in full, or search members and scripts. Not required before exec: its description already names the namespaces.",
218
+ parameters: DiscoverToolSchema,
219
+ promptSnippet: "List code-mode namespaces and their TypeScript declarations",
220
+ executionMode: "parallel",
221
+ async execute(_toolCallId, parameters, _signal, _onUpdate, execution) {
222
+ const service = isolate();
223
+ if (!service) return text("Code mode is not available on this host.", true);
224
+ const namespaces = visible(service);
225
+ const listed = scripts && service.liveObjects ? await scripts.list(activeDomains(execution)) : [];
226
+ if (parameters.namespace !== void 0) {
227
+ const found = namespaces.find((namespace) => namespace.name === parameters.namespace);
228
+ if (!found) {
229
+ const names = namespaces.map((namespace) => namespace.name).join(", ") || "none";
230
+ return text(`Unknown namespace "${parameters.namespace}". Registered: ${names}.`, true);
231
+ }
232
+ return text(truncate(found.declarations, MAX_DECLARATION_CHARS));
233
+ }
234
+ if (parameters.query !== void 0) {
235
+ const needle = parameters.query.toLowerCase();
236
+ const hits = [];
237
+ for (const namespace of namespaces) {
238
+ const lines = namespace.declarations.split("\n");
239
+ lines.forEach((line, index) => {
240
+ if (!line.toLowerCase().includes(needle) || hits.length >= MAX_QUERY_LINES) return;
241
+ const doc = lines[index - 1]?.trim().startsWith("/**") ? `${lines[index - 1]?.trim()} ` : "";
242
+ hits.push(`${namespace.name}: ${doc}${line.trim()}`);
243
+ });
244
+ }
245
+ for (const script of listed) {
246
+ if (hits.length >= MAX_QUERY_LINES) break;
247
+ if (`${script.specifier} ${script.description}`.toLowerCase().includes(needle)) hits.push(`script ${script.specifier}: ${script.description}`);
248
+ }
249
+ return text(hits.length > 0 ? hits.join("\n") : `No members or scripts match "${parameters.query}".`);
250
+ }
251
+ const sections = [];
252
+ if (namespaces.length === 0) sections.push("No namespaces are registered in this session.");
253
+ for (const namespace of namespaces) sections.push(`- ${namespace.name}: ${namespace.summary}\n members: ${memberNames(namespace).join(", ")}`);
254
+ sections.push(GLOBALS_HELP);
255
+ if (!service.liveObjects) sections.push("This host runs plain JavaScript with JSON-only functions.");
256
+ if (listed.length > 0) {
257
+ sections.push(`Scripts. ${SCRIPTS_HELP}`);
258
+ for (const script of listed.slice(0, MAX_LISTED_SCRIPTS)) sections.push(`- ${script.specifier}${script.description ? `: ${script.description}` : ""}`);
259
+ if (listed.length > MAX_LISTED_SCRIPTS) sections.push(`...and ${listed.length - MAX_LISTED_SCRIPTS} more; use discover({ query }) to search.`);
260
+ }
261
+ if (namespaces.length > 0) sections.push("Call discover({ namespace }) for full types.");
262
+ return text(sections.join("\n"));
263
+ }
264
+ },
265
+ exec: {
266
+ name: "exec",
267
+ label: "Exec",
268
+ get description() {
269
+ const service = isolate();
270
+ return [
271
+ "Run a TypeScript script inside the Po server with live objects from the namespaces below in scope.",
272
+ "It runs with full server trust, like bash. Keep each call to one logical step.",
273
+ (service ? visible(service) : []).map((namespace) => `- ${namespace.name}: ${namespace.summary}`).join("\n") || "(no namespaces registered yet; call discover to check)",
274
+ GLOBALS_HELP,
275
+ ...scripts && service?.liveObjects ? [`${SCRIPTS_HELP} discover lists saved and domain scripts.`] : [],
276
+ "Use discover({ namespace }) for full signatures when needed."
277
+ ].join("\n");
278
+ },
279
+ parameters: ExecToolSchema,
280
+ promptSnippet: "Run a TypeScript script against live Po objects (browser and other namespaces)",
281
+ executionMode: "serial",
282
+ async execute(_toolCallId, parameters, signal, _onUpdate, execution) {
283
+ const service = isolate();
284
+ if (!service) return text("Code mode is not available on this host.", true);
285
+ if (busy) return text("Another exec run is still active in this session. Wait for it to finish.", true);
286
+ busy = true;
287
+ const controller = new AbortController();
288
+ const runSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
289
+ const cleanups = [];
290
+ const output = createOutput();
291
+ const run = {
292
+ sessionId: execution.sessionId,
293
+ signal: runSignal,
294
+ onDispose: (cleanup) => void cleanups.push(cleanup)
295
+ };
296
+ try {
297
+ let saved;
298
+ try {
299
+ const file = await scripts?.save(parameters.code);
300
+ if (file) saved = `Saved as ${file.specifier} (${file.path})`;
301
+ } catch (error) {
302
+ output.note(`Could not save the script: ${error instanceof Error ? error.message : String(error)}`);
303
+ }
304
+ const globals = {
305
+ console: output.console,
306
+ image: output.addImage,
307
+ sleep: (ms) => sleep(ms, runSignal)
308
+ };
309
+ const deny = /* @__PURE__ */ new Set();
310
+ for (const namespace of visible(service)) {
311
+ globals[namespace.name] = namespace.bind(run);
312
+ for (const member of namespace.deny ?? []) deny.add(member);
313
+ }
314
+ const deadlineMs = Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS));
315
+ return toResult(await service.run({
316
+ source: parameters.code,
317
+ globals,
318
+ deadlineMs,
319
+ signal: runSignal,
320
+ deny: [...deny],
321
+ onDiagnostic: output.note,
322
+ ...scripts ? { resolveImport: (specifier) => scripts.resolve(specifier, activeDomains(execution)) } : {}
323
+ }), output, saved);
324
+ } catch (error) {
325
+ return text(`Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`, true);
326
+ } finally {
327
+ controller.abort();
328
+ for (const cleanup of cleanups.reverse()) await Promise.resolve().then(cleanup).catch((error) => output.note(`cleanup failed: ${String(error)}`));
329
+ busy = false;
330
+ }
331
+ }
332
+ }
333
+ };
334
+ }
335
+ //#endregion
336
+ Object.defineProperty(exports, "createCodemodeRegistry", {
337
+ enumerable: true,
338
+ get: function() {
339
+ return createCodemodeRegistry;
340
+ }
341
+ });
342
+ Object.defineProperty(exports, "createCodemodeTools", {
343
+ enumerable: true,
344
+ get: function() {
345
+ return createCodemodeTools;
346
+ }
347
+ });
348
+
349
+ //# sourceMappingURL=codemodeTools-BX2qieCR.cjs.map