@agimon-ai/po-codemode 0.0.1-alpha.1 → 0.0.1-alpha.3
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/README.md +3 -3
- package/dist/{codemodeTools-CSYUxIeA.mjs → codemodeTools-BdwOARH8.mjs} +55 -10
- package/dist/codemodeTools-BdwOARH8.mjs.map +1 -0
- package/dist/{codemodeTools-BX2qieCR.cjs → codemodeTools-CLgSDqfU.cjs} +55 -10
- package/dist/codemodeTools-CLgSDqfU.cjs.map +1 -0
- package/dist/extensions/server.cjs +8 -9
- package/dist/extensions/server.cjs.map +1 -1
- package/dist/extensions/server.mjs +8 -9
- package/dist/extensions/server.mjs.map +1 -1
- package/dist/extensions/web.mjs +295 -0
- package/dist/extensions/web.mjs.map +1 -0
- package/dist/index.cjs +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.d.mts.map +1 -1
- package/dist/index.mjs +1 -1
- package/llms.txt +1 -1
- package/package.json +22 -5
- package/src/prompts/{po-use-codemode → how-to-codemode}/SKILL.md +3 -1
- package/dist/codemodeTools-BX2qieCR.cjs.map +0 -1
- package/dist/codemodeTools-CSYUxIeA.mjs.map +0 -1
package/README.md
CHANGED
|
@@ -29,11 +29,11 @@ Show code mode namespaces
|
|
|
29
29
|
|
|
30
30
|
## Package behavior
|
|
31
31
|
|
|
32
|
-
|
|
32
|
+
Call `discover({ namespace: 'browser' })` for current types, then `exec({ code: 'return await browser.snapshot({});' })`. Namespace plugins supply their own `codemode-how-to-<plugin>` guides. Their summaries and the base `how-to-codemode` guide stay in the system prompt, outside skill search; `load_skill` still reads their full instructions by exact name.
|
|
33
33
|
|
|
34
|
-
##
|
|
34
|
+
## How-to guide
|
|
35
35
|
|
|
36
|
-
The published package includes `llms.txt` and `src/prompts/
|
|
36
|
+
The published package includes `llms.txt` and `src/prompts/how-to-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
37
|
|
|
38
38
|
## Public API
|
|
39
39
|
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assertCodemodeNamespaceName } from "@agimon-ai/po-core/codemode";
|
|
2
|
+
import { invalidImageReason } from "@agimon-ai/po-core/headless";
|
|
2
3
|
import { Type } from "typebox";
|
|
3
4
|
//#region src/services/codemodeRegistry/index.ts
|
|
4
5
|
/** The session's namespaces and script folders, in registration order. One name per session. */
|
|
@@ -64,8 +65,12 @@ const MAX_TIMEOUT_MS = 12e4;
|
|
|
64
65
|
const MIN_TIMEOUT_MS = 1e3;
|
|
65
66
|
const MAX_LOG_CHARS = 1e4;
|
|
66
67
|
const MAX_VALUE_CHARS = 65536;
|
|
67
|
-
const MAX_DECLARATION_CHARS =
|
|
68
|
+
const MAX_DECLARATION_CHARS = 24e3;
|
|
68
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;
|
|
69
74
|
const MAX_LISTED_SCRIPTS = 20;
|
|
70
75
|
const MAX_IMAGES = 4;
|
|
71
76
|
const MAX_IMAGE_BYTES = 5242880;
|
|
@@ -95,7 +100,8 @@ function format(value) {
|
|
|
95
100
|
}
|
|
96
101
|
function memberNames(namespace) {
|
|
97
102
|
const names = /* @__PURE__ */ new Set();
|
|
98
|
-
|
|
103
|
+
const declaration = new RegExp(`^declare const ${namespace.name}: \\{([\\s\\S]*?)^\\};`, "mu").exec(namespace.declarations)?.[1] ?? "";
|
|
104
|
+
for (const line of declaration.split("\n")) {
|
|
99
105
|
const name = MEMBER_LINE.exec(line)?.[1];
|
|
100
106
|
if (name) names.add(name);
|
|
101
107
|
}
|
|
@@ -132,6 +138,8 @@ function createOutput() {
|
|
|
132
138
|
if (images.length >= MAX_IMAGES) throw new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);
|
|
133
139
|
imageBytes += Math.ceil(data.length * 3 / 4);
|
|
134
140
|
if (imageBytes > MAX_IMAGE_BYTES) throw new RangeError("Images from one exec run exceed 5 MB.");
|
|
141
|
+
const invalid = invalidImageReason(data, mime);
|
|
142
|
+
if (invalid !== void 0) throw new TypeError(`image() rejected an undecodable image: ${invalid}.`);
|
|
135
143
|
images.push({
|
|
136
144
|
data,
|
|
137
145
|
mimeType: mime
|
|
@@ -155,7 +163,39 @@ function createOutput() {
|
|
|
155
163
|
function activeDomains(execution) {
|
|
156
164
|
return execution?.selection?.domains;
|
|
157
165
|
}
|
|
158
|
-
|
|
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) {
|
|
159
199
|
const content = [];
|
|
160
200
|
if (output.lines.length > 0) content.push({
|
|
161
201
|
type: "text",
|
|
@@ -193,6 +233,7 @@ function toResult(result, output, saved) {
|
|
|
193
233
|
});
|
|
194
234
|
return {
|
|
195
235
|
content,
|
|
236
|
+
...calls.length > 0 ? { details: { calls } } : {},
|
|
196
237
|
...result.ok ? {} : { isError: true }
|
|
197
238
|
};
|
|
198
239
|
}
|
|
@@ -208,7 +249,7 @@ function sleep(ms, signal) {
|
|
|
208
249
|
}
|
|
209
250
|
/** `discover` and `exec` for one session, over the namespaces its packages contributed. */
|
|
210
251
|
function createCodemodeTools({ registry, isolate, scripts }) {
|
|
211
|
-
let
|
|
252
|
+
let running = 0;
|
|
212
253
|
const visible = (service) => registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);
|
|
213
254
|
return {
|
|
214
255
|
discover: {
|
|
@@ -282,16 +323,20 @@ function createCodemodeTools({ registry, isolate, scripts }) {
|
|
|
282
323
|
async execute(_toolCallId, parameters, signal, _onUpdate, execution) {
|
|
283
324
|
const service = isolate();
|
|
284
325
|
if (!service) return text("Code mode is not available on this host.", true);
|
|
285
|
-
if (
|
|
286
|
-
|
|
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;
|
|
287
328
|
const controller = new AbortController();
|
|
288
329
|
const runSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
289
330
|
const cleanups = [];
|
|
331
|
+
const calls = [];
|
|
290
332
|
const output = createOutput();
|
|
291
333
|
const run = {
|
|
292
334
|
sessionId: execution.sessionId,
|
|
293
335
|
signal: runSignal,
|
|
294
|
-
onDispose: (cleanup) => void cleanups.push(cleanup)
|
|
336
|
+
onDispose: (cleanup) => void cleanups.push(cleanup),
|
|
337
|
+
record: (call) => {
|
|
338
|
+
if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call));
|
|
339
|
+
}
|
|
295
340
|
};
|
|
296
341
|
try {
|
|
297
342
|
let saved;
|
|
@@ -320,13 +365,13 @@ function createCodemodeTools({ registry, isolate, scripts }) {
|
|
|
320
365
|
deny: [...deny],
|
|
321
366
|
onDiagnostic: output.note,
|
|
322
367
|
...scripts ? { resolveImport: (specifier) => scripts.resolve(specifier, activeDomains(execution)) } : {}
|
|
323
|
-
}), output, saved);
|
|
368
|
+
}), output, saved, calls);
|
|
324
369
|
} catch (error) {
|
|
325
370
|
return text(`Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`, true);
|
|
326
371
|
} finally {
|
|
327
372
|
controller.abort();
|
|
328
373
|
for (const cleanup of cleanups.reverse()) await Promise.resolve().then(cleanup).catch((error) => output.note(`cleanup failed: ${String(error)}`));
|
|
329
|
-
|
|
374
|
+
running -= 1;
|
|
330
375
|
}
|
|
331
376
|
}
|
|
332
377
|
}
|
|
@@ -335,4 +380,4 @@ function createCodemodeTools({ registry, isolate, scripts }) {
|
|
|
335
380
|
//#endregion
|
|
336
381
|
export { createCodemodeRegistry as n, createCodemodeTools as t };
|
|
337
382
|
|
|
338
|
-
//# sourceMappingURL=codemodeTools-
|
|
383
|
+
//# sourceMappingURL=codemodeTools-BdwOARH8.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codemodeTools-BdwOARH8.mjs","names":[],"sources":["../src/services/codemodeRegistry/index.ts","../src/schemas/codemodeTools.ts","../src/services/codemodeTools/index.ts"],"sourcesContent":["import {\n assertCodemodeNamespaceName,\n type PoCodemodeNamespace,\n type PoCodemodeRegistration,\n type PoCodemodeScriptSource,\n type PoCodemodeService,\n} from '@agimon-ai/po-core/codemode';\n\n/** The session's namespaces and script folders, in registration order. One name per session. */\nexport function createCodemodeRegistry(): PoCodemodeService {\n const entries = new Map<string, { source: string; namespace: PoCodemodeNamespace }>();\n const scripts = new Set<PoCodemodeScriptSource>();\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const listener of listeners) listener();\n };\n return {\n register(source: string, namespace: PoCodemodeNamespace): PoCodemodeRegistration {\n assertCodemodeNamespaceName(namespace.name);\n const taken = entries.get(namespace.name);\n if (taken) {\n throw new Error(\n `Code-mode namespace \"${namespace.name}\" from ${source} is already registered by ${taken.source}.`,\n );\n }\n const entry = { source, namespace };\n entries.set(namespace.name, entry);\n notify();\n return {\n dispose: () => {\n if (entries.get(namespace.name) !== entry) return;\n entries.delete(namespace.name);\n notify();\n },\n };\n },\n list: () => [...entries.values()].map((entry) => entry.namespace),\n registerScripts(_source: string, entry: PoCodemodeScriptSource): PoCodemodeRegistration {\n const owned = { domain: entry.domain, directory: entry.directory };\n scripts.add(owned);\n notify();\n return { dispose: () => void (scripts.delete(owned) && notify()) };\n },\n listScripts: () => [...scripts],\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n","import { Type, type Static } from 'typebox';\n\nexport const DiscoverToolSchema = Type.Object({\n namespace: Type.Optional(Type.String({ description: 'Show the full TypeScript declarations of one namespace.' })),\n query: Type.Optional(Type.String({ description: 'Find matching members across every namespace.' })),\n});\nexport type DiscoverToolParams = Static<typeof DiscoverToolSchema>;\n\nexport const ExecToolSchema = Type.Object({\n code: Type.String({\n description:\n 'TypeScript body of an async function. Top-level await and return work. The returned value, console output and image() calls come back.',\n }),\n timeoutMs: Type.Optional(\n Type.Integer({ minimum: 1_000, maximum: 120_000, description: 'Deadline in milliseconds. Default 30000.' }),\n ),\n});\nexport type ExecToolParams = Static<typeof ExecToolSchema>;\n","import type {\n PoCodemodeCall,\n PoCodemodeNamespace,\n PoCodemodeRun,\n PoCodemodeService,\n} from '@agimon-ai/po-core/codemode';\nimport {\n invalidImageReason,\n type PoHeadlessContent,\n type PoHeadlessExecutionContext,\n type PoHeadlessTool,\n type PoHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\nimport type { PoIsolateResult, PoIsolateService } from '@agimon-ai/po-core/platform';\n\nimport {\n DiscoverToolSchema,\n ExecToolSchema,\n type DiscoverToolParams,\n type ExecToolParams,\n} from '../../schemas/codemodeTools';\nimport type { CodemodeScriptsPort } from '../codemodeScripts/type';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_TIMEOUT_MS = 120_000;\nconst MIN_TIMEOUT_MS = 1_000;\nconst MAX_LOG_CHARS = 10_000;\nconst MAX_VALUE_CHARS = 64 * 1024;\nconst MAX_DECLARATION_CHARS = 24_000;\nconst MAX_QUERY_LINES = 40;\n// The main agent and its subagents share one exec tool, so several runs can overlap.\nconst MAX_CONCURRENT_RUNS = 8;\n// Recorded calls ride the result's details into the transcript, so they are few and small.\nconst MAX_RECORDED_CALLS = 50;\nconst MAX_RECORDED_TEXT = 8_000;\nconst MAX_RECORDED_JSON = 16_000;\nconst MAX_LISTED_SCRIPTS = 20;\nconst MAX_IMAGES = 4;\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\nconst DEFAULT_IMAGE_MIME = 'image/png';\nconst MEMBER_LINE = /^\\s{2}(?:readonly\\s+)?(\\w+)\\s*[(?:<]/u;\n\nconst GLOBALS_HELP =\n 'Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). ' +\n 'Return a value with `return`.';\nconst SCRIPTS_HELP =\n 'Every exec run is saved. Call a saved script with `await (await import(specifier))(args)`; ' +\n 'inside it, `args` is the argument and its `return` is the result.';\n\nexport interface CodemodeToolsOptions {\n readonly registry: PoCodemodeService;\n /** Resolved per call, so a host that binds the isolate late still works. */\n readonly isolate: () => PoIsolateService | undefined;\n /** Saves every exec body and backs `import()`; without it nothing is saved or importable. */\n readonly scripts?: CodemodeScriptsPort;\n}\n\nexport interface CodemodeTools {\n readonly discover: PoHeadlessTool<typeof DiscoverToolSchema>;\n readonly exec: PoHeadlessTool<typeof ExecToolSchema>;\n}\n\nfunction text(value: string, isError = false): PoHeadlessToolResult {\n return { content: [{ type: 'text', text: value }], ...(isError ? { isError: true } : {}) };\n}\n\nfunction truncate(value: string, limit: number): string {\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n[truncated ${value.length - limit} chars]`;\n}\n\nfunction format(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n const json = JSON.stringify(value, null, 2);\n if (json !== undefined) return json;\n } catch {\n // Cyclic or exotic values fall back to their string form.\n }\n return String(value);\n}\n\nfunction memberNames(namespace: PoCodemodeNamespace): string[] {\n const names = new Set<string>();\n const declaration =\n new RegExp(`^declare const ${namespace.name}: \\\\{([\\\\s\\\\S]*?)^\\\\};`, 'mu').exec(namespace.declarations)?.[1] ?? '';\n for (const line of declaration.split('\\n')) {\n const name = MEMBER_LINE.exec(line)?.[1];\n if (name) names.add(name);\n }\n return [...names];\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = '';\n for (let index = 0; index < bytes.length; index += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));\n }\n return btoa(binary);\n}\n\n/** Collects what a script prints and the images it returns, within the output caps. */\nfunction createOutput() {\n const lines: string[] = [];\n const images: { data: string; mimeType: string }[] = [];\n let imageBytes = 0;\n const log =\n (level: string) =>\n (...args: unknown[]) => {\n const line = args.map(format).join(' ');\n lines.push(level === 'log' || level === 'info' ? line : `[${level}] ${line}`);\n };\n const note = (message: string): void => void lines.push(`[note] ${message}`);\n const addImage = (input: unknown, mimeType?: unknown): void => {\n if (typeof input === 'object' && input !== null && 'images' in input && Array.isArray(input.images)) {\n for (const image of input.images) addImage(image);\n return;\n }\n let data: string;\n let mime = typeof mimeType === 'string' ? mimeType : DEFAULT_IMAGE_MIME;\n if (typeof input === 'string')\n data = input.replace(/^data:([^;]+);base64,/u, (_match, type: string) => ((mime = type), ''));\n else if (ArrayBuffer.isView(input))\n data = bytesToBase64(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));\n else if (typeof input === 'object' && input !== null && 'data' in input && typeof input.data === 'string') {\n data = input.data;\n if ('mimeType' in input && typeof input.mimeType === 'string') mime = input.mimeType;\n } else throw new TypeError('image() takes base64 text, bytes, or { data, mimeType }.');\n if (images.length >= MAX_IMAGES) throw new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);\n imageBytes += Math.ceil((data.length * 3) / 4);\n if (imageBytes > MAX_IMAGE_BYTES) throw new RangeError('Images from one exec run exceed 5 MB.');\n const invalid = invalidImageReason(data, mime);\n if (invalid !== undefined) throw new TypeError(`image() rejected an undecodable image: ${invalid}.`);\n images.push({ data, mimeType: mime });\n };\n const console = { log: log('log'), info: log('info'), warn: log('warn'), error: log('error'), debug: log('debug') };\n return { console, note, addImage, lines, images };\n}\n\n/** The session's active domains; every registered domain when the host reports none. */\nfunction activeDomains(execution: PoHeadlessExecutionContext | undefined): readonly string[] | undefined {\n return execution?.selection?.domains;\n}\n\n/** A JSON copy of `value`, or undefined when it does not serialise or is larger than `limit` characters. */\nfunction bounded<T>(value: T, limit: number): T | undefined {\n try {\n const json = JSON.stringify(value);\n return json !== undefined && json.length <= limit ? (JSON.parse(json) as T) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The call as it is kept in the transcript: text blocks only, clipped, with args and details dropped when large. */\nfunction recordedCall(call: PoCodemodeCall): PoCodemodeCall {\n const content = (call.result?.content ?? []).flatMap((block) => {\n const { type, text } = (block ?? {}) as { type?: unknown; text?: unknown };\n return type === 'text' && typeof text === 'string'\n ? [{ type: 'text', text: truncate(text, MAX_RECORDED_TEXT) }]\n : [];\n });\n const details = bounded(call.result?.details, MAX_RECORDED_JSON);\n return {\n name: call.name,\n tool: call.tool,\n args: bounded(call.args, MAX_RECORDED_JSON) ?? {},\n ok: call.ok,\n ms: Math.max(0, Math.round(call.ms)),\n ...(call.error === undefined ? {} : { error: truncate(call.error, MAX_RECORDED_TEXT) }),\n ...(call.result === undefined ? {} : { result: { content, ...(details === undefined ? {} : { details }) } }),\n };\n}\n\nfunction toResult(\n result: PoIsolateResult,\n output: ReturnType<typeof createOutput>,\n saved: string | undefined,\n calls: readonly PoCodemodeCall[],\n): PoHeadlessToolResult {\n const content: PoHeadlessContent[] = [];\n if (output.lines.length > 0) content.push({ type: 'text', text: truncate(output.lines.join('\\n'), MAX_LOG_CHARS) });\n if (result.ok) {\n if (ArrayBuffer.isView(result.value)) {\n content.push({ type: 'text', text: 'The script returned bytes. Pass them to image(data, mimeType) instead.' });\n } else if (result.value !== undefined) {\n content.push({ type: 'text', text: truncate(format(result.value), MAX_VALUE_CHARS) });\n }\n } else {\n const { kind, name, message } = result.error;\n const hint = kind === 'timeout' ? ' Raise timeoutMs or split the work into smaller exec calls.' : '';\n content.push({ type: 'text', text: `${name}: ${message}${hint}` });\n }\n if (content.length === 0) content.push({ type: 'text', text: '(no return value)' });\n if (saved !== undefined) content.push({ type: 'text', text: saved });\n for (const image of output.images) content.push({ type: 'image', data: image.data, mimeType: image.mimeType });\n return {\n content,\n ...(calls.length > 0 ? { details: { calls } } : {}),\n ...(result.ok ? {} : { isError: true }),\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(new Error('Run ended.'));\n const timer = setTimeout(resolve, Math.max(0, ms));\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer);\n reject(new Error('Run ended.'));\n },\n { once: true },\n );\n });\n}\n\n/** `discover` and `exec` for one session, over the namespaces its packages contributed. */\nexport function createCodemodeTools({ registry, isolate, scripts }: CodemodeToolsOptions): CodemodeTools {\n let running = 0;\n\n const visible = (service: PoIsolateService): PoCodemodeNamespace[] =>\n registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);\n\n // ponytail: the cockpit's generic tool item renders both for now; add a poWeb renderer for exec code and images when it earns one.\n // web-plugin-tool-renderers: ignore discover, plain text result\n const discover: CodemodeTools['discover'] = {\n name: 'discover',\n label: 'Discover',\n description:\n 'List the code-mode namespaces and reusable scripts you can use from `exec`, show one namespace in full, ' +\n 'or search members and scripts. ' +\n 'Not required before exec: its description already names the namespaces.',\n parameters: DiscoverToolSchema,\n promptSnippet: 'List code-mode namespaces and their TypeScript declarations',\n executionMode: 'parallel',\n async execute(_toolCallId, parameters: DiscoverToolParams, _signal, _onUpdate, execution) {\n const service = isolate();\n if (!service) return text('Code mode is not available on this host.', true);\n const namespaces = visible(service);\n // Imports need a host with live objects; the edge saves scripts but cannot chain them.\n const listed = scripts && service.liveObjects ? await scripts.list(activeDomains(execution)) : [];\n if (parameters.namespace !== undefined) {\n const found = namespaces.find((namespace) => namespace.name === parameters.namespace);\n if (!found) {\n const names = namespaces.map((namespace) => namespace.name).join(', ') || 'none';\n return text(`Unknown namespace \"${parameters.namespace}\". Registered: ${names}.`, true);\n }\n return text(truncate(found.declarations, MAX_DECLARATION_CHARS));\n }\n if (parameters.query !== undefined) {\n const needle = parameters.query.toLowerCase();\n const hits: string[] = [];\n for (const namespace of namespaces) {\n const lines = namespace.declarations.split('\\n');\n lines.forEach((line, index) => {\n if (!line.toLowerCase().includes(needle) || hits.length >= MAX_QUERY_LINES) return;\n const doc = lines[index - 1]?.trim().startsWith('/**') ? `${lines[index - 1]?.trim()} ` : '';\n hits.push(`${namespace.name}: ${doc}${line.trim()}`);\n });\n }\n for (const script of listed) {\n if (hits.length >= MAX_QUERY_LINES) break;\n if (`${script.specifier} ${script.description}`.toLowerCase().includes(needle)) {\n hits.push(`script ${script.specifier}: ${script.description}`);\n }\n }\n return text(hits.length > 0 ? hits.join('\\n') : `No members or scripts match \"${parameters.query}\".`);\n }\n const sections: string[] = [];\n if (namespaces.length === 0) sections.push('No namespaces are registered in this session.');\n for (const namespace of namespaces) {\n sections.push(`- ${namespace.name}: ${namespace.summary}\\n members: ${memberNames(namespace).join(', ')}`);\n }\n sections.push(GLOBALS_HELP);\n if (!service.liveObjects) sections.push('This host runs plain JavaScript with JSON-only functions.');\n if (listed.length > 0) {\n sections.push(`Scripts. ${SCRIPTS_HELP}`);\n for (const script of listed.slice(0, MAX_LISTED_SCRIPTS)) {\n sections.push(`- ${script.specifier}${script.description ? `: ${script.description}` : ''}`);\n }\n if (listed.length > MAX_LISTED_SCRIPTS) {\n sections.push(`...and ${listed.length - MAX_LISTED_SCRIPTS} more; use discover({ query }) to search.`);\n }\n }\n if (namespaces.length > 0) sections.push('Call discover({ namespace }) for full types.');\n return text(sections.join('\\n'));\n },\n };\n\n // web-plugin-tool-renderers: ignore exec, generic item until a code and image renderer exists\n const exec: CodemodeTools['exec'] = {\n name: 'exec',\n label: 'Exec',\n get description(): string {\n const service = isolate();\n const namespaces = service ? visible(service) : [];\n const listed = namespaces.map((namespace) => `- ${namespace.name}: ${namespace.summary}`).join('\\n');\n return [\n 'Run a TypeScript script inside the Po server with live objects from the namespaces below in scope.',\n 'It runs with full server trust, like bash. Keep each call to one logical step.',\n listed || '(no namespaces registered yet; call discover to check)',\n GLOBALS_HELP,\n ...(scripts && service?.liveObjects ? [`${SCRIPTS_HELP} discover lists saved and domain scripts.`] : []),\n 'Use discover({ namespace }) for full signatures when needed.',\n ].join('\\n');\n },\n parameters: ExecToolSchema,\n promptSnippet: 'Run a TypeScript script against live Po objects (browser and other namespaces)',\n executionMode: 'serial',\n async execute(_toolCallId, parameters: ExecToolParams, signal, _onUpdate, execution) {\n const service = isolate();\n if (!service) return text('Code mode is not available on this host.', true);\n if (running >= MAX_CONCURRENT_RUNS)\n return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);\n running += 1;\n const controller = new AbortController();\n const runSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;\n const cleanups: (() => void | Promise<void>)[] = [];\n const calls: PoCodemodeCall[] = [];\n const output = createOutput();\n const run: PoCodemodeRun = {\n sessionId: execution.sessionId,\n signal: runSignal,\n onDispose: (cleanup) => void cleanups.push(cleanup),\n record: (call) => {\n if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call));\n },\n };\n try {\n let saved: string | undefined;\n try {\n const file = await scripts?.save(parameters.code);\n if (file) saved = `Saved as ${file.specifier} (${file.path})`;\n } catch (error) {\n output.note(`Could not save the script: ${error instanceof Error ? error.message : String(error)}`);\n }\n const globals: Record<string, unknown> = {\n console: output.console,\n image: output.addImage,\n sleep: (ms: number) => sleep(ms, runSignal),\n };\n const deny = new Set<string>();\n for (const namespace of visible(service)) {\n globals[namespace.name] = namespace.bind(run);\n for (const member of namespace.deny ?? []) deny.add(member);\n }\n const deadlineMs = Math.min(\n MAX_TIMEOUT_MS,\n Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n );\n const result = await service.run({\n source: parameters.code,\n globals,\n deadlineMs,\n signal: runSignal,\n deny: [...deny],\n onDiagnostic: output.note,\n ...(scripts ? { resolveImport: (specifier) => scripts.resolve(specifier, activeDomains(execution)) } : {}),\n });\n return toResult(result, output, saved, calls);\n } catch (error) {\n return text(\n `Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`,\n true,\n );\n } finally {\n controller.abort();\n for (const cleanup of cleanups.reverse()) {\n await Promise.resolve()\n .then(cleanup)\n .catch((error: unknown) => output.note(`cleanup failed: ${String(error)}`));\n }\n running -= 1;\n }\n },\n };\n\n return { discover, exec };\n}\n"],"mappings":";;;;;AASA,SAAgB,yBAA4C;CAC1D,MAAM,0BAAU,IAAI,IAAgE;CACpF,MAAM,0BAAU,IAAI,IAA4B;CAChD,MAAM,4BAAY,IAAI,IAAgB;CACtC,MAAM,eAAqB;EACzB,KAAK,MAAM,YAAY,WAAW,SAAS;CAC7C;CACA,OAAO;EACL,SAAS,QAAgB,WAAwD;GAC/E,4BAA4B,UAAU,IAAI;GAC1C,MAAM,QAAQ,QAAQ,IAAI,UAAU,IAAI;GACxC,IAAI,OACF,MAAM,IAAI,MACR,wBAAwB,UAAU,KAAK,SA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AC7B,KAAK,MAAM,aAAa,QAAQ,OAAO,GAAG;MACxC,QAAQ,UAAU,QAAQ,UAAU,KAAK,GAAG;MAC5C,KAAK,MAAM,UAAU,UAAU,QAAQ,CAAC,GAAG,KAAK,IAAI,MAAM;KAC5D;KACA,MAAM,aAAa,KAAK,IACtB,gBACA,KAAK,IAAI,gBAAgB,WAAW,aAAa,kBAAkB,CACrE;KAUA,OAAO,SAAS,MATK,QAAQ,IAAI;MAC/B,QAAQ,WAAW;MACnB;MACA;MACA,QAAQ;MACR,MAAM,CAAC,GAAG,IAAI;MACd,cAAc,OAAO;MACrB,GAAI,UAAU,EAAE,gBAAgB,cAAc,QAAQ,QAAQ,WAAW,cAAc,SAAS,CAAC,EAAE,IAAI,CAAC;KAC1G,CAAC,GACuB,QAAQ,OAAO,KAAK;IAC9C,SAAS,OAAO;KACd,OAAO,KACL,uCAAuC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC5F,IACF;IACF,UAAU;KACR,WAAW,MAAM;KACjB,KAAK,MAAM,WAAW,SAAS,QAAQ,GACrC,MAAM,QAAQ,QAAQ,CAAC,CACpB,KAAK,OAAO,CAAC,CACb,OAAO,UAAmB,OAAO,KAAK,mBAAmB,OAAO,KAAK,GAAG,CAAC;KAE9E,WAAW;IACb;GACF;EAGoB;CAAE;AAC1B"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
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");
|
|
2
3
|
let typebox = require("typebox");
|
|
3
4
|
//#region src/services/codemodeRegistry/index.ts
|
|
4
5
|
/** The session's namespaces and script folders, in registration order. One name per session. */
|
|
@@ -64,8 +65,12 @@ const MAX_TIMEOUT_MS = 12e4;
|
|
|
64
65
|
const MIN_TIMEOUT_MS = 1e3;
|
|
65
66
|
const MAX_LOG_CHARS = 1e4;
|
|
66
67
|
const MAX_VALUE_CHARS = 65536;
|
|
67
|
-
const MAX_DECLARATION_CHARS =
|
|
68
|
+
const MAX_DECLARATION_CHARS = 24e3;
|
|
68
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;
|
|
69
74
|
const MAX_LISTED_SCRIPTS = 20;
|
|
70
75
|
const MAX_IMAGES = 4;
|
|
71
76
|
const MAX_IMAGE_BYTES = 5242880;
|
|
@@ -95,7 +100,8 @@ function format(value) {
|
|
|
95
100
|
}
|
|
96
101
|
function memberNames(namespace) {
|
|
97
102
|
const names = /* @__PURE__ */ new Set();
|
|
98
|
-
|
|
103
|
+
const declaration = new RegExp(`^declare const ${namespace.name}: \\{([\\s\\S]*?)^\\};`, "mu").exec(namespace.declarations)?.[1] ?? "";
|
|
104
|
+
for (const line of declaration.split("\n")) {
|
|
99
105
|
const name = MEMBER_LINE.exec(line)?.[1];
|
|
100
106
|
if (name) names.add(name);
|
|
101
107
|
}
|
|
@@ -132,6 +138,8 @@ function createOutput() {
|
|
|
132
138
|
if (images.length >= MAX_IMAGES) throw new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);
|
|
133
139
|
imageBytes += Math.ceil(data.length * 3 / 4);
|
|
134
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}.`);
|
|
135
143
|
images.push({
|
|
136
144
|
data,
|
|
137
145
|
mimeType: mime
|
|
@@ -155,7 +163,39 @@ function createOutput() {
|
|
|
155
163
|
function activeDomains(execution) {
|
|
156
164
|
return execution?.selection?.domains;
|
|
157
165
|
}
|
|
158
|
-
|
|
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) {
|
|
159
199
|
const content = [];
|
|
160
200
|
if (output.lines.length > 0) content.push({
|
|
161
201
|
type: "text",
|
|
@@ -193,6 +233,7 @@ function toResult(result, output, saved) {
|
|
|
193
233
|
});
|
|
194
234
|
return {
|
|
195
235
|
content,
|
|
236
|
+
...calls.length > 0 ? { details: { calls } } : {},
|
|
196
237
|
...result.ok ? {} : { isError: true }
|
|
197
238
|
};
|
|
198
239
|
}
|
|
@@ -208,7 +249,7 @@ function sleep(ms, signal) {
|
|
|
208
249
|
}
|
|
209
250
|
/** `discover` and `exec` for one session, over the namespaces its packages contributed. */
|
|
210
251
|
function createCodemodeTools({ registry, isolate, scripts }) {
|
|
211
|
-
let
|
|
252
|
+
let running = 0;
|
|
212
253
|
const visible = (service) => registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);
|
|
213
254
|
return {
|
|
214
255
|
discover: {
|
|
@@ -282,16 +323,20 @@ function createCodemodeTools({ registry, isolate, scripts }) {
|
|
|
282
323
|
async execute(_toolCallId, parameters, signal, _onUpdate, execution) {
|
|
283
324
|
const service = isolate();
|
|
284
325
|
if (!service) return text("Code mode is not available on this host.", true);
|
|
285
|
-
if (
|
|
286
|
-
|
|
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;
|
|
287
328
|
const controller = new AbortController();
|
|
288
329
|
const runSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
|
|
289
330
|
const cleanups = [];
|
|
331
|
+
const calls = [];
|
|
290
332
|
const output = createOutput();
|
|
291
333
|
const run = {
|
|
292
334
|
sessionId: execution.sessionId,
|
|
293
335
|
signal: runSignal,
|
|
294
|
-
onDispose: (cleanup) => void cleanups.push(cleanup)
|
|
336
|
+
onDispose: (cleanup) => void cleanups.push(cleanup),
|
|
337
|
+
record: (call) => {
|
|
338
|
+
if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call));
|
|
339
|
+
}
|
|
295
340
|
};
|
|
296
341
|
try {
|
|
297
342
|
let saved;
|
|
@@ -320,13 +365,13 @@ function createCodemodeTools({ registry, isolate, scripts }) {
|
|
|
320
365
|
deny: [...deny],
|
|
321
366
|
onDiagnostic: output.note,
|
|
322
367
|
...scripts ? { resolveImport: (specifier) => scripts.resolve(specifier, activeDomains(execution)) } : {}
|
|
323
|
-
}), output, saved);
|
|
368
|
+
}), output, saved, calls);
|
|
324
369
|
} catch (error) {
|
|
325
370
|
return text(`Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`, true);
|
|
326
371
|
} finally {
|
|
327
372
|
controller.abort();
|
|
328
373
|
for (const cleanup of cleanups.reverse()) await Promise.resolve().then(cleanup).catch((error) => output.note(`cleanup failed: ${String(error)}`));
|
|
329
|
-
|
|
374
|
+
running -= 1;
|
|
330
375
|
}
|
|
331
376
|
}
|
|
332
377
|
}
|
|
@@ -346,4 +391,4 @@ Object.defineProperty(exports, "createCodemodeTools", {
|
|
|
346
391
|
}
|
|
347
392
|
});
|
|
348
393
|
|
|
349
|
-
//# sourceMappingURL=codemodeTools-
|
|
394
|
+
//# sourceMappingURL=codemodeTools-CLgSDqfU.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codemodeTools-CLgSDqfU.cjs","names":["Type","invalidImageReason"],"sources":["../src/services/codemodeRegistry/index.ts","../src/schemas/codemodeTools.ts","../src/services/codemodeTools/index.ts"],"sourcesContent":["import {\n assertCodemodeNamespaceName,\n type PoCodemodeNamespace,\n type PoCodemodeRegistration,\n type PoCodemodeScriptSource,\n type PoCodemodeService,\n} from '@agimon-ai/po-core/codemode';\n\n/** The session's namespaces and script folders, in registration order. One name per session. */\nexport function createCodemodeRegistry(): PoCodemodeService {\n const entries = new Map<string, { source: string; namespace: PoCodemodeNamespace }>();\n const scripts = new Set<PoCodemodeScriptSource>();\n const listeners = new Set<() => void>();\n const notify = (): void => {\n for (const listener of listeners) listener();\n };\n return {\n register(source: string, namespace: PoCodemodeNamespace): PoCodemodeRegistration {\n assertCodemodeNamespaceName(namespace.name);\n const taken = entries.get(namespace.name);\n if (taken) {\n throw new Error(\n `Code-mode namespace \"${namespace.name}\" from ${source} is already registered by ${taken.source}.`,\n );\n }\n const entry = { source, namespace };\n entries.set(namespace.name, entry);\n notify();\n return {\n dispose: () => {\n if (entries.get(namespace.name) !== entry) return;\n entries.delete(namespace.name);\n notify();\n },\n };\n },\n list: () => [...entries.values()].map((entry) => entry.namespace),\n registerScripts(_source: string, entry: PoCodemodeScriptSource): PoCodemodeRegistration {\n const owned = { domain: entry.domain, directory: entry.directory };\n scripts.add(owned);\n notify();\n return { dispose: () => void (scripts.delete(owned) && notify()) };\n },\n listScripts: () => [...scripts],\n subscribe(listener: () => void): () => void {\n listeners.add(listener);\n return () => listeners.delete(listener);\n },\n };\n}\n","import { Type, type Static } from 'typebox';\n\nexport const DiscoverToolSchema = Type.Object({\n namespace: Type.Optional(Type.String({ description: 'Show the full TypeScript declarations of one namespace.' })),\n query: Type.Optional(Type.String({ description: 'Find matching members across every namespace.' })),\n});\nexport type DiscoverToolParams = Static<typeof DiscoverToolSchema>;\n\nexport const ExecToolSchema = Type.Object({\n code: Type.String({\n description:\n 'TypeScript body of an async function. Top-level await and return work. The returned value, console output and image() calls come back.',\n }),\n timeoutMs: Type.Optional(\n Type.Integer({ minimum: 1_000, maximum: 120_000, description: 'Deadline in milliseconds. Default 30000.' }),\n ),\n});\nexport type ExecToolParams = Static<typeof ExecToolSchema>;\n","import type {\n PoCodemodeCall,\n PoCodemodeNamespace,\n PoCodemodeRun,\n PoCodemodeService,\n} from '@agimon-ai/po-core/codemode';\nimport {\n invalidImageReason,\n type PoHeadlessContent,\n type PoHeadlessExecutionContext,\n type PoHeadlessTool,\n type PoHeadlessToolResult,\n} from '@agimon-ai/po-core/headless';\nimport type { PoIsolateResult, PoIsolateService } from '@agimon-ai/po-core/platform';\n\nimport {\n DiscoverToolSchema,\n ExecToolSchema,\n type DiscoverToolParams,\n type ExecToolParams,\n} from '../../schemas/codemodeTools';\nimport type { CodemodeScriptsPort } from '../codemodeScripts/type';\n\nconst DEFAULT_TIMEOUT_MS = 30_000;\nconst MAX_TIMEOUT_MS = 120_000;\nconst MIN_TIMEOUT_MS = 1_000;\nconst MAX_LOG_CHARS = 10_000;\nconst MAX_VALUE_CHARS = 64 * 1024;\nconst MAX_DECLARATION_CHARS = 24_000;\nconst MAX_QUERY_LINES = 40;\n// The main agent and its subagents share one exec tool, so several runs can overlap.\nconst MAX_CONCURRENT_RUNS = 8;\n// Recorded calls ride the result's details into the transcript, so they are few and small.\nconst MAX_RECORDED_CALLS = 50;\nconst MAX_RECORDED_TEXT = 8_000;\nconst MAX_RECORDED_JSON = 16_000;\nconst MAX_LISTED_SCRIPTS = 20;\nconst MAX_IMAGES = 4;\nconst MAX_IMAGE_BYTES = 5 * 1024 * 1024;\nconst DEFAULT_IMAGE_MIME = 'image/png';\nconst MEMBER_LINE = /^\\s{2}(?:readonly\\s+)?(\\w+)\\s*[(?:<]/u;\n\nconst GLOBALS_HELP =\n 'Globals: console.log/info/warn/error, image(data, mimeType?) to return a screenshot, sleep(ms). ' +\n 'Return a value with `return`.';\nconst SCRIPTS_HELP =\n 'Every exec run is saved. Call a saved script with `await (await import(specifier))(args)`; ' +\n 'inside it, `args` is the argument and its `return` is the result.';\n\nexport interface CodemodeToolsOptions {\n readonly registry: PoCodemodeService;\n /** Resolved per call, so a host that binds the isolate late still works. */\n readonly isolate: () => PoIsolateService | undefined;\n /** Saves every exec body and backs `import()`; without it nothing is saved or importable. */\n readonly scripts?: CodemodeScriptsPort;\n}\n\nexport interface CodemodeTools {\n readonly discover: PoHeadlessTool<typeof DiscoverToolSchema>;\n readonly exec: PoHeadlessTool<typeof ExecToolSchema>;\n}\n\nfunction text(value: string, isError = false): PoHeadlessToolResult {\n return { content: [{ type: 'text', text: value }], ...(isError ? { isError: true } : {}) };\n}\n\nfunction truncate(value: string, limit: number): string {\n return value.length <= limit ? value : `${value.slice(0, limit)}\\n[truncated ${value.length - limit} chars]`;\n}\n\nfunction format(value: unknown): string {\n if (typeof value === 'string') return value;\n try {\n const json = JSON.stringify(value, null, 2);\n if (json !== undefined) return json;\n } catch {\n // Cyclic or exotic values fall back to their string form.\n }\n return String(value);\n}\n\nfunction memberNames(namespace: PoCodemodeNamespace): string[] {\n const names = new Set<string>();\n const declaration =\n new RegExp(`^declare const ${namespace.name}: \\\\{([\\\\s\\\\S]*?)^\\\\};`, 'mu').exec(namespace.declarations)?.[1] ?? '';\n for (const line of declaration.split('\\n')) {\n const name = MEMBER_LINE.exec(line)?.[1];\n if (name) names.add(name);\n }\n return [...names];\n}\n\nfunction bytesToBase64(bytes: Uint8Array): string {\n let binary = '';\n for (let index = 0; index < bytes.length; index += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(index, index + 0x8000));\n }\n return btoa(binary);\n}\n\n/** Collects what a script prints and the images it returns, within the output caps. */\nfunction createOutput() {\n const lines: string[] = [];\n const images: { data: string; mimeType: string }[] = [];\n let imageBytes = 0;\n const log =\n (level: string) =>\n (...args: unknown[]) => {\n const line = args.map(format).join(' ');\n lines.push(level === 'log' || level === 'info' ? line : `[${level}] ${line}`);\n };\n const note = (message: string): void => void lines.push(`[note] ${message}`);\n const addImage = (input: unknown, mimeType?: unknown): void => {\n if (typeof input === 'object' && input !== null && 'images' in input && Array.isArray(input.images)) {\n for (const image of input.images) addImage(image);\n return;\n }\n let data: string;\n let mime = typeof mimeType === 'string' ? mimeType : DEFAULT_IMAGE_MIME;\n if (typeof input === 'string')\n data = input.replace(/^data:([^;]+);base64,/u, (_match, type: string) => ((mime = type), ''));\n else if (ArrayBuffer.isView(input))\n data = bytesToBase64(new Uint8Array(input.buffer, input.byteOffset, input.byteLength));\n else if (typeof input === 'object' && input !== null && 'data' in input && typeof input.data === 'string') {\n data = input.data;\n if ('mimeType' in input && typeof input.mimeType === 'string') mime = input.mimeType;\n } else throw new TypeError('image() takes base64 text, bytes, or { data, mimeType }.');\n if (images.length >= MAX_IMAGES) throw new RangeError(`An exec run returns at most ${MAX_IMAGES} images.`);\n imageBytes += Math.ceil((data.length * 3) / 4);\n if (imageBytes > MAX_IMAGE_BYTES) throw new RangeError('Images from one exec run exceed 5 MB.');\n const invalid = invalidImageReason(data, mime);\n if (invalid !== undefined) throw new TypeError(`image() rejected an undecodable image: ${invalid}.`);\n images.push({ data, mimeType: mime });\n };\n const console = { log: log('log'), info: log('info'), warn: log('warn'), error: log('error'), debug: log('debug') };\n return { console, note, addImage, lines, images };\n}\n\n/** The session's active domains; every registered domain when the host reports none. */\nfunction activeDomains(execution: PoHeadlessExecutionContext | undefined): readonly string[] | undefined {\n return execution?.selection?.domains;\n}\n\n/** A JSON copy of `value`, or undefined when it does not serialise or is larger than `limit` characters. */\nfunction bounded<T>(value: T, limit: number): T | undefined {\n try {\n const json = JSON.stringify(value);\n return json !== undefined && json.length <= limit ? (JSON.parse(json) as T) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/** The call as it is kept in the transcript: text blocks only, clipped, with args and details dropped when large. */\nfunction recordedCall(call: PoCodemodeCall): PoCodemodeCall {\n const content = (call.result?.content ?? []).flatMap((block) => {\n const { type, text } = (block ?? {}) as { type?: unknown; text?: unknown };\n return type === 'text' && typeof text === 'string'\n ? [{ type: 'text', text: truncate(text, MAX_RECORDED_TEXT) }]\n : [];\n });\n const details = bounded(call.result?.details, MAX_RECORDED_JSON);\n return {\n name: call.name,\n tool: call.tool,\n args: bounded(call.args, MAX_RECORDED_JSON) ?? {},\n ok: call.ok,\n ms: Math.max(0, Math.round(call.ms)),\n ...(call.error === undefined ? {} : { error: truncate(call.error, MAX_RECORDED_TEXT) }),\n ...(call.result === undefined ? {} : { result: { content, ...(details === undefined ? {} : { details }) } }),\n };\n}\n\nfunction toResult(\n result: PoIsolateResult,\n output: ReturnType<typeof createOutput>,\n saved: string | undefined,\n calls: readonly PoCodemodeCall[],\n): PoHeadlessToolResult {\n const content: PoHeadlessContent[] = [];\n if (output.lines.length > 0) content.push({ type: 'text', text: truncate(output.lines.join('\\n'), MAX_LOG_CHARS) });\n if (result.ok) {\n if (ArrayBuffer.isView(result.value)) {\n content.push({ type: 'text', text: 'The script returned bytes. Pass them to image(data, mimeType) instead.' });\n } else if (result.value !== undefined) {\n content.push({ type: 'text', text: truncate(format(result.value), MAX_VALUE_CHARS) });\n }\n } else {\n const { kind, name, message } = result.error;\n const hint = kind === 'timeout' ? ' Raise timeoutMs or split the work into smaller exec calls.' : '';\n content.push({ type: 'text', text: `${name}: ${message}${hint}` });\n }\n if (content.length === 0) content.push({ type: 'text', text: '(no return value)' });\n if (saved !== undefined) content.push({ type: 'text', text: saved });\n for (const image of output.images) content.push({ type: 'image', data: image.data, mimeType: image.mimeType });\n return {\n content,\n ...(calls.length > 0 ? { details: { calls } } : {}),\n ...(result.ok ? {} : { isError: true }),\n };\n}\n\nfunction sleep(ms: number, signal: AbortSignal): Promise<void> {\n return new Promise((resolve, reject) => {\n if (signal.aborted) return reject(new Error('Run ended.'));\n const timer = setTimeout(resolve, Math.max(0, ms));\n signal.addEventListener(\n 'abort',\n () => {\n clearTimeout(timer);\n reject(new Error('Run ended.'));\n },\n { once: true },\n );\n });\n}\n\n/** `discover` and `exec` for one session, over the namespaces its packages contributed. */\nexport function createCodemodeTools({ registry, isolate, scripts }: CodemodeToolsOptions): CodemodeTools {\n let running = 0;\n\n const visible = (service: PoIsolateService): PoCodemodeNamespace[] =>\n registry.list().filter((namespace) => service.liveObjects || namespace.portable === true);\n\n // ponytail: the cockpit's generic tool item renders both for now; add a poWeb renderer for exec code and images when it earns one.\n // web-plugin-tool-renderers: ignore discover, plain text result\n const discover: CodemodeTools['discover'] = {\n name: 'discover',\n label: 'Discover',\n description:\n 'List the code-mode namespaces and reusable scripts you can use from `exec`, show one namespace in full, ' +\n 'or search members and scripts. ' +\n 'Not required before exec: its description already names the namespaces.',\n parameters: DiscoverToolSchema,\n promptSnippet: 'List code-mode namespaces and their TypeScript declarations',\n executionMode: 'parallel',\n async execute(_toolCallId, parameters: DiscoverToolParams, _signal, _onUpdate, execution) {\n const service = isolate();\n if (!service) return text('Code mode is not available on this host.', true);\n const namespaces = visible(service);\n // Imports need a host with live objects; the edge saves scripts but cannot chain them.\n const listed = scripts && service.liveObjects ? await scripts.list(activeDomains(execution)) : [];\n if (parameters.namespace !== undefined) {\n const found = namespaces.find((namespace) => namespace.name === parameters.namespace);\n if (!found) {\n const names = namespaces.map((namespace) => namespace.name).join(', ') || 'none';\n return text(`Unknown namespace \"${parameters.namespace}\". Registered: ${names}.`, true);\n }\n return text(truncate(found.declarations, MAX_DECLARATION_CHARS));\n }\n if (parameters.query !== undefined) {\n const needle = parameters.query.toLowerCase();\n const hits: string[] = [];\n for (const namespace of namespaces) {\n const lines = namespace.declarations.split('\\n');\n lines.forEach((line, index) => {\n if (!line.toLowerCase().includes(needle) || hits.length >= MAX_QUERY_LINES) return;\n const doc = lines[index - 1]?.trim().startsWith('/**') ? `${lines[index - 1]?.trim()} ` : '';\n hits.push(`${namespace.name}: ${doc}${line.trim()}`);\n });\n }\n for (const script of listed) {\n if (hits.length >= MAX_QUERY_LINES) break;\n if (`${script.specifier} ${script.description}`.toLowerCase().includes(needle)) {\n hits.push(`script ${script.specifier}: ${script.description}`);\n }\n }\n return text(hits.length > 0 ? hits.join('\\n') : `No members or scripts match \"${parameters.query}\".`);\n }\n const sections: string[] = [];\n if (namespaces.length === 0) sections.push('No namespaces are registered in this session.');\n for (const namespace of namespaces) {\n sections.push(`- ${namespace.name}: ${namespace.summary}\\n members: ${memberNames(namespace).join(', ')}`);\n }\n sections.push(GLOBALS_HELP);\n if (!service.liveObjects) sections.push('This host runs plain JavaScript with JSON-only functions.');\n if (listed.length > 0) {\n sections.push(`Scripts. ${SCRIPTS_HELP}`);\n for (const script of listed.slice(0, MAX_LISTED_SCRIPTS)) {\n sections.push(`- ${script.specifier}${script.description ? `: ${script.description}` : ''}`);\n }\n if (listed.length > MAX_LISTED_SCRIPTS) {\n sections.push(`...and ${listed.length - MAX_LISTED_SCRIPTS} more; use discover({ query }) to search.`);\n }\n }\n if (namespaces.length > 0) sections.push('Call discover({ namespace }) for full types.');\n return text(sections.join('\\n'));\n },\n };\n\n // web-plugin-tool-renderers: ignore exec, generic item until a code and image renderer exists\n const exec: CodemodeTools['exec'] = {\n name: 'exec',\n label: 'Exec',\n get description(): string {\n const service = isolate();\n const namespaces = service ? visible(service) : [];\n const listed = namespaces.map((namespace) => `- ${namespace.name}: ${namespace.summary}`).join('\\n');\n return [\n 'Run a TypeScript script inside the Po server with live objects from the namespaces below in scope.',\n 'It runs with full server trust, like bash. Keep each call to one logical step.',\n listed || '(no namespaces registered yet; call discover to check)',\n GLOBALS_HELP,\n ...(scripts && service?.liveObjects ? [`${SCRIPTS_HELP} discover lists saved and domain scripts.`] : []),\n 'Use discover({ namespace }) for full signatures when needed.',\n ].join('\\n');\n },\n parameters: ExecToolSchema,\n promptSnippet: 'Run a TypeScript script against live Po objects (browser and other namespaces)',\n executionMode: 'serial',\n async execute(_toolCallId, parameters: ExecToolParams, signal, _onUpdate, execution) {\n const service = isolate();\n if (!service) return text('Code mode is not available on this host.', true);\n if (running >= MAX_CONCURRENT_RUNS)\n return text(`This session already has ${MAX_CONCURRENT_RUNS} exec runs active. Wait for one to finish.`, true);\n running += 1;\n const controller = new AbortController();\n const runSignal = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;\n const cleanups: (() => void | Promise<void>)[] = [];\n const calls: PoCodemodeCall[] = [];\n const output = createOutput();\n const run: PoCodemodeRun = {\n sessionId: execution.sessionId,\n signal: runSignal,\n onDispose: (cleanup) => void cleanups.push(cleanup),\n record: (call) => {\n if (calls.length < MAX_RECORDED_CALLS) calls.push(recordedCall(call));\n },\n };\n try {\n let saved: string | undefined;\n try {\n const file = await scripts?.save(parameters.code);\n if (file) saved = `Saved as ${file.specifier} (${file.path})`;\n } catch (error) {\n output.note(`Could not save the script: ${error instanceof Error ? error.message : String(error)}`);\n }\n const globals: Record<string, unknown> = {\n console: output.console,\n image: output.addImage,\n sleep: (ms: number) => sleep(ms, runSignal),\n };\n const deny = new Set<string>();\n for (const namespace of visible(service)) {\n globals[namespace.name] = namespace.bind(run);\n for (const member of namespace.deny ?? []) deny.add(member);\n }\n const deadlineMs = Math.min(\n MAX_TIMEOUT_MS,\n Math.max(MIN_TIMEOUT_MS, parameters.timeoutMs ?? DEFAULT_TIMEOUT_MS),\n );\n const result = await service.run({\n source: parameters.code,\n globals,\n deadlineMs,\n signal: runSignal,\n deny: [...deny],\n onDiagnostic: output.note,\n ...(scripts ? { resolveImport: (specifier) => scripts.resolve(specifier, activeDomains(execution)) } : {}),\n });\n return toResult(result, output, saved, calls);\n } catch (error) {\n return text(\n `Code mode could not run the script: ${error instanceof Error ? error.message : String(error)}`,\n true,\n );\n } finally {\n controller.abort();\n for (const cleanup of cleanups.reverse()) {\n await Promise.resolve()\n .then(cleanup)\n .catch((error: unknown) => output.note(`cleanup failed: ${String(error)}`));\n }\n running -= 1;\n }\n },\n };\n\n return { discover, exec };\n}\n"],"mappings":";;;;;AASA,SAAgB,yBAA4C;CAC1D,MAAM,0BAAU,IAAI,IAAgE;CACpF,MAAM,0BAAU,IAAI,IAA4B;CAChD,MAAM,4BAAY,IAAI,IAAgB;CACtC,MAAM,eAAqB;EACzB,KAAK,MAAM,YAAY,WAAW,SAAS;CAC7C;CACA,OAAO;EACL,SAAS,QAAgB,WAAwD;GAC/E,CAAA,GAAA,4BAAA,4BAAA,CAA4B,UAAU,IAAI;GAC1C,MAAM,QAAQ,QAAQ,IAAI,UAAU,IAAI;GACxC,IAAI,OACF,MAAM,IAAI,MACR,wBAAwB,UAAU,KAAK,SAAS,OAAO,4BAA4B,MAAM,OAAO,EAClG;GAEF,MAAM,QAAQ;IAAE;IAAQ;GAAU;GAClC,QAAQ,IAAI,UAAU,MAAM,KAAK;GACjC,OAAO;GACP,OAAO,EACL,eAAe;IACb,IAAI,QAAQ,IAAI,UAAU,IAAI,MAAM,OAAO;IAC3C,QAAQ,OAAO,UAAU,IAAI;IAC7B,OAAO;GACT,EACF;EACF;EACA,YAAY,CAAC,GAAG,QAAQ,OAAO,CAAC,CAAC,CAAC,KAAK,UAAU,MAAM,SAAS;EAChE,gBAAgB,SAAiB,OAAuD;GACtF,MAAM,QAAQ;IAAE,QAAQ,MAAM;IAAQ,WAAW,MAAM;GAAU;GACjE,QAAQ,IAAI,KAAK;GACjB,OAAO;G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AO;MACrB,GAAI,UAAU,EAAE,gBAAgB,cAAc,QAAQ,QAAQ,WAAW,cAAc,SAAS,CAAC,EAAE,IAAI,CAAC;KAC1G,CAAC,GACuB,QAAQ,OAAO,KAAK;IAC9C,SAAS,OAAO;KACd,OAAO,KACL,uCAAuC,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK,KAC5F,IACF;IACF,UAAU;KACR,WAAW,MAAM;KACjB,KAAK,MAAM,WAAW,SAAS,QAAQ,GACrC,MAAM,QAAQ,QAAQ,CAAC,CACpB,KAAK,OAAO,CAAC,CACb,OAAO,UAAmB,OAAO,KAAK,mBAAmB,OAAO,KAAK,GAAG,CAAC;KAE9E,WAAW;IACb;GACF;EAGoB;CAAE;AAC1B"}
|
|
@@ -2,12 +2,11 @@ Object.defineProperties(exports, {
|
|
|
2
2
|
__esModule: { value: true },
|
|
3
3
|
[Symbol.toStringTag]: { value: "Module" }
|
|
4
4
|
});
|
|
5
|
-
const require_codemodeTools = require("../codemodeTools-
|
|
5
|
+
const require_codemodeTools = require("../codemodeTools-CLgSDqfU.cjs");
|
|
6
6
|
let _agimon_ai_po_core_codemode = require("@agimon-ai/po-core/codemode");
|
|
7
7
|
let _agimon_ai_po_core_serverPlugin = require("@agimon-ai/po-core/serverPlugin");
|
|
8
8
|
let _agimon_ai_po_core_extensionFile = require("@agimon-ai/po-core/extensionFile");
|
|
9
9
|
let _agimon_ai_po_core_platform = require("@agimon-ai/po-core/platform");
|
|
10
|
-
let _agimon_ai_po_core_help = require("@agimon-ai/po-core/help");
|
|
11
10
|
//#region src/services/codemodeScripts/index.ts
|
|
12
11
|
const SESSION_FOLDER = "codemode";
|
|
13
12
|
const SESSION_PREFIX = "session:";
|
|
@@ -151,14 +150,14 @@ var root_server_default = (0, _agimon_ai_po_core_extensionFile.defineRoot)(root)
|
|
|
151
150
|
//#region src/extensions/workspaces/sessions/(backend)/contract/codemode.server.ts
|
|
152
151
|
var codemode_server_default = (0, _agimon_ai_po_core_extensionFile.defineServiceContract)(_agimon_ai_po_core_codemode.PO_CODEMODE_SERVICE, { scope: "session" });
|
|
153
152
|
//#endregion
|
|
154
|
-
//#region src/extensions/workspaces/sessions/(backend)/resource/
|
|
155
|
-
var
|
|
156
|
-
name: "
|
|
153
|
+
//#region src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server.ts
|
|
154
|
+
var how_to_codemode_server_default = (0, _agimon_ai_po_core_extensionFile.defineResource)({
|
|
155
|
+
name: "how-to-codemode",
|
|
157
156
|
description: "Use @agimon-ai/po-codemode: Code mode for Po sessions: discover and exec over namespaces other packages contribute",
|
|
158
|
-
|
|
157
|
+
pinned: true,
|
|
159
158
|
kind: "skill",
|
|
160
|
-
path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/
|
|
161
|
-
read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/
|
|
159
|
+
path: (0, _agimon_ai_po_core_serverPlugin.packageResourcePath)(require("url").pathToFileURL(__filename).href, "src/prompts/how-to-codemode/SKILL.md"),
|
|
160
|
+
read: () => (0, _agimon_ai_po_core_serverPlugin.readPackageResource)(require("url").pathToFileURL(__filename).href, "src/prompts/how-to-codemode/SKILL.md")
|
|
162
161
|
});
|
|
163
162
|
//#endregion
|
|
164
163
|
//#region src/extensions/workspaces/sessions/(backend)/tool/discover.server.ts
|
|
@@ -187,7 +186,7 @@ const serverPlugin = (0, _agimon_ai_po_core_serverPlugin.defineServerPlugin)({
|
|
|
187
186
|
return {
|
|
188
187
|
...(0, _agimon_ai_po_core_extensionFile.composeRootHooks)(scopeSession),
|
|
189
188
|
get resources() {
|
|
190
|
-
return [at(
|
|
189
|
+
return [at(how_to_codemode_server_default, contextSession)];
|
|
191
190
|
},
|
|
192
191
|
get tools() {
|
|
193
192
|
return [via({ name: "discover" }, at(discover_server_default, contextSession)), via({ name: "exec" }, at(exec_server_default, contextSession))];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.cjs","names":["BACKGROUND_CONTEXT","getOrThrow","createCodemodeRegistry","PO_SERVER_SCOPE_SERVICE","requirePoServerScope","PO_CODEMODE_CONTRACT","PO_SESSION_FILES_SERVICE","readPoFs","createCodemodeTools","readPoIsolate","defineRoot","defineRoot","contribution","defineServiceContract","PO_CODEMODE_SERVICE","defineResource","PO_HELP_WHEN","packageResourcePath","readPackageResource","defineServerTool","defineServerTool","defineServerPlugin","composeServerProviderOverrides","rootSession","contractCodemode","composeRootInjects","composeRootHooks","resourcePoUseCodemode","toolDiscover","toolExec"],"sources":["../../src/services/codemodeScripts/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/contract/codemode.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/po-use-codemode.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/discover.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/exec.server.ts","../../generated/server.ts"],"sourcesContent":["import type { PoCodemodeService } from '@agimon-ai/po-core/codemode';\nimport { BACKGROUND_CONTEXT, getOrThrow, type FileSystem } from '@agimon-ai/po-core/platform';\n\nimport type { CodemodeScriptEntry, CodemodeScriptsPort } from './type';\n\nconst SESSION_FOLDER = 'codemode';\nconst SESSION_PREFIX = 'session:';\nconst EXTENSION = '.ts';\nconst EXEC_FILE = /^exec-(\\d+)\\.ts$/u;\nconst DOC_COMMENT = /^\\s*\\/\\*\\*([\\s\\S]*?)\\*\\//u;\nconst MAX_DESCRIPTION_CHARS = 160;\nconst DEFAULT_LIST_LIMIT = 200;\n\nexport interface CodemodeScriptsOptions {\n readonly registry: PoCodemodeService;\n /** Resolved per call, so services bound after the root still work. */\n readonly fs: () => FileSystem | undefined;\n /** The session's `po/session-files` temporary directory. */\n readonly temporaryDirectory: () => string | undefined;\n}\n\nconst withExtension = (name: string): string => (name.endsWith(EXTENSION) ? name : `${name}${EXTENSION}`);\n\n/** First paragraph of a leading `/** ... *\\/` comment, else the first line of code, on one line. */\nexport function describeScript(source: string): string {\n const doc = DOC_COMMENT.exec(source)?.[1];\n const lines = doc === undefined ? source.split('\\n') : doc.split('\\n').map((line) => line.replace(/^\\s*\\*\\s?/u, ''));\n const paragraph: string[] = [];\n for (const line of lines.map((item) => item.trim())) {\n if (line) paragraph.push(line);\n else if (paragraph.length > 0) break;\n if (doc === undefined && paragraph.length > 0) break;\n }\n const text = paragraph.join(' ');\n return text.length <= MAX_DESCRIPTION_CHARS ? text : `${text.slice(0, MAX_DESCRIPTION_CHARS - 3)}...`;\n}\n\n/** Session scripts live in `<temporaryDirectory>/codemode`; domain scripts in registered folders. */\nexport class FileSystemCodemodeScriptsService implements CodemodeScriptsPort {\n constructor(private readonly options: CodemodeScriptsOptions) {}\n\n private sessionDirectory(): string | undefined {\n const base = this.options.temporaryDirectory();\n return base === undefined ? undefined : `${base}/${SESSION_FOLDER}`;\n }\n\n private requireFs(): FileSystem {\n const fs = this.options.fs();\n if (!fs) throw new Error('Saved scripts need a file system, which this host does not provide.');\n return fs;\n }\n\n private sources(domains?: readonly string[]) {\n return this.options.registry.listScripts().filter((source) => !domains || domains.includes(source.domain));\n }\n\n /** `.ts` file names in a folder; a missing folder has none. */\n private async names(fs: FileSystem, directory: string): Promise<string[]> {\n const listed = await fs.listDir(directory, BACKGROUND_CONTEXT);\n if (!listed.ok && listed.error.code === 'not_found') return [];\n return getOrThrow(listed)\n .filter((info) => info.kind === 'file' && info.name.endsWith(EXTENSION))\n .map((info) => info.name)\n .sort((left, right) => left.localeCompare(right, undefined, { numeric: true }));\n }\n\n async save(code: string) {\n const fs = this.options.fs();\n const directory = this.sessionDirectory();\n if (!fs || directory === undefined) return undefined;\n getOrThrow(await fs.createDir(directory, { recursive: true }, BACKGROUND_CONTEXT));\n const taken = (await this.names(fs, directory)).map((name) => Number(EXEC_FILE.exec(name)?.[1] ?? 0));\n const name = `exec-${Math.max(0, ...taken) + 1}`;\n const path = `${directory}/${name}${EXTENSION}`;\n getOrThrow(await fs.writeFile(path, code, BACKGROUND_CONTEXT));\n return { specifier: `${SESSION_PREFIX}${name}`, path };\n }\n\n private candidates(specifier: string, domains?: readonly string[]): string[] {\n if (specifier.startsWith('/')) return [specifier];\n const session = this.sessionDirectory();\n if (specifier.startsWith(SESSION_PREFIX)) {\n return session === undefined ? [] : [`${session}/${withExtension(specifier.slice(SESSION_PREFIX.length))}`];\n }\n const slash = specifier.indexOf('/');\n const domain = slash > 0 ? specifier.slice(0, slash) : undefined;\n const folders = this.sources(domains).filter((source) => source.domain === domain);\n if (folders.length > 0) {\n return folders.map((source) => `${source.directory}/${withExtension(specifier.slice(slash + 1))}`);\n }\n if (session !== undefined && (specifier.startsWith('.') || specifier.endsWith(EXTENSION))) {\n return [`${session}/${withExtension(specifier.replace(/^\\.\\//u, ''))}`];\n }\n return [];\n }\n\n async resolve(specifier: string, domains?: readonly string[]) {\n const fs = this.requireFs();\n for (const path of this.candidates(specifier, domains)) {\n const read = await fs.readTextFile(path, BACKGROUND_CONTEXT);\n if (read.ok) return { id: path, source: read.value };\n if (read.error.code !== 'not_found') getOrThrow(read);\n }\n const available = (await this.list(domains)).map((entry) => entry.specifier).join(', ') || 'none';\n throw new Error(`Unknown script \"${specifier}\". Available: ${available}.`);\n }\n\n async list(domains?: readonly string[], limit = DEFAULT_LIST_LIMIT): Promise<CodemodeScriptEntry[]> {\n const fs = this.options.fs();\n if (!fs) return [];\n const found: { specifier: string; path: string }[] = [];\n for (const source of this.sources(domains)) {\n for (const name of await this.names(fs, source.directory)) {\n found.push({\n specifier: `${source.domain}/${name.slice(0, -EXTENSION.length)}`,\n path: `${source.directory}/${name}`,\n });\n }\n }\n const session = this.sessionDirectory();\n if (session !== undefined) {\n for (const name of (await this.names(fs, session)).reverse()) {\n found.push({ specifier: `${SESSION_PREFIX}${name.slice(0, -EXTENSION.length)}`, path: `${session}/${name}` });\n }\n }\n const entries: CodemodeScriptEntry[] = [];\n for (const entry of found.slice(0, limit)) {\n const read = await fs.readTextFile(entry.path, BACKGROUND_CONTEXT);\n entries.push({ ...entry, description: read.ok ? describeScript(read.value) : '' });\n }\n return entries;\n }\n}\n","import { PO_CODEMODE_CONTRACT } from '@agimon-ai/po-core/codemode';\nimport { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport { PO_SESSION_FILES_SERVICE, readPoFs, readPoIsolate } from '@agimon-ai/po-core/platform';\nimport {\n PO_SERVER_SCOPE_SERVICE,\n requirePoServerScope,\n type PoServerPluginContext,\n} from '@agimon-ai/po-core/serverPlugin';\n\nimport { createCodemodeRegistry } from '../../../../../services/codemodeRegistry';\nimport { FileSystemCodemodeScriptsService } from '../../../../../services/codemodeScripts';\nimport { createCodemodeTools } from '../../../../../services/codemodeTools';\n\n/** One registry per session: contributors register into it, `discover` and `exec` read it. */\nexport function createCodemodeSession({ context }: PoServerPluginContext) {\n const registry = createCodemodeRegistry();\n // The binding unwinds with this injected fiber, so the root needs no withdraw of its own.\n context.inject([PO_SERVER_SCOPE_SERVICE], (scoped) =>\n requirePoServerScope(scoped).provide(PO_CODEMODE_CONTRACT, registry),\n );\n let temporaryDirectory: string | undefined;\n context.inject([PO_SESSION_FILES_SERVICE], (scoped) => {\n temporaryDirectory = scoped.get(PO_SESSION_FILES_SERVICE)?.temporaryDirectory;\n return () => {\n temporaryDirectory = undefined;\n };\n });\n const scripts = new FileSystemCodemodeScriptsService({\n registry,\n fs: () => readPoFs(context),\n temporaryDirectory: () => temporaryDirectory,\n });\n const tools = createCodemodeTools({ registry, isolate: () => readPoIsolate(context), scripts });\n return { value: { registry, ...tools } };\n}\n\nconst root = defineRoot(createCodemodeSession);\nexport type CodemodeServerScope = Awaited<ReturnType<typeof root>>['value'];\nexport default root;\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\n\nimport contribution from './_lib/root.server';\n\nexport default defineRoot(contribution);\n","import { PO_CODEMODE_SERVICE, type PoCodemodeService } from '@agimon-ai/po-core/codemode';\nimport { defineServiceContract } from '@agimon-ai/po-core/extensionFile';\n\nexport default defineServiceContract<PoCodemodeService>(PO_CODEMODE_SERVICE, { scope: 'session' });\n","// @scaffold-generated\nimport { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { PO_HELP_WHEN } from '@agimon-ai/po-core/help';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'po-use-codemode',\n description:\n 'Use @agimon-ai/po-codemode: Code mode for Po sessions: discover and exec over namespaces other packages contribute',\n when: PO_HELP_WHEN,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/po-use-codemode/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/po-use-codemode/SKILL.md'),\n});\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool(\n (context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.discover,\n);\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool((context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.exec);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport contractCodemode from '../src/extensions/workspaces/sessions/(backend)/contract/codemode.server';\nimport resourcePoUseCodemode from '../src/extensions/workspaces/sessions/(backend)/resource/po-use-codemode.server';\nimport toolDiscover from '../src/extensions/workspaces/sessions/(backend)/tool/discover.server';\nimport toolExec from '../src/extensions/workspaces/sessions/(backend)/tool/exec.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-codemode',\n providerOverrides: composeServerProviderOverrides(rootSession),\n provides: {\n session: [contractCodemode],\n },\n injects: composeRootInjects({ session: [rootSession] }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourcePoUseCodemode, contextSession)]; },\n get tools(): PoServerSessionPlugin['tools'] { return [via({ name: 'discover' }, at(toolDiscover, contextSession)), via({ name: 'exec' }, at(toolExec, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;;AAKA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;AAU3B,MAAM,iBAAiB,SAA0B,KAAK,SAAS,SAAS,IAAI,OAAO,GAAG,OAAO;;AAG7F,SAAgB,eAAe,QAAwB;CACrD,MAAM,MAAM,YAAY,KAAK,MAAM,CAAC,GAAG;CACvC,MAAM,QAAQ,QAAQ,KAAA,IAAY,OAAO,MAAM,IAAI,IAAI,IAAI,MAAM,IAAI,CAAC,CAAC,KAAK,SAAS,KAAK,QAAQ,cAAc,EAAE,CAAC;CACnH,MAAM,YAAsB,CA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C,CAAC;GAAG;GACzK,UAAU,CAAC,GAAI,aAAa,YAAY,CAAC,CAAE;GAC3C,IAAI,aAAkD;IAAE,OAAO,CAAC,GAAI,aAAa,cAAc,CAAC,CAAE;GAAG;EACvG;CACF;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"server.cjs","names":["BACKGROUND_CONTEXT","getOrThrow","createCodemodeRegistry","PO_SERVER_SCOPE_SERVICE","requirePoServerScope","PO_CODEMODE_CONTRACT","PO_SESSION_FILES_SERVICE","readPoFs","createCodemodeTools","readPoIsolate","defineRoot","defineRoot","contribution","defineServiceContract","PO_CODEMODE_SERVICE","defineResource","packageResourcePath","readPackageResource","defineServerTool","defineServerTool","defineServerPlugin","composeServerProviderOverrides","rootSession","contractCodemode","composeRootInjects","composeRootHooks","resourceHowToCodemode","toolDiscover","toolExec"],"sources":["../../src/services/codemodeScripts/index.ts","../../src/extensions/workspaces/sessions/(backend)/_lib/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/root.server.ts","../../src/extensions/workspaces/sessions/(backend)/contract/codemode.server.ts","../../src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/discover.server.ts","../../src/extensions/workspaces/sessions/(backend)/tool/exec.server.ts","../../generated/server.ts"],"sourcesContent":["import type { PoCodemodeService } from '@agimon-ai/po-core/codemode';\nimport { BACKGROUND_CONTEXT, getOrThrow, type FileSystem } from '@agimon-ai/po-core/platform';\n\nimport type { CodemodeScriptEntry, CodemodeScriptsPort } from './type';\n\nconst SESSION_FOLDER = 'codemode';\nconst SESSION_PREFIX = 'session:';\nconst EXTENSION = '.ts';\nconst EXEC_FILE = /^exec-(\\d+)\\.ts$/u;\nconst DOC_COMMENT = /^\\s*\\/\\*\\*([\\s\\S]*?)\\*\\//u;\nconst MAX_DESCRIPTION_CHARS = 160;\nconst DEFAULT_LIST_LIMIT = 200;\n\nexport interface CodemodeScriptsOptions {\n readonly registry: PoCodemodeService;\n /** Resolved per call, so services bound after the root still work. */\n readonly fs: () => FileSystem | undefined;\n /** The session's `po/session-files` temporary directory. */\n readonly temporaryDirectory: () => string | undefined;\n}\n\nconst withExtension = (name: string): string => (name.endsWith(EXTENSION) ? name : `${name}${EXTENSION}`);\n\n/** First paragraph of a leading `/** ... *\\/` comment, else the first line of code, on one line. */\nexport function describeScript(source: string): string {\n const doc = DOC_COMMENT.exec(source)?.[1];\n const lines = doc === undefined ? source.split('\\n') : doc.split('\\n').map((line) => line.replace(/^\\s*\\*\\s?/u, ''));\n const paragraph: string[] = [];\n for (const line of lines.map((item) => item.trim())) {\n if (line) paragraph.push(line);\n else if (paragraph.length > 0) break;\n if (doc === undefined && paragraph.length > 0) break;\n }\n const text = paragraph.join(' ');\n return text.length <= MAX_DESCRIPTION_CHARS ? text : `${text.slice(0, MAX_DESCRIPTION_CHARS - 3)}...`;\n}\n\n/** Session scripts live in `<temporaryDirectory>/codemode`; domain scripts in registered folders. */\nexport class FileSystemCodemodeScriptsService implements CodemodeScriptsPort {\n constructor(private readonly options: CodemodeScriptsOptions) {}\n\n private sessionDirectory(): string | undefined {\n const base = this.options.temporaryDirectory();\n return base === undefined ? undefined : `${base}/${SESSION_FOLDER}`;\n }\n\n private requireFs(): FileSystem {\n const fs = this.options.fs();\n if (!fs) throw new Error('Saved scripts need a file system, which this host does not provide.');\n return fs;\n }\n\n private sources(domains?: readonly string[]) {\n return this.options.registry.listScripts().filter((source) => !domains || domains.includes(source.domain));\n }\n\n /** `.ts` file names in a folder; a missing folder has none. */\n private async names(fs: FileSystem, directory: string): Promise<string[]> {\n const listed = await fs.listDir(directory, BACKGROUND_CONTEXT);\n if (!listed.ok && listed.error.code === 'not_found') return [];\n return getOrThrow(listed)\n .filter((info) => info.kind === 'file' && info.name.endsWith(EXTENSION))\n .map((info) => info.name)\n .sort((left, right) => left.localeCompare(right, undefined, { numeric: true }));\n }\n\n async save(code: string) {\n const fs = this.options.fs();\n const directory = this.sessionDirectory();\n if (!fs || directory === undefined) return undefined;\n getOrThrow(await fs.createDir(directory, { recursive: true }, BACKGROUND_CONTEXT));\n const taken = (await this.names(fs, directory)).map((name) => Number(EXEC_FILE.exec(name)?.[1] ?? 0));\n const name = `exec-${Math.max(0, ...taken) + 1}`;\n const path = `${directory}/${name}${EXTENSION}`;\n getOrThrow(await fs.writeFile(path, code, BACKGROUND_CONTEXT));\n return { specifier: `${SESSION_PREFIX}${name}`, path };\n }\n\n private candidates(specifier: string, domains?: readonly string[]): string[] {\n if (specifier.startsWith('/')) return [specifier];\n const session = this.sessionDirectory();\n if (specifier.startsWith(SESSION_PREFIX)) {\n return session === undefined ? [] : [`${session}/${withExtension(specifier.slice(SESSION_PREFIX.length))}`];\n }\n const slash = specifier.indexOf('/');\n const domain = slash > 0 ? specifier.slice(0, slash) : undefined;\n const folders = this.sources(domains).filter((source) => source.domain === domain);\n if (folders.length > 0) {\n return folders.map((source) => `${source.directory}/${withExtension(specifier.slice(slash + 1))}`);\n }\n if (session !== undefined && (specifier.startsWith('.') || specifier.endsWith(EXTENSION))) {\n return [`${session}/${withExtension(specifier.replace(/^\\.\\//u, ''))}`];\n }\n return [];\n }\n\n async resolve(specifier: string, domains?: readonly string[]) {\n const fs = this.requireFs();\n for (const path of this.candidates(specifier, domains)) {\n const read = await fs.readTextFile(path, BACKGROUND_CONTEXT);\n if (read.ok) return { id: path, source: read.value };\n if (read.error.code !== 'not_found') getOrThrow(read);\n }\n const available = (await this.list(domains)).map((entry) => entry.specifier).join(', ') || 'none';\n throw new Error(`Unknown script \"${specifier}\". Available: ${available}.`);\n }\n\n async list(domains?: readonly string[], limit = DEFAULT_LIST_LIMIT): Promise<CodemodeScriptEntry[]> {\n const fs = this.options.fs();\n if (!fs) return [];\n const found: { specifier: string; path: string }[] = [];\n for (const source of this.sources(domains)) {\n for (const name of await this.names(fs, source.directory)) {\n found.push({\n specifier: `${source.domain}/${name.slice(0, -EXTENSION.length)}`,\n path: `${source.directory}/${name}`,\n });\n }\n }\n const session = this.sessionDirectory();\n if (session !== undefined) {\n for (const name of (await this.names(fs, session)).reverse()) {\n found.push({ specifier: `${SESSION_PREFIX}${name.slice(0, -EXTENSION.length)}`, path: `${session}/${name}` });\n }\n }\n const entries: CodemodeScriptEntry[] = [];\n for (const entry of found.slice(0, limit)) {\n const read = await fs.readTextFile(entry.path, BACKGROUND_CONTEXT);\n entries.push({ ...entry, description: read.ok ? describeScript(read.value) : '' });\n }\n return entries;\n }\n}\n","import { PO_CODEMODE_CONTRACT } from '@agimon-ai/po-core/codemode';\nimport { defineRoot } from '@agimon-ai/po-core/extensionFile';\nimport { PO_SESSION_FILES_SERVICE, readPoFs, readPoIsolate } from '@agimon-ai/po-core/platform';\nimport {\n PO_SERVER_SCOPE_SERVICE,\n requirePoServerScope,\n type PoServerPluginContext,\n} from '@agimon-ai/po-core/serverPlugin';\n\nimport { createCodemodeRegistry } from '../../../../../services/codemodeRegistry';\nimport { FileSystemCodemodeScriptsService } from '../../../../../services/codemodeScripts';\nimport { createCodemodeTools } from '../../../../../services/codemodeTools';\n\n/** One registry per session: contributors register into it, `discover` and `exec` read it. */\nexport function createCodemodeSession({ context }: PoServerPluginContext) {\n const registry = createCodemodeRegistry();\n // The binding unwinds with this injected fiber, so the root needs no withdraw of its own.\n context.inject([PO_SERVER_SCOPE_SERVICE], (scoped) =>\n requirePoServerScope(scoped).provide(PO_CODEMODE_CONTRACT, registry),\n );\n let temporaryDirectory: string | undefined;\n context.inject([PO_SESSION_FILES_SERVICE], (scoped) => {\n temporaryDirectory = scoped.get(PO_SESSION_FILES_SERVICE)?.temporaryDirectory;\n return () => {\n temporaryDirectory = undefined;\n };\n });\n const scripts = new FileSystemCodemodeScriptsService({\n registry,\n fs: () => readPoFs(context),\n temporaryDirectory: () => temporaryDirectory,\n });\n const tools = createCodemodeTools({ registry, isolate: () => readPoIsolate(context), scripts });\n return { value: { registry, ...tools } };\n}\n\nconst root = defineRoot(createCodemodeSession);\nexport type CodemodeServerScope = Awaited<ReturnType<typeof root>>['value'];\nexport default root;\n","import { defineRoot } from '@agimon-ai/po-core/extensionFile';\n\nimport contribution from './_lib/root.server';\n\nexport default defineRoot(contribution);\n","import { PO_CODEMODE_SERVICE, type PoCodemodeService } from '@agimon-ai/po-core/codemode';\nimport { defineServiceContract } from '@agimon-ai/po-core/extensionFile';\n\nexport default defineServiceContract<PoCodemodeService>(PO_CODEMODE_SERVICE, { scope: 'session' });\n","// @scaffold-generated\nimport { defineResource } from '@agimon-ai/po-core/extensionFile';\nimport { packageResourcePath, readPackageResource } from '@agimon-ai/po-core/serverPlugin';\n\nexport default defineResource({\n name: 'how-to-codemode',\n description:\n 'Use @agimon-ai/po-codemode: Code mode for Po sessions: discover and exec over namespaces other packages contribute',\n pinned: true,\n kind: 'skill' as const,\n path: packageResourcePath(import.meta.url, 'src/prompts/how-to-codemode/SKILL.md'),\n read: () => readPackageResource(import.meta.url, 'src/prompts/how-to-codemode/SKILL.md'),\n});\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool(\n (context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.discover,\n);\n","import { defineServerTool, type WithRoot } from '@agimon-ai/po-core/extensionFile';\nimport type { PoServerPluginContext } from '@agimon-ai/po-core/serverPlugin';\n\nimport type { CodemodeServerScope } from '../_lib/root.server';\n\nexport default defineServerTool((context: WithRoot<PoServerPluginContext, CodemodeServerScope>) => context.root.exec);\n","// Generated by @agimon-ai/po-build. Do not edit by hand.\nimport { defineServerPlugin, type PoServerSessionPlugin } from '@agimon-ai/po-core/serverPlugin';\nimport { composeServerProviderOverrides } from '@agimon-ai/po-core/serverPlugin';\nimport { composeRootHooks, composeRootInjects } from '@agimon-ai/po-core/extensionFile';\n\nimport rootSession from '../src/extensions/workspaces/sessions/(backend)/root.server';\nimport contractCodemode from '../src/extensions/workspaces/sessions/(backend)/contract/codemode.server';\nimport resourceHowToCodemode from '../src/extensions/workspaces/sessions/(backend)/resource/how-to-codemode.server';\nimport toolDiscover from '../src/extensions/workspaces/sessions/(backend)/tool/discover.server';\nimport toolExec from '../src/extensions/workspaces/sessions/(backend)/tool/exec.server';\n\ntype Factory<T, C> = (context: C) => T;\nconst at = <T, C>(value: T | Factory<T, C>, context: C): T =>\n typeof value === 'function' ? (value as Factory<T, C>)(context) : value;\nconst via = <T>(identity: Record<string, unknown>, value: unknown): T =>\n (value === undefined ? undefined : { ...identity, ...(value as object) }) as T;\n\nexport const serverPlugin = defineServerPlugin({\n name: '@agimon-ai/po-codemode',\n providerOverrides: composeServerProviderOverrides(rootSession),\n provides: {\n session: [contractCodemode],\n },\n injects: composeRootInjects({ session: [rootSession] }),\n session: async (context) => {\n const scopeSession = await context.scopeRoot('session', rootSession, context);\n const contextSession = { ...context, root: scopeSession.value };\n return {\n ...composeRootHooks(scopeSession),\n get resources(): PoServerSessionPlugin['resources'] { return [at(resourceHowToCodemode, contextSession)]; },\n get tools(): PoServerSessionPlugin['tools'] { return [via({ name: 'discover' }, at(toolDiscover, contextSession)), via({ name: 'exec' }, at(toolExec, contextSession))]; },\n services: [...(scopeSession.services ?? [])],\n get activities(): PoServerSessionPlugin['activities'] { return [...(scopeSession.activities ?? [])]; },\n };\n },\n});\n\nexport default serverPlugin;\n"],"mappings":";;;;;;;;;;AAKA,MAAM,iBAAiB;AACvB,MAAM,iBAAiB;AACvB,MAAM,YAAY;AAClB,MAAM,YAAY;AAClB,MAAM,cAAc;AACpB,MAAM,wBAAwB;AAC9B,MAAM,qBAAqB;AAU3B,MAAM,iBAAiB,SAA0B,KAAK,SAAS,SAAS,IAAI,OAAO,GAAG,OAAO;;AAG7F,SAAgB,eAAe,QAAwB;CACrD,MAAM,MAAM,YAAY,KAAK,MAAM,CAAC,GAAG;CACvC,MAAM,QAAQ,QAAQ,KAAA,IAAY,OAAO,MAAM,IAAI,IAAI,IAAI,MAAM,IA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