@agimon-ai/po-codemode 0.0.1-alpha.4 → 0.0.1-alpha.40

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@agimon-ai/po-codemode",
3
- "version": "0.0.1-alpha.4",
3
+ "version": "0.0.1-alpha.40",
4
4
  "description": "Code mode for Po sessions: discover and exec over namespaces other packages contribute",
5
5
  "keywords": [
6
6
  "ai",
@@ -38,6 +38,9 @@
38
38
  "import": "./dist/apiContracts.mjs",
39
39
  "require": "./dist/apiContracts.cjs"
40
40
  },
41
+ "./extensions/native": {
42
+ "import": "./dist/extensions/native.mjs"
43
+ },
41
44
  "./extensions/server": {
42
45
  "types": "./dist/extensions/server.d.mts",
43
46
  "import": "./dist/extensions/server.mjs",
@@ -52,38 +55,61 @@
52
55
  "access": "public"
53
56
  },
54
57
  "dependencies": {
55
- "@agimon-ai/po-config": "0.0.0-alpha.31",
56
- "@agimon-ai/po-core": "0.0.0-alpha.31",
57
- "@agimon-ai/po-web-components": "0.0.0-alpha.31",
58
+ "@agimon-ai/po-config": "0.0.0-alpha.67",
59
+ "@agimon-ai/po-core": "0.0.0-alpha.67",
60
+ "@agimon-ai/po-web-components": "0.0.0-alpha.67",
58
61
  "@deepseek-ai/cordis": "4.0.5",
59
- "react": "19.3.0",
60
- "typebox": "1.3.37"
62
+ "react": "19.3.1",
63
+ "typebox": "1.4.2"
61
64
  },
62
65
  "devDependencies": {
63
- "@agimon-ai/po-build": "0.0.0-alpha.31",
64
- "@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.31",
65
- "@agimon-ai/vibe-lint-plugin-po-web": "0.0.0-alpha.31",
66
- "@earendil-works/pi-coding-agent": "1.3.0",
66
+ "@agimon-ai/po-build": "0.0.0-alpha.67",
67
+ "@agimon-ai/po-native-components": "0.0.0-alpha.67",
68
+ "@agimon-ai/vibe-lint-plugin-po-extension": "0.0.0-alpha.67",
69
+ "@agimon-ai/vibe-lint-plugin-po-web": "0.0.0-alpha.67",
70
+ "@earendil-works/pi-coding-agent": "1.4.0",
67
71
  "@types/node": "26.6.5",
68
72
  "@types/react": "19.3.0",
69
73
  "@types/react-dom": "19.3.0",
70
74
  "@vitest/coverage-v8": "5.0.4",
71
- "react-dom": "19.3.0",
75
+ "react-dom": "19.3.1",
76
+ "react-native": "0.88.0",
77
+ "react-native-unistyles": "3.5.3",
72
78
  "tsdown": "0.23.1",
73
79
  "typescript": "7.0.2",
74
80
  "vitest": "5.0.4"
75
81
  },
76
82
  "peerDependencies": {
77
- "@earendil-works/pi-coding-agent": "1.3.0"
83
+ "@agimon-ai/po-native-components": "0.0.0-alpha.67",
84
+ "@earendil-works/pi-coding-agent": "1.4.0",
85
+ "react-native": "0.88.0",
86
+ "react-native-unistyles": "^3.5.3"
78
87
  },
79
88
  "peerDependenciesMeta": {
89
+ "@agimon-ai/po-native-components": {
90
+ "optional": true
91
+ },
80
92
  "@earendil-works/pi-coding-agent": {
81
93
  "optional": true
94
+ },
95
+ "react-native": {
96
+ "optional": true
97
+ },
98
+ "react-native-unistyles": {
99
+ "optional": true
82
100
  }
83
101
  },
84
102
  "engines": {
85
103
  "node": ">=24"
86
104
  },
105
+ "poNative": {
106
+ "pluginId": "codemode",
107
+ "channels": [],
108
+ "client": "./dist/extensions/native.mjs",
109
+ "scopes": [
110
+ "session"
111
+ ]
112
+ },
87
113
  "poServer": {
88
114
  "entry": "./generated/server.ts",
89
115
  "dist": "./dist/extensions/server.mjs",
@@ -111,7 +137,7 @@
111
137
  "scripts": {
112
138
  "build": "tsdown",
113
139
  "test": "vitest --run",
114
- "typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.web.json",
140
+ "typecheck": "tsrs --noEmit && tsrs --noEmit -p tsconfig.web.json && tsrs --noEmit -p tsconfig.native.json",
115
141
  "lint": "oxlint . && oxfmt . --check",
116
142
  "fixcode": "oxlint . --fix && oxfmt ."
117
143
  }
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: codemode-how-to-llm
3
- description: 'Use the llm namespace inside exec for one-shot text and schema-checked JSON transformations and pipelines.'
3
+ description: 'Have a model classify, extract or summarize data inside a script, with JSON output checked against a schema. Use when a script step needs judgement over many items or messy text; answer directly when no script needs the result.'
4
4
  ---
5
5
 
6
6
  # Use LLM transformations
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: codemode-how-to-shell
3
- description: 'Use shell.bash inside exec for short deadline-bound Bash commands whose output needs code-side post-processing.'
3
+ description: 'Run a quick command inside a script and work with its output as data. Use when command output needs parsing or filtering in code; use the bash tool for long-running, interactive or visible commands.'
4
4
  ---
5
5
 
6
6
  # Short Bash commands in code mode
@@ -1,11 +1,11 @@
1
1
  ---
2
2
  name: how-to-codemode
3
- description: 'Use @agimon-ai/po-codemode: run TypeScript against live Po objects with the discover and exec tools. Use when a task needs several steps on a namespace such as browser in one call.'
3
+ description: 'Do multi-step work in one call: script loops, filtering and chained calls across live namespaces in exec instead of many separate tool calls. Use when a task repeats a tool, combines namespaces, or needs a long-running workflow.'
4
4
  ---
5
5
 
6
6
  # Use code mode
7
7
 
8
- Code mode gives you two tools.
8
+ Code mode gives you two foreground tools, plus background execution on Node hosts.
9
9
 
10
10
  - `discover`: with no arguments, lists the namespaces this session has (for example `browser`) and their members, plus reusable scripts from the active domains and this session's saved scripts (capped, newest first). `discover({ namespace })` shows full TypeScript declarations; `discover({ query })` finds members, script names and script descriptions.
11
11
  - `exec`: runs a TypeScript async function body. Namespaces are in scope as globals. `return` a value, use `console.log` for notes, `image(data, mimeType)` to send back a screenshot, and `sleep(ms)` to wait.
@@ -39,21 +39,34 @@ const { default: isNumber } = await import('npm:is-number@7');
39
39
  return isNumber(42);
40
40
  ```
41
41
 
42
- Packages auto-install through upm on first use with no approval prompt. Registry names, scoped names, versions, ranges, tags and package subpaths are supported. URLs, git, file dependencies, aliases and traversal are rejected. Use a larger `timeoutMs` for the first install. The shared store follows the existing two-day release-age policy; exact or locked versions bypass it. Lifecycle scripts are skipped.
42
+ Packages auto-install through upm on first use with no approval prompt. Every session uses the hub's single install project, `<PO_HOME>/runtime`, and its shared store. One selector per package name is allowed: a conflicting version or a Po-managed dependency is refused rather than replaced. Imports serialize with `po sync`; if sync removes an import, the next import restores it from the store. Registry names, scoped names, versions, ranges, tags and package subpaths are supported. URLs, git, file dependencies, aliases and traversal are rejected. Use a larger `timeoutMs` for the first install. The shared store follows the existing two-day release-age policy; exact or locked versions bypass it. Lifecycle scripts are skipped.
43
43
 
44
44
  npm modules retain their real namespace exports, including `.default`. Constructors work with `new`; subclassing and `instanceof` are unsupported. Package code has full Node authority, even though `require`, `process` and `fetch` are absent from script globals. It is not a security boundary: synchronous package code cannot be preempted and opened resources are not automatically closed. Cancellation cannot stop an upm install, but prevents importing its result. Edge hosts do not support imports.
45
45
 
46
46
  For model transformations inside scripts, discover `llm` and load `codemode-how-to-llm`.
47
47
 
48
+ ## Background execution (Node only)
49
+
50
+ Use `exec_background({ code, timeoutMs? })` for orchestration that outlives foreground exec, such as Mastra workflows awaiting `team.run`. It returns `{ id }` immediately. End the turn: one `po-codemode-finished` message will contain the bounded result and logs after namespace and child cleanup. Do not poll. Images and recorded calls remain in the message's result details.
51
+
52
+ - Default deadline: 30 minutes. Maximum: 2 hours. Foreground and background share eight execution slots.
53
+ - `exec_cancel({ id, reason? })` stops an owned job; its terminal message follows cleanup.
54
+ - The job survives the launching tool's signal, but stops on deadline, explicit cancellation or session close. The workflow step stays open through child cleanup and completion-message admission.
55
+ - Background scripts are in memory, not resumable. After restart, retry from prepared artifacts; their awaited children are interrupted, not resumed.
56
+ - Both background tools are main-agent-only. `team.run` children also lack `exec` and `discover`.
57
+ - Catch errors **inside callbacks** passed to imported packages and return explicit failure objects. The membrane logs callback throws/rejections and returns `undefined`, so throwing is not a reliable workflow failure channel. Check child statuses and artifact results rather than trusting only the workflow engine's success flag.
58
+ - Mastra `npm:@mastra/core@1.78.0/workflows` with `npm:zod@3.25.76` passed the compatibility spike. Use `await workflow.createRun()`, then `run.start(...)`. Bound live children with `.foreach(step, { concurrency: 3 })`, awaiting each `team.run` and each sequential phase.
59
+
48
60
  ## Promote a script
49
61
 
50
- To keep a useful script, copy the saved file with normal file tools to `plugins/<domain>/codemode/<name>.ts`. Start it with a `/** ... */` comment whose first paragraph says what it does and what `args` it takes; `discover` shows that paragraph. Sessions with that domain active then call it as `<domain>/<name>`.
62
+ To keep a useful script, copy the saved file with normal file tools to `plugins/<domain>/codemode/<name>.ts`. Start it with a `/** ... */` comment whose first paragraph says what it does and what `args` it takes; `discover` shows that paragraph. Sessions with that domain active see its name in the `exec` description and call it as `<domain>/<name>`.
51
63
 
52
64
  ## Rules
53
65
 
54
66
  - Keep each `exec` call to one logical step, then look at the result before the next.
55
- - Script code stops at its deadline (30 s by default, `timeoutMs` up to 120 s), including its loops and recursion. Native npm code is not preemptible.
67
+ - Foreground script code stops at its deadline (30 s by default, `timeoutMs` up to 120 s), including its loops and recursion. Background scripts have a longer asynchronous deadline, not a longer synchronous budget. Native npm code is not preemptible.
56
68
  - Objects you get from a namespace are live. Listeners you add and the objects themselves stop working when the run ends; keep state in the namespace, not in script variables.
57
69
  - `exec` runs inside the Po server with full trust, like `bash`. Do not use it to bypass a blocked tool.
70
+ - A member `discover` marks `(asks first)` or `(needs the person)` never waits. When the person must decide, the call is recorded and throws `ApprovalPendingError` (check `error.name`; it carries `approvalId`), and the exec result lists what waits. Catch it, keep working, and do not retry: the call runs once with the same first argument after Approve, and its outcome arrives as a message. Pass only JSON in that argument. Take back a request you no longer need with `approval_withdraw`.
58
71
  - There is no `eval`, `Function`, `setTimeout`, `fetch`, `require` or `process` inside a script.
59
- - Subagents have `exec` too, and up to 8 runs can overlap across you and them. Namespaces are shared, so a run sees the pages and tasks another agent made.
72
+ - Ordinary subagents may have `exec`, subject to their restrictions. Awaited `team.run` children do not. Up to 8 foreground/background runs can overlap. Namespaces are shared, so a run sees the pages and tasks another agent made.
@@ -1,432 +0,0 @@
1
- let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
2
- let _agimon_ai_po_core_headless = require("@agimon-ai/po-core/headless");
3
- let typebox = require("typebox");
4
- //#region src/services/codemodeRegistry/index.ts
5
- /** The session's namespaces and script folders, in registration order. One name per session. */
6
- function createCodemodeRegistry() {
7
- const entries = /* @__PURE__ */ new Map();
8
- const scripts = /* @__PURE__ */ new Set();
9
- const listeners = /* @__PURE__ */ new Set();
10
- const notify = () => {
11
- for (const listener of listeners) listener();
12
- };
13
- return {
14
- register(source, namespace) {
15
- (0, _agimon_ai_po_core_codemode.assertCodemodeNamespaceName)(namespace.name);
16
- const taken = entries.get(namespace.name);
17
- if (taken) throw new Error(`Code-mode namespace "${namespace.name}" from ${source} is already registered by ${taken.source}.`);
18
- const entry = {
19
- source,
20
- namespace
21
- };
22
- entries.set(namespace.name, entry);
23
- notify();
24
- return { dispose: () => {
25
- if (entries.get(namespace.name) !== entry) return;
26
- entries.delete(namespace.name);
27
- notify();
28
- } };
29
- },
30
- list: () => [...entries.values()].map((entry) => entry.namespace),
31
- registerScripts(_source, entry) {
32
- const owned = {
33
- domain: entry.domain,
34
- directory: entry.directory
35
- };
36
- scripts.add(owned);
37
- notify();
38
- return { dispose: () => void (scripts.delete(owned) && notify()) };
39
- },
40
- listScripts: () => [...scripts],
41
- subscribe(listener) {
42
- listeners.add(listener);
43
- return () => listeners.delete(listener);
44
- }
45
- };
46
- }
47
- //#endregion
48
- //#region src/schemas/codemodeTools.ts
49
- const DiscoverToolSchema = typebox.Type.Object({
50
- namespace: typebox.Type.Optional(typebox.Type.String({ description: "Show the full TypeScript declarations of one namespace." })),
51
- query: typebox.Type.Optional(typebox.Type.String({ description: "Find matching members across every namespace." }))
52
- });
53
- const ExecToolSchema = typebox.Type.Object({
54
- 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." }),
55
- timeoutMs: typebox.Type.Optional(typebox.Type.Integer({
56
- minimum: 1e3,
57
- maximum: 12e4,
58
- description: "Deadline in milliseconds. Default 30000."
59
- }))
60
- });
61
- //#endregion
62
- //#region src/services/codemodeTools/index.ts
63
- const DEFAULT_TIMEOUT_MS = 3e4;
64
- const MAX_TIMEOUT_MS = 12e4;
65
- const MIN_TIMEOUT_MS = 1e3;
66
- const MAX_LOG_CHARS = 1e4;
67
- const MAX_VALUE_CHARS = 65536;
68
- const MAX_DECLARATION_CHARS = 24e3;
69
- const MAX_QUERY_LINES = 40;
70
- const MAX_CONCURRENT_RUNS = 8;
71
- const MAX_RECORDED_CALLS = 50;
72
- const MAX_RECORDED_TEXT = 8e3;
73
- const MAX_RECORDED_JSON = 16e3;
74
- const MAX_LISTED_SCRIPTS = 20;
75
- const MAX_IMAGES = 4;
76
- const MAX_IMAGE_BYTES = 5242880;
77
- const DEFAULT_IMAGE_MIME = "image/png";
78
- const MEMBER_LINE = /^\s{2}(?:readonly\s+)?(\w+)\s*[(?:<]/u;
79
- const GLOBALS_HELP = "Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). Return a value with `return`.";
80
- 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.";
81
- function text(value, isError = false) {
82
- return {
83
- content: [{
84
- type: "text",
85
- text: value
86
- }],
87
- ...isError ? { isError: true } : {}
88
- };
89
- }
90
- function truncate(value, limit) {
91
- return value.length <= limit ? value : `${value.slice(0, limit)}\n[truncated ${value.length - limit} chars]`;
92
- }
93
- function format(value) {
94
- if (typeof value === "string") return value;
95
- try {
96
- const json = JSON.stringify(value, null, 2);
97
- if (json !== void 0) return json;
98
- } catch {}
99
- return String(value);
100
- }
101
- function memberNames(namespace) {
102
- const names = /* @__PURE__ */ new Set();
103
- const declaration = new RegExp(`^declare const ${namespace.name}: \\{([\\s\\S]*?)^\\};`, "mu").exec(namespace.declarations)?.[1] ?? "";
104
- for (const line of declaration.split("\n")) {
105
- const name = MEMBER_LINE.exec(line)?.[1];
106
- if (name) names.add(name);
107
- }
108
- return [...names];
109
- }
110
- function bytesToBase64(bytes) {
111
- let binary = "";
112
- for (let index = 0; index < bytes.length; index += 32768) binary += String.fromCharCode(...bytes.subarray(index, index + 32768));
113
- return btoa(binary);
114
- }
115
- /** Collects what a script prints and the images it returns, within the output caps. */
116
- function createOutput() {
117
- const lines = [];
118
- const images = [];
119
- let imageBytes = 0;
120
- const log = (level) => (...args) => {
121
- const line = args.map(format).join(" ");
122
- lines.push(level === "log" || level === "info" ? line : `[${level}] ${line}`);
123
- };
124
- const note = (message) => void lines.push(`[note] ${message}`);
125
- const addImage = (input, mimeType) => {
126
- if (typeof input === "object" && input !== null && "images" in input && Array.isArray(input.images)) {
127
- for (const image of input.images) addImage(image);
128
- return;
129
- }
130
- let data;
131
- let mime = typeof mimeType === "string" ? mimeType : DEFAULT_IMAGE_MIME;
132
- if (typeof input === "string") data = input.replace(/^data:([^;]+);base64,/u, (_match, type) => (mime = type, ""));
133
- else if (ArrayBuffer.isView(input)) data = bytesToBase64(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));
134
- else if (typeof input === "object" && input !== null && "data" in input && typeof input.data === "string") {
135
- data = input.data;
136
- if ("mimeType" in input && typeof input.mimeType === "string") mime = input.mimeType;
137
- } else throw new TypeError("image() takes base64 text, bytes, or { data, mimeType }.");
138
- if (images.length >= MAX_IMAGES) throw new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);
139
- imageBytes += Math.ceil(data.length * 3 / 4);
140
- if (imageBytes > MAX_IMAGE_BYTES) throw new RangeError("Images from one exec run exceed 5 MB.");
141
- const invalid = (0, _agimon_ai_po_core_headless.invalidImageReason)(data, mime);
142
- if (invalid !== void 0) throw new TypeError(`image() rejected an undecodable image: ${invalid}.`);
143
- images.push({
144
- data,
145
- mimeType: mime
146
- });
147
- };
148
- return {
149
- console: {
150
- log: log("log"),
151
- info: log("info"),
152
- warn: log("warn"),
153
- error: log("error"),
154
- debug: log("debug")
155
- },
156
- note,
157
- addImage,
158
- lines,
159
- images
160
- };
161
- }
162
- /** The session's active domains; every registered domain when the host reports none. */
163
- function activeDomains(execution) {
164
- return execution?.selection?.domains;
165
- }
166
- /** A JSON copy of `value`, or undefined when it does not serialise or is larger than `limit` characters. */
167
- function bounded(value, limit) {
168
- try {
169
- const json = JSON.stringify(value);
170
- return json !== void 0 && json.length <= limit ? JSON.parse(json) : void 0;
171
- } catch {
172
- return;
173
- }
174
- }
175
- /** The call as it is kept in the transcript: text blocks only, clipped, with args and details dropped when large. */
176
- function recordedCall(call) {
177
- const content = (call.result?.content ?? []).flatMap((block) => {
178
- const { type, text } = block ?? {};
179
- return type === "text" && typeof text === "string" ? [{
180
- type: "text",
181
- text: truncate(text, MAX_RECORDED_TEXT)
182
- }] : [];
183
- });
184
- const details = bounded(call.result?.details, MAX_RECORDED_JSON);
185
- return {
186
- name: call.name,
187
- tool: call.tool,
188
- args: bounded(call.args, MAX_RECORDED_JSON) ?? {},
189
- ok: call.ok,
190
- ms: Math.max(0, Math.round(call.ms)),
191
- ...call.error === void 0 ? {} : { error: truncate(call.error, MAX_RECORDED_TEXT) },
192
- ...call.result === void 0 ? {} : { result: {
193
- content,
194
- ...details === void 0 ? {} : { details }
195
- } }
196
- };
197
- }
198
- function toResult(result, output, saved, calls) {
199
- const content = [];
200
- if (output.lines.length > 0) content.push({
201
- type: "text",
202
- text: truncate(output.lines.join("\n"), MAX_LOG_CHARS)
203
- });
204
- if (result.ok) {
205
- if (ArrayBuffer.isView(result.value)) content.push({
206
- type: "text",
207
- text: "The script returned bytes. Pass them to image(data, mimeType) instead."
208
- });
209
- else if (result.value !== void 0) content.push({
210
- type: "text",
211
- text: truncate(format(result.value), MAX_VALUE_CHARS)
212
- });
213
- } else {
214
- const { kind, name, message } = result.error;
215
- const hint = kind === "timeout" ? " Raise timeoutMs or split the work into smaller exec calls." : "";
216
- content.push({
217
- type: "text",
218
- text: `${name}: ${message}${hint}`
219
- });
220
- }
221
- if (content.length === 0) content.push({
222
- type: "text",
223
- text: "(no return value)"
224
- });
225
- if (saved !== void 0) content.push({
226
- type: "text",
227
- text: saved
228
- });
229
- for (const image of output.images) content.push({
230
- type: "image",
231
- data: image.data,
232
- mimeType: image.mimeType
233
- });
234
- return {
235
- content,
236
- ...calls.length > 0 ? { details: { calls } } : {},
237
- ...result.ok ? {} : { isError: true }
238
- };
239
- }
240
- function sleep(ms, signal) {
241
- return new Promise((resolve, reject) => {
242
- if (signal.aborted) return reject(/* @__PURE__ */ new Error("Run ended."));
243
- const timer = setTimeout(resolve, Math.max(0, ms));
244
- signal.addEventListener("abort", () => {
245
- clearTimeout(timer);
246
- reject(/* @__PURE__ */ new Error("Run ended."));
247
- }, { once: true });
248
- });
249
- }
250
- /** `discover` and `exec` for one session, over the namespaces its packages contributed. */
251
- function createCodemodeTools({ registry, isolate, scripts, npm }) {
252
- let running = 0;
253
- const visible = (service) => registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);
254
- return {
255
- discover: {
256
- name: "discover",
257
- label: "Discover",
258
- 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.",
259
- parameters: DiscoverToolSchema,
260
- promptSnippet: "List code-mode namespaces and their TypeScript declarations",
261
- executionMode: "parallel",
262
- async execute(_toolCallId, parameters, _signal, _onUpdate, execution) {
263
- const service = isolate();
264
- if (!service) return text("Code mode is not available on this host.", true);
265
- const namespaces = visible(service);
266
- const listed = scripts && service.liveObjects ? await scripts.list(activeDomains(execution)) : [];
267
- if (parameters.namespace !== void 0) {
268
- const found = namespaces.find((namespace) => namespace.name === parameters.namespace);
269
- if (!found) {
270
- const names = namespaces.map((namespace) => namespace.name).join(", ") || "none";
271
- return text(`Unknown namespace "${parameters.namespace}". Registered: ${names}.`, true);
272
- }
273
- return text(truncate(found.declarations, MAX_DECLARATION_CHARS));
274
- }
275
- if (parameters.query !== void 0) {
276
- const needle = parameters.query.toLowerCase();
277
- const hits = [];
278
- for (const namespace of namespaces) {
279
- const lines = namespace.declarations.split("\n");
280
- lines.forEach((line, index) => {
281
- if (!line.toLowerCase().includes(needle) || hits.length >= MAX_QUERY_LINES) return;
282
- const doc = lines[index - 1]?.trim().startsWith("/**") ? `${lines[index - 1]?.trim()} ` : "";
283
- hits.push(`${namespace.name}: ${doc}${line.trim()}`);
284
- });
285
- }
286
- for (const script of listed) {
287
- if (hits.length >= MAX_QUERY_LINES) break;
288
- if (`${script.specifier} ${script.description}`.toLowerCase().includes(needle)) hits.push(`script ${script.specifier}: ${script.description}`);
289
- }
290
- return text(hits.length > 0 ? hits.join("\n") : `No members or scripts match "${parameters.query}".`);
291
- }
292
- const sections = [];
293
- if (namespaces.length === 0) sections.push("No namespaces are registered in this session.");
294
- for (const namespace of namespaces) sections.push(`- ${namespace.name}: ${namespace.summary}\n members: ${memberNames(namespace).join(", ")}`);
295
- sections.push(GLOBALS_HELP);
296
- if (!service.liveObjects) sections.push("This host runs plain JavaScript with JSON-only functions.");
297
- if (listed.length > 0) {
298
- sections.push(`Scripts. ${SCRIPTS_HELP}`);
299
- for (const script of listed.slice(0, MAX_LISTED_SCRIPTS)) sections.push(`- ${script.specifier}${script.description ? `: ${script.description}` : ""}`);
300
- if (listed.length > MAX_LISTED_SCRIPTS) sections.push(`...and ${listed.length - MAX_LISTED_SCRIPTS} more; use discover({ query }) to search.`);
301
- }
302
- if (namespaces.length > 0) sections.push("Call discover({ namespace }) for full types.");
303
- return text(sections.join("\n"));
304
- }
305
- },
306
- exec: {
307
- name: "exec",
308
- label: "Exec",
309
- get description() {
310
- const service = isolate();
311
- return [
312
- "Run a TypeScript script inside the Po server with live objects from the namespaces below in scope.",
313
- "It runs with full server trust, like bash. Keep each call to one logical step.",
314
- (service ? visible(service) : []).map((namespace) => `- ${namespace.name}: ${namespace.summary}`).join("\n") || "(no namespaces registered yet; call discover to check)",
315
- GLOBALS_HELP,
316
- ...scripts && service?.liveObjects ? [`${SCRIPTS_HELP} discover lists saved and domain scripts.`] : [],
317
- "Use discover({ namespace }) for full signatures when needed."
318
- ].join("\n");
319
- },
320
- parameters: ExecToolSchema,
321
- promptSnippet: "Run a TypeScript script against live Po objects (browser and other namespaces)",
322
- executionMode: "serial",
323
- async execute(_toolCallId, parameters, signal, _onUpdate, execution) {
324
- const service = isolate();
325
- if (!service) return text("Code mode is not available on this host.", true);
326
- if (running >= MAX_CONCURRENT_RUNS) return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);
327
- running += 1;
328
- const controller = new AbortController();
329
- const runSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
330
- const cleanups = [];
331
- const calls = [];
332
- const output = createOutput();
333
- const run = {
334
- sessionId: execution.sessionId,
335
- signal: runSignal,
336
- onDispose: (cleanup) => void cleanups.push(cleanup),
337
- record: (call) => {
338
- if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call));
339
- }
340
- };
341
- try {
342
- let saved;
343
- try {
344
- const file = await scripts?.save(parameters.code);
345
- if (file) saved = `Saved as ${file.specifier} (${file.path})`;
346
- } catch (error) {
347
- output.note(`Could not save the script: ${error instanceof Error ? error.message : String(error)}`);
348
- }
349
- const globals = {
350
- console: output.console,
351
- image: output.addImage,
352
- sleep: (ms) => sleep(ms, runSignal)
353
- };
354
- const deny = /* @__PURE__ */ new Set();
355
- for (const namespace of visible(service)) {
356
- globals[namespace.name] = namespace.bind(run);
357
- for (const member of namespace.deny ?? []) deny.add(member);
358
- }
359
- const deadlineMs = Math.min(MAX_TIMEOUT_MS, Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS));
360
- return toResult(await service.run({
361
- source: parameters.code,
362
- globals,
363
- deadlineMs,
364
- signal: runSignal,
365
- deny: [...deny],
366
- onDiagnostic: output.note,
367
- resolveImport: async (specifier) => {
368
- if (!specifier.startsWith("npm:")) {
369
- if (!scripts) throw new Error("Script imports are not available on this host.");
370
- return scripts.resolve(specifier, activeDomains(execution));
371
- }
372
- const loader = npm?.();
373
- if (!loader) throw new Error("npm imports are not available on this host.");
374
- run.signal.throwIfAborted();
375
- const started = Date.now();
376
- try {
377
- const exports = await loader.import(specifier, {
378
- sessionId: run.sessionId,
379
- signal: run.signal
380
- });
381
- run.signal.throwIfAborted();
382
- run.record?.({
383
- name: "npm.import",
384
- tool: "npm",
385
- args: { specifier },
386
- ms: Date.now() - started,
387
- ok: true
388
- });
389
- return {
390
- kind: "module",
391
- id: specifier,
392
- exports
393
- };
394
- } catch (error) {
395
- run.record?.({
396
- name: "npm.import",
397
- tool: "npm",
398
- args: { specifier },
399
- ms: Date.now() - started,
400
- ok: false,
401
- error: error instanceof Error ? error.message : String(error)
402
- });
403
- throw error;
404
- }
405
- }
406
- }), output, saved, calls);
407
- } catch (error) {
408
- return text(`Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`, true);
409
- } finally {
410
- controller.abort();
411
- for (const cleanup of cleanups.reverse()) await Promise.resolve().then(cleanup).catch((error) => output.note(`cleanup failed: ${String(error)}`));
412
- running -= 1;
413
- }
414
- }
415
- }
416
- };
417
- }
418
- //#endregion
419
- Object.defineProperty(exports, "createCodemodeRegistry", {
420
- enumerable: true,
421
- get: function() {
422
- return createCodemodeRegistry;
423
- }
424
- });
425
- Object.defineProperty(exports, "createCodemodeTools", {
426
- enumerable: true,
427
- get: function() {
428
- return createCodemodeTools;
429
- }
430
- });
431
-
432
- //# sourceMappingURL=codemodeTools-BQDVk-4P.cjs.map