memeloop 0.1.2 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/browser.d.cts +14 -14
- package/dist/browser.d.ts +14 -14
- package/dist/{chunk-MAJWHAKR.js → chunk-5VYZV33O.js} +3 -2
- package/dist/{chunk-MAJWHAKR.js.map → chunk-5VYZV33O.js.map} +1 -1
- package/dist/chunk-ECNKBH5A.js +1235 -0
- package/dist/chunk-ECNKBH5A.js.map +1 -0
- package/dist/{chunk-MRKY4HGF.js → chunk-EPHRIRAL.js} +20 -11
- package/dist/chunk-EPHRIRAL.js.map +1 -0
- package/dist/{chunk-KFS2EJT6.js → chunk-K5KZJNDP.js} +2 -2
- package/dist/{chunk-2C6BJZI3.js → chunk-KV6TC5UJ.js} +3 -3
- package/dist/{chunk-T7FSXWFR.js → chunk-LGUGYRR4.js} +4 -4
- package/dist/{chunk-T7FSXWFR.js.map → chunk-LGUGYRR4.js.map} +1 -1
- package/dist/chunk-MXRXYGWW.js +1 -0
- package/dist/conversation.d.cts +3 -3
- package/dist/conversation.d.ts +3 -3
- package/dist/device-network-portable.cjs +757 -144
- package/dist/device-network-portable.cjs.map +1 -1
- package/dist/device-network-portable.d.cts +24 -14
- package/dist/device-network-portable.d.ts +24 -14
- package/dist/device-network-portable.js +18 -2
- package/dist/device-network.cjs +776 -154
- package/dist/device-network.cjs.map +1 -1
- package/dist/device-network.d.cts +5 -5
- package/dist/device-network.d.ts +5 -5
- package/dist/device-network.js +19 -3
- package/dist/{fetchProvider-WWnWnQFP.d.ts → fetchProvider-BhqRqi5-.d.ts} +1 -1
- package/dist/{fetchProvider-toTHy5Nu.d.cts → fetchProvider-HJ_FkORN.d.cts} +1 -1
- package/dist/index.cjs +785 -158
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +16 -16
- package/dist/index.d.ts +16 -16
- package/dist/index.js +26 -8
- package/dist/index.js.map +1 -1
- package/dist/{interface-IrKBFtL1.d.ts → interface-3C3eG8Hn.d.cts} +13 -1
- package/dist/{interface-IrKBFtL1.d.cts → interface-3C3eG8Hn.d.ts} +13 -1
- package/dist/llm-providers.d.cts +2 -2
- package/dist/llm-providers.d.ts +2 -2
- package/dist/loop-api.cjs +4 -3
- package/dist/loop-api.cjs.map +1 -1
- package/dist/loop-api.d.cts +7 -7
- package/dist/loop-api.d.ts +7 -7
- package/dist/loop-api.js +4 -4
- package/dist/mobile.cjs +3 -3
- package/dist/mobile.cjs.map +1 -1
- package/dist/mobile.d.cts +5 -5
- package/dist/mobile.d.ts +5 -5
- package/dist/mobile.js +2 -2
- package/dist/{orchestration-portable-BHB_YrNN.d.ts → orchestration-portable-BbkwLbC9.d.ts} +4 -4
- package/dist/{orchestration-portable-mvYBvGBb.d.cts → orchestration-portable-DNKzAtNq.d.cts} +4 -4
- package/dist/orchestration-portable.d.cts +5 -5
- package/dist/orchestration-portable.d.ts +5 -5
- package/dist/pairingInvite-DDx_-IAp.d.cts +271 -0
- package/dist/pairingInvite-Dkz8CLsb.d.ts +271 -0
- package/dist/{promptConcat-0WNFTg4l.d.ts → promptConcat-CUEIA_3T.d.ts} +3 -3
- package/dist/{promptConcat-D6wr5V-V.d.cts → promptConcat-VLe5SEN4.d.cts} +3 -3
- package/dist/{providerRegistry-CPsktuiX.d.cts → providerRegistry-BDGGs5gz.d.cts} +2 -2
- package/dist/{providerRegistry-Bi6pAvSj.d.ts → providerRegistry-CaFK_aUd.d.ts} +2 -2
- package/dist/{registry-D0kbxksn.d.cts → registry-DNSEVYug.d.cts} +3 -3
- package/dist/{registry-DDbvhlhs.d.ts → registry-yGnYHWhq.d.ts} +3 -3
- package/dist/{remoteClient-CBggnRy3.d.cts → remoteClient-BKmQEQY9.d.cts} +1 -1
- package/dist/{remoteClient-B_spK019.d.ts → remoteClient-D5hco6cS.d.ts} +1 -1
- package/dist/{runtime-PGWR6FIV.js → runtime-6EELHWVB.js} +3 -3
- package/dist/{scriptDeploymentPipeline-CXJcC82H.d.ts → scriptDeploymentPipeline-B1q-UhrO.d.ts} +1 -1
- package/dist/{scriptDeploymentPipeline-yG1ZhVVI.d.cts → scriptDeploymentPipeline-XJzQyYys.d.cts} +1 -1
- package/dist/{syncCloudDevices-Ds_Kcgrv.d.cts → syncCloudDevices-BFw_c1g5.d.cts} +6 -5
- package/dist/{syncCloudDevices-BEqwgrhD.d.ts → syncCloudDevices-C8fCUhnX.d.ts} +6 -5
- package/dist/{types-CdFVSntj.d.ts → types-C8gnhG9M.d.cts} +6 -4
- package/dist/{types-7pYti-k9.d.cts → types-CcFFIk8W.d.ts} +6 -4
- package/package.json +1 -1
- package/dist/chunk-426CJUZP.js +0 -630
- package/dist/chunk-426CJUZP.js.map +0 -1
- package/dist/chunk-MRKY4HGF.js.map +0 -1
- package/dist/chunk-VZKQX5PP.js +0 -1
- package/dist/pairingInvite-BXPWY3aM.d.cts +0 -149
- package/dist/pairingInvite-Cuz0wuq9.d.ts +0 -149
- /package/dist/{chunk-KFS2EJT6.js.map → chunk-K5KZJNDP.js.map} +0 -0
- /package/dist/{chunk-2C6BJZI3.js.map → chunk-KV6TC5UJ.js.map} +0 -0
- /package/dist/{chunk-VZKQX5PP.js.map → chunk-MXRXYGWW.js.map} +0 -0
- /package/dist/{runtime-PGWR6FIV.js.map → runtime-6EELHWVB.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/orchestration/agentClient.ts","../src/tools/schemaRegistry.ts","../src/orchestration/scripts/scriptRuntime.ts","../src/orchestration/scripts/scriptAdmission.ts","../src/orchestration/scripts/scriptValidation.ts","../src/orchestration/scripts/scriptDeploymentPipeline.ts","../src/loops/agent-agent-loop/builtinLoopSources.ts","../src/loopAPI/scriptLoader.ts","../src/loopAPI/agent-agent-loop/scriptLoader.ts","../src/loopAPI/agent-agent-loop/loop.ts","../src/loops/agent-tool-loop/builtinLoopSources.ts","../src/loopAPI/agent-tool-loop/scriptLoader.ts","../src/loopAPI/agent-tool-loop/scriptRunner.ts","../src/loopAPI/agent-tool-loop/loop.ts","../src/loopAPI/plugins/builtinLoopsPlugin.ts","../src/tools/builtins/askQuestion.ts","../src/tools/builtins/questionWaitRegistry.ts","../src/tools/builtins/askUserQuestion.ts","../src/tools/builtins/mcpClient.ts","../src/tools/builtins/mcpForward.ts","../src/tools/builtins/orchestration.ts","../src/tools/builtins/remoteAgent.ts","../src/tools/builtins/spawnAgent.ts","../src/agent/agentProfiles.ts","../src/agent/agentProfileRegistry.ts","../src/tools/builtins/task.ts","../src/tools/builtins/todoWrite.ts","../src/loopAPI/plugins/builtinToolsPlugin.ts","../src/promptUtilities/builtinPromptPlugins.ts","../src/runtime.ts"],"sourcesContent":["import type { AgentOrchestrationClient } from './client.js';\nimport type { OrchestrationOwnerReference } from './client.js';\nimport { OrchestrationError } from './errors.js';\nimport type {\n AgentRunCondition,\n AgentRunManifest,\n AgentRunResource,\n AgentTrustLevel,\n AgentWorkloadCompletionPolicy,\n AgentWorkloadCondition,\n AgentWorkloadManifest,\n AgentWorkloadModelPolicy,\n AgentWorkloadNetworkPolicy,\n AgentWorkloadPlacement,\n AgentWorkloadResource,\n AgentWorkloadStoragePolicy,\n AgentWorkloadToolPolicy,\n} from './resources.js';\nimport { agentRunReference, agentWorkloadReference, createAgentRunManifest, createAgentWorkloadManifest, isAgentRun, isAgentWorkload } from './resources.js';\n\nexport interface CreateAgentWorkloadOptions {\n name?: string;\n generateName?: string;\n namespace?: string;\n profileId?: string;\n scriptReference?: string;\n promptReference?: string;\n trust?: AgentTrustLevel;\n placement?: AgentWorkloadPlacement;\n modelPolicy?: AgentWorkloadModelPolicy;\n toolPolicy?: AgentWorkloadToolPolicy;\n networkPolicy?: AgentWorkloadNetworkPolicy;\n storagePolicy?: AgentWorkloadStoragePolicy;\n completionPolicy?: AgentWorkloadCompletionPolicy;\n ownerReferences?: OrchestrationOwnerReference[];\n idempotencyKey?: string;\n}\n\nexport interface CreateAgentRunOptions {\n name?: string;\n generateName?: string;\n namespace?: string;\n workloadName: string;\n workloadNamespace?: string;\n promptReference?: string;\n retry?: number;\n timeoutMs?: number;\n idempotencyKey?: string;\n}\n\nexport interface WaitForConditionOptions {\n timeout?: number;\n interval?: number;\n signal?: AbortSignal;\n /** Host cancellation hook for runtimes that expose a boolean marker instead of AbortSignal. */\n isCancelled?: () => boolean;\n}\n\nexport interface AgentClient {\n createWorkload(options: CreateAgentWorkloadOptions): Promise<AgentWorkloadResource>;\n getWorkload(name: string, namespace?: string): Promise<AgentWorkloadResource | null>;\n deleteWorkload(name: string, namespace?: string): Promise<void>;\n waitForWorkloadCondition(\n name: string,\n condition: AgentWorkloadCondition,\n options?: WaitForConditionOptions,\n ): Promise<{ observedResourceVersion: string; matched: true }>;\n\n createRun(options: CreateAgentRunOptions): Promise<AgentRunResource>;\n getRun(name: string, namespace?: string): Promise<AgentRunResource | null>;\n deleteRun(name: string, namespace?: string): Promise<void>;\n waitForRunCondition(\n name: string,\n condition: AgentRunCondition,\n options?: WaitForConditionOptions,\n ): Promise<{ observedResourceVersion: string; matched: true }>;\n}\n\nfunction requireName(name: string | undefined, generateName: string | undefined, label: string): string {\n if (name) return name;\n if (generateName) return `${generateName}${Math.random().toString(36).slice(2, 8)}`;\n throw new OrchestrationError({ code: 'INVALID', message: `${label} requires name or generateName`, retryable: false });\n}\n\nconst CANCELLATION_POLL_INTERVAL_MS = 50;\n\nfunction cancellationError(lastResourceVersion: string): OrchestrationError {\n return new OrchestrationError({\n code: 'CANCELLED',\n message: 'condition wait cancelled',\n retryable: false,\n details: { lastResourceVersion },\n });\n}\n\nfunction throwIfCancelled(options: WaitForConditionOptions, lastResourceVersion: string): void {\n if (options.signal?.aborted || options.isCancelled?.() === true) {\n throw cancellationError(lastResourceVersion);\n }\n}\n\nfunction abortableDelay(ms: number, signal: AbortSignal | undefined, lastResourceVersion: string): Promise<void> {\n if (!signal) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timeout);\n signal.removeEventListener('abort', onAbort);\n reject(cancellationError(lastResourceVersion));\n };\n const timeout = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal.addEventListener('abort', onAbort, { once: true });\n if (signal.aborted) onAbort();\n });\n}\n\nasync function waitInterval(ms: number, options: WaitForConditionOptions, lastResourceVersion: string): Promise<void> {\n if (!options.isCancelled) {\n await abortableDelay(ms, options.signal, lastResourceVersion);\n return;\n }\n\n for (let remaining = ms; remaining > 0; remaining -= CANCELLATION_POLL_INTERVAL_MS) {\n throwIfCancelled(options, lastResourceVersion);\n await abortableDelay(Math.min(remaining, CANCELLATION_POLL_INTERVAL_MS), options.signal, lastResourceVersion);\n }\n throwIfCancelled(options, lastResourceVersion);\n}\n\nexport async function waitForCondition<\n TResource extends { metadata?: { resourceVersion?: string }; status?: { conditions?: Array<{ type: string; status: 'True' | 'False' | 'Unknown' }> } },\n>(\n get: () => Promise<TResource | null>,\n condition: { type: string; status: 'True' | 'False' | 'Unknown' },\n options: WaitForConditionOptions,\n): Promise<{ observedResourceVersion: string; matched: true }> {\n const intervalMs = Math.max(100, options.interval ?? 1000);\n const timeoutMs = options.timeout ?? 30_000;\n const deadline = Date.now() + timeoutMs;\n let lastResourceVersion = '0';\n\n while (true) {\n throwIfCancelled(options, lastResourceVersion);\n const resource = await get();\n throwIfCancelled(options, lastResourceVersion);\n if (resource) {\n lastResourceVersion = resource.metadata?.resourceVersion ?? '0';\n const match = resource.status?.conditions?.find(\n (candidate) => candidate.type === condition.type && candidate.status === condition.status,\n );\n if (match) {\n return { observedResourceVersion: lastResourceVersion, matched: true };\n }\n }\n\n if (Date.now() + intervalMs > deadline) {\n throw new OrchestrationError({\n code: 'TIMEOUT',\n message: `condition ${condition.type}=${condition.status} not met within ${timeoutMs}ms`,\n retryable: true,\n details: { lastResourceVersion },\n });\n }\n\n await waitInterval(intervalMs, options, lastResourceVersion);\n }\n}\n\nexport function createAgentClient(client: AgentOrchestrationClient, defaultNamespace?: string): AgentClient {\n function resolveNamespace(namespace?: string): string | undefined {\n return namespace ?? defaultNamespace;\n }\n\n return {\n async createWorkload(options: CreateAgentWorkloadOptions): Promise<AgentWorkloadResource> {\n const name = requireName(options.name, options.generateName, 'AgentWorkload');\n const manifest: AgentWorkloadManifest = createAgentWorkloadManifest(name, {\n profileId: options.profileId,\n scriptReference: options.scriptReference,\n promptReference: options.promptReference,\n trust: options.trust,\n placement: options.placement,\n modelPolicy: options.modelPolicy,\n toolPolicy: options.toolPolicy,\n networkPolicy: options.networkPolicy,\n storagePolicy: options.storagePolicy,\n completionPolicy: options.completionPolicy,\n ownerReferences: options.ownerReferences,\n });\n const result = await client.apply(manifest, {\n idempotencyKey: options.idempotencyKey,\n fieldManager: 'memeloop-agent-client',\n });\n if (!isAgentWorkload(result)) {\n throw new OrchestrationError({ code: 'UNKNOWN_EFFECT', message: 'apply returned a non-AgentWorkload resource', retryable: false });\n }\n return result;\n },\n\n async getWorkload(name: string, namespace?: string): Promise<AgentWorkloadResource | null> {\n const result = await client.get(agentWorkloadReference(name, resolveNamespace(namespace)));\n return result && isAgentWorkload(result) ? result : null;\n },\n\n async deleteWorkload(name: string, namespace?: string): Promise<void> {\n await client.delete(agentWorkloadReference(name, resolveNamespace(namespace)));\n },\n\n async waitForWorkloadCondition(\n name: string,\n condition: AgentWorkloadCondition,\n options: WaitForConditionOptions = {},\n ): Promise<{ observedResourceVersion: string; matched: true }> {\n return waitForCondition(\n () => this.getWorkload(name, defaultNamespace),\n condition,\n options,\n );\n },\n\n async createRun(options: CreateAgentRunOptions): Promise<AgentRunResource> {\n const name = requireName(options.name, options.generateName, 'AgentRun');\n const manifest: AgentRunManifest = createAgentRunManifest(name, {\n workloadRef: agentWorkloadReference(options.workloadName, options.workloadNamespace ?? defaultNamespace),\n promptReference: options.promptReference,\n retry: options.retry,\n timeoutMs: options.timeoutMs,\n });\n const result = await client.apply(manifest, {\n idempotencyKey: options.idempotencyKey,\n fieldManager: 'memeloop-agent-client',\n });\n if (!isAgentRun(result)) {\n throw new OrchestrationError({ code: 'UNKNOWN_EFFECT', message: 'apply returned a non-AgentRun resource', retryable: false });\n }\n return result;\n },\n\n async getRun(name: string, namespace?: string): Promise<AgentRunResource | null> {\n const result = await client.get(agentRunReference(name, resolveNamespace(namespace)));\n return result && isAgentRun(result) ? result : null;\n },\n\n async deleteRun(name: string, namespace?: string): Promise<void> {\n await client.delete(agentRunReference(name, resolveNamespace(namespace)));\n },\n\n async waitForRunCondition(\n name: string,\n condition: AgentRunCondition,\n options: WaitForConditionOptions = {},\n ): Promise<{ observedResourceVersion: string; matched: true }> {\n return waitForCondition(\n () => this.getRun(name, defaultNamespace),\n condition,\n options,\n );\n },\n };\n}\n","import { zodToJsonSchema } from 'zod-to-json-schema';\n\nconst toolSchemas = new Map<string, unknown>();\nconst toolMetadata = new Map<string, { displayName: string; description: string }>();\n\n/**\n * Convert either a legacy host's Zod 3 schema, a current Zod 4 schema,\n * schema, or an already portable JSON Schema without silently widening a\n * registered tool to an unconstrained object.\n */\nexport function toolSchemaToJsonSchema(value: unknown): Record<string, unknown> {\n const native = (\n value as { toJSONSchema?: () => Record<string, unknown> } | undefined\n )?.toJSONSchema?.();\n if (native) return structuredClone(native);\n\n if (value !== null && typeof value === 'object' && '_def' in value) {\n const converted = zodToJsonSchema(value as never, {\n $refStrategy: 'none',\n });\n return structuredClone(converted as Record<string, unknown>);\n }\n\n if (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n ('type' in value ||\n 'properties' in value ||\n '$ref' in value ||\n 'oneOf' in value ||\n 'anyOf' in value)\n ) {\n return structuredClone(value as Record<string, unknown>);\n }\n\n throw new TypeError(\n 'Tool parameter schema must be a Zod schema or a portable JSON Schema',\n );\n}\n\nexport function registerToolParameterSchema(\n toolId: string,\n schema: unknown,\n metadata?: { displayName: string; description: string },\n): void {\n toolSchemas.set(toolId, schema);\n if (metadata) {\n toolMetadata.set(toolId, metadata);\n }\n}\n\nexport function getToolParameterSchema(toolId: string): unknown {\n return toolSchemas.get(toolId);\n}\n\nexport function getToolMetadata(\n toolId: string,\n): { displayName: string; description: string } | undefined {\n return toolMetadata.get(toolId);\n}\n","/**\n * Script sandbox/runtime selection (plan 24.18) and remote deployment (plan 24.14).\n *\n * - RuntimeClass: declares module isolation, resource limits, cancellation,\n * and supported trust classes for generated scripts.\n * - Sandbox selection: maps script trust class to appropriate RuntimeClass.\n * - Remote deployment: script declares placement desires; scheduler picks node.\n *\n * Scripts cannot silently run in an unrestricted controller process.\n */\n\nimport type { ScriptTrustClass } from './scriptAdmission.js';\n\n// ─── RuntimeClass ──────────────────────────────────────────────────────\n\nexport interface RuntimeClassSpec {\n /** Module isolation level. */\n isolation: 'none' | 'process' | 'container';\n /** CPU limit in millicores (1000 = 1 core). */\n cpuLimitMillis?: number;\n /** Memory limit in bytes. */\n memoryLimitBytes?: number;\n /** Wall-clock time limit in milliseconds. */\n timeLimitMs?: number;\n /** Whether the runtime supports cancellation signals. */\n supportsCancellation: boolean;\n /** Supported trust classes for this runtime. */\n supportedTrustClasses: ScriptTrustClass[];\n /** Whether network access is allowed (outbound-only for quarantine). */\n networkAccess: 'none' | 'outbound-only' | 'full';\n}\n\nexport interface RuntimeClassResource {\n apiVersion: 'execution.memeloop.io/v1alpha1';\n kind: 'RuntimeClass';\n metadata: {\n name: string;\n namespace?: string;\n };\n spec: RuntimeClassSpec;\n}\n\n// ─── Built-in Runtime Classes ──────────────────────────────────────────\n\nexport const BUILTIN_RUNTIME_CLASSES: Record<string, RuntimeClassSpec> = {\n 'trusted-process': {\n isolation: 'process',\n cpuLimitMillis: 2000,\n memoryLimitBytes: 512 * 1024 * 1024, // 512 MiB\n timeLimitMs: 300_000, // 5 min\n supportsCancellation: true,\n supportedTrustClasses: ['trusted'],\n networkAccess: 'full',\n },\n 'restricted-process': {\n isolation: 'process',\n cpuLimitMillis: 1000,\n memoryLimitBytes: 128 * 1024 * 1024, // 128 MiB\n timeLimitMs: 120_000, // 2 min\n supportsCancellation: true,\n supportedTrustClasses: ['trusted', 'restricted'],\n networkAccess: 'outbound-only',\n },\n 'quarantine-process': {\n isolation: 'process',\n cpuLimitMillis: 500,\n // A Node VM plus the trusted worker bootstrap needs more than 32 MiB RSS;\n // the Linux host enforces this value as cgroup MemoryMax, not only V8 heap.\n memoryLimitBytes: 96 * 1024 * 1024, // 96 MiB\n timeLimitMs: 30_000, // 30 sec\n supportsCancellation: true,\n supportedTrustClasses: ['quarantine'],\n networkAccess: 'none',\n },\n};\n\n// ─── Sandbox Selection ─────────────────────────────────────────────────\n\nexport interface SandboxSelectionResult {\n runtimeClass: string;\n isolation: RuntimeClassSpec['isolation'];\n cpuLimitMillis: number;\n memoryLimitBytes: number;\n timeLimitMs: number;\n networkAccess: RuntimeClassSpec['networkAccess'];\n}\n\n/**\n * Select the most restrictive RuntimeClass capable of hosting the given\n * trust class. Throws when no available RuntimeClass supports the trust\n * class — there is no silent fallback (24.18).\n */\nexport function selectRuntimeClass(trustClass: ScriptTrustClass, available: string[] = Object.keys(BUILTIN_RUNTIME_CLASSES)): SandboxSelectionResult {\n // Prefer exact match by trust class.\n const exact = available.find((name) => {\n const spec = BUILTIN_RUNTIME_CLASSES[name];\n return spec?.supportedTrustClasses.includes(trustClass);\n });\n\n if (!exact) {\n throw new Error('No RuntimeClass available for trust class: ' + trustClass);\n }\n const name = exact;\n const spec = BUILTIN_RUNTIME_CLASSES[name];\n\n return {\n runtimeClass: name,\n isolation: spec.isolation,\n cpuLimitMillis: spec.cpuLimitMillis ?? 500,\n memoryLimitBytes: spec.memoryLimitBytes ?? 32 * 1024 * 1024,\n timeLimitMs: spec.timeLimitMs ?? 30_000,\n networkAccess: spec.networkAccess,\n };\n}\n\n// ─── Remote Deployment Descriptor ──────────────────────────────────────\n\n/**\n * Reference to a content-addressed ArtifactRecord holding the script source\n * (plan 24.15/24.47). Remote deployments never carry raw script source\n * strings; the target node resolves the artifact by identity and verifies\n * it against `contentDigest` before loading.\n */\nexport interface ScriptArtifactReference {\n /** API version of the artifact resource (`artifacts.memeloop.io/v1alpha1`). */\n apiVersion: string;\n /** Resource kind; always `ArtifactRecord`. */\n kind: 'ArtifactRecord';\n /** Artifact resource name. */\n name: string;\n /** Artifact namespace, if any. */\n namespace?: string;\n /**\n * Content digest (`sha256:<hex>`) of the NORMALIZED script source. The\n * remote node must verify the fetched artifact content against this\n * digest before admission.\n */\n contentDigest: string;\n}\n\nexport interface RemoteDeploymentRequest {\n /**\n * Content-addressed reference to the script artifact. Raw script source\n * is never transported inside a deployment request.\n */\n artifactRef: ScriptArtifactReference;\n /** Trust class assigned by admission. */\n trustClass: ScriptTrustClass;\n /** Desired lifecycle. */\n lifecycle: 'run-once' | 'service' | 'schedule';\n /** Runtime class to use. */\n runtimeClass: string;\n /** Node selector for scheduling. */\n nodeSelector?: Record<string, string>;\n /** Environment variables (never credentials). */\n env?: Record<string, string>;\n /** Network attachment requirements enforced before the script starts. */\n networkPolicy?: import('../resources.js').AgentWorkloadNetworkPolicy;\n /** Existing claims to publish before the script starts. */\n storagePolicy?: import('../resources.js').AgentWorkloadStoragePolicy;\n}\n\nexport interface RemoteDeploymentResult {\n /** Workload name created on the target node. */\n workloadName: string;\n /** Node the workload was placed on. */\n nodeName: string;\n /** When the deployment was requested. */\n requestedAt: string;\n}\n","/**\n * Script admission policy and checkpoint compatibility (plan 24.17, 24.19).\n *\n * - Admission: trust class, author, imports, resource limits, approval\n * - Compatibility: script digest/API version vs checkpoint schema\n *\n * Quarantine scripts cannot enable arbitrary network imports or plugin loading.\n * A changed script cannot resume an incompatible checkpoint without explicit\n * converter or restart policy.\n */\n\nimport type { ScriptValidationResult } from './scriptValidation.js';\n\nexport type ScriptTrustClass = 'trusted' | 'restricted' | 'quarantine';\n\nexport interface ScriptAdmissionRequest {\n /** The validated script result. */\n script: ScriptValidationResult;\n /** Trust class of the author (e.g., the Agent that generated the script). */\n authorTrust: ScriptTrustClass;\n /** Requested interfaces the script wants to use. */\n requestedInterfaces: string[];\n /** Optional checkpoint digest the script expects to resume from. */\n expectedCheckpointDigest?: string;\n /** The checkpoint's API version (for compatibility check). */\n checkpointApiVersion?: string;\n}\n\nexport interface ScriptAdmissionDecision {\n admitted: boolean;\n reason: string;\n /** Which interfaces are approved for this script. */\n approvedInterfaces: string[];\n /** Whether the checkpoint is compatible. */\n checkpointCompatible: boolean;\n /** If not admitted, whether the author can retry with changes. */\n retryable: boolean;\n}\n\ninterface TrustProfile {\n maxScriptBytes: number;\n allowedInterfaces: string[];\n forbiddenImports: string[];\n requireDefaultExport: boolean;\n allowUntrustedInputs: boolean;\n}\n\nconst TRUST_PROFILES: Record<ScriptTrustClass, TrustProfile> = {\n trusted: {\n maxScriptBytes: 1_048_576, // 1 MiB\n allowedInterfaces: ['resource', 'loop-runtime', 'tool-execution', 'model-provider', 'network', 'storage', 'credential-broker', 'artifact'],\n forbiddenImports: [],\n requireDefaultExport: true,\n allowUntrustedInputs: false,\n },\n restricted: {\n maxScriptBytes: 256_000, // 256 KiB\n allowedInterfaces: ['resource', 'loop-runtime', 'model-provider'],\n forbiddenImports: ['node:fs', 'node:child_process', 'node:net', 'node:http', 'node:https'],\n requireDefaultExport: true,\n allowUntrustedInputs: false,\n },\n quarantine: {\n maxScriptBytes: 64_000, // 64 KiB\n allowedInterfaces: ['loop-runtime'], // No network, no file system, no model provider\n forbiddenImports: ['node:fs', 'node:child_process', 'node:net', 'node:http', 'node:https', 'node:os', 'node:crypto'],\n requireDefaultExport: true,\n allowUntrustedInputs: false,\n },\n};\n\nconst COMPATIBLE_CHECKPOINT_VERSIONS = new Set(['loops.memeloop.io/v1alpha1']);\n\n/**\n * The full interface set a host may grant to scripts authored under the\n * given trust class — a defensive copy of the trust profile's allowlist.\n *\n * Hosts wiring a {@link ../loopAPI/types.ScriptLoadGate} or a deployment\n * pipeline should pass these as `requestedInterfaces`; {@link admitScript}\n * rejects any request outside the trust profile, so this is the widest set\n * that can ever be approved for that class. Callers may pass a narrower\n * subset to further restrict a specific runtime.\n */\nexport function defaultRequestedInterfacesForTrustClass(trustClass: ScriptTrustClass): string[] {\n return [...TRUST_PROFILES[trustClass].allowedInterfaces];\n}\n\n/** Maximum script size in bytes admitted for the given trust class. */\nexport function maxScriptBytesForTrustClass(trustClass: ScriptTrustClass): number {\n return TRUST_PROFILES[trustClass].maxScriptBytes;\n}\n\n/**\n * Decide whether a generated script may be admitted for execution.\n */\nexport function admitScript(request: ScriptAdmissionRequest): ScriptAdmissionDecision {\n const profile = TRUST_PROFILES[request.authorTrust];\n const approvedInterfaces: string[] = [];\n\n // 1. Size check.\n if (request.script.sizeBytes > profile.maxScriptBytes) {\n return {\n admitted: false,\n reason: `Script size ${request.script.sizeBytes} exceeds ${request.authorTrust} limit ${profile.maxScriptBytes}`,\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: true,\n };\n }\n\n // 2. Syntax check.\n if (!request.script.valid) {\n return {\n admitted: false,\n reason: `Script validation failed: ${request.script.errors.join('; ')}`,\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: true,\n };\n }\n\n // 3. Export check.\n if (profile.requireDefaultExport && !request.script.hasDefaultExport) {\n return {\n admitted: false,\n reason: 'Script must export a default async generator',\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: true,\n };\n }\n\n // 4. Import policy.\n for (const imp of request.script.imports) {\n // Forbidden imports per trust profile.\n if (profile.forbiddenImports.includes(imp) || profile.forbiddenImports.includes(imp.replace(/^node:/, ''))) {\n return {\n admitted: false,\n reason: `Import '${imp}' not allowed for ${request.authorTrust} scripts`,\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: false,\n };\n }\n }\n\n // 5. Interface policy.\n for (const iface of request.requestedInterfaces) {\n if (!profile.allowedInterfaces.includes(iface)) {\n return {\n admitted: false,\n reason: `Interface '${iface}' not allowed for ${request.authorTrust} scripts`,\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: false,\n };\n }\n approvedInterfaces.push(iface);\n }\n\n // 6. Checkpoint compatibility.\n let checkpointCompatible = true;\n if (request.expectedCheckpointDigest && request.checkpointApiVersion) {\n if (!COMPATIBLE_CHECKPOINT_VERSIONS.has(request.checkpointApiVersion)) {\n checkpointCompatible = false;\n }\n // Changed script digest cannot resume old checkpoint without explicit converter.\n if (request.expectedCheckpointDigest !== request.script.digest) {\n checkpointCompatible = false;\n }\n }\n\n return {\n admitted: true,\n reason: `Admitted as ${request.authorTrust}`,\n approvedInterfaces,\n checkpointCompatible,\n retryable: false,\n };\n}\n","/**\n * Generated-script validation and normalization (plan 24.16).\n *\n * Validates Agent-generated .mjs scripts before they are scheduled:\n * - Syntax check via a real JavaScript parser (Acorn) — regexes could be\n * fooled by comments/strings/regex literals; an AST cannot.\n * - Required export shape: the default export must be an async generator\n * function (inline or via an identifier bound to one in the same module).\n * - Import extraction from the AST: static `import` declarations, re-exports\n * (`export ... from`), and string-literal dynamic `import()` arguments.\n * Non-literal dynamic imports are rejected because they defeat admission.\n * - Forbidden imports: no Node builtins except 'node:events'.\n * - Size limits.\n * - Canonical SHA-256 digest for provenance. The digest commits to the\n * NORMALIZED source (see {@link normalizeScript}), so semantically\n * identical scripts with different line endings share one digest.\n *\n * Security note: this runs in the controller process, but never executes\n * the script. Execution is delegated to the sandbox from plan 24.48.\n */\n\nimport { parse } from 'acorn';\n\nconst MAX_SCRIPT_BYTES = 1_048_576; // 1 MiB\n\nexport interface ScriptValidationResult {\n valid: boolean;\n /**\n * Canonical SHA-256 hex digest of the NORMALIZED source\n * (`normalizeScript(source)`). The digest commits to the normalized form,\n * not the raw bytes, so CRLF/LF variants of the same script are equal.\n */\n digest: string;\n /** Detected imports, from the AST (static, re-export, literal dynamic). */\n imports: string[];\n /** Whether the script's default export is an async generator function. */\n hasDefaultExport: boolean;\n /**\n * Whether the script contains a dynamic `import()` whose argument is not\n * a string literal. Such scripts are always invalid: the import target\n * cannot be known statically, which defeats admission control.\n */\n hasNonLiteralDynamicImport: boolean;\n /** Human-readable errors if invalid. */\n errors: string[];\n /** Normalized source size in bytes. */\n sizeBytes: number;\n}\n\n/** Minimal structural type for generic AST traversal. */\ninterface AstNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isAstNode(value: unknown): value is AstNode {\n return typeof value === 'object' && value !== null && typeof (value as AstNode).type === 'string';\n}\n\n/**\n * Recursively visit every node in an ESTree AST. Only properties holding\n * node-like values (objects/arrays of objects with a string `type`) are\n * traversed, so scalar fields (names, literals, ranges) are skipped.\n */\nfunction walkAst(node: AstNode, visit: (node: AstNode) => void): void {\n visit(node);\n for (const key of Object.keys(node)) {\n const value: unknown = node[key];\n if (Array.isArray(value)) {\n for (const child of value as unknown[]) {\n if (isAstNode(child)) walkAst(child, visit);\n }\n } else if (isAstNode(value)) {\n walkAst(value, visit);\n }\n }\n}\n\nfunction isAsyncGeneratorFunction(node: AstNode | null | undefined): boolean {\n if (!node) return false;\n return (\n (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') &&\n node.async === true &&\n node.generator === true\n );\n}\n\nfunction getStaticImportSource(node: AstNode): string | undefined {\n const source = node.source as AstNode | null | undefined;\n if (source && source.type === 'Literal' && typeof source.value === 'string') {\n return source.value;\n }\n return undefined;\n}\n\n/** Detect `module.exports = ...` or `exports.foo = ...` assignments. */\nfunction isCommonJsExportAssignment(node: AstNode): boolean {\n if (node.type !== 'AssignmentExpression') return false;\n const left = node.left as AstNode | undefined;\n if (!left || left.type !== 'MemberExpression' || left.computed === true) return false;\n const object = left.object as AstNode | undefined;\n const property = left.property as AstNode | undefined;\n if (!object || object.type !== 'Identifier' || !property || property.type !== 'Identifier') {\n return false;\n }\n if (object.name === 'exports') return true;\n return object.name === 'module' && property.name === 'exports';\n}\n\n/**\n * Compute the canonical SHA-256 hex digest of an already-normalized script.\n * Callers with raw source must pass it through {@link normalizeScript} first\n * (or use {@link validateScript}, which normalizes internally).\n */\nexport async function digestNormalizedScript(normalizedSource: string): Promise<string> {\n const encoded = new TextEncoder().encode(normalizedSource);\n const hash = await crypto.subtle.digest('SHA-256', encoded);\n return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Validate a script string using a real AST parse (Acorn).\n * Returns a structured result; never throws.\n */\nexport async function validateScript(source: string): Promise<ScriptValidationResult> {\n const errors: string[] = [];\n const imports: string[] = [];\n let hasDefaultExport = false;\n let hasNonLiteralDynamicImport = false;\n\n const normalized = normalizeScript(source);\n const encoded = new TextEncoder().encode(normalized);\n\n // Size check (on the canonical form the digest commits to).\n if (encoded.length > MAX_SCRIPT_BYTES) {\n errors.push(`Script exceeds ${MAX_SCRIPT_BYTES} bytes (got ${encoded.length})`);\n }\n if (normalized.trim().length === 0) {\n errors.push('Script is empty');\n }\n\n // The digest commits to the normalized source, never the raw bytes.\n const digest = await digestNormalizedScript(normalized);\n\n // Parse with a real JavaScript parser. Comments, strings, template\n // literals, and regex literals cannot smuggle fake imports/exports.\n let program: AstNode | undefined;\n if (normalized.trim().length > 0) {\n try {\n program = parse(normalized, { ecmaVersion: 'latest', sourceType: 'module' }) as unknown as AstNode;\n } catch (error) {\n errors.push(`Syntax error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n if (program) {\n const topLevel = Array.isArray(program.body) ? (program.body as AstNode[]) : [];\n\n // 1. Default export shape (top-level statements only).\n for (const statement of topLevel) {\n if (statement.type !== 'ExportDefaultDeclaration') continue;\n const declaration = statement.declaration as AstNode | undefined;\n if (isAsyncGeneratorFunction(declaration)) {\n hasDefaultExport = true;\n } else if (declaration?.type === 'Identifier') {\n // Disguised default export: `async function* run() {} export default run;`\n const identifier = declaration;\n hasDefaultExport = topLevel.some((candidate) => {\n if (isAsyncGeneratorFunction(candidate) && (candidate.id as AstNode | undefined)?.name === identifier.name) {\n return true;\n }\n if (candidate.type === 'VariableDeclaration' && Array.isArray(candidate.declarations)) {\n return (candidate.declarations as AstNode[]).some(\n (declarator) =>\n (declarator.id as AstNode | undefined)?.name === identifier.name &&\n isAsyncGeneratorFunction(declarator.init as AstNode | undefined),\n );\n }\n return false;\n });\n }\n }\n\n // 2. Imports, re-exports, dynamic imports, and CommonJS (full AST walk).\n walkAst(program, (node) => {\n if (node.type === 'ImportDeclaration') {\n const specifier = getStaticImportSource(node);\n if (specifier !== undefined) imports.push(specifier);\n } else if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') {\n // Re-exports (`export { x } from '...'`, `export * from '...'`) import too.\n const specifier = getStaticImportSource(node);\n if (specifier !== undefined) imports.push(specifier);\n } else if (node.type === 'ImportExpression') {\n const specifier = getStaticImportSource(node);\n if (specifier !== undefined) {\n imports.push(specifier);\n } else {\n hasNonLiteralDynamicImport = true;\n }\n } else if (isCommonJsExportAssignment(node)) {\n errors.push('CommonJS module.exports not supported (use ESM export)');\n }\n });\n }\n\n // 3. Forbidden imports.\n for (const specifier of imports) {\n if (isForbiddenImport(specifier)) {\n errors.push(`Forbidden import: ${specifier}`);\n }\n }\n\n // 4. Non-literal dynamic imports defeat admission control.\n if (hasNonLiteralDynamicImport) {\n errors.push('Dynamic import() with a non-literal argument is not allowed (defeats admission control)');\n }\n\n // 5. Required export shape.\n if (!hasDefaultExport) {\n errors.push('Script must export a default async generator function');\n }\n\n return {\n valid: errors.length === 0,\n digest,\n imports,\n hasDefaultExport,\n hasNonLiteralDynamicImport,\n errors,\n sizeBytes: encoded.length,\n };\n}\n\n/**\n * Normalize a script to a canonical form for digest stability.\n * Strips BOM, normalizes line endings to LF, and trims trailing whitespace.\n * Idempotent: `normalizeScript(normalizeScript(s)) === normalizeScript(s)`.\n * The canonical digest in {@link validateScript} commits to this form.\n */\nexport function normalizeScript(source: string): string {\n return source\n .replace(/^\\uFEFF/, '') // BOM\n .replace(/\\r\\n/g, '\\n') // CRLF → LF\n .replace(/\\r/g, '\\n') // CR → LF\n .split('\\n')\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim() + '\\n';\n}\n\nfunction isForbiddenImport(spec: string): boolean {\n // Node builtins are forbidden except 'events'.\n const builtins = new Set([\n 'fs',\n 'path',\n 'child_process',\n 'net',\n 'http',\n 'https',\n 'os',\n 'crypto',\n 'tls',\n 'dgram',\n 'dns',\n 'readline',\n 'repl',\n 'stream',\n 'timers',\n 'tty',\n 'url',\n 'util',\n 'v8',\n 'vm',\n 'worker_threads',\n 'zlib',\n 'assert',\n 'buffer',\n 'querystring',\n 'string_decoder',\n ]);\n const base = spec.replace(/^node:/, '');\n if (builtins.has(base) && spec !== 'node:events') return true;\n\n // Libp2p imports are forbidden.\n if (spec.startsWith('@libp2p/') || spec.startsWith('@chainsafe/libp2p') || spec === 'libp2p') {\n return true;\n }\n\n // Process/tool-specific: scripts cannot import the host runtime.\n if (spec === 'memeloop' || spec.startsWith('memeloop/')) return true;\n\n return false;\n}\n","/**\n * Generated-script deployment pipeline (plans 24.14–24.19, 24.47).\n *\n * Connects the full security chain for remote/generated scripts:\n *\n * normalizeScript → validateScript (Acorn AST) → admitScript (trust-class\n * policy) → ArtifactRecord manifest (content-addressed) → persist via the\n * injected artifact store port → selectRuntimeClass →\n * RemoteDeploymentRequest (artifactRef only — raw source is never carried).\n *\n * Also provides {@link createScriptLoadGate}, the production\n * {@link ScriptLoadGate} implementation for the in-process script loading\n * path (`loopAPI/scriptLoader`): validate (AST) → admit → assign\n * trustClass/RuntimeClass before any `import()` executes.\n *\n * Everything here is pure and portable; artifact persistence sits behind the\n * {@link ScriptArtifactStore} port so the CLI can back it with real storage.\n */\n\nimport type { ScriptLoadGate, ScriptLoadGateDecision } from '../../loopAPI/types.js';\nimport { waitForCondition, type WaitForConditionOptions } from '../agentClient.js';\nimport type { AgentOrchestrationClient, OrchestrationOwnerReference } from '../client.js';\nimport { OrchestrationError } from '../errors.js';\nimport {\n AGENT_WORKLOAD_API_VERSION,\n AGENT_WORKLOAD_KIND,\n type AgentWorkloadCompletionPolicy,\n type AgentWorkloadManifest,\n type AgentWorkloadNetworkPolicy,\n type AgentWorkloadResource,\n type AgentWorkloadStoragePolicy,\n type ArtifactRecordManifest,\n createAgentWorkloadManifest,\n createArtifactRecordManifest,\n} from '../resources.js';\nimport { containsSecrets } from '../security/secretRedaction.js';\nimport { admitScript, defaultRequestedInterfacesForTrustClass, type ScriptAdmissionDecision, type ScriptTrustClass } from './scriptAdmission.js';\nimport { type RemoteDeploymentRequest, type SandboxSelectionResult, selectRuntimeClass } from './scriptRuntime.js';\nimport { normalizeScript, type ScriptValidationResult, validateScript } from './scriptValidation.js';\n\n// ─── Artifact persistence port ─────────────────────────────────────────\n\n/**\n * Port: persists a script ArtifactRecord manifest plus its normalized\n * content. Implementations (e.g. CLI storage) must store content addressed\n * by `manifest.spec.contentHash` and must not trust content whose hash does\n * not match the manifest.\n */\nexport interface ScriptArtifactStore {\n putArtifact(manifest: ArtifactRecordManifest, normalizedContent: string): Promise<void> | void;\n}\n\n// ─── Deployment pipeline ───────────────────────────────────────────────\n\n/** Input for {@link deployGeneratedScript}. */\nexport interface ScriptDeploymentRequest {\n /** Raw generated `.mjs` source (normalized internally). */\n source: string;\n /** Trust class of the author (the Agent that generated the script). */\n authorTrust: ScriptTrustClass;\n /** Interfaces the script requests (loop-runtime, model-provider, ...). */\n requestedInterfaces: string[];\n /** Desired lifecycle for the remote workload. */\n lifecycle: 'run-once' | 'service' | 'schedule';\n /** Node selector for scheduling. */\n nodeSelector?: Record<string, string>;\n /** Environment variables (never credentials). */\n env?: Record<string, string>;\n /** Network attachment requirements for the deployed workload. */\n networkPolicy?: AgentWorkloadNetworkPolicy;\n /** Existing volume claims required by the deployed workload. */\n storagePolicy?: AgentWorkloadStoragePolicy;\n /** Optional checkpoint digest the script expects to resume from. */\n expectedCheckpointDigest?: string;\n /** API version of the expected checkpoint (plan 24.19). */\n checkpointApiVersion?: string;\n /** Namespace for the ArtifactRecord and deployment. */\n namespace?: string;\n}\n\n/** Tunables for {@link deployGeneratedScript}. */\nexport interface ScriptDeploymentPipelineOptions {\n /** Artifact persistence port; when omitted the manifest is built but not persisted. */\n artifactStore?: ScriptArtifactStore;\n /** RuntimeClass names available for selection (defaults to all built-ins). */\n availableRuntimeClasses?: string[];\n}\n\n/** Result of {@link deployGeneratedScript}; `deployed` gates artifact/deployment presence. */\nexport interface ScriptDeploymentResult {\n /** Whether a deployment request was produced. */\n deployed: boolean;\n /** Human-readable outcome (validation/admission/enforcement reason). */\n reason: string;\n /** AST validation outcome (always present). */\n validation: ScriptValidationResult;\n /** Admission decision (present once validation passed). */\n admission?: ScriptAdmissionDecision;\n /** Content-addressed artifact manifest (present when deployed). */\n artifact?: ArtifactRecordManifest;\n /** Selected RuntimeClass (present when deployed). */\n runtimeClass?: SandboxSelectionResult;\n /** Deployment request referencing the artifact by digest (present when deployed). */\n deployment?: RemoteDeploymentRequest;\n /** Applied AgentWorkload (present when deployed through an orchestration facade). */\n workload?: AgentWorkloadResource;\n}\n\n// ─── Scheduler consumption (plan 24.14) ────────────────────────────────\n\n/** Lifecycle declared by the script → workload completion policy. */\nconst LIFECYCLE_TO_COMPLETION_POLICY: Record<RemoteDeploymentRequest['lifecycle'], AgentWorkloadCompletionPolicy> = {\n 'run-once': 'complete',\n service: 'daemon',\n schedule: 'detach',\n};\n\nexport interface RemoteDeploymentWorkloadOptions {\n /** Workload name (defaults to the content-addressed artifact name). */\n name?: string;\n namespace?: string;\n ownerReferences?: OrchestrationOwnerReference[];\n}\n\n/**\n * Translate a {@link RemoteDeploymentRequest} into an AgentWorkload manifest\n * the binding controller (24.56) can schedule. The script declares placement\n * and lifecycle; the scheduler — never the script — selects the node.\n */\nexport function remoteDeploymentToWorkloadManifest(\n deployment: RemoteDeploymentRequest,\n options: RemoteDeploymentWorkloadOptions = {},\n): AgentWorkloadManifest {\n const manifest = createAgentWorkloadManifest(options.name ?? deployment.artifactRef.name, {\n scriptReference: deployment.artifactRef.contentDigest,\n trust: deployment.trustClass,\n runtimeClass: deployment.runtimeClass,\n completionPolicy: LIFECYCLE_TO_COMPLETION_POLICY[deployment.lifecycle],\n ...(deployment.nodeSelector ? { placement: { nodeSelector: deployment.nodeSelector } } : {}),\n ...(deployment.env ? { env: deployment.env } : {}),\n ...(deployment.networkPolicy ? { networkPolicy: deployment.networkPolicy } : {}),\n ...(deployment.storagePolicy ? { storagePolicy: deployment.storagePolicy } : {}),\n ...(options.ownerReferences ? { ownerReferences: options.ownerReferences } : {}),\n });\n const namespace = options.namespace ?? deployment.artifactRef.namespace;\n if (namespace !== undefined) {\n manifest.metadata.namespace = namespace;\n }\n return manifest;\n}\n\n/**\n * Run the full generated-script security chain and produce a remote\n * deployment request. Never throws for script-content problems — invalid or\n * inadmissible scripts yield `deployed: false` with a structured reason.\n *\n * Checkpoint compatibility (plan 24.19) is enforced here: when the caller\n * expects to resume a checkpoint and admission found it incompatible, no\n * deployment is produced (an explicit converter or restart policy would be\n * required first).\n */\nexport async function deployGeneratedScript(\n request: ScriptDeploymentRequest,\n options: ScriptDeploymentPipelineOptions = {},\n): Promise<ScriptDeploymentResult> {\n // 1. Normalize + validate (Acorn AST, canonical digest).\n const validation = await validateScript(request.source);\n if (!validation.valid) {\n return {\n deployed: false,\n reason: `Script validation failed: ${validation.errors.join('; ')}`,\n validation,\n };\n }\n\n // 2. Admission (trust-class policy, plan 24.17/24.19).\n const admission = admitScript({\n script: validation,\n authorTrust: request.authorTrust,\n requestedInterfaces: request.requestedInterfaces,\n expectedCheckpointDigest: request.expectedCheckpointDigest,\n checkpointApiVersion: request.checkpointApiVersion,\n });\n if (!admission.admitted) {\n return { deployed: false, reason: admission.reason, validation, admission };\n }\n if (request.expectedCheckpointDigest !== undefined && !admission.checkpointCompatible) {\n return {\n deployed: false,\n reason: 'Checkpoint is incompatible with this script digest/API version; an explicit converter or restart policy is required',\n validation,\n admission,\n };\n }\n\n // 2b. env guard (plan 24.35): workload env is persisted in the ControlStore\n // spec, so secret-shaped values are rejected here rather than redacted.\n for (const [name, value] of Object.entries(request.env ?? {})) {\n if (containsSecrets(value)) {\n return {\n deployed: false,\n reason: `Environment variable '${name}' carries a secret-shaped value; workload env must never contain credentials (plan 24.35)`,\n validation,\n admission,\n };\n }\n }\n\n // 3. Content-addressed ArtifactRecord manifest (plan 24.15/24.47).\n const contentDigest = `sha256:${validation.digest}`;\n const artifactName = `script-${validation.digest}`;\n const artifact = createArtifactRecordManifest(artifactName, {\n contentHash: contentDigest,\n sizeBytes: validation.sizeBytes,\n mimeType: 'text/javascript',\n producer: { trust: request.authorTrust },\n trust: request.authorTrust,\n });\n if (request.namespace !== undefined) {\n artifact.metadata.namespace = request.namespace;\n }\n await options.artifactStore?.putArtifact(artifact, normalizeScript(request.source));\n\n // 4. RuntimeClass selection (plan 24.18).\n const runtimeClass = selectRuntimeClass(request.authorTrust, options.availableRuntimeClasses);\n\n // 5. Deployment request referencing the artifact by digest — never raw source.\n const deployment: RemoteDeploymentRequest = {\n artifactRef: {\n apiVersion: artifact.apiVersion,\n kind: 'ArtifactRecord',\n name: artifactName,\n namespace: artifact.metadata.namespace,\n contentDigest,\n },\n trustClass: request.authorTrust,\n lifecycle: request.lifecycle,\n runtimeClass: runtimeClass.runtimeClass,\n nodeSelector: request.nodeSelector,\n env: request.env,\n networkPolicy: request.networkPolicy,\n storagePolicy: request.storagePolicy,\n };\n\n return {\n deployed: true,\n reason: admission.reason,\n validation,\n admission,\n artifact,\n runtimeClass,\n deployment,\n };\n}\n\n// ─── Script load gate (production admission for in-process loading) ────\n\n/** Configuration for {@link createScriptLoadGate}. */\nexport interface ScriptLoadGateConfig {\n /** Trust class to assign admitted scripts (plan 24.17). */\n authorTrust: ScriptTrustClass;\n /** Interfaces admitted scripts may request. */\n requestedInterfaces: string[];\n /** RuntimeClass names available for selection (defaults to all built-ins). */\n availableRuntimeClasses?: string[];\n /** Optional checkpoint digest admitted scripts expect to resume from. */\n expectedCheckpointDigest?: string;\n /** API version of the expected checkpoint (plan 24.19). */\n checkpointApiVersion?: string;\n}\n\n/**\n * Create the production {@link ScriptLoadGate}: every non-builtin source is\n * validated (Acorn AST), admitted under the configured trust-class policy,\n * and assigned a RuntimeClass before the loader is allowed to `import()` it.\n * The gate verifies that the digest computed by the loader matches the\n * digest of the source it validated, so the admitted bytes are exactly the\n * imported bytes.\n */\nexport function createScriptLoadGate(config: ScriptLoadGateConfig): ScriptLoadGate {\n return {\n async admitScriptLoad(request): Promise<ScriptLoadGateDecision> {\n const validation = await validateScript(request.normalizedSource);\n if (!validation.valid) {\n return { allowed: false, reason: `Script validation failed: ${validation.errors.join('; ')}` };\n }\n if (validation.digest !== request.digest) {\n return { allowed: false, reason: 'Digest mismatch between loader and validated source' };\n }\n const admission = admitScript({\n script: validation,\n authorTrust: config.authorTrust,\n requestedInterfaces: config.requestedInterfaces,\n expectedCheckpointDigest: config.expectedCheckpointDigest,\n checkpointApiVersion: config.checkpointApiVersion,\n });\n if (!admission.admitted) {\n return { allowed: false, reason: admission.reason };\n }\n if (config.expectedCheckpointDigest !== undefined && !admission.checkpointCompatible) {\n return {\n allowed: false,\n reason: 'Checkpoint is incompatible with this script digest/API version; an explicit converter or restart policy is required',\n };\n }\n const runtimeClass = selectRuntimeClass(config.authorTrust, config.availableRuntimeClasses);\n return {\n allowed: true,\n trustClass: config.authorTrust,\n runtimeClass: runtimeClass.runtimeClass,\n checkpointCompatible: admission.checkpointCompatible,\n };\n },\n };\n}\n\n// ─── Agent-facing deployment client (plan 24.14) ───────────────────────\n\n/**\n * Host-bound configuration for {@link createScriptDeploymentClient}.\n * Trust and interface ceilings come from the host, never from the calling\n * script — a script cannot elevate its own trust class or widen the\n * interface set beyond what the host configured.\n */\nexport interface ScriptDeploymentClientConfig {\n /** Trust class the host assigns to deployments from this context. */\n authorTrust: ScriptTrustClass;\n /**\n * Interface ceiling for deployments (defaults to the widest set\n * admissible for `authorTrust`). Scripts may request a narrower subset;\n * anything wider is rejected by admission.\n */\n requestedInterfaces?: string[];\n /** RuntimeClass names available for selection (defaults to all built-ins). */\n availableRuntimeClasses?: string[];\n /** Artifact persistence port; when omitted manifests are built but not persisted. */\n artifactStore?: ScriptArtifactStore;\n /** Default namespace for produced ArtifactRecords and deployments. */\n namespace?: string;\n /**\n * Orchestration facade. When present, `deploy` also applies an\n * AgentWorkload so the scheduler binds a node (plan 24.14); when absent,\n * `deploy` only produces the deployment request and the readiness/deletion\n * methods reject with UNSUPPORTED.\n */\n orchestration?: AgentOrchestrationClient;\n /** Field manager for applied workloads (default `memeloop/script-deployment`). */\n fieldManager?: string;\n}\n\n/** Request a script makes through the deployment client. */\nexport interface ScriptDeploymentClientRequest {\n /** Raw generated `.mjs` source (normalized internally). */\n source: string;\n /** Desired lifecycle for the remote workload. */\n lifecycle: 'run-once' | 'service' | 'schedule';\n /** Optional narrower interface subset (must stay within the host ceiling). */\n requestedInterfaces?: string[];\n /** Node selector for scheduling. */\n nodeSelector?: Record<string, string>;\n /** Environment variables (never credentials). */\n env?: Record<string, string>;\n /** Network attachment requirements for the deployed workload. */\n networkPolicy?: AgentWorkloadNetworkPolicy;\n /** Existing volume claims required by the deployed workload. */\n storagePolicy?: AgentWorkloadStoragePolicy;\n /** Optional checkpoint digest the script expects to resume from. */\n expectedCheckpointDigest?: string;\n /** API version of the expected checkpoint (plan 24.19). */\n checkpointApiVersion?: string;\n /** Namespace override (defaults to the configured namespace). */\n namespace?: string;\n}\n\n/** Agent-facing handle for declarative script deployment (plan 24.14). */\nexport interface ScriptDeploymentClient {\n /**\n * Validate, admit, persist, and package a generated script as a\n * {@link RemoteDeploymentRequest} referencing its ArtifactRecord by\n * digest. When an orchestration facade is configured, also applies the\n * AgentWorkload so the scheduler binds a node. Never throws for\n * script-content problems — inadmissible scripts yield `deployed: false`\n * with a structured reason.\n */\n deploy(request: ScriptDeploymentClientRequest): Promise<ScriptDeploymentResult>;\n /**\n * Wait until the scheduler has bound the deployment's workload\n * (`Scheduled=True` condition written by the binding controller).\n */\n waitForScheduled(\n name: string,\n options?: WaitForConditionOptions & { namespace?: string },\n ): Promise<{ observedResourceVersion: string; matched: true }>;\n /** Delete the deployment's workload. */\n deleteDeployment(name: string, namespace?: string): Promise<void>;\n}\n\n/**\n * Create the Agent-facing deployment client injected into `.mjs` scripts\n * as `ctx.scriptClient` (plan 24.14). The script declares placement and\n * lifecycle; trust, interface ceilings, and persistence are bound by the\n * host. The scheduler — not the script — selects the target node.\n */\nexport function createScriptDeploymentClient(config: ScriptDeploymentClientConfig): ScriptDeploymentClient {\n const interfaceCeiling = config.requestedInterfaces ?? defaultRequestedInterfacesForTrustClass(config.authorTrust);\n\n function requireOrchestration(): AgentOrchestrationClient {\n if (!config.orchestration) {\n throw new OrchestrationError({\n code: 'UNSUPPORTED',\n message: 'script deployment scheduling requires a host-configured orchestration facade',\n retryable: false,\n });\n }\n return config.orchestration;\n }\n\n return {\n async deploy(request) {\n const result = await deployGeneratedScript(\n {\n source: request.source,\n authorTrust: config.authorTrust,\n requestedInterfaces: request.requestedInterfaces ?? interfaceCeiling,\n lifecycle: request.lifecycle,\n nodeSelector: request.nodeSelector,\n env: request.env,\n networkPolicy: request.networkPolicy,\n storagePolicy: request.storagePolicy,\n expectedCheckpointDigest: request.expectedCheckpointDigest,\n checkpointApiVersion: request.checkpointApiVersion,\n namespace: request.namespace ?? config.namespace,\n },\n {\n artifactStore: config.artifactStore,\n availableRuntimeClasses: config.availableRuntimeClasses,\n },\n );\n\n if (result.deployed && result.deployment && config.orchestration) {\n const manifest = remoteDeploymentToWorkloadManifest(result.deployment, {\n namespace: request.namespace ?? config.namespace,\n });\n const workload = await config.orchestration.apply<typeof manifest.spec>(manifest, {\n idempotencyKey: result.deployment.artifactRef.contentDigest,\n fieldManager: config.fieldManager ?? 'memeloop/script-deployment',\n });\n return { ...result, workload: workload as AgentWorkloadResource };\n }\n return result;\n },\n\n async waitForScheduled(name, options = {}) {\n const orchestration = requireOrchestration();\n const { namespace, ...waitOptions } = options;\n return waitForCondition(\n () =>\n orchestration.get({\n apiVersion: AGENT_WORKLOAD_API_VERSION,\n kind: AGENT_WORKLOAD_KIND,\n name,\n namespace: namespace ?? config.namespace,\n }),\n { type: 'Scheduled', status: 'True' },\n waitOptions,\n );\n },\n\n async deleteDeployment(name, namespace) {\n const orchestration = requireOrchestration();\n await orchestration.delete({\n apiVersion: AGENT_WORKLOAD_API_VERSION,\n kind: AGENT_WORKLOAD_KIND,\n name,\n namespace: namespace ?? config.namespace,\n });\n },\n };\n}\n","// Generated by scripts/generate-loop-sources.mjs. Edit the sibling .mjs files instead.\n\nexport const AgentAgentLoopArtifactResourceLifecycleScriptId = 'builtin:agent-agent-loop/artifact-resource-lifecycle';\nexport const AgentAgentLoopDeclarativeAgentRunScriptId = 'builtin:agent-agent-loop/declarative-agent-run';\nexport const AgentAgentLoopQualityGateScriptId = 'builtin:agent-agent-loop/quality-gate';\n\nexport const BUILTIN_AGENT_AGENT_LOOP_ARTIFACT_RESOURCE_LIFECYCLE_SCRIPT_ID = AgentAgentLoopArtifactResourceLifecycleScriptId;\nexport const BUILTIN_AGENT_AGENT_LOOP_DECLARATIVE_AGENT_RUN_SCRIPT_ID = AgentAgentLoopDeclarativeAgentRunScriptId;\nexport const BUILTIN_AGENT_AGENT_LOOP_QUALITY_GATE_SCRIPT_ID = AgentAgentLoopQualityGateScriptId;\n\nexport const builtinAgentAgentLoopSources: Readonly<Record<string, string>> = {\n [AgentAgentLoopArtifactResourceLifecycleScriptId]: [\n '// @ts-check',\n '',\n 'function resourceName(value) {',\n ' const normalized = value.toLowerCase().replace(/[^a-z0-9-]+/g, \"-\").replace(/^-+|-+$/g, \"\");',\n ' return (normalized || \"artifact\").slice(0, 56);',\n '}',\n '',\n \"/** @param {import('../../loopAPI/agent-agent-loop/loop.js').AgentAgentScriptContext} ctx */\",\n 'export default async function run(ctx) {',\n ' if (!ctx.orchestration) {',\n ' throw new Error(\"artifact-resource-lifecycle requires the orchestration resource facade\");',\n ' }',\n '',\n ' const metadata = ctx.profile?.metadata ?? {};',\n ' const contentHash = typeof metadata.contentHash === \"string\"',\n ' ? metadata.contentHash',\n ' : \"sha256:0000000000000000000000000000000000000000000000000000000000000000\";',\n ' const artifactName = resourceName(`script-${ctx.input.conversationId}`);',\n ' const query = {',\n ' apiVersion: \"artifacts.memeloop.io/v1alpha1\",',\n ' kind: \"ArtifactRecord\",',\n ' namespace: \"default\",',\n ' };',\n ' const abortController = new AbortController();',\n ' const events = ctx.orchestration.watch(query, {',\n ' resourceVersion: \"0\",',\n ' sendInitialEvents: true,',\n ' allowBookmarks: true,',\n ' timeoutMs: 5_000,',\n ' signal: abortController.signal,',\n ' })[Symbol.asyncIterator]();',\n ' const nextEvent = events.next();',\n '',\n ' try {',\n ' const artifact = await ctx.orchestration.apply({',\n ' apiVersion: query.apiVersion,',\n ' kind: query.kind,',\n ' metadata: {',\n ' name: artifactName,',\n ' namespace: query.namespace,',\n ' labels: { \"memeloop.io/artifact-purpose\": \"generated-script\" },',\n ' },',\n ' spec: {',\n ' contentHash,',\n ' mimeType: \"text/javascript\",',\n ' producer: { trust: \"restricted\" },',\n ' trust: \"restricted\",',\n ' },',\n ' }, {',\n ' fieldManager: \"agent-agent-script-example\",',\n ' idempotencyKey: `${ctx.input.conversationId}:artifact`,',\n ' });',\n '',\n ' const observed = await nextEvent;',\n ' if (observed.done || observed.value.type !== \"ADDED\") {',\n ' throw new Error(\"artifact watch ended before observing the created resource\");',\n ' }',\n '',\n ' const reference = {',\n ' apiVersion: artifact.apiVersion,',\n ' kind: artifact.kind,',\n ' name: artifact.metadata.name,',\n ' namespace: artifact.metadata.namespace,',\n ' uid: artifact.metadata.uid,',\n ' };',\n ' const fetched = await ctx.orchestration.get(reference, {',\n ' resourceVersion: artifact.metadata.resourceVersion,',\n ' });',\n ' const listed = await ctx.orchestration.list(query, {',\n ' resourceVersion: artifact.metadata.resourceVersion,',\n ' resourceVersionMatch: \"not-older-than\",',\n ' limit: 10,',\n ' });',\n ' if (!fetched || !listed.items.some((item) => item.metadata.uid === artifact.metadata.uid)) {',\n ' throw new Error(\"created artifact was not readable through the resource facade\");',\n ' }',\n '',\n ' await ctx.orchestration.delete(reference, {',\n ' idempotencyKey: `${ctx.input.conversationId}:artifact-delete`,',\n ' preconditions: {',\n ' uid: artifact.metadata.uid,',\n ' resourceVersion: artifact.metadata.resourceVersion,',\n ' },',\n ' });',\n ' ctx.finish(`verified artifact lifecycle ${artifact.metadata.name}@${observed.value.resourceVersion}`);',\n ' } finally {',\n ' abortController.abort();',\n ' await events.return?.();',\n ' }',\n '}',\n '',\n ].join('\\n'),\n [AgentAgentLoopDeclarativeAgentRunScriptId]: [\n '// @ts-check',\n '',\n 'function resourceName(value) {',\n ' const normalized = value.toLowerCase().replace(/[^a-z0-9-]+/g, \"-\").replace(/^-+|-+$/g, \"\");',\n ' return (normalized || \"agent-run\").slice(0, 48);',\n '}',\n '',\n \"/** @param {import('../../loopAPI/agent-agent-loop/loop.js').AgentAgentScriptContext} ctx */\",\n 'export default async function run(ctx) {',\n ' if (!ctx.agentClient) {',\n ' throw new Error(\"declarative-agent-run requires the orchestration resource facade\");',\n ' }',\n '',\n ' const metadata = ctx.profile?.metadata ?? {};',\n ' const childProfileId = typeof metadata.childProfileId === \"string\"',\n ' ? metadata.childProfileId',\n ' : ctx.agents[0]?.profileId;',\n ' if (!childProfileId) {',\n ' throw new Error(\"declarative-agent-run requires metadata.childProfileId or one configured agent\");',\n ' }',\n '',\n ' const baseName = resourceName(`child-${ctx.input.conversationId}`);',\n ' const workloadName = `${baseName}-workload`;',\n ' const runName = `${baseName}-run`;',\n ' const workload = await ctx.agentClient.createWorkload({',\n ' name: workloadName,',\n ' profileId: childProfileId,',\n ' promptReference: `conversation:${ctx.input.conversationId}:input`,',\n ' trust: \"restricted\",',\n ' placement: {',\n ' nodeSelector: { \"memeloop.io/worker-pool\": \"restricted\" },',\n ' antiAffinity: [ctx.input.conversationId],',\n ' },',\n ' modelPolicy: {',\n ' modelClass: \"local-model\",',\n ' budget: { maxTokens: 8_192 },',\n ' },',\n ' toolPolicy: {',\n ' defaultAction: \"deny\",',\n ' allowedToolClasses: [\"read-only\"],',\n ' },',\n ' networkPolicy: {',\n ' networkClass: \"restricted-egress\",',\n ' egress: \"restricted\",',\n ' },',\n ' storagePolicy: {',\n ' storageClass: \"ephemeral\",',\n ' },',\n ' completionPolicy: \"complete\",',\n ' idempotencyKey: `${ctx.input.conversationId}:workload`,',\n ' });',\n ' const agentRun = await ctx.agentClient.createRun({',\n ' name: runName,',\n ' workloadName: workload.metadata.name,',\n ' workloadNamespace: workload.metadata.namespace,',\n ' promptReference: `conversation:${ctx.input.conversationId}:input`,',\n ' timeoutMs: 120_000,',\n ' idempotencyKey: `${ctx.input.conversationId}:run`,',\n ' });',\n '',\n ' if (metadata.waitForCompletion === true) {',\n ' await ctx.agentClient.waitForRunCondition(',\n ' agentRun.metadata.name,',\n ' { type: \"Completed\", status: \"True\" },',\n ' { timeout: 5_000, interval: 100 },',\n ' );',\n ' }',\n '',\n ' ctx.finish(`scheduled ${workload.metadata.name}/${agentRun.metadata.name}`);',\n '}',\n '',\n ].join('\\n'),\n [AgentAgentLoopQualityGateScriptId]: [\n '// @ts-check',\n '',\n 'function positiveInteger(value, fallback) {',\n ' const number = Number(value);',\n ' return Number.isFinite(number) && number > 0 ? Math.floor(number) : fallback;',\n '}',\n '',\n 'function asEntries(value, fallback) {',\n ' return Array.isArray(value) && value.length > 0 ? value : fallback;',\n '}',\n '',\n 'function withConversationIds(ctx, entries, phase, iteration) {',\n ' return entries.map((entry, index) => {',\n ' const record = typeof entry === \"string\" ? { profile: entry } : entry;',\n ' return {',\n ' ...record,',\n ' conversationId:',\n ' record.conversationId ?? `${ctx.input.conversationId}:${phase}:${iteration}:${index}`,',\n ' };',\n ' });',\n '}',\n '',\n 'function resultText(ctx, result) {',\n ' return result.text || ctx.formatAgentResults(result, { includeFailureSection: true });',\n '}',\n '',\n 'function reviewText(ctx, result) {',\n ' return ctx.formatAgentResults(result, { includeFailureSection: true });',\n '}',\n '',\n 'function approved(result) {',\n ' return (',\n ' result.failures.length === 0 &&',\n ' result.results.length > 0 &&',\n ' result.results.every((item) => /^\\\\s*APPROVED\\\\b/imu.test(item.text))',\n ' );',\n '}',\n '',\n 'function feedbackBlock(ctx, history) {',\n ' if (history.length === 0) return \"No prior review feedback.\";',\n ' return history',\n ' .map((entry) =>',\n ' [',\n ' `Iteration ${entry.iteration}`,',\n ' `Attempt:\\\\n${resultText(ctx, entry.attempt)}`,',\n ' `Review:\\\\n${reviewText(ctx, entry.review)}`,',\n ' ].join(\"\\\\n\\\\n\"),',\n ' )',\n ' .join(\"\\\\n\\\\n---\\\\n\\\\n\");',\n '}',\n '',\n 'function workerPrompt(ctx, goal, iteration, previousAttempt, history) {',\n ' if (!previousAttempt) return goal;',\n ' return [',\n ' \"Continue working on the original goal until the reviewer can approve it.\",',\n ' \"Do not summarize the review. Produce the corrected deliverable itself.\",',\n ' `Original goal:\\\\n${goal}`,',\n ' `Previous deliverable:\\\\n${resultText(ctx, previousAttempt)}`,',\n ' `Review history:\\\\n${feedbackBlock(ctx, history)}`,',\n ' `This is revision attempt ${iteration}.`,',\n ' ].join(\"\\\\n\\\\n\");',\n '}',\n '',\n 'function reviewPrompt(ctx, goal, attempt, history) {',\n ' return [',\n ' \"You are the quality gate for this delegated agent run.\",',\n ' \"Return APPROVED on the first line only when the deliverable fully satisfies the original goal and is ready to send to the user.\",',\n ' \"Return REVISE on the first line when more work is required, followed by concrete blocking issues and exact changes needed.\",',\n ' \"Do not approve partial progress.\",',\n ' `Original goal:\\\\n${goal}`,',\n ' `Candidate deliverable:\\\\n${resultText(ctx, attempt)}`,',\n ' `Earlier review history:\\\\n${feedbackBlock(ctx, history)}`,',\n ' ].join(\"\\\\n\\\\n\");',\n '}',\n '',\n 'async function runBatch(ctx, mode, input) {',\n ' return mode === \"sequential\" ? ctx.runSequential(input) : ctx.runParallel(input);',\n '}',\n '',\n \"/** @param {import('../../loopAPI/agent-agent-loop/loop.js').AgentAgentScriptContext} ctx */\",\n 'export default async function run(ctx) {',\n ' const metadata = ctx.profile?.metadata ?? {};',\n ' const goal = ctx.input.message;',\n ' const maxIterations = positiveInteger(metadata.maxIterations, 4);',\n ' const mode = metadata.mode === \"sequential\" ? \"sequential\" : \"parallel\";',\n ' const reviewMode = metadata.reviewMode === \"sequential\" ? \"sequential\" : \"parallel\";',\n ' const defaultAgents = ctx.getAgentEntries(\"agents\");',\n ' const workers = asEntries(',\n ' ctx.getAgentEntries(\"workers\"),',\n ' asEntries(ctx.getAgentEntries(\"draftAgents\"), defaultAgents),',\n ' );',\n ' const reviewers = asEntries(',\n ' ctx.getAgentEntries(\"reviewers\"),',\n ' asEntries(ctx.getAgentEntries(\"reviewAgents\"), defaultAgents),',\n ' );',\n ' const fixers = asEntries(',\n ' ctx.getAgentEntries(\"fixers\"),',\n ' asEntries(ctx.getAgentEntries(\"revisionAgents\"), workers),',\n ' );',\n ' const history = [];',\n ' let attempt;',\n '',\n ' if (workers.length === 0 || reviewers.length === 0) {',\n ' ctx.finish(',\n ' \"AgentAgent quality gate requires worker and reviewer agents. Configure metadata.workers/reviewers or metadata.agents.\",',\n ' );',\n ' return;',\n ' }',\n '',\n ' for (let iteration = 1; iteration <= maxIterations; iteration += 1) {',\n ' if (ctx.isCancelled()) break;',\n ' const activeWorkers = iteration === 1 ? workers : fixers;',\n ' const attemptKey = `quality-gate:${iteration}:attempt`;',\n ' const previousAttempt = attempt;',\n ' const savedAttempt = await ctx.loadCheckpoint(attemptKey);',\n ' if (savedAttempt) {',\n ' attempt = savedAttempt;',\n ' } else {',\n ' ctx.emit({',\n ' type: \"thinking\",',\n ' data: { status: \"quality-gate-work\", conversationId: ctx.input.conversationId, iteration },',\n ' });',\n ' attempt = await runBatch(ctx, mode, {',\n ' agents: withConversationIds(ctx, activeWorkers, \"work\", iteration),',\n ' prompt: workerPrompt(ctx, goal, iteration, previousAttempt, history),',\n ' });',\n ' await ctx.checkpoint(attemptKey, attempt);',\n ' }',\n '',\n ' if (attempt.failures.length > 0 && attempt.results.length === 0) {',\n ' history.push({',\n ' iteration,',\n ' attempt,',\n ' review: { results: [], failures: attempt.failures, text: \"\" },',\n ' });',\n ' continue;',\n ' }',\n '',\n ' const reviewKey = `quality-gate:${iteration}:review`;',\n ' let review = await ctx.loadCheckpoint(reviewKey);',\n ' if (!review) {',\n ' ctx.emit({',\n ' type: \"thinking\",',\n ' data: {',\n ' status: \"quality-gate-review\",',\n ' conversationId: ctx.input.conversationId,',\n ' iteration,',\n ' },',\n ' });',\n ' review = await runBatch(ctx, reviewMode, {',\n ' agents: withConversationIds(ctx, reviewers, \"review\", iteration),',\n ' prompt: reviewPrompt(ctx, goal, attempt, history),',\n ' });',\n ' await ctx.checkpoint(reviewKey, review);',\n ' }',\n ' history.push({ iteration, attempt, review });',\n '',\n ' if (approved(review)) {',\n ' ctx.finish(resultText(ctx, attempt));',\n ' return;',\n ' }',\n ' }',\n '',\n ' ctx.finish(',\n ' [',\n ' \"Quality gate did not approve the delegated work before the iteration limit.\",',\n ' attempt ? resultText(ctx, attempt) : \"No deliverable was produced.\",',\n ' \"Review trail:\",',\n ' feedbackBlock(ctx, history),',\n ' ]',\n ' .filter(Boolean)',\n ' .join(\"\\\\n\\\\n\"),',\n ' );',\n '}',\n '',\n ].join('\\n'),\n};\n\nexport function getBuiltinAgentAgentLoopSource(id: string): string | undefined {\n return builtinAgentAgentLoopSources[id];\n}\n","/**\n * Agent loop script loader (plan 24.15: source is never imported directly\n * from an LLM string without passing the admission chain).\n *\n * Loading rules:\n * - Builtin loop sources are allowlisted by content digest at startup\n * ({@link registerBuiltinScriptSources}); they load with zero gate overhead.\n * - Any other source-bearing reference (`source` refs and `data:` URLs) must\n * pass the host-injected {@link ScriptLoadGate}: validate (AST) → admit\n * (trust-class policy) → only then `import()`.\n * - When no gate is configured, all non-builtin sources are DENIED\n * (fail-closed) with a structured {@link ScriptLoadDeniedError}.\n *\n * Admission results (trust class, RuntimeClass, checkpoint compatibility)\n * are attached to the loaded script via {@link LOADED_SCRIPT_METADATA} so\n * hosts can enforce sandboxing.\n */\n\nimport { digestNormalizedScript, normalizeScript } from '../orchestration/scripts/scriptValidation.js';\nimport type { AgentLoopScriptPolicy, LoopProfileScriptReference, ScriptLoadGate } from './types.js';\n\nexport type AgentLoopScriptReference = string | LoopProfileScriptReference;\n\nexport interface LoadAgentLoopScriptOptions extends AgentLoopScriptPolicy {\n getBuiltinScriptSource?: (id: string) => string | undefined;\n scriptType?: string;\n}\n\nconst DEFAULT_POLICY = {\n allowBuiltin: true,\n allowFile: false,\n allowNetwork: false,\n allowSource: false,\n allowSpecifier: true,\n} as const;\n\n// ─── Loaded-script admission metadata ──────────────────────────────────\n\n/** Symbol under which the admission result is attached to a loaded script. */\nexport const LOADED_SCRIPT_METADATA: unique symbol = Symbol('memeloop.loadedScriptMetadata');\n\n/** Admission metadata attached to every source-loaded script. */\nexport interface LoadedScriptMetadata {\n /** Canonical SHA-256 hex digest of the normalized source. */\n digest: string;\n /** True when the digest matched the builtin allowlist (first-party code). */\n builtin: boolean;\n /** Trust class assigned by admission (plan 24.17). */\n trustClass?: string;\n /** RuntimeClass name the host must enforce for this script (plan 24.18). */\n runtimeClass?: string;\n /** Whether the script may resume its expected checkpoint (plan 24.19). */\n checkpointCompatible?: boolean;\n}\n\ntype LoadedScriptFunction = (...arguments_: never[]) => unknown;\n\nfunction isLoadedScriptFunction(value: unknown): value is LoadedScriptFunction {\n return typeof value === 'function';\n}\n\n/**\n * Read the admission metadata attached to a loaded script, or `undefined`\n * when the script was provided directly (not loaded through this module).\n */\nexport function getLoadedScriptMetadata(script: unknown): LoadedScriptMetadata | undefined {\n if (!isLoadedScriptFunction(script)) return undefined;\n return (script as unknown as Record<PropertyKey, unknown>)[LOADED_SCRIPT_METADATA] as LoadedScriptMetadata | undefined;\n}\n\nfunction attachLoadedScriptMetadata(script: LoadedScriptFunction, metadata: LoadedScriptMetadata): void {\n // Module-level caching means the same function object can be returned for\n // repeated loads of an identical specifier; the metadata is derived from\n // the source digest, so re-attaching is unnecessary.\n if (getLoadedScriptMetadata(script) !== undefined) return;\n Object.defineProperty(script, LOADED_SCRIPT_METADATA, {\n value: metadata,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n}\n\n// ─── Builtin digest allowlist ──────────────────────────────────────────\n\nconst builtinScriptDigests = new Set<string>();\n\n/**\n * Register pre-computed digests of first-party builtin loop sources.\n * Idempotent; hosts typically use {@link registerBuiltinScriptSources}.\n */\nexport function registerBuiltinScriptDigests(digests: Iterable<string>): void {\n for (const digest of digests) {\n builtinScriptDigests.add(digest);\n }\n}\n\n/**\n * Compute canonical digests for builtin loop sources and register them in\n * the startup allowlist. Returns the registered digests.\n */\nexport async function registerBuiltinScriptSources(sources: Record<string, string>): Promise<string[]> {\n const digests: string[] = [];\n for (const source of Object.values(sources)) {\n digests.push(await digestNormalizedScript(normalizeScript(source)));\n }\n registerBuiltinScriptDigests(digests);\n return digests;\n}\n\n/** Check whether a canonical digest belongs to a registered builtin source. */\nexport function isRegisteredBuiltinScriptDigest(digest: string): boolean {\n return builtinScriptDigests.has(digest);\n}\n\n// ─── Denial error ──────────────────────────────────────────────────────\n\n/** Structured error thrown when the script load gate denies a source. */\nexport class ScriptLoadDeniedError extends Error {\n readonly code = 'SCRIPT_LOAD_DENIED' as const;\n\n constructor(\n /** Canonical digest of the denied script. */\n readonly digest: string,\n /** Reason reported by the gate. */\n readonly gateReason: string,\n ) {\n super(`Agent loop script load denied (sha256:${digest}): ${gateReason}`);\n this.name = 'ScriptLoadDeniedError';\n }\n}\n\n/**\n * Default gate used when the host provides none: denies every non-builtin\n * script source (fail-closed, plan 24.15).\n */\nexport const FAIL_CLOSED_SCRIPT_LOAD_GATE: ScriptLoadGate = {\n admitScriptLoad: () => ({\n allowed: false,\n reason: 'No script load gate configured; non-builtin script sources are denied by default (fail-closed)',\n }),\n};\n\n// ─── Helpers ───────────────────────────────────────────────────────────\n\nfunction getExportedScript(moduleExports: unknown): unknown {\n if (typeof moduleExports === 'function') return moduleExports;\n if (!moduleExports || typeof moduleExports !== 'object') return undefined;\n\n const record = moduleExports as Record<string, unknown>;\n return record.default ?? record.run;\n}\n\nfunction sourceToDataSpecifier(source: string, name = 'agent-loop-script.mjs'): string {\n return `data:text/javascript;charset=utf-8,${encodeURIComponent(`${source}\\n//# sourceURL=${name}`)}`;\n}\n\nfunction normalizeScriptReference(scriptReference: AgentLoopScriptReference): LoopProfileScriptReference {\n if (typeof scriptReference !== 'string') return scriptReference;\n if (scriptReference.startsWith('builtin:')) return { kind: 'builtin', id: scriptReference };\n return { kind: 'specifier', specifier: scriptReference };\n}\n\nfunction isFileSpecifier(specifier: string): boolean {\n return specifier.startsWith('file:') || specifier.startsWith('/') || specifier.startsWith('./') || specifier.startsWith('../');\n}\n\nfunction isNetworkSpecifier(specifier: string): boolean {\n return specifier.startsWith('http:') || specifier.startsWith('https:');\n}\n\nfunction isSourceSpecifier(specifier: string): boolean {\n return specifier.startsWith('data:text/javascript') || specifier.startsWith('data:application/javascript');\n}\n\n/**\n * Decode the source carried by a `data:` script specifier. Returns\n * `undefined` when the payload cannot be decoded; callers must treat an\n * undecodable data URL as a denial (fail-closed).\n */\nfunction decodeDataScriptSpecifier(specifier: string): string | undefined {\n const commaIndex = specifier.indexOf(',');\n if (commaIndex < 0) return undefined;\n const metadata = specifier.slice('data:'.length, commaIndex);\n const payload = specifier.slice(commaIndex + 1);\n try {\n if (metadata.split(';').includes('base64')) {\n // atob is available in browsers and Node ≥ 16; no Buffer needed.\n return atob(payload);\n }\n return decodeURIComponent(payload);\n } catch {\n return undefined;\n }\n}\n\nfunction assertSpecifierAllowed(specifier: string, policy: Required<Pick<LoadAgentLoopScriptOptions, 'allowFile' | 'allowNetwork' | 'allowSource' | 'allowSpecifier'>>): void {\n if (!policy.allowSpecifier) {\n throw new Error('Agent loop script import specifiers are disabled by policy.');\n }\n if (isSourceSpecifier(specifier) && !policy.allowSource) {\n throw new Error('Agent loop script source/data URLs are disabled by policy.');\n }\n if (isFileSpecifier(specifier) && !policy.allowFile) {\n throw new Error('Agent loop script file imports are disabled by policy.');\n }\n if (isNetworkSpecifier(specifier) && !policy.allowNetwork) {\n throw new Error('Agent loop script network imports are disabled by policy.');\n }\n}\n\n/**\n * Load an agent loop script. Source-bearing references (builtin sources,\n * `source` refs, `data:` URLs) are admitted by content digest before\n * `import()`: builtin digests load directly, everything else must pass the\n * host's {@link ScriptLoadGate} and is denied when no gate is configured.\n */\nexport async function loadAgentLoopScript<TScript>(\n scriptReference: AgentLoopScriptReference,\n options: LoadAgentLoopScriptOptions = {},\n): Promise<TScript> {\n const policy = { ...DEFAULT_POLICY, ...options };\n const importModule = options.importModule ?? ((specifier: string) => import(specifier));\n const normalized = normalizeScriptReference(scriptReference);\n const scriptType = options.scriptType ?? 'Agent loop script';\n let scriptSpecifier: string;\n let sourceForAdmission: string | undefined;\n\n if (normalized.kind === 'builtin') {\n if (!policy.allowBuiltin) {\n throw new Error('Built-in agent loop scripts are disabled by policy.');\n }\n const source = options.getBuiltinScriptSource?.(normalized.id);\n if (!source) throw new Error(`Unknown built-in agent loop script: ${normalized.id}`);\n sourceForAdmission = source;\n scriptSpecifier = sourceToDataSpecifier(source, normalized.id);\n } else if (normalized.kind === 'source') {\n if (!policy.allowSource) {\n throw new Error('Agent loop script source strings are disabled by policy.');\n }\n sourceForAdmission = normalized.source;\n scriptSpecifier = sourceToDataSpecifier(normalized.source, normalized.name);\n } else {\n scriptSpecifier = normalized.specifier;\n assertSpecifierAllowed(scriptSpecifier, policy);\n if (isSourceSpecifier(scriptSpecifier)) {\n sourceForAdmission = decodeDataScriptSpecifier(scriptSpecifier);\n if (sourceForAdmission === undefined) {\n throw new ScriptLoadDeniedError('undecodable', 'data: script specifier payload could not be decoded');\n }\n }\n }\n\n // Admit source-bearing scripts by content digest before import().\n let metadata: LoadedScriptMetadata | undefined;\n if (sourceForAdmission !== undefined) {\n const normalizedSource = normalizeScript(sourceForAdmission);\n const digest = await digestNormalizedScript(normalizedSource);\n if (isRegisteredBuiltinScriptDigest(digest)) {\n // First-party builtin source: allowlisted by digest at startup.\n metadata = { digest, builtin: true, trustClass: 'trusted' };\n } else {\n const gate = options.scriptLoadGate ?? FAIL_CLOSED_SCRIPT_LOAD_GATE;\n const decision = await gate.admitScriptLoad({ normalizedSource, digest, reference: normalized, scriptType });\n if (!decision.allowed) {\n throw new ScriptLoadDeniedError(digest, decision.reason ?? 'denied by script load gate');\n }\n metadata = {\n digest,\n builtin: false,\n trustClass: decision.trustClass,\n runtimeClass: decision.runtimeClass,\n checkpointCompatible: decision.checkpointCompatible,\n };\n }\n }\n\n const moduleExports: unknown = await importModule(scriptSpecifier);\n const exportedScript = getExportedScript(moduleExports);\n\n if (!isLoadedScriptFunction(exportedScript)) {\n throw new TypeError(\n `${scriptType} \"${scriptSpecifier}\" must export a default function or named run function.`,\n );\n }\n\n if (metadata) {\n attachLoadedScriptMetadata(exportedScript, metadata);\n }\n\n return exportedScript as TScript;\n}\n","import { builtinAgentAgentLoopSources, getBuiltinAgentAgentLoopSource } from '../../loops/agent-agent-loop/builtinLoopSources.js';\nimport { type AgentLoopScriptReference, loadAgentLoopScript, registerBuiltinScriptSources } from '../scriptLoader.js';\nimport type { AgentLoopScriptPolicy } from '../types.js';\nimport type { AgentAgentLoopScript } from './loop.js';\n\nexport type LoadAgentAgentLoopScriptOptions = AgentLoopScriptPolicy;\n\nexport type AgentAgentLoopScriptReference = AgentLoopScriptReference;\n\nlet builtinDigestsRegistered: Promise<unknown> | undefined;\n\n/**\n * Register the first-party builtin loop sources in the digest allowlist\n * once, so builtin scripts load without gate overhead while every other\n * source must pass the script load gate (plan 24.15).\n */\nfunction ensureBuiltinDigestsRegistered(): Promise<unknown> {\n builtinDigestsRegistered ??= registerBuiltinScriptSources(builtinAgentAgentLoopSources);\n return builtinDigestsRegistered;\n}\n\nexport async function loadAgentAgentLoopScript(\n scriptReference: AgentAgentLoopScriptReference,\n options: LoadAgentAgentLoopScriptOptions = {},\n): Promise<AgentAgentLoopScript> {\n await ensureBuiltinDigestsRegistered();\n return loadAgentLoopScript<AgentAgentLoopScript>(scriptReference, {\n ...options,\n getBuiltinScriptSource: getBuiltinAgentAgentLoopSource,\n scriptType: 'AgentAgentLoop script',\n });\n}\n","/**\n * AgentAgent_Loop — a loop that orchestrates child agents.\n *\n * This loop does NOT call the LLM directly. Instead it coordinates child agents:\n * - running a child agent and feeding its result to another child agent (review / verify)\n * - splitting work across multiple parallel child agents\n * - looping back to a child agent with feedback when a reviewer rejects the output\n *\n * The loop script (.mjs) holds the orchestration logic. This file provides the\n * runtime that invokes the script and manages child agent runs.\n */\n\nimport type { AgentClient, AgentOrchestrationClient, ScriptDeploymentClient } from '../../orchestration/index.js';\nimport { createAgentClient, createScriptDeploymentClient } from '../../orchestration/index.js';\nimport type { AgentLoopDefinition, AgentLoopGenerator, AgentLoopInput, AgentLoopRuntime, AgentLoopStep, LoopProfile } from '../types.js';\nimport { type AgentAgentLoopScriptReference, loadAgentAgentLoopScript, type LoadAgentAgentLoopScriptOptions } from './scriptLoader.js';\n\nconst LOOP_ID = 'agent-agent-loop';\nconst LOOP_NAME = 'AgentAgent Loop';\nconst LOOP_DESC = 'Orchestrates child agents to collaborate on a task. Supports sequential chaining, parallel execution, and feedback loops.';\n\n/**\n * Typed API passed to a AgentAgent `.mjs` script.\n *\n * The API is intentionally primitive: scripts decide the workflow shape, role\n * names, approval rules, retry limits, and delivery gates. This runtime only\n * handles child-agent execution, progress events, cancellation, state, and\n * checkpoints.\n */\nexport interface AgentAgentLoopScriptArguments {\n /** The parent turn input. `input.message` is the user's original goal. */\n input: AgentLoopInput;\n /** Host/runtime context for advanced integrations. Prefer the typed helpers below when possible. */\n context: AgentAgentLoopContext;\n /** Active profile. Scripts may define their own workflow-specific metadata keys here. */\n profile?: LoopProfile;\n /** Normalized worker agents read from `context.agents` or `profile.metadata.agents`. */\n agents: AgentAgentDescriptor[];\n /**\n * Read raw agent entries from `profile.metadata[key]`; defaults to `agents`.\n * This is deliberately generic so scripts can choose names like `critics`,\n * `builders`, `verifiers`, or any other workflow-specific role.\n */\n getAgentEntries: (key?: string) => AgentAgentConfigEntry[];\n /** Low-level runtime hooks. Prefer `state`, `checkpoint`, `emit`, and run helpers first. */\n runtime?: Partial<AgentLoopRuntime>;\n /** Policy-scoped declarative manager facade. It never exposes raw infrastructure drivers or secrets. */\n orchestration?: AgentOrchestrationClient;\n /** Typed convenience client for creating, reading, and deleting Agent workloads and runs. */\n agentClient?: AgentClient;\n /**\n * Declarative generated-script deployment (plan 24.14). The script declares\n * placement and lifecycle; trust, interface ceilings, and persistence are\n * host-bound. Undefined when the host provides no deployment configuration.\n */\n scriptClient?: ScriptDeploymentClient;\n /** Run one child agent and collect all yielded steps into a text result. */\n runAgent: (input: AgentAgentRunAgentInput) => Promise<AgentAgentRunAgentResult>;\n /** Run child agents concurrently. Use `runSequential` when order matters. */\n runAgents: (inputs: AgentAgentRunAgentInput[]) => Promise<AgentAgentRunAgentResult[]>;\n /** Run a batch of agents in order, aggregating successful output and failures. */\n runSequential: (input?: AgentAgentBatchRunInput) => Promise<AgentAgentBatchRunResult>;\n /** Run a batch of agents concurrently, aggregating successful output and failures. */\n runParallel: (input?: AgentAgentBatchRunInput) => Promise<AgentAgentBatchRunResult>;\n /** Format a batch result for final delivery or an intermediate report. */\n formatAgentResults: (result: AgentAgentBatchRunResult, options?: AgentAgentFormatResultsOptions) => string;\n /** Emit a formatted batch result as the parent loop's final/user-visible message. */\n finishAgentResults: (result: AgentAgentBatchRunResult, options?: AgentAgentFormatResultsOptions) => void;\n /** Emit a raw loop step upstream. Use sparingly; helpers already emit progress. */\n emit: (step: AgentLoopStep) => void;\n /** Emit a user-visible message or step and end the script's work. */\n finish: (message: string | AgentLoopStep) => void;\n /** True when the host cancelled this parent run. Long-running scripts should check this between phases. */\n isCancelled: () => boolean;\n /** Write an observability event through the host runtime logger. */\n log: (event: string, data?: Record<string, unknown>) => void;\n /** Per-run persistent state scoped by the host runtime. */\n state: AgentLoopRuntime['state'];\n /** Record a resumable milestone for long workflows. */\n checkpoint: AgentLoopRuntime['checkpoint'];\n /** Read a milestone recorded by an earlier process and skip completed work. */\n loadCheckpoint: AgentLoopRuntime['loadCheckpoint'];\n}\n\nexport type AgentAgentScriptContext = AgentAgentLoopScriptArguments;\n\nexport type AgentAgentContext = AgentAgentScriptContext;\n\nexport interface AgentAgentDescriptor {\n /** Child profile id to run. */\n profileId: string;\n /** Prompt override for this child run. Defaults to the parent input message. */\n prompt?: string;\n /** Conversation id override. Defaults to `${parent}:child:${index}` for batch helpers. */\n conversationId?: string;\n /** Optional human-readable role label, e.g. \"implementer\" or \"reviewer\". */\n label?: string;\n [key: string]: unknown;\n}\n\nexport type AgentAgentConfigEntry =\n | string\n | ({\n profileId?: string;\n profile?: string;\n prompt?: string;\n conversationId?: string;\n label?: string;\n } & Record<string, unknown>);\n\nexport interface AgentAgentRunAgentInput {\n /** Child profile id. `profile` is accepted as an ergonomic alias for scripts. */\n profileId?: string;\n profile?: string;\n /** Defaults to the parent input message. */\n prompt?: string;\n conversationId?: string;\n label?: string;\n}\n\nexport interface AgentAgentRunAgentResult {\n profileId: string;\n conversationId: string;\n steps: AgentLoopStep[];\n text: string;\n}\n\nexport interface AgentAgentRunAgentFailure {\n profileId: string;\n conversationId?: string;\n error: string;\n}\n\nexport interface AgentAgentBatchRunInput {\n /** Agents to run. Defaults to `ctx.agents`. */\n agents?: AgentAgentConfigEntry[];\n /** Prompt shared by every agent in this batch. Defaults to the parent input message. */\n prompt?: string;\n /** When false, the first child failure rejects the batch. Defaults to true. */\n continueOnError?: boolean;\n}\n\nexport interface AgentAgentBatchRunResult {\n results: AgentAgentRunAgentResult[];\n failures: AgentAgentRunAgentFailure[];\n text: string;\n}\n\nexport interface AgentAgentFormatResultsOptions {\n emptyMessage?: string;\n failureHeader?: string;\n includeFailureSection?: boolean;\n}\n\nexport type AgentAgentLoopScriptResult =\n | AgentLoopGenerator\n | AgentLoopStep\n | AgentLoopStep[]\n | string\n | undefined;\n\nexport type AgentAgentLoopScript = (\n scriptArguments: AgentAgentLoopScriptArguments,\n) => AgentAgentLoopScriptResult | Promise<AgentAgentLoopScriptResult>;\n\nexport interface AgentAgentLoopContext {\n [key: string]: unknown;\n profile?: LoopProfile;\n runtime?: Partial<AgentLoopRuntime>;\n agents?: AgentAgentConfigEntry[];\n script?: AgentAgentLoopScript;\n loadScript?: (\n script: AgentAgentLoopScriptReference,\n context: AgentAgentLoopContext,\n ) => AgentAgentLoopScript | Promise<AgentAgentLoopScript>;\n scriptPolicy?: LoadAgentAgentLoopScriptOptions;\n}\n\nfunction isAsyncIterable(value: unknown): value is AgentLoopGenerator {\n return Boolean(value && typeof value === 'object' && Symbol.asyncIterator in value);\n}\n\nfunction messageStep(message: string): AgentLoopStep {\n return { type: 'message', data: message };\n}\n\nfunction stepText(step: AgentLoopStep): string | undefined {\n if (step.type !== 'message') return undefined;\n if (typeof step.data === 'string') return step.data;\n if (step.data && typeof step.data === 'object' && 'content' in step.data) {\n const content = (step.data as { content?: unknown }).content;\n return typeof content === 'string' ? content : undefined;\n }\n return undefined;\n}\n\nfunction profileIdFromEntry(entry: AgentAgentConfigEntry): string | undefined {\n if (typeof entry === 'string') return entry;\n return entry.profileId ?? entry.profile;\n}\n\nfunction readProfileAgentEntries(profile?: LoopProfile, key = 'agents'): AgentAgentConfigEntry[] | undefined {\n const metadata = profile?.metadata;\n if (!metadata) return undefined;\n\n const entries = metadata[key];\n if (Array.isArray(entries)) return entries as AgentAgentConfigEntry[];\n\n return undefined;\n}\n\nfunction normalizeAgentAgents(\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n entries?: AgentAgentConfigEntry[],\n prompt?: string,\n): AgentAgentDescriptor[] {\n const configuredEntries = entries ?? context.agents ?? readProfileAgentEntries(context.profile) ?? [];\n return configuredEntries.flatMap((entry, index) => {\n const profileId = profileIdFromEntry(entry);\n if (!profileId) return [];\n const record = typeof entry === 'string' ? {} : entry;\n return {\n ...record,\n profileId,\n prompt: prompt ?? record.prompt,\n conversationId: record.conversationId ?? `${input.conversationId}:child:${index}`,\n label: record.label,\n };\n });\n}\n\nfunction formatAgentResults(\n result: AgentAgentBatchRunResult,\n options: AgentAgentFormatResultsOptions = {},\n): string {\n const emptyMessage = options.emptyMessage ?? 'No child agent output.';\n const failureHeader = options.failureHeader ?? 'Failed child agents:';\n const includeFailureSection = options.includeFailureSection !== false;\n const sections = [result.text || emptyMessage];\n\n if (includeFailureSection && result.failures.length > 0) {\n sections.push(`${failureHeader}\\n${result.failures.map(failure => `${failure.profileId}: ${failure.error}`).join('\\n')}`);\n }\n\n return sections.filter(Boolean).join('\\n\\n');\n}\n\nfunction createScriptArguments(\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n emittedSteps: AgentLoopStep[],\n): AgentAgentLoopScriptArguments {\n const agentEntries = context.agents ?? readProfileAgentEntries(context.profile) ?? [];\n const agents = normalizeAgentAgents(input, context, agentEntries);\n const getAgentEntries = (key = 'agents'): AgentAgentConfigEntry[] => {\n if (key === 'agents') return agentEntries;\n return readProfileAgentEntries(context.profile, key) ?? [];\n };\n\n const emit = (step: AgentLoopStep): void => {\n emittedSteps.push(step);\n context.runtime?.emit?.(step);\n };\n\n const log = (event: string, data?: Record<string, unknown>): void => {\n context.runtime?.log?.(event, data);\n };\n\n const isCancelled = (): boolean => context.runtime?.signal?.cancelled === true;\n\n // Monotonic counter for unique child conversation IDs across concurrent runs\n // of the same profile (24.57 collision fix).\n let childCounter = 0;\n\n const runAgent = async (childInput: AgentAgentRunAgentInput): Promise<AgentAgentRunAgentResult> => {\n if (isCancelled()) throw new Error('AgentAgent_Loop cancelled before child agent start');\n const profileId = childInput.profileId ?? childInput.profile;\n if (!profileId) throw new Error('ctx.runAgent requires profileId or profile');\n if (!context.runtime?.runChildAgent) throw new Error('ctx.runAgent requires runtime.runChildAgent');\n\n const childConversationId = childInput.conversationId ?? `${input.conversationId}:child:${profileId}:${++childCounter}`;\n const prompt = childInput.prompt ?? input.message;\n emit({\n type: 'thinking',\n data: { status: 'child-agent-started', profileId, conversationId: childConversationId },\n });\n\n const steps: AgentLoopStep[] = [];\n const chunks: string[] = [];\n try {\n for await (\n const step of context.runtime.runChildAgent({\n profileId,\n prompt,\n conversationId: childConversationId,\n })\n ) {\n if (isCancelled()) throw new Error('AgentAgent_Loop cancelled during child agent run');\n steps.push(step);\n const text = stepText(step);\n if (text) chunks.push(text);\n emit({\n type: 'thinking',\n data: { status: 'child-agent-step', profileId, conversationId: childConversationId, step },\n });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emit({\n type: 'thinking',\n data: { status: 'child-agent-failed', profileId, conversationId: childConversationId, error: message },\n });\n throw error;\n }\n\n emit({\n type: 'thinking',\n data: { status: 'child-agent-completed', profileId, conversationId: childConversationId },\n });\n return { profileId, conversationId: childConversationId, steps, text: chunks.join('').trim() };\n };\n\n const runBatch = async (\n batchInput: AgentAgentBatchRunInput | undefined,\n mode: 'parallel' | 'sequential',\n ): Promise<AgentAgentBatchRunResult> => {\n const batchAgents = normalizeAgentAgents(input, context, batchInput?.agents, batchInput?.prompt);\n const continueOnError = batchInput?.continueOnError !== false;\n const results: AgentAgentRunAgentResult[] = [];\n const failures: AgentAgentRunAgentFailure[] = [];\n\n const runOne = async (agent: AgentAgentDescriptor): Promise<void> => {\n if (isCancelled()) {\n emit({\n type: 'thinking',\n data: { status: 'cancelled', conversationId: input.conversationId },\n });\n return;\n }\n try {\n const result = await runAgent(agent);\n results.push(result);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n failures.push({ profileId: agent.profileId, conversationId: agent.conversationId, error: message });\n if (!continueOnError) throw error;\n }\n };\n\n if (mode === 'parallel') {\n await Promise.all(batchAgents.map(agent => runOne(agent)));\n } else {\n for (const agent of batchAgents) {\n await runOne(agent);\n if (isCancelled()) break;\n }\n }\n\n return { results, failures, text: results.map(result => result.text).filter(Boolean).join('\\n\\n') };\n };\n\n const agentClient = context.runtime?.orchestration ? createAgentClient(context.runtime.orchestration) : undefined;\n const scriptClient = context.runtime?.scriptDeployment ? createScriptDeploymentClient(context.runtime.scriptDeployment) : undefined;\n\n return {\n input,\n context,\n profile: context.profile,\n agents,\n getAgentEntries,\n runtime: context.runtime,\n orchestration: context.runtime?.orchestration,\n agentClient,\n scriptClient,\n runAgent,\n runAgents: inputs => Promise.all(inputs.map(runAgent)),\n runSequential: batchInput => runBatch(batchInput, 'sequential'),\n runParallel: batchInput => runBatch(batchInput, 'parallel'),\n formatAgentResults,\n finishAgentResults: (result, options) => {\n emit(messageStep(formatAgentResults(result, options)));\n },\n emit,\n finish: message => {\n emit(typeof message === 'string' ? messageStep(message) : message);\n },\n isCancelled,\n log,\n state: context.runtime?.state ?? {\n get: async () => undefined,\n set: async () => undefined,\n update: async () => undefined,\n },\n checkpoint: context.runtime?.checkpoint ?? (async () => undefined),\n loadCheckpoint: context.runtime?.loadCheckpoint ?? (async () => undefined),\n };\n}\n\nasync function* drainEmittedSteps(steps: AgentLoopStep[]): AgentLoopGenerator {\n while (steps.length > 0) {\n const step = steps.shift();\n if (step) yield step;\n }\n}\n\nasync function* runScript(\n script: AgentAgentLoopScript,\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n): AgentLoopGenerator {\n const emittedSteps: AgentLoopStep[] = [];\n const scriptArguments = createScriptArguments(input, context, emittedSteps);\n const result = await script(scriptArguments);\n\n yield* drainEmittedSteps(emittedSteps);\n if (isAsyncIterable(result)) {\n yield* result;\n yield* drainEmittedSteps(emittedSteps);\n } else if (typeof result === 'string') {\n yield messageStep(result);\n } else if (Array.isArray(result)) {\n yield* result;\n } else if (result) {\n yield result;\n }\n}\n\nfunction asAgentAgentContext(context: { [key: string]: unknown }): AgentAgentLoopContext {\n return context as AgentAgentLoopContext;\n}\n\nasync function resolveScript(\n context: AgentAgentLoopContext,\n): Promise<AgentAgentLoopScript | undefined> {\n if (context.script) return context.script;\n const scriptReference = context.profile?.scriptReference ?? context.profile?.scriptRef ?? context.profile?.script;\n if (scriptReference) {\n if (context.loadScript) return context.loadScript(scriptReference, context);\n return loadAgentAgentLoopScript(scriptReference, context.scriptPolicy);\n }\n return undefined;\n}\n\n/**\n * Create the AgentAgent_Loop definition and register it with the loop registry.\n */\nexport function createAgentAgentLoopDefinition(): AgentLoopDefinition {\n return {\n id: LOOP_ID,\n name: LOOP_NAME,\n description: LOOP_DESC,\n createRunner: (rawContext) => {\n return async function* agentAgentLoop(input) {\n const context = asAgentAgentContext(rawContext);\n const script = await resolveScript(context);\n\n yield {\n type: 'thinking',\n data: { status: 'agent-agent-loop-loop-started', conversationId: input.conversationId },\n };\n context.runtime?.log?.('agent-agent-loop-loop-started', {\n conversationId: input.conversationId,\n profileId: context.profile?.id,\n });\n\n if (script) {\n yield* runScript(script, input, context);\n yield {\n type: 'thinking',\n data: { status: 'completed', conversationId: input.conversationId },\n };\n return;\n }\n\n yield {\n type: 'thinking',\n data: { status: 'script-missing', conversationId: input.conversationId },\n };\n yield {\n type: 'message',\n data: 'AgentAgentLoop requires an explicit loop script. Configure profile.scriptReference or provide context.script.',\n };\n yield {\n type: 'thinking',\n data: { status: 'completed', conversationId: input.conversationId },\n };\n };\n },\n };\n}\n\n/** Export loop id for consumers. */\nexport function getAgentAgentLoopId(): string {\n return LOOP_ID;\n}\n","// Generated by scripts/generate-loop-sources.mjs. Edit the sibling .mjs files instead.\n\nexport const AgentToolLoopDefaultScriptId = 'builtin:agent-tool-loop/default';\n\nexport const BUILTIN_AGENT_TOOL_LOOP_DEFAULT_SCRIPT_ID = AgentToolLoopDefaultScriptId;\n\nexport const builtinAgentToolLoopSources: Readonly<Record<string, string>> = {\n [AgentToolLoopDefaultScriptId]: [\n '// @ts-check',\n '',\n \"/** @param {import('../../loopAPI/agent-tool-loop/loop.js').AgentToolLoopScriptContext} ctx */\",\n 'export default async function* run(ctx) {',\n ' const state = ctx.createState();',\n '',\n ' try {',\n ' const start = await ctx.startTurn(state);',\n ' if (start.step) yield start.step;',\n \" if (start.action === 'stop') return;\",\n '',\n ' while (true) {',\n ' const result = yield* ctx.runIteration(state);',\n \" if (result.action === 'stop') return;\",\n ' }',\n ' } catch (error) {',\n \" await ctx.stopTurn(state, 'error');\",\n ' throw error;',\n ' } finally {',\n ' await ctx.stopTurn(state);',\n ' }',\n '}',\n ].join('\\n'),\n};\n\nexport function getBuiltinAgentToolLoopSource(id: string): string | undefined {\n return builtinAgentToolLoopSources[id];\n}\n","import { builtinAgentToolLoopSources, getBuiltinAgentToolLoopSource } from '../../loops/agent-tool-loop/builtinLoopSources.js';\nimport { type AgentLoopScriptReference, loadAgentLoopScript, registerBuiltinScriptSources } from '../scriptLoader.js';\nimport type { AgentLoopScriptPolicy } from '../types.js';\nimport type { AgentToolLoopScript } from './loop.js';\n\nexport type LoadAgentToolLoopScriptOptions = AgentLoopScriptPolicy;\n\nexport type AgentToolLoopScriptReference = AgentLoopScriptReference;\n\nlet builtinDigestsRegistered: Promise<unknown> | undefined;\n\n/**\n * Register the first-party builtin loop sources in the digest allowlist\n * once, so builtin scripts load without gate overhead while every other\n * source must pass the script load gate (plan 24.15).\n */\nfunction ensureBuiltinDigestsRegistered(): Promise<unknown> {\n builtinDigestsRegistered ??= registerBuiltinScriptSources(builtinAgentToolLoopSources);\n return builtinDigestsRegistered;\n}\n\nexport async function loadAgentToolLoopScript(\n scriptReference: AgentToolLoopScriptReference,\n options: LoadAgentToolLoopScriptOptions = {},\n): Promise<AgentToolLoopScript> {\n await ensureBuiltinDigestsRegistered();\n return loadAgentLoopScript<AgentToolLoopScript>(scriptReference, {\n ...options,\n getBuiltinScriptSource: getBuiltinAgentToolLoopSource,\n scriptType: 'AgentToolLoop script',\n });\n}\n","import type { AgentLoopGenerator, AgentLoopInput, AgentLoopStep } from '../types.js';\nimport type { AgentToolLoopContext, AgentToolLoopScript, AgentToolLoopScriptContext } from './contracts.js';\nimport { loadAgentToolLoopScript } from './scriptLoader.js';\nimport { createAgentToolLoopState, runAgentToolLoopIteration, startAgentToolLoopTurn, stopAgentToolLoopTurn } from './turnPrimitives.js';\n\nfunction isAsyncIterable(value: unknown): value is AgentLoopGenerator {\n return Boolean(value && typeof value === 'object' && Symbol.asyncIterator in value);\n}\n\nfunction messageStep(message: string): AgentLoopStep {\n return { type: 'message', data: message };\n}\n\nasync function* drainEmittedSteps(steps: AgentLoopStep[]): AgentLoopGenerator {\n while (steps.length > 0) {\n const step = steps.shift();\n if (step) yield step;\n }\n}\n\nexport function asAgentToolLoopContext(rawContext: { [key: string]: unknown }): AgentToolLoopContext {\n return rawContext as unknown as AgentToolLoopContext;\n}\n\nexport async function resolveAgentToolLoopScript(context: AgentToolLoopContext): Promise<AgentToolLoopScript | undefined> {\n if (context.script) return context.script;\n const scriptReference = context.profile?.scriptReference ?? context.profile?.scriptRef ?? context.profile?.script;\n if (!scriptReference) return undefined;\n if (context.loadScript) return context.loadScript(scriptReference, context);\n return loadAgentToolLoopScript(scriptReference, context.scriptPolicy);\n}\n\nfunction createAgentToolLoopScriptContext(\n input: AgentLoopInput,\n context: AgentToolLoopContext,\n emittedSteps: AgentLoopStep[],\n): AgentToolLoopScriptContext {\n const emit = (step: AgentLoopStep): void => {\n emittedSteps.push(step);\n context.runtime?.emit?.(step);\n };\n return {\n input,\n context,\n profile: context.profile,\n createState: () => createAgentToolLoopState(context),\n startTurn: state => startAgentToolLoopTurn(context, input, state),\n runIteration: state => runAgentToolLoopIteration(context, input, state),\n stopTurn: (state, reason) => stopAgentToolLoopTurn(context, input, state, reason),\n emit,\n finish: message => {\n emit(typeof message === 'string' ? messageStep(message) : message);\n },\n isCancelled: () => context.runtime?.signal?.cancelled === true || context.agentToolLoop?.isCancelled?.(input.conversationId) === true,\n log: (event, data) => {\n context.runtime?.log?.(event, data);\n context.logger?.debug?.(event, data);\n },\n };\n}\n\nexport async function* runAgentToolLoopScript(\n script: AgentToolLoopScript,\n input: AgentLoopInput,\n context: AgentToolLoopContext,\n): AgentLoopGenerator {\n const emittedSteps: AgentLoopStep[] = [];\n const result = await script(createAgentToolLoopScriptContext(input, context, emittedSteps));\n\n yield* drainEmittedSteps(emittedSteps);\n if (isAsyncIterable(result)) {\n yield* result;\n yield* drainEmittedSteps(emittedSteps);\n } else if (typeof result === 'string') {\n yield messageStep(result);\n } else if (Array.isArray(result)) {\n yield* result;\n } else if (result) {\n yield result;\n }\n}\n","import type { AgentLoopDefinition } from '../types.js';\nimport { createAgentToolLoopRunner } from './directRunner.js';\nimport { asAgentToolLoopContext, resolveAgentToolLoopScript, runAgentToolLoopScript } from './scriptRunner.js';\n\nexport type {\n AgentToolLoopContext,\n AgentToolLoopIterationGenerator,\n AgentToolLoopIterationResult,\n AgentToolLoopScript,\n AgentToolLoopScriptContext,\n AgentToolLoopScriptReference,\n AgentToolLoopState,\n AgentToolLoopTurnStartResult,\n LoadAgentToolLoopScriptOptions,\n} from './contracts.js';\n\nexport { createAgentToolLoopRunner } from './directRunner.js';\n\nexport function createAgentToolLoopDefinition(name = 'AgentToolLoop'): AgentLoopDefinition {\n return {\n id: 'agent-tool-loop',\n name,\n description: 'Agent/tool loop that alternates between LLM output and external tool execution.',\n createRunner: (rawContext) => {\n const context = asAgentToolLoopContext(rawContext);\n return async function* agentToolLoop(input) {\n const script = await resolveAgentToolLoopScript(context);\n if (script) {\n yield* runAgentToolLoopScript(script, input, context);\n return;\n }\n yield* createAgentToolLoopRunner(context)(input);\n };\n },\n };\n}\n","/**\n * Built-in loop registrations — installed at startup so getLoopRegistry().createRunner('agent-tool-loop') works.\n *\n * This module allows hosts to skip manual registerLoop() for the built-in loop types.\n * Hosts can still override by calling registerLoop() with the same id after.\n */\n\nimport { createAgentAgentLoopDefinition, getAgentAgentLoopId } from '../agent-agent-loop/loop.js';\nimport { createAgentToolLoopDefinition } from '../agent-tool-loop/loop.js';\nimport { getLoopRegistry } from '../registry.js';\n\nexport const AGENT_TOOL_LOOP_ID = 'agent-tool-loop';\nexport const AGENT_AGENT_LOOP_ID = getAgentAgentLoopId();\n\n/**\n * Register the default built-in loops (agent-tool-loop and agent-agent-loop) with the loop registry.\n * Safe to call multiple times — skips already-registered loops.\n */\nexport function registerBuiltinLoops(): void {\n const registry = getLoopRegistry();\n\n if (!registry.getLoop(AGENT_TOOL_LOOP_ID)) {\n registry.registerLoop(createAgentToolLoopDefinition('AgentToolLoop'));\n }\n\n if (!registry.getLoop(AGENT_AGENT_LOOP_ID)) {\n registry.registerLoop(createAgentAgentLoopDefinition());\n }\n}\n","import { z } from 'zod';\n\nimport { waitForQuestionAnswer } from './questionWaitRegistry.js';\nimport type { BuiltinToolContext } from './types.js';\n\nexport const askQuestionConfigSchema = z.object({\n question: z.string().min(1),\n /**\n * Desktop / TidGi 的 LLM 工具参数里通常不会显式携带 conversationId,\n * 由宿主侧上下文负责关联;这里允许缺省,交给宿主回调侧做路由。\n */\n conversationId: z.string().min(1).optional(),\n timeoutMs: z.number().int().positive().max(3_600_000).optional(),\n inputType: z.enum(['single-select', 'multi-select', 'text']).optional(),\n options: z\n .array(\n z.object({\n label: z.string(),\n description: z.string().optional(),\n }),\n )\n .optional(),\n allowFreeform: z.boolean().optional().default(true),\n});\n\n/**\n * Must match `tool_use name=\"ask-question\"` extracted by responsePatternUtility.\n */\nexport const ASK_QUESTION_TOOL_ID = 'ask-question';\n\nexport async function askQuestionImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = askQuestionConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: 'invalid_askQuestion_args' };\n }\n const { question, conversationId, timeoutMs, inputType, options, allowFreeform } = parsed.data;\n const questionId = crypto.randomUUID();\n const timeout = timeoutMs ?? 300_000;\n context.notifyAskQuestion?.({\n questionId,\n question,\n conversationId,\n inputType,\n options,\n allowFreeform,\n });\n try {\n const answer = await waitForQuestionAnswer(questionId, timeout);\n return { result: answer };\n } catch (error) {\n return { error: error instanceof Error ? error.message : 'askQuestion_failed' };\n }\n}\n","type Pending = {\n resolve: (answer: string) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst pending = new Map<string, Pending>();\n\nexport function resolveQuestionAnswer(questionId: string, answer: string): boolean {\n const p = pending.get(questionId);\n if (!p) return false;\n clearTimeout(p.timer);\n pending.delete(questionId);\n p.resolve(answer);\n return true;\n}\n\nexport function waitForQuestionAnswer(questionId: string, timeoutMs: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(questionId);\n reject(new Error('askQuestion_timeout'));\n }, timeoutMs);\n pending.set(questionId, { resolve, reject, timer });\n });\n}\n","/**\n * AskUserQuestion Tool — Pause agent execution and ask user for input.\n *\n * Uses the existing askQuestion pattern (notifyAskQuestion + waitForQuestionAnswer)\n * but provides a dedicated tool ID for explicit user question prompting.\n */\nimport { z } from 'zod';\n\nimport { waitForQuestionAnswer } from './questionWaitRegistry.js';\nimport type { BuiltinToolContext } from './types.js';\n\nexport const askUserQuestionConfigSchema = z.object({\n question: z.string().min(1).describe('The question to ask the user'),\n inputType: z\n .enum(['text', 'single-select', 'multi-select'])\n .optional()\n .default('text')\n .describe('Type of input expected: text, single-select, or multi-select'),\n options: z\n .array(\n z.object({\n label: z.string().min(1),\n description: z.string().optional(),\n }),\n )\n .optional()\n .describe('Options for single-select or multi-select input types'),\n allowFreeform: z\n .boolean()\n .optional()\n .default(true)\n .describe('Allow free-text input even for select types'),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .max(3_600_000)\n .optional()\n .default(300_000)\n .describe('Timeout in milliseconds (default 5 minutes)'),\n});\n\nexport const ASK_USER_QUESTION_TOOL_ID = 'askUserQuestion';\n\nexport async function askUserQuestionImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = askUserQuestionConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: `invalid_askUserQuestion_args: ${parsed.error.message}` };\n }\n\n const { question, inputType, options, allowFreeform, timeoutMs } = parsed.data;\n const questionId = crypto.randomUUID();\n const conversationId = context.agent?.id ?? context.activeToolConversationId;\n\n context.notifyAskQuestion?.({\n questionId,\n question,\n conversationId,\n inputType,\n options,\n allowFreeform,\n });\n\n try {\n const answer = await waitForQuestionAnswer(questionId, timeoutMs);\n return { result: answer };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'askUserQuestion_failed';\n return { error: message };\n }\n}\n","import type { BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'mcpClient';\n\nexport const mcpClientConfigSchema = {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Target node ID' },\n serverName: { type: 'string', description: 'MCP server name on that node' },\n toolName: { type: 'string', description: 'Tool to invoke' },\n args: { type: 'object', description: 'Tool arguments' },\n },\n required: ['nodeId', 'serverName', 'toolName'],\n} as const;\n\nexport const mcpClientImpl: BuiltinToolImpl = async (arguments_, context) => {\n const nodeId = arguments_.nodeId as string | undefined;\n const serverName = arguments_.serverName as string | undefined;\n const toolName = arguments_.toolName as string | undefined;\n const toolArguments = (arguments_.args as Record<string, unknown>) ?? {};\n\n if (!nodeId || !serverName || !toolName) {\n return {\n error: 'mcpClient requires nodeId, serverName, and toolName',\n };\n }\n\n if (!context.mcpCallRemote) {\n return {\n error: 'MCP proxy not configured (no mcpCallRemote in context). Connect to nodes that expose MCP.',\n };\n }\n\n try {\n const result = await context.mcpCallRemote(nodeId, serverName, toolName, toolArguments);\n return { result };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { error: `MCP call failed: ${message}` };\n }\n};\n\nexport function getMcpClientToolId(): string {\n return TOOL_ID;\n}\n","import type { BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'mcpForward';\n\nexport const mcpForwardConfigSchema = {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['list', 'listTools'],\n description: \"Action: 'list' returns nodes with MCP servers, 'listTools' returns all available MCP tools across nodes\",\n },\n },\n} as const;\n\ninterface McpServerInfo {\n name: string;\n}\n\ninterface McpToolInfo {\n nodeId: string;\n serverName: string;\n name: string;\n description?: string;\n}\n\n/**\n * MCP forwarding tool: discover MCP servers and tools on connected nodes.\n * - action=list: returns nodes with their MCP servers\n * - action=listTools: returns all available MCP tools across all nodes\n */\nexport const mcpForwardImpl: BuiltinToolImpl = async (arguments_, context) => {\n const action = (arguments_.action as string | undefined) ?? 'list';\n\n if (!context.getPeers) {\n return { error: 'Peer list not configured (no getPeers).' };\n }\n\n if (!context.sendRpcToNode) {\n return { error: 'Remote node RPC not configured (no sendRpcToNode).' };\n }\n\n const peers = await context.getPeers();\n const online = peers.filter((p) => p.reachability.state === 'online');\n\n if (action === 'list') {\n // List devices with their MCP servers\n const result: Array<{ nodeId: string; name: string; mcpServers: McpServerInfo[] }> = [];\n\n for (const node of online) {\n try {\n const response = (await context.sendRpcToNode(\n node.peerId,\n 'memeloop.mcp.listServers',\n {},\n )) as {\n servers?: McpServerInfo[];\n };\n const servers = Array.isArray(response?.servers) ? response.servers : [];\n if (servers.length > 0) {\n result.push({\n nodeId: node.peerId,\n name: node.displayName,\n mcpServers: servers,\n });\n }\n } catch {\n // Skip devices that don't support MCP or fail to respond\n }\n }\n\n return { nodes: result };\n }\n\n if (action === 'listTools') {\n // List all MCP tools across all devices\n const allTools: McpToolInfo[] = [];\n\n for (const node of online) {\n try {\n const response = (await context.sendRpcToNode(\n node.peerId,\n 'memeloop.mcp.listTools',\n {},\n )) as {\n tools?: Array<{ serverName: string; name: string; description?: string }>;\n };\n const tools = Array.isArray(response?.tools) ? response.tools : [];\n for (const tool of tools) {\n allTools.push({\n nodeId: node.peerId,\n serverName: tool.serverName,\n name: tool.name,\n description: tool.description,\n });\n }\n } catch {\n // Skip devices that don't support MCP or fail to respond\n }\n }\n\n return { tools: allTools };\n }\n\n return { error: `Unknown action: ${action}` };\n};\n\nexport function getMcpForwardToolId(): string {\n return TOOL_ID;\n}\n","import type {\n AgentOrchestrationClient,\n OrchestrationApplyOptions,\n OrchestrationConditionStatus,\n OrchestrationDeleteOptions,\n OrchestrationGetOptions,\n OrchestrationListOptions,\n OrchestrationManifestMetadata,\n OrchestrationPreconditions,\n OrchestrationResourceManifest,\n OrchestrationResourceQuery,\n OrchestrationResourceReference,\n} from '../../orchestration/index.js';\nimport { OrchestrationError, toOrchestrationErrorData, waitForCondition } from '../../orchestration/index.js';\nimport type { BuiltinToolImpl } from './types.js';\n\nexport const ORCHESTRATION_TOOL_ID = 'orchestration';\n\nexport const orchestrationConfigSchema = {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['capabilities', 'apply', 'get', 'list', 'wait', 'delete'],\n description: 'Declarative orchestration resource operation.',\n },\n resource: {\n type: 'object',\n description: 'Resource manifest for apply. status and actor fields are not accepted.',\n },\n reference: {\n type: 'object',\n description: 'Resource reference for get, wait, or delete.',\n },\n query: {\n type: 'object',\n description: 'Resource query for list.',\n },\n condition: {\n type: 'object',\n description: 'Condition to wait for. Required when action is wait.',\n },\n options: {\n type: 'object',\n description: 'Operation options. Only documented fields are forwarded.',\n },\n },\n required: ['action'],\n} as const;\n\nfunction objectValue(value: unknown, field: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw invalidError(`${field} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction invalidError(message: string): OrchestrationError {\n return new OrchestrationError({ code: 'INVALID', message, retryable: false });\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction optionalBoolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n if (value === undefined) return undefined;\n const record = objectValue(value, 'record');\n const entries = Object.entries(record);\n if (entries.some(([, entry]) => typeof entry !== 'string')) {\n throw invalidError('record values must be strings');\n }\n return Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction metadataValue(value: unknown): OrchestrationManifestMetadata {\n const metadata = objectValue(value, 'resource.metadata');\n return {\n name: optionalString(metadata.name),\n generateName: optionalString(metadata.generateName),\n namespace: optionalString(metadata.namespace),\n labels: stringRecord(metadata.labels),\n annotations: stringRecord(metadata.annotations),\n };\n}\n\nfunction resourceValue(value: unknown): OrchestrationResourceManifest {\n const resource = objectValue(value, 'resource');\n const apiVersion = optionalString(resource.apiVersion);\n const kind = optionalString(resource.kind);\n if (!apiVersion || !kind) throw invalidError('resource requires apiVersion and kind');\n return {\n apiVersion,\n kind,\n metadata: metadataValue(resource.metadata),\n spec: objectValue(resource.spec, 'resource.spec'),\n };\n}\n\nfunction referenceValue(value: unknown): OrchestrationResourceReference {\n const reference = objectValue(value, 'reference');\n const apiVersion = optionalString(reference.apiVersion);\n const kind = optionalString(reference.kind);\n const name = optionalString(reference.name);\n const uid = optionalString(reference.uid);\n if (!apiVersion || !kind || (!name && !uid)) {\n throw invalidError('reference requires apiVersion, kind, and name or uid');\n }\n return {\n apiVersion,\n kind,\n name,\n namespace: optionalString(reference.namespace),\n uid,\n };\n}\n\nfunction queryValue(value: unknown): OrchestrationResourceQuery {\n const query = objectValue(value, 'query');\n const kind = optionalString(query.kind);\n if (!kind) throw invalidError('query requires kind');\n return {\n apiVersion: optionalString(query.apiVersion),\n kind,\n namespace: optionalString(query.namespace),\n labels: stringRecord(query.labels),\n };\n}\n\nfunction preconditionsValue(value: unknown): OrchestrationPreconditions | undefined {\n if (value === undefined) return undefined;\n const preconditions = objectValue(value, 'options.preconditions');\n return {\n uid: optionalString(preconditions.uid),\n resourceVersion: optionalString(preconditions.resourceVersion),\n generation: typeof preconditions.generation === 'number' ? preconditions.generation : undefined,\n };\n}\n\nfunction applyOptions(value: unknown): OrchestrationApplyOptions | undefined {\n if (value === undefined) return undefined;\n const options = objectValue(value, 'options');\n return {\n idempotencyKey: optionalString(options.idempotencyKey),\n fieldManager: optionalString(options.fieldManager),\n force: optionalBoolean(options.force),\n dryRun: optionalBoolean(options.dryRun),\n preconditions: preconditionsValue(options.preconditions),\n };\n}\n\nfunction getOptions(value: unknown): OrchestrationGetOptions | undefined {\n if (value === undefined) return undefined;\n const options = objectValue(value, 'options');\n return { resourceVersion: optionalString(options.resourceVersion) };\n}\n\nfunction listOptions(value: unknown): OrchestrationListOptions | undefined {\n if (value === undefined) return undefined;\n const options = objectValue(value, 'options');\n return {\n resourceVersion: optionalString(options.resourceVersion),\n resourceVersionMatch: options.resourceVersionMatch === 'exact' || options.resourceVersionMatch === 'not-older-than'\n ? options.resourceVersionMatch\n : undefined,\n limit: typeof options.limit === 'number' ? options.limit : undefined,\n continueToken: optionalString(options.continueToken),\n };\n}\n\nfunction deleteOptions(value: unknown): OrchestrationDeleteOptions | undefined {\n if (value === undefined) return undefined;\n const options = objectValue(value, 'options');\n const propagationPolicy = options.propagationPolicy;\n const validPropagationPolicy = propagationPolicy === 'orphan' || propagationPolicy === 'background' || propagationPolicy === 'foreground'\n ? propagationPolicy\n : undefined;\n return {\n idempotencyKey: optionalString(options.idempotencyKey),\n preconditions: preconditionsValue(options.preconditions),\n propagationPolicy: validPropagationPolicy,\n dryRun: optionalBoolean(options.dryRun),\n };\n}\n\nfunction waitConditionValue(value: unknown): { type: string; status: OrchestrationConditionStatus } {\n const condition = objectValue(value, 'condition');\n const type = optionalString(condition.type);\n if (!type) throw invalidError('condition requires type');\n const status = condition.status === 'True' || condition.status === 'False' || condition.status === 'Unknown'\n ? condition.status\n : 'True';\n return { type, status };\n}\n\nfunction waitOptions(value: unknown): { timeout?: number; interval?: number } {\n if (value === undefined) return {};\n const options = objectValue(value, 'options');\n const timeout = typeof options.timeout === 'number' ? options.timeout : undefined;\n const interval = typeof options.interval === 'number' ? options.interval : undefined;\n if (timeout !== undefined && timeout <= 0) throw invalidError('timeout must be positive');\n if (interval !== undefined && interval <= 0) throw invalidError('interval must be positive');\n return { timeout, interval };\n}\n\nasync function waitForResourceCondition(\n context: Parameters<BuiltinToolImpl>[1],\n client: AgentOrchestrationClient,\n reference: OrchestrationResourceReference,\n condition: { type: string; status: OrchestrationConditionStatus },\n options: { timeout?: number; interval?: number },\n): Promise<{ observedResourceVersion: string; matched: true }> {\n return waitForCondition(\n () => client.get(reference, { resourceVersion: undefined }),\n condition,\n {\n ...options,\n isCancelled: () =>\n context.isCancelled?.() === true ||\n (context.activeToolConversationId !== undefined && context.conversationCancellation?.has(context.activeToolConversationId) === true),\n },\n );\n}\n\nexport const orchestrationImpl: BuiltinToolImpl = async (arguments_, context) => {\n const client = context.orchestration;\n if (!client) {\n return {\n error: {\n code: 'UNSUPPORTED',\n message: 'Orchestration manager not configured.',\n retryable: false,\n },\n };\n }\n\n try {\n switch (arguments_.action) {\n case 'capabilities':\n return await client.getCapabilities();\n case 'apply':\n return await client.apply(resourceValue(arguments_.resource), applyOptions(arguments_.options));\n case 'get':\n return await client.get(referenceValue(arguments_.reference), getOptions(arguments_.options));\n case 'list':\n return await client.list(queryValue(arguments_.query), listOptions(arguments_.options));\n case 'wait':\n return await waitForResourceCondition(\n context,\n client,\n referenceValue(arguments_.reference),\n waitConditionValue(arguments_.condition),\n waitOptions(arguments_.options),\n );\n case 'delete':\n return await client.delete(referenceValue(arguments_.reference), deleteOptions(arguments_.options));\n default:\n throw invalidError('orchestration requires a supported action');\n }\n } catch (error) {\n return { error: toOrchestrationErrorData(error) };\n }\n};\n","import { createAgentClient } from '../../orchestration/index.js';\nimport type { AgentOrchestrationClient } from '../../orchestration/index.js';\nimport { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'remoteAgent';\nconst REMOTE_LOG_POLL_INTERVAL_MS = 500;\nconst REMOTE_LOG_IDLE_POLLS = 2;\n\ntype RemoteConversationMessage = {\n messageId?: string;\n role?: string;\n content?: unknown;\n};\n\nfunction messageContentToText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (content == null) return '';\n try {\n return JSON.stringify(content);\n } catch {\n return Object.prototype.toString.call(content);\n }\n}\n\nfunction getRemoteStreamChunkContent(chunk: unknown): unknown {\n if (chunk != null && typeof chunk === 'object' && 'content' in chunk) {\n return Reflect.get(chunk, 'content');\n }\n\n return undefined;\n}\n\nfunction summarizeRemoteMessages(messages: RemoteConversationMessage[]): string {\n const relevant = messages.filter((message) => message.role && message.role !== 'user');\n if (relevant.length === 0) {\n return '(task dispatched; waiting for remote output)';\n }\n const joined = relevant\n .map((message) => {\n const role = typeof message.role === 'string' ? message.role : 'message';\n const content = messageContentToText(message.content).trim();\n return content.length > 0 ? `[${role}] ${content}` : '';\n })\n .filter((line) => line.length > 0)\n .join('\\n');\n return joined.trim() || '(task dispatched; remote messages had no readable content)';\n}\n\nasync function collectRemoteConversationSummary(\n sendRpc: NonNullable<BuiltinToolContext['sendRpcToNode']>,\n nodeId: string,\n conversationId: string,\n timeoutMs: number,\n): Promise<string> {\n const startedAt = Date.now();\n const knownMessageIds = new Set<string>();\n const collectedMessages: RemoteConversationMessage[] = [];\n let idlePolls = 0;\n\n while (Date.now() - startedAt < timeoutMs) {\n const response = (await sendRpc(nodeId, 'memeloop.chat.pullAgentRunLog', {\n conversationId,\n knownMessageIds: [...knownMessageIds],\n })) as { messages?: RemoteConversationMessage[] };\n const newMessages = Array.isArray(response?.messages) ? response.messages : [];\n\n if (newMessages.length > 0) {\n idlePolls = 0;\n for (const message of newMessages) {\n if (typeof message.messageId === 'string' && message.messageId.length > 0) {\n knownMessageIds.add(message.messageId);\n }\n collectedMessages.push(message);\n }\n } else if (collectedMessages.some((message) => message.role && message.role !== 'user')) {\n idlePolls += 1;\n if (idlePolls >= REMOTE_LOG_IDLE_POLLS) {\n break;\n }\n }\n\n await new Promise((resolve) => setTimeout(resolve, REMOTE_LOG_POLL_INTERVAL_MS));\n }\n\n return summarizeRemoteMessages(collectedMessages);\n}\n\nasync function supportsAgentWorkload(client: AgentOrchestrationClient): Promise<boolean> {\n try {\n const caps = await client.getCapabilities();\n return caps.operations.includes('apply') && caps.resourceKinds.includes('AgentWorkload');\n } catch {\n return false;\n }\n}\n\nasync function runRemoteAgentViaOrchestration(\n client: AgentOrchestrationClient,\n nodeId: string,\n definitionId: string,\n message: string,\n localNodeId: string | undefined,\n): Promise<Record<string, unknown>> {\n const timestamp = Date.now().toString(36);\n const conversationId = `remote:${nodeId}:${definitionId}:${timestamp}`;\n const agents = createAgentClient(client);\n const workload = await agents.createWorkload({\n name: conversationId,\n profileId: definitionId,\n promptReference: message,\n completionPolicy: 'complete',\n placement: { requiredNode: nodeId },\n });\n const run = await agents.createRun({\n name: `${conversationId}-run`,\n workloadName: workload.metadata.name,\n promptReference: message,\n });\n const result = await agents.waitForRunCondition(\n run.metadata.name,\n { type: 'Completed', status: 'True' },\n { timeout: 30_000, interval: 1000 },\n );\n const finalRun = await agents.getRun(run.metadata.name);\n const summary = finalRun?.status?.summary ?? '(no summary)';\n const shortSummary = truncateToolSummary(summary);\n const resolvedNodeId = localNodeId?.trim() || 'local';\n return {\n summary,\n remoteNodeId: nodeId,\n remoteConversationId: conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId: resolvedNodeId,\n resourceVersion: result.observedResourceVersion,\n },\n },\n };\n}\n\nexport const remoteAgentConfigSchema = {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Target node ID to run the agent-run on' },\n definitionId: { type: 'string', description: 'Agent definition ID on that node' },\n message: { type: 'string', description: 'Task message for the remote agent' },\n },\n required: ['nodeId', 'definitionId', 'message'],\n} as const;\n\n/** List policy-filtered execution targets and capabilities. No direct peer enumeration. */\nexport const remoteAgentListImpl: BuiltinToolImpl = async (_arguments, context) => {\n if (context.orchestration) {\n try {\n const caps = await context.orchestration.getCapabilities();\n const targets = caps.resourceKinds.map((kind) => ({\n kind,\n interfaces: caps.interfaces,\n operations: caps.operations,\n }));\n return {\n targets,\n capabilities: caps.interfaces,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n targets: [],\n error: `Orchestration target discovery failed: ${message}`,\n };\n }\n }\n\n return {\n targets: [],\n error: 'Direct peer enumeration is disabled. Configure an orchestration manager to discover execution targets.',\n };\n};\n\nexport const remoteAgentImpl: BuiltinToolImpl = async (arguments_, context) => {\n const nodeId = arguments_.nodeId as string | undefined;\n const definitionId = arguments_.definitionId as string | undefined;\n const message = arguments_.message as string | undefined;\n\n if (!nodeId || !definitionId || typeof message !== 'string') {\n return remoteAgentListImpl(arguments_, context);\n }\n\n try {\n if (context.orchestration && (await supportsAgentWorkload(context.orchestration))) {\n return await runRemoteAgentViaOrchestration(context.orchestration, nodeId, definitionId, message, context.localNodeId);\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : messageContentToText(error);\n return { error: `remoteAgent failed: ${errorMessage}` };\n }\n\n const sendRpc = context.sendRpcToNode\n ? async (nodeId: string, method: string, parameters: unknown) => context.sendRpcToNode?.(nodeId, method, parameters)\n : undefined;\n if (!sendRpc) {\n return {\n error: 'Remote node RPC not configured (no sendRpcToNode). Connect to peer nodes first.',\n };\n }\n\n try {\n const createResult = (await sendRpc(nodeId, 'memeloop.agent.create', {\n definitionId,\n })) as { conversationId?: string };\n const conversationId = createResult?.conversationId;\n if (!conversationId) {\n return { error: 'Remote agent.create did not return conversationId', raw: createResult };\n }\n\n await sendRpc(nodeId, 'memeloop.agent.send', {\n conversationId,\n message,\n });\n\n const subscribeStream = (\n context as BuiltinToolContext & {\n subscribeRemoteStream?: (\n nodeId: string,\n conversationId: string,\n onChunk: (chunk: unknown) => void,\n ) => () => void;\n }\n ).subscribeRemoteStream;\n const streamWaitMs = context.remoteAgentStreamTimeoutMs ?? 30_000;\n const chunks: string[] = [];\n if (subscribeStream) {\n await new Promise<void>((resolve) => {\n const unsub = subscribeStream(nodeId, conversationId, (chunk) => {\n if (typeof chunk === 'string') chunks.push(chunk);\n else {\n const chunkContent = getRemoteStreamChunkContent(chunk);\n if (chunkContent !== undefined) {\n chunks.push(messageContentToText(chunkContent));\n }\n }\n });\n setTimeout(() => {\n unsub();\n resolve();\n }, streamWaitMs);\n });\n }\n\n const fullSummary = chunks.length > 0\n ? chunks.join('').trim()\n : await collectRemoteConversationSummary(sendRpc, nodeId, conversationId, streamWaitMs);\n const shortSummary = truncateToolSummary(fullSummary);\n return {\n summary: fullSummary,\n remoteNodeId: nodeId,\n remoteConversationId: conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId,\n },\n },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : messageContentToText(error);\n return { error: `remoteAgent failed: ${message}` };\n }\n};\n\nexport function getRemoteAgentToolId(): string {\n return TOOL_ID;\n}\n","import { createAgentClient } from '../../orchestration/index.js';\nimport type { AgentOrchestrationClient } from '../../orchestration/index.js';\nimport { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'spawnAgent';\n\nasync function supportsAgentWorkload(client: AgentOrchestrationClient): Promise<boolean> {\n try {\n const caps = await client.getCapabilities();\n return caps.operations.includes('apply') && caps.resourceKinds.includes('AgentWorkload');\n } catch {\n return false;\n }\n}\n\nasync function runSpawnAgentViaOrchestration(\n client: AgentOrchestrationClient,\n definitionId: string,\n message: string,\n conversationId: string,\n localNodeId: string | undefined,\n): Promise<Record<string, unknown>> {\n const agents = createAgentClient(client);\n const workload = await agents.createWorkload({\n name: conversationId,\n profileId: definitionId,\n completionPolicy: 'complete',\n });\n const run = await agents.createRun({\n name: `${conversationId}-run`,\n workloadName: workload.metadata.name,\n promptReference: message,\n });\n const result = await agents.waitForRunCondition(\n run.metadata.name,\n { type: 'Completed', status: 'True' },\n { timeout: 30_000, interval: 1000 },\n );\n const finalRun = await agents.getRun(run.metadata.name);\n const summary = finalRun?.status?.summary ?? '(no summary)';\n const shortSummary = truncateToolSummary(summary);\n const nodeId = localNodeId?.trim() || 'local';\n return {\n summary,\n conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId,\n resourceVersion: result.observedResourceVersion,\n },\n },\n };\n}\n\nasync function runSpawnAgentLocally(\n runLocalAgent: NonNullable<BuiltinToolContext['runLocalAgent']>,\n definitionId: string,\n message: string,\n conversationId: string,\n localNodeId: string | undefined,\n): Promise<Record<string, unknown>> {\n const chunks: string[] = [];\n for await (const step of runLocalAgent({ conversationId, message })) {\n if (step.type === 'message' && typeof step.data === 'string') {\n chunks.push(step.data);\n }\n if (\n step.type === 'message' &&\n step.data != null &&\n typeof step.data === 'object' &&\n 'content' in step.data\n ) {\n const c = (step.data as { content?: string }).content;\n if (typeof c === 'string') chunks.push(c);\n }\n }\n const fullSummary = chunks.join('').trim() || '(no text output)';\n const shortSummary = truncateToolSummary(fullSummary);\n const nodeId = localNodeId?.trim() || 'local';\n return {\n summary: fullSummary,\n conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId,\n },\n },\n };\n}\n\nexport const spawnAgentConfigSchema = {\n type: 'object',\n properties: {\n definitionId: { type: 'string', description: 'Agent definition ID to use for the agent-run' },\n message: { type: 'string', description: 'User message / task for the agent-run' },\n },\n required: ['definitionId', 'message'],\n} as const;\n\nexport const spawnAgentImpl: BuiltinToolImpl = async (arguments_, context) => {\n const definitionId = arguments_.definitionId as string | undefined;\n const message = arguments_.message as string | undefined;\n\n if (!definitionId || typeof message !== 'string') {\n return { error: 'spawnAgent requires definitionId and message' };\n }\n\n const conversationId = `spawn:${definitionId}:${Date.now().toString(36)}`;\n\n try {\n if (context.orchestration && (await supportsAgentWorkload(context.orchestration))) {\n return await runSpawnAgentViaOrchestration(context.orchestration, definitionId, message, conversationId, context.localNodeId);\n }\n\n if (!context.runLocalAgent) {\n return {\n error: 'Local agent runner not configured (no runLocalAgent in context).',\n };\n }\n return await runSpawnAgentLocally(\n (input) => context.runLocalAgent!(input),\n definitionId,\n message,\n conversationId,\n context.localNodeId,\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return { error: `spawnAgent failed: ${errorMessage}`, conversationId };\n }\n};\n\nexport function getSpawnAgentToolId(): string {\n return TOOL_ID;\n}\n","import type { AgentDefinition as ProtocolAgentDefinition } from './types.js';\n\n/**\n * Extended agent definition used by the agent profile registry.\n * Wraps the protocol-level AgentDefinition with additional runtime metadata.\n */\nexport interface AgentProfile {\n /** Unique ID for this agent (matches protocol id convention like \"memeloop:build\") */\n id: string;\n /** Display name */\n name: string;\n /** Agent type / role */\n type: AgentProfileType;\n /** System prompt / instructions for the agent */\n prompt: string;\n /** Tool permission rules (mutually exclusive with permissive defaults) */\n permissions: ToolPermissionRules;\n /** Optional model override (provider/model string) */\n model?: string;\n /** Underlying protocol-compatible definition for framework integration */\n protocolDef: ProtocolAgentDefinition;\n}\n\nexport type AgentProfileType = 'build' | 'plan' | 'explore' | 'oracle' | 'librarian';\n\nexport interface ToolPermissionRules {\n /** Default action for tools not matching any rule */\n default: 'allow' | 'ask' | 'deny';\n /** Per-tool or wildcard rules */\n rules: Array<{ pattern: string; action: 'allow' | 'ask' | 'deny' }>;\n}\n\nfunction makeBuiltinDefinition(\n id: string,\n name: string,\n type: AgentProfileType,\n prompt: string,\n permissions: ToolPermissionRules,\n model?: string,\n): AgentProfile {\n const systemPrompt = prompt;\n const tools: string[] = []; // runtime tools; permissions govern access\n return {\n id,\n name,\n type,\n prompt,\n permissions,\n model,\n protocolDef: {\n id,\n name,\n description: prompt.slice(0, 200),\n systemPrompt,\n tools,\n version: '1.0.0',\n modelConfig: model\n ? {\n provider: model.split('/')[0] ?? 'memeloop',\n model: model.split('/').slice(1).join('/') || model,\n }\n : undefined,\n },\n };\n}\n\n/**\n * Build agent: full access, default model.\n * Primary agent for executing tasks, writing code, running commands.\n */\nexport const buildAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:build',\n 'Build Agent',\n 'build',\n \"You are a build agent capable of executing tasks, writing and editing files, running commands, and making changes. Use tools to accomplish the user's goals efficiently.\",\n { default: 'allow', rules: [] },\n);\n\n/**\n * Plan agent: read-only, denies file edits and terminal execution.\n * Used for high-level planning and task decomposition.\n */\nexport const planAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:plan',\n 'Plan Agent',\n 'plan',\n 'You are a planning agent. Your role is to analyze requirements, decompose tasks, and create structured plans. You CANNOT write files or execute terminal commands. Only use read and search tools.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Explore agent: read + search tools only.\n * Fast search and codebase exploration without modification.\n */\nexport const exploreAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:explore',\n 'Explore Agent',\n 'explore',\n 'You are an exploration agent specialized in fast codebase search and discovery. You have read and search tools. Do NOT modify files or run terminal commands. Focus on finding relevant code, files, and patterns.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n { pattern: 'lsp.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Oracle agent: read-only, for architecture consultation and code review.\n */\nexport const oracleAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:oracle',\n 'Oracle Agent',\n 'oracle',\n 'You are an oracle agent specialized in architecture analysis, code review, and constraint verification. You have read access only. Review code, identify issues, and provide expert architectural guidance.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n { pattern: 'lsp.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Librarian agent: read + web search tools only.\n * External documentation lookup and context gathering.\n */\nexport const librarianAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:librarian',\n 'Librarian Agent',\n 'librarian',\n 'You are a librarian agent specialized in external documentation lookup, web search, and context gathering. Use web search tools to find relevant documentation, APIs, and examples. Do NOT modify files or run terminal commands.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'web.*', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n ],\n },\n);\n\n/** Built-in agent profiles used by the task delegation tool. */\nexport const BUILTIN_AGENT_PROFILES: AgentProfile[] = [\n buildAgent,\n planAgent,\n exploreAgent,\n oracleAgent,\n librarianAgent,\n];\n","import type { AgentProfile, AgentProfileType } from './agentProfiles.js';\nimport { BUILTIN_AGENT_PROFILES } from './agentProfiles.js';\n\n/**\n * Registry for agent profiles used by task delegation.\n * Pre-seeded with built-in profiles (build, plan, explore, oracle, librarian).\n */\nexport class AgentProfileRegistry {\n private readonly profiles = new Map<string, AgentProfile>();\n\n constructor() {\n this.seedDefaults();\n }\n\n /** Seed the registry with built-in agent profiles. */\n private seedDefaults(): void {\n for (const profile of BUILTIN_AGENT_PROFILES) {\n this.profiles.set(profile.id, profile);\n }\n }\n\n /**\n * Register a new agent profile or override an existing one.\n * Throws if the profile is invalid.\n */\n registerAgentProfile(profile: AgentProfile): void {\n if (!profile.id || typeof profile.id !== 'string' || profile.id.trim().length === 0) {\n throw new Error('Agent profile must have a non-empty id');\n }\n if (!profile.name || typeof profile.name !== 'string') {\n throw new Error('Agent profile must have a name');\n }\n if (!profile.type || typeof profile.type !== 'string') {\n throw new Error('Agent profile must have a type');\n }\n if (!profile.prompt || typeof profile.prompt !== 'string') {\n throw new Error('Agent profile must have a prompt');\n }\n if (!profile.permissions || typeof profile.permissions.default !== 'string') {\n throw new Error('Agent profile must have valid permissions');\n }\n this.profiles.set(profile.id, profile);\n }\n\n /**\n * Get an agent profile by ID.\n * Returns undefined if not found.\n */\n getAgentProfile(id: string): AgentProfile | undefined {\n return this.profiles.get(id);\n }\n\n /**\n * List all registered agent profiles.\n */\n listAgentProfiles(): AgentProfile[] {\n return Array.from(this.profiles.values());\n }\n\n /**\n * List agent profiles filtered by type.\n */\n listAgentProfilesByType(type: AgentProfileType): AgentProfile[] {\n return this.listAgentProfiles().filter((profile) => profile.type === type);\n }\n\n /**\n * Remove an agent profile by ID.\n */\n unregisterAgentProfile(id: string): boolean {\n return this.profiles.delete(id);\n }\n\n /**\n * Reset the registry to only built-in defaults.\n */\n reset(): void {\n this.profiles.clear();\n this.seedDefaults();\n }\n}\n\n/** Shared singleton instance for convenience. */\nlet defaultRegistry: AgentProfileRegistry | null = null;\n\nexport function getAgentProfileRegistry(): AgentProfileRegistry {\n if (!defaultRegistry) {\n defaultRegistry = new AgentProfileRegistry();\n }\n return defaultRegistry;\n}\n\nexport function resetAgentProfileRegistry(): void {\n if (defaultRegistry) {\n defaultRegistry.reset();\n }\n defaultRegistry = null;\n}\n","import { getAgentProfileRegistry } from '../../agent/agentProfileRegistry.js';\nimport { createAgentClient } from '../../orchestration/index.js';\nimport type { AgentOrchestrationClient } from '../../orchestration/index.js';\nimport { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'task';\n\nasync function supportsAgentWorkload(client: AgentOrchestrationClient): Promise<boolean> {\n try {\n const caps = await client.getCapabilities();\n return caps.operations.includes('apply') && caps.resourceKinds.includes('AgentWorkload');\n } catch {\n return false;\n }\n}\n\nasync function runTaskViaOrchestration(\n client: AgentOrchestrationClient,\n agentId: string,\n prompt: string,\n background: boolean | undefined,\n localNodeId: string | undefined,\n conversationId: string,\n permissions: { default: 'allow' | 'ask' | 'deny'; rules: Array<{ pattern: string; action: 'allow' | 'ask' | 'deny' }> },\n): Promise<Record<string, unknown>> {\n const agents = createAgentClient(client);\n const workload = await agents.createWorkload({\n name: conversationId,\n profileId: agentId,\n promptReference: prompt,\n completionPolicy: background ? 'detach' : 'complete',\n toolPolicy: {\n defaultAction: permissions.default,\n rules: permissions.rules,\n },\n });\n const run = await agents.createRun({\n name: `${conversationId}-run`,\n workloadName: workload.metadata.name,\n promptReference: prompt,\n });\n\n const nodeId = localNodeId?.trim() || 'local';\n\n if (background) {\n return {\n summary: `Background task \"${agentId}\" launched. Task ID: ${conversationId}`,\n conversationId,\n agentId,\n taskId: conversationId,\n background: true,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: `[bg-task] ${agentId}: ${conversationId}`,\n detailRef: {\n type: 'agent-run' as const,\n conversationId,\n nodeId,\n resourceVersion: run.metadata.resourceVersion,\n },\n },\n };\n }\n\n const result = await agents.waitForRunCondition(\n run.metadata.name,\n { type: 'Completed', status: 'True' },\n { timeout: 30_000, interval: 1000 },\n );\n const finalRun = await agents.getRun(run.metadata.name);\n const text = finalRun?.status?.summary ?? '(no summary)';\n const shortSummary = truncateToolSummary(text);\n return {\n result: text,\n conversationId,\n agentId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run' as const,\n conversationId,\n nodeId,\n resourceVersion: result.observedResourceVersion,\n },\n },\n };\n}\n\nasync function runTaskLocally(\n runLocalAgent: NonNullable<BuiltinToolContext['runLocalAgent']>,\n context: BuiltinToolContext,\n agentId: string,\n prompt: string,\n background: boolean | undefined,\n conversationId: string,\n): Promise<Record<string, unknown>> {\n async function collectOutput(\n gen: AsyncIterable<{ type: string; data?: unknown }>,\n ): Promise<{ text: string; conversationId: string }> {\n const chunks: string[] = [];\n for await (const step of gen) {\n if (step.type === 'message') {\n if (typeof step.data === 'string') {\n chunks.push(step.data);\n } else if (step.data != null && typeof step.data === 'object' && 'content' in step.data) {\n const c = (step.data as { content?: string }).content;\n if (typeof c === 'string') chunks.push(c);\n }\n }\n }\n return { text: chunks.join('').trim() || '(no text output)', conversationId };\n }\n\n if (background) {\n const gen = runLocalAgent({ conversationId, message: prompt });\n void collectOutput(gen).catch(() => {\n /* background errors are non-fatal */\n });\n\n const nodeId = context.localNodeId?.trim() || 'local';\n return {\n summary: `Background task \"${agentId}\" launched. Task ID: ${conversationId}`,\n conversationId,\n agentId,\n taskId: conversationId,\n background: true,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: `[bg-task] ${agentId}: ${conversationId}`,\n detailRef: {\n type: 'agent-run' as const,\n conversationId,\n nodeId,\n },\n },\n };\n }\n\n const gen = runLocalAgent({ conversationId, message: prompt });\n const { text, conversationId: cid } = await collectOutput(gen);\n\n const shortSummary = truncateToolSummary(text);\n const nodeId = context.localNodeId?.trim() || 'local';\n return {\n result: text,\n conversationId: cid,\n agentId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run' as const,\n conversationId: cid,\n nodeId,\n },\n },\n };\n}\n\nexport const taskToolConfigSchema = {\n type: 'object',\n properties: {\n agent: {\n type: 'string',\n description: \"Agent ID to delegate to (e.g. 'memeloop:build', 'memeloop:explore')\",\n },\n prompt: {\n type: 'string',\n description: 'Task prompt / instructions for the delegated agent',\n },\n background: {\n type: 'boolean',\n description: 'If true, runs asynchronously and returns a task ID immediately',\n },\n },\n required: ['agent', 'prompt'],\n} as const;\n\n/**\n * Check if we're already nested too deep in agent-runs.\n * The conversationId format for agent-runs is `agentId:timestamp`.\n * We check the current conversation for nesting depth heuristics.\n */\nfunction isTooDeeplyNested(context: { activeToolConversationId?: string }): boolean {\n const cid = context.activeToolConversationId;\n if (!cid) return false;\n // Count how many colons indicate nesting depth\n const depth = cid.split(':').length - 1;\n // Allow up to 2 levels of nesting (agent:sub:timestamp = 2 colons)\n return depth > 2;\n}\n\n/**\n * Set up per-agent tool permissions on the framework context so that\n * the AgentToolLoop's resolveToolPermission picks up the agent's restrictions.\n */\nfunction applyAgentPermissions(\n context: { agentToolLoop?: { toolPermissions?: Record<string, unknown> } },\n agentId: string,\n defaultAction: 'allow' | 'ask' | 'deny',\n rules: Array<{ pattern: string; action: 'allow' | 'ask' | 'deny' }>,\n): void {\n const tp = context.agentToolLoop ?? (context.agentToolLoop = {});\n const tperm = (tp.toolPermissions ?? (tp.toolPermissions = {})) as {\n perAgent?: Record<\n string,\n { default?: string; rules?: Array<{ pattern: string; action: string }> }\n >;\n };\n const perAgent = tperm.perAgent ?? (tperm.perAgent = {});\n perAgent[agentId] = { default: defaultAction, rules };\n}\n\nexport const taskToolImpl: BuiltinToolImpl = async (arguments_, context) => {\n const agentId = arguments_.agent as string | undefined;\n const prompt = arguments_.prompt as string | undefined;\n const background = arguments_.background as boolean | undefined;\n\n if (!agentId || typeof prompt !== 'string' || prompt.trim().length === 0) {\n return { error: \"task requires 'agent' (string) and 'prompt' (non-empty string)\" };\n }\n\n if (isTooDeeplyNested(context)) {\n return {\n error: 'Maximum agent nesting depth exceeded. Cannot delegate further.',\n };\n }\n\n const registry = getAgentProfileRegistry();\n const agentProfile = registry.getAgentProfile(agentId);\n if (!agentProfile) {\n const available = registry\n .listAgentProfiles()\n .map((a) => a.id)\n .join(', ');\n return {\n error: `Agent \"${agentId}\" not found in registry. Available: [${available}]`,\n };\n }\n\n const permissions = {\n default: agentProfile.permissions.default,\n rules: agentProfile.permissions.rules,\n };\n\n const timestamp = Date.now().toString(36);\n const conversationId = `${agentProfile.id}:${timestamp}`;\n\n try {\n if (context.orchestration && (await supportsAgentWorkload(context.orchestration))) {\n return await runTaskViaOrchestration(\n context.orchestration,\n agentProfile.id,\n prompt,\n background,\n context.localNodeId,\n conversationId,\n permissions,\n );\n }\n\n if (!context.runLocalAgent) {\n return {\n error: 'Local agent runner not configured (no runLocalAgent in context).',\n };\n }\n\n applyAgentPermissions(\n context as { agentToolLoop?: { toolPermissions?: Record<string, unknown> } },\n agentProfile.id,\n permissions.default,\n permissions.rules,\n );\n\n return await runTaskLocally(\n (input) => context.runLocalAgent!(input),\n context,\n agentProfile.id,\n prompt,\n background,\n conversationId,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n error: `Task execution failed: ${message}`,\n conversationId,\n agentId: agentProfile.id,\n };\n }\n};\n\nexport function getTaskToolId(): string {\n return TOOL_ID;\n}\n","/**\n * TodoWrite Tool — Manage structured todo lists stored in conversation context.\n *\n * Supports operations: create, update, complete, list, remove.\n * Todo state is stored in-memory per conversation, keyed by conversationId.\n */\nimport { z } from 'zod';\n\nimport type { BuiltinToolContext } from './types.js';\n\nexport const todoWriteConfigSchema = z.object({\n action: z\n .enum(['create', 'update', 'complete', 'list', 'remove'])\n .describe('Action: create, update, complete, list, or remove'),\n id: z.string().min(1).optional().describe('Todo item ID (required for update/complete/remove)'),\n content: z.string().min(1).optional().describe('Todo item content (required for create/update)'),\n status: z\n .enum(['pending', 'in_progress', 'completed', 'cancelled'])\n .optional()\n .describe(\"Status (defaults to 'pending' for create)\"),\n priority: z\n .enum(['high', 'medium', 'low'])\n .optional()\n .default('medium')\n .describe('Priority level'),\n});\n\nexport const TODO_WRITE_TOOL_ID = 'todoWrite';\n\ninterface TodoItem {\n id: string;\n content: string;\n status: 'pending' | 'in_progress' | 'completed' | 'cancelled';\n priority: 'high' | 'medium' | 'low';\n createdAt: number;\n updatedAt: number;\n}\n\n/**\n * In-memory per-conversation todo store.\n * In production this could be backed by IAgentStorage for persistence.\n */\nconst conversationTodos = new Map<string, Map<string, TodoItem>>();\n\n/** Exported for test cleanup. */\nexport function __clearTodoStore(): void {\n conversationTodos.clear();\n}\n\nfunction getConversationTodos(\n conversationId: string,\n): Map<string, TodoItem> {\n let todos = conversationTodos.get(conversationId);\n if (!todos) {\n todos = new Map<string, TodoItem>();\n conversationTodos.set(conversationId, todos);\n }\n return todos;\n}\n\nfunction formatTodoList(todos: Map<string, TodoItem>): string {\n if (todos.size === 0) {\n return '(No todos)';\n }\n\n const statusOrder: Record<string, number> = {\n in_progress: 0,\n pending: 1,\n completed: 2,\n cancelled: 3,\n };\n\n const sorted = [...todos.values()].sort(\n (a, b) =>\n (statusOrder[a.status] ?? 99) - (statusOrder[b.status] ?? 99) ||\n b.updatedAt - a.updatedAt,\n );\n\n const statusIcons: Record<string, string> = {\n pending: '○',\n in_progress: '◉',\n completed: '✓',\n cancelled: '✗',\n };\n\n return sorted\n .map(\n (t) => `${statusIcons[t.status] ?? '?'} [${t.priority}] ${t.content} (id: ${t.id})`,\n )\n .join('\\n');\n}\n\nfunction getConversationId(context: BuiltinToolContext): string {\n return context.agent?.id ?? context.activeToolConversationId ?? 'default';\n}\n\nexport async function todoWriteImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = todoWriteConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: `invalid_todoWrite_args: ${parsed.error.message}` };\n }\n\n const { action, id, content, status, priority } = parsed.data;\n const conversationId = getConversationId(context);\n const todos = getConversationTodos(conversationId);\n const now = Date.now();\n\n switch (action) {\n case 'create': {\n if (!content) {\n return { error: 'content is required for create action' };\n }\n const newId = id ?? crypto.randomUUID();\n if (todos.has(newId)) {\n return { error: `Todo with id '${newId}' already exists. Use update action.` };\n }\n const item: TodoItem = {\n id: newId,\n content,\n status: status ?? 'pending',\n priority,\n createdAt: now,\n updatedAt: now,\n };\n todos.set(newId, item);\n return {\n result: `Todo created: [${item.priority}] ${item.content} (id: ${item.id})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'update': {\n if (!id) {\n return { error: 'id is required for update action' };\n }\n const existing = todos.get(id);\n if (!existing) {\n return { error: `Todo with id '${id}' not found` };\n }\n if (content !== undefined) existing.content = content;\n if (status !== undefined) existing.status = status;\n existing.priority = priority ?? existing.priority;\n existing.updatedAt = now;\n return {\n result: `Todo updated: [${existing.priority}] ${existing.content} (id: ${existing.id}, status: ${existing.status})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'complete': {\n if (!id) {\n return { error: 'id is required for complete action' };\n }\n const existing = todos.get(id);\n if (!existing) {\n return { error: `Todo with id '${id}' not found` };\n }\n existing.status = 'completed';\n existing.updatedAt = now;\n return {\n result: `Todo completed: [${existing.priority}] ${existing.content} (id: ${existing.id})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'remove': {\n if (!id) {\n // Remove all completed/cancelled todos\n let removed = 0;\n for (const [key, item] of todos) {\n if (item.status === 'completed' || item.status === 'cancelled') {\n todos.delete(key);\n removed++;\n }\n }\n return {\n result: `Removed ${removed} completed/cancelled todo(s)\\n\\n${formatTodoList(todos)}`,\n };\n }\n const removed = todos.delete(id);\n return {\n result: removed\n ? `Todo removed: ${id}\\n\\n${formatTodoList(todos)}`\n : `Todo with id '${id}' not found\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'list':\n default: {\n return {\n result: `Todo list (${todos.size} items):\\n\\n${formatTodoList(todos)}`,\n };\n }\n }\n}\n","/**\n * Builtin tool plugins — registers core tools as LoopPlugin entries.\n *\n * Each tool is a separate LoopPlugin that can be overridden by user/host plugins\n * with the same id. The plugin.install callback calls the tool registry to\n * register the tool implementation.\n *\n * These are registered in the loop registry at startup and loaded by\n * `registerBuiltinTools` via plugin discovery.\n */\n\nimport type { ToolOperationEffect } from '../../orchestration/resources.js';\nimport { registerToolParameterSchema } from '../../tools/schemaRegistry.js';\nimport type { IToolRegistry } from '../../types.js';\nimport { getLoopRegistry } from '../registry.js';\nimport type { LoopPlugin } from '../types.js';\n\n// ─── Import tool implementations ─────────────────────────────────────\n\nimport { ASK_QUESTION_TOOL_ID, askQuestionConfigSchema, askQuestionImpl } from '../../tools/builtins/askQuestion.js';\nimport { ASK_USER_QUESTION_TOOL_ID, askUserQuestionConfigSchema, askUserQuestionImpl } from '../../tools/builtins/askUserQuestion.js';\nimport { getMcpClientToolId, mcpClientConfigSchema, mcpClientImpl } from '../../tools/builtins/mcpClient.js';\nimport { getMcpForwardToolId, mcpForwardConfigSchema, mcpForwardImpl } from '../../tools/builtins/mcpForward.js';\nimport { ORCHESTRATION_TOOL_ID, orchestrationConfigSchema, orchestrationImpl } from '../../tools/builtins/orchestration.js';\nimport { getRemoteAgentToolId, remoteAgentConfigSchema, remoteAgentImpl } from '../../tools/builtins/remoteAgent.js';\nimport { getSpawnAgentToolId, spawnAgentConfigSchema, spawnAgentImpl } from '../../tools/builtins/spawnAgent.js';\nimport { getTaskToolId, taskToolConfigSchema, taskToolImpl } from '../../tools/builtins/task.js';\nimport { TODO_WRITE_TOOL_ID, todoWriteConfigSchema, todoWriteImpl } from '../../tools/builtins/todoWrite.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from '../../tools/builtins/types.js';\n\n// ─── Plugin id constants ───────────────────────────────────────────\n\nexport const PLUGIN_MCP_CLIENT = 'builtin:mcp-client';\nexport const PLUGIN_MCP_FORWARD = 'builtin:mcp-forward';\nexport const PLUGIN_ORCHESTRATION = 'builtin:orchestration';\nexport const PLUGIN_SPAWN_AGENT = 'builtin:spawn-agent';\nexport const PLUGIN_REMOTE_AGENT = 'builtin:remote-agent';\nexport const PLUGIN_ASK_QUESTION = 'builtin:ask-question';\nexport const PLUGIN_TODO_WRITE = 'builtin:todo-write';\nexport const PLUGIN_ASK_USER_QUESTION = 'builtin:ask-user-question';\nexport const PLUGIN_TASK = 'builtin:task';\n\nexport const BUILTIN_TOOL_PLUGIN_IDS = [\n PLUGIN_MCP_CLIENT,\n PLUGIN_MCP_FORWARD,\n PLUGIN_ORCHESTRATION,\n PLUGIN_SPAWN_AGENT,\n PLUGIN_REMOTE_AGENT,\n PLUGIN_ASK_QUESTION,\n PLUGIN_TODO_WRITE,\n PLUGIN_ASK_USER_QUESTION,\n PLUGIN_TASK,\n] as const;\n\ninterface BuiltinToolPluginOptions {\n id: string;\n toolId: string;\n schema: unknown;\n metadata: { displayName: string; description: string };\n implementation: BuiltinToolImpl;\n effect?: ToolOperationEffect;\n}\n\nfunction getToolRegistry(context: { [key: string]: unknown }): IToolRegistry | undefined {\n return context.toolRegistry as IToolRegistry | undefined;\n}\n\nfunction createBuiltinToolPlugin(options: BuiltinToolPluginOptions): LoopPlugin {\n return {\n id: options.id,\n targetLoopId: '*',\n install: (context) => {\n const registry = getToolRegistry(context);\n if (!registry) return;\n\n const builtinContext = context as unknown as BuiltinToolContext;\n const implementation = (arguments_: Record<string, unknown>) => options.implementation(arguments_, builtinContext);\n if (options.effect === undefined) {\n registry.registerTool(options.toolId, implementation, options.schema);\n } else {\n registry.registerTool(\n options.toolId,\n implementation,\n options.schema,\n options.effect,\n );\n }\n registerToolParameterSchema(options.toolId, options.schema, options.metadata);\n },\n };\n}\n\nconst builtinToolPlugins: LoopPlugin[] = [\n createBuiltinToolPlugin({\n id: PLUGIN_MCP_CLIENT,\n toolId: getMcpClientToolId(),\n schema: mcpClientConfigSchema,\n metadata: {\n displayName: 'MCP Client',\n description: 'Call a tool on a remote MCP server (transparent proxy). Requires nodeId, serverName, toolName, and optional args.',\n },\n implementation: mcpClientImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_MCP_FORWARD,\n toolId: getMcpForwardToolId(),\n schema: mcpForwardConfigSchema,\n metadata: {\n displayName: 'MCP Forward',\n description: \"Discover MCP servers and tools on connected nodes. Use action='list' for nodes with servers, action='listTools' for all available tools.\",\n },\n implementation: mcpForwardImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_ORCHESTRATION,\n toolId: ORCHESTRATION_TOOL_ID,\n schema: orchestrationConfigSchema,\n metadata: {\n displayName: 'Orchestration',\n description: 'Discover and manage declarative resources through the policy-scoped orchestration manager.',\n },\n implementation: orchestrationImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_SPAWN_AGENT,\n toolId: getSpawnAgentToolId(),\n schema: spawnAgentConfigSchema,\n metadata: {\n displayName: 'Spawn Agent',\n description: 'Run a local agent-agent-loop with the given definition and message. Returns summary.',\n },\n implementation: spawnAgentImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_REMOTE_AGENT,\n toolId: getRemoteAgentToolId(),\n schema: remoteAgentConfigSchema,\n metadata: {\n displayName: 'Remote Agent',\n description: 'Create and run a agent-agent-loop on a remote node. Requires nodeId, definitionId, message. List nodes with no args.',\n },\n implementation: remoteAgentImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_ASK_QUESTION,\n toolId: ASK_QUESTION_TOOL_ID,\n schema: askQuestionConfigSchema,\n metadata: {\n displayName: 'Ask Question',\n description: 'Block until the user answers (via memeloop.agent.resolveQuestion RPC). Args: question, conversationId, optional timeoutMs.',\n },\n implementation: askQuestionImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_TODO_WRITE,\n toolId: TODO_WRITE_TOOL_ID,\n effect: 'update',\n schema: todoWriteConfigSchema,\n metadata: {\n displayName: 'Todo Write',\n description: 'Manage structured todo lists: create, update, complete, list, remove. Todos scoped per conversation.',\n },\n implementation: todoWriteImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_ASK_USER_QUESTION,\n toolId: ASK_USER_QUESTION_TOOL_ID,\n schema: askUserQuestionConfigSchema,\n metadata: {\n displayName: 'Ask User Question',\n description: 'Pause agent and ask user a question. Supports text, single-select, and multi-select input types. Blocks until answered.',\n },\n implementation: askUserQuestionImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_TASK,\n toolId: getTaskToolId(),\n schema: taskToolConfigSchema,\n metadata: {\n displayName: 'Task Delegation',\n description: 'Delegate a task to a specialized agent-agent-loop (build, plan, explore, oracle, librarian). Supports sync (default) and background modes.',\n },\n implementation: taskToolImpl,\n }),\n];\n\nexport function getBuiltinToolPlugins(): LoopPlugin[] {\n return builtinToolPlugins;\n}\n\n/** Register all builtin tool plugins with the loop registry. */\nexport function registerBuiltinToolPlugins(): void {\n const loopRegistry = getLoopRegistry();\n\n for (const plugin of builtinToolPlugins) {\n if (loopRegistry.getPlugin(plugin.id)) continue;\n loopRegistry.registerPlugin(plugin);\n }\n}\n","import { getActivePluginRegistry } from '../tools/pluginRegistry.js';\nimport type { PromptConcatHooks, PromptConcatTool } from '../tools/types.js';\n\nimport type { PromptNode } from './types.js';\n\nexport const FULL_REPLACEMENT_PLUGIN_TOOL_ID = 'fullReplacement';\nexport const DYNAMIC_POSITION_PLUGIN_TOOL_ID = 'dynamicPosition';\n\nfunction registerFullReplacement(reg: Map<string, PromptConcatTool>): void {\n if (reg.has(FULL_REPLACEMENT_PLUGIN_TOOL_ID)) return;\n reg.set(FULL_REPLACEMENT_PLUGIN_TOOL_ID, (hooks: PromptConcatHooks) => {\n hooks.processPrompts.tapAsync(\n 'fullReplacementLite',\n (context: { messages: unknown[]; maxReplacementChars?: number }, callback) => {\n const msgs = context.messages;\n if (!Array.isArray(msgs)) {\n callback();\n return;\n }\n const maxChars = context?.maxReplacementChars ?? 48_000;\n if (!Number.isFinite(maxChars) || maxChars <= 0) {\n callback();\n return;\n }\n let total = 0;\n const kept: unknown[] = [];\n for (let index = msgs.length - 1; index >= 0; index--) {\n const m = msgs[index] as { content?: unknown };\n const c = typeof m?.content === 'string'\n ? m.content\n : m?.content != null\n ? JSON.stringify(m.content)\n : '';\n total += c.length;\n if (total > maxChars) break;\n kept.push(m);\n }\n kept.reverse();\n context.messages = kept;\n callback();\n },\n );\n });\n}\n\n/**\n * TidGi `dynamicPosition` 极简版:根级 `prompt` 若带 `dynamicPosition: \"deferToEnd\"`,\n * 在用户轮次 ≥2 时将该节点移到同级列表末尾(多轮后再强调尾部 system/user 块)。\n */\nfunction registerDynamicPosition(reg: Map<string, PromptConcatTool>): void {\n if (reg.has(DYNAMIC_POSITION_PLUGIN_TOOL_ID)) return;\n reg.set(DYNAMIC_POSITION_PLUGIN_TOOL_ID, (hooks: PromptConcatHooks) => {\n hooks.processPrompts.tapAsync(\n 'dynamicPositionLite',\n (context: { messages: unknown[]; prompts?: PromptNode[] }, callback) => {\n const prompts = context.prompts;\n const messages = context.messages;\n if (!Array.isArray(prompts) || prompts.length < 2 || !Array.isArray(messages)) {\n callback();\n return;\n }\n const userTurns = messages.filter((m) => (m as { role?: string })?.role === 'user').length;\n if (userTurns < 2) {\n callback();\n return;\n }\n const deferred: PromptNode[] = [];\n const rest: PromptNode[] = [];\n for (const n of prompts) {\n if (n?.dynamicPosition === 'deferToEnd') deferred.push(n);\n else rest.push(n);\n }\n if (deferred.length === 0) {\n callback();\n return;\n }\n context.prompts = [...rest, ...deferred] as typeof context.prompts;\n callback();\n },\n );\n });\n}\n\n/**\n * 注册内置 prompt 插件(fullReplacement、dynamicPosition)。\n * @param target 若传入(如节点 `ToolRegistry` 上的 Map),只写入该表;否则写入活动注册表(全局或 ALS)。\n */\nexport function registerBuiltinPromptPlugins(target?: Map<string, PromptConcatTool>): void {\n const reg = target ?? getActivePluginRegistry();\n registerFullReplacement(reg);\n registerDynamicPosition(reg);\n}\n","import type { ChatMessage } from './conversation/index.js';\nimport type { ConversationMeta } from './sync/protocol.js';\n\nimport { registerBuiltinLoops } from './loopAPI/plugins/builtinLoopsPlugin.js';\nimport { registerBuiltinToolPlugins } from './loopAPI/plugins/builtinToolsPlugin.js';\nimport { getLoopRegistry } from './loopAPI/registry.js';\nimport type { AgentLoopGenerator, AgentLoopInput, AgentLoopRuntime, LoopProfile } from './loopAPI/types.js';\nimport { getBuiltinLoopProfile } from './loopProfiles/loadBuiltins.js';\nimport { registerBuiltinPromptPlugins } from './promptUtilities/builtinPromptPlugins.js';\nimport { nextLamportClockForConversation } from './storage/nextLamport.js';\nimport type { AgentFrameworkContext } from './types.js';\n\nexport interface CreateAgentOptions {\n definitionId: string;\n initialMessage?: string;\n}\n\nexport interface SendMessageOptions {\n conversationId: string;\n message: string;\n definitionId?: string;\n userMessage?: AgentLoopInput['userMessage'];\n resumeSession?: ChatMessage[];\n}\n\nexport interface MemeLoopRuntime {\n createAgent(options: CreateAgentOptions): Promise<{ conversationId: string }>;\n sendMessage(options: SendMessageOptions): Promise<void>;\n cancelAgent(conversationId: string): Promise<void>;\n subscribeToUpdates(conversationId: string, listener: (update: unknown) => void): () => void;\n}\n\nexport interface CreateAgentLoopRunnerOptions {\n definitionId: string;\n conversationId?: string;\n}\n\nasync function drainAgentLoop(\n gen: AgentLoopGenerator,\n conversationId: string,\n notify: (conversationId: string, update: unknown) => void,\n): Promise<void> {\n try {\n for await (const step of gen) {\n notify(conversationId, { type: 'agent-step', step });\n }\n notify(conversationId, { type: 'agent-done' });\n } catch (error) {\n notify(conversationId, {\n type: 'agent-error',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nfunction inferDefinitionIdFromConversationId(conversationId: string): string {\n const parts = conversationId.split(':');\n if (parts.length >= 2) return parts.slice(0, -1).join(':');\n return conversationId;\n}\n\nasync function resolveDefinitionId(\n context: AgentFrameworkContext,\n conversationId: string,\n): Promise<string> {\n try {\n const meta = await context.storage.getConversationMeta(conversationId);\n if (meta?.definitionId) return meta.definitionId;\n } catch {\n /* optional for old storage adapters */\n }\n return inferDefinitionIdFromConversationId(conversationId);\n}\n\nasync function resolveLoopProfile(\n context: AgentFrameworkContext,\n definitionId: string,\n): Promise<LoopProfile | null> {\n const definition = (context.resolveAgentDefinition ? await context.resolveAgentDefinition(definitionId) : null) ??\n (await context.storage.getAgentDefinition(definitionId)) ??\n getBuiltinLoopProfile(definitionId) ??\n null;\n if (!definition) return null;\n return definition as unknown as LoopProfile;\n}\n\nasync function createProfileRunner(\n context: AgentFrameworkContext,\n definitionId: string,\n runtime?: Partial<AgentLoopRuntime>,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n const profile = await resolveLoopProfile(context, definitionId);\n if (!profile) return null;\n return createAgentProfileRunner(context, profile, runtime);\n}\n\n/**\n * Create a loop runner for an already-resolved profile. Registers builtin\n * loops/tools/prompts and threads the host script policy through, exactly\n * like the definition-based path.\n */\nexport async function createAgentProfileRunner(\n context: AgentFrameworkContext,\n profile: LoopProfile,\n runtime?: Partial<AgentLoopRuntime>,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n registerBuiltinLoops();\n registerBuiltinToolPlugins();\n registerBuiltinPromptPlugins(context.tools.getPromptPlugins?.());\n\n const runnerContext = {\n ...context,\n runtime,\n scriptPolicy: context.loopScriptPolicy,\n toolRegistry: context.tools,\n } as { [key: string]: unknown };\n return getLoopRegistry().createRunnerForProfile(profile, runnerContext);\n}\n\n/**\n * Create a loop runner for a profile with a fresh per-conversation script\n * runtime (state, checkpoints, cancellation, child propagation). Used by the\n * workload execution path (plan 24.14) where the profile is synthesized from\n * a resource rather than resolved from the definition store.\n */\nexport async function createAgentLoopScriptRunner(\n context: AgentFrameworkContext,\n profile: LoopProfile,\n conversationId: string,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n const cancellation = context.conversationCancellation ?? new Set<string>();\n context.conversationCancellation ??= cancellation;\n const scriptState = new Map<string, unknown>();\n return createAgentProfileRunner(\n context,\n profile,\n createScriptRuntime(context, cancellation, scriptState, conversationId),\n );\n}\n\nfunction createScriptRuntime(\n context: AgentFrameworkContext,\n cancellation: Set<string>,\n scriptState: Map<string, unknown>,\n conversationId: string,\n parentConversationId?: string,\n): Partial<AgentLoopRuntime> {\n const stateKey = (key: string): string => `${conversationId}:${key}`;\n return {\n orchestration: context.orchestration,\n scriptDeployment: context.scriptDeployment,\n runChildAgent: async function*(input) {\n const childRuntime = createScriptRuntime(\n context,\n cancellation,\n scriptState,\n input.conversationId,\n conversationId,\n );\n const run = await createProfileRunner(context, input.profileId, childRuntime);\n if (!run) {\n yield {\n type: 'message',\n data: `Child agent profile not found: ${input.profileId}`,\n };\n return;\n }\n yield* run({ conversationId: input.conversationId, message: input.prompt });\n },\n log: (event, data) => context.logger?.debug?.(event, data),\n emit: () => undefined,\n signal: {\n get cancelled() {\n return cancellation.has(conversationId) || (parentConversationId ? cancellation.has(parentConversationId) : false);\n },\n },\n state: {\n get: async <T>(key: string) => {\n const local = scriptState.get(stateKey(key)) as T | undefined;\n if (local !== undefined) return local;\n const persisted = await context.loopCheckpoints?.loadCheckpoint<T>(conversationId, `state:${key}`);\n if (persisted !== undefined) scriptState.set(stateKey(key), persisted);\n return persisted;\n },\n set: async (key, value) => {\n scriptState.set(stateKey(key), value);\n await context.loopCheckpoints?.saveCheckpoint(conversationId, `state:${key}`, value);\n },\n update: async (key, updater) => {\n const fullKey = stateKey(key);\n const previous = scriptState.get(fullKey);\n const next = updater(previous);\n scriptState.set(fullKey, next);\n await context.loopCheckpoints?.saveCheckpoint(conversationId, `state:${key}`, next);\n },\n },\n checkpoint: async (key, result) => {\n scriptState.set(stateKey(`checkpoint:${key}`), result);\n await context.loopCheckpoints?.saveCheckpoint(conversationId, key, result);\n },\n loadCheckpoint: async <T>(key: string) => {\n const memoryKey = stateKey(`checkpoint:${key}`);\n if (scriptState.has(memoryKey)) return scriptState.get(memoryKey) as T;\n const result = await context.loopCheckpoints?.loadCheckpoint<T>(conversationId, key);\n if (result !== undefined) scriptState.set(memoryKey, result);\n return result;\n },\n };\n}\n\nexport async function createAgentLoopRunner(\n context: AgentFrameworkContext,\n options: CreateAgentLoopRunnerOptions,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n const cancellation = context.conversationCancellation ?? new Set<string>();\n context.conversationCancellation ??= cancellation;\n const scriptState = new Map<string, unknown>();\n const conversationId = options.conversationId ?? options.definitionId;\n return createProfileRunner(\n context,\n options.definitionId,\n createScriptRuntime(context, cancellation, scriptState, conversationId),\n );\n}\n\nexport function createMemeLoopRuntime(context: AgentFrameworkContext): MemeLoopRuntime {\n const listeners = new Map<string, Set<(update: unknown) => void>>();\n const cancellation = context.conversationCancellation ?? new Set<string>();\n const scriptState = new Map<string, unknown>();\n context.conversationCancellation ??= cancellation;\n\n function notify(conversationId: string, update: unknown) {\n const set = listeners.get(conversationId);\n if (!set) return;\n for (const listener of set) {\n listener(update);\n }\n }\n\n async function runAgentLoop(input: AgentLoopInput, definitionId: string): Promise<boolean> {\n const run = context.runAgentToolLoop ?? await createProfileRunner(\n context,\n definitionId,\n createScriptRuntime(context, cancellation, scriptState, input.conversationId),\n );\n if (!run) return false;\n void drainAgentLoop(run(input), input.conversationId, notify);\n return true;\n }\n\n async function* runChildAgent(input: Parameters<NonNullable<AgentFrameworkContext['runChildAgent']>>[0]): AgentLoopGenerator {\n const run = await createProfileRunner(\n context,\n input.profileId,\n createScriptRuntime(context, cancellation, scriptState, input.conversationId),\n );\n if (!run) {\n yield {\n type: 'message',\n data: `Child agent profile not found: ${input.profileId}`,\n };\n return;\n }\n yield* run({ conversationId: input.conversationId, message: input.prompt });\n }\n\n context.runChildAgent ??= runChildAgent;\n\n return {\n async createAgent(options) {\n const now = Date.now();\n const conversationId = `${options.definitionId}:${now.toString(36)}`;\n cancellation?.delete(conversationId);\n\n const meta: ConversationMeta = {\n conversationId,\n title: options.definitionId,\n lastMessagePreview: context.runAgentToolLoop ? '' : options.initialMessage ?? '',\n lastMessageTimestamp: now,\n messageCount: context.runAgentToolLoop || !options.initialMessage ? 0 : 1,\n originNodeId: 'local',\n definitionId: options.definitionId,\n isUserInitiated: true,\n };\n await context.storage.upsertConversationMetadata(meta);\n\n if (options.initialMessage) {\n const started = await runAgentLoop(\n { conversationId, message: options.initialMessage },\n options.definitionId,\n );\n if (started) {\n notify(conversationId, { type: 'created', conversationId });\n return { conversationId };\n }\n }\n\n if (options.initialMessage) {\n const message: ChatMessage = {\n messageId: `${conversationId}:m1`,\n conversationId,\n originNodeId: meta.originNodeId,\n timestamp: now,\n lamportClock: 1,\n role: 'user',\n content: options.initialMessage,\n };\n await context.storage.appendMessage(message);\n }\n\n notify(conversationId, { type: 'created', conversationId });\n return { conversationId };\n },\n async sendMessage(options) {\n cancellation?.delete(options.conversationId);\n const definitionId = options.definitionId ?? await resolveDefinitionId(context, options.conversationId);\n const started = await runAgentLoop(\n {\n conversationId: options.conversationId,\n message: options.message,\n userMessage: options.userMessage,\n resumeSession: options.resumeSession,\n },\n definitionId,\n );\n if (started) {\n notify(options.conversationId, { type: 'message-queued' });\n return;\n }\n\n if (options.resumeSession && options.resumeSession.length > 0) {\n await context.storage.insertMessagesIfAbsent(options.resumeSession);\n }\n\n const now = Date.now();\n const lamportClock = await nextLamportClockForConversation(\n context.storage,\n options.conversationId,\n );\n const hostUserMessage = options.userMessage;\n const message: ChatMessage = {\n ...hostUserMessage,\n messageId: hostUserMessage?.messageId ?? `${options.conversationId}:${now.toString(36)}`,\n conversationId: options.conversationId,\n originNodeId: hostUserMessage?.originNodeId ?? 'local',\n timestamp: hostUserMessage?.timestamp ?? now,\n lamportClock: hostUserMessage?.lamportClock ?? lamportClock,\n role: 'user',\n content: hostUserMessage?.content ?? options.message,\n };\n await context.storage.appendMessage(message);\n notify(options.conversationId, { type: 'message-queued' });\n },\n async cancelAgent(conversationId) {\n cancellation?.add(conversationId);\n notify(conversationId, { type: 'cancelled' });\n },\n subscribeToUpdates(conversationId, listener) {\n const set = listeners.get(conversationId) ?? new Set();\n set.add(listener);\n listeners.set(conversationId, set);\n return () => {\n const current = listeners.get(conversationId);\n if (!current) return;\n current.delete(listener);\n if (current.size === 0) {\n listeners.delete(conversationId);\n }\n };\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8EA,SAAS,YAAY,MAA0B,cAAkC,OAAuB;AACtG,MAAI,KAAM,QAAO;AACjB,MAAI,aAAc,QAAO,GAAG,YAAY,GAAG,KAAK,OAAO,EAAE,SAAS,EAAE,EAAE,MAAM,GAAG,CAAC,CAAC;AACjF,QAAM,IAAI,mBAAmB,EAAE,MAAM,WAAW,SAAS,GAAG,KAAK,kCAAkC,WAAW,MAAM,CAAC;AACvH;AAEA,IAAM,gCAAgC;AAEtC,SAAS,kBAAkB,qBAAiD;AAC1E,SAAO,IAAI,mBAAmB;AAAA,IAC5B,MAAM;AAAA,IACN,SAAS;AAAA,IACT,WAAW;AAAA,IACX,SAAS,EAAE,oBAAoB;AAAA,EACjC,CAAC;AACH;AAEA,SAAS,iBAAiB,SAAkC,qBAAmC;AAC7F,MAAI,QAAQ,QAAQ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EAC5E,CAAC,+CAA+C,GAAG;AAAA,IACjD;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AAAA,EACX,CAAC,yCAAyC,GAAG;AAAA,IAC3C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AAAA,EACX,CAAC,iCAAiC,GAAG;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AA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AAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["name","spec","waitOptions","builtinDigestsRegistered","ensureBuiltinDigestsRegistered","isAsyncIterable","messageStep","drainEmittedSteps","z","z","TOOL_ID","TOOL_ID","nodeId","message","TOOL_ID","supportsAgentWorkload","TOOL_ID","supportsAgentWorkload","gen","nodeId","z","removed"]}
|
|
1
|
+
{"version":3,"sources":["../src/orchestration/agentClient.ts","../src/tools/schemaRegistry.ts","../src/orchestration/scripts/scriptRuntime.ts","../src/orchestration/scripts/scriptAdmission.ts","../src/orchestration/scripts/scriptValidation.ts","../src/orchestration/scripts/scriptDeploymentPipeline.ts","../src/loops/agent-agent-loop/builtinLoopSources.ts","../src/loopAPI/scriptLoader.ts","../src/loopAPI/agent-agent-loop/scriptLoader.ts","../src/loopAPI/agent-agent-loop/loop.ts","../src/loops/agent-tool-loop/builtinLoopSources.ts","../src/loopAPI/agent-tool-loop/scriptLoader.ts","../src/loopAPI/agent-tool-loop/scriptRunner.ts","../src/loopAPI/agent-tool-loop/loop.ts","../src/loopAPI/plugins/builtinLoopsPlugin.ts","../src/tools/builtins/askQuestion.ts","../src/tools/builtins/questionWaitRegistry.ts","../src/tools/builtins/askUserQuestion.ts","../src/tools/builtins/mcpClient.ts","../src/tools/builtins/mcpForward.ts","../src/tools/builtins/orchestration.ts","../src/tools/builtins/remoteAgent.ts","../src/tools/builtins/spawnAgent.ts","../src/agent/agentProfiles.ts","../src/agent/agentProfileRegistry.ts","../src/tools/builtins/task.ts","../src/tools/builtins/todoWrite.ts","../src/loopAPI/plugins/builtinToolsPlugin.ts","../src/promptUtilities/builtinPromptPlugins.ts","../src/runtime.ts"],"sourcesContent":["import type { AgentOrchestrationClient } from './client.js';\nimport type { OrchestrationOwnerReference } from './client.js';\nimport { OrchestrationError } from './errors.js';\nimport type {\n AgentRunCondition,\n AgentRunManifest,\n AgentRunResource,\n AgentTrustLevel,\n AgentWorkloadCompletionPolicy,\n AgentWorkloadCondition,\n AgentWorkloadManifest,\n AgentWorkloadModelPolicy,\n AgentWorkloadNetworkPolicy,\n AgentWorkloadPlacement,\n AgentWorkloadResource,\n AgentWorkloadStoragePolicy,\n AgentWorkloadToolPolicy,\n} from './resources.js';\nimport { agentRunReference, agentWorkloadReference, createAgentRunManifest, createAgentWorkloadManifest, isAgentRun, isAgentWorkload } from './resources.js';\n\nexport interface CreateAgentWorkloadOptions {\n name?: string;\n generateName?: string;\n namespace?: string;\n profileId?: string;\n scriptReference?: string;\n promptReference?: string;\n trust?: AgentTrustLevel;\n placement?: AgentWorkloadPlacement;\n modelPolicy?: AgentWorkloadModelPolicy;\n toolPolicy?: AgentWorkloadToolPolicy;\n networkPolicy?: AgentWorkloadNetworkPolicy;\n storagePolicy?: AgentWorkloadStoragePolicy;\n completionPolicy?: AgentWorkloadCompletionPolicy;\n ownerReferences?: OrchestrationOwnerReference[];\n idempotencyKey?: string;\n}\n\nexport interface CreateAgentRunOptions {\n name?: string;\n generateName?: string;\n namespace?: string;\n workloadName: string;\n workloadNamespace?: string;\n promptReference?: string;\n retry?: number;\n timeoutMs?: number;\n idempotencyKey?: string;\n}\n\nexport interface WaitForConditionOptions {\n timeout?: number;\n interval?: number;\n signal?: AbortSignal;\n /** Host cancellation hook for runtimes that expose a boolean marker instead of AbortSignal. */\n isCancelled?: () => boolean;\n}\n\nexport interface AgentClient {\n createWorkload(options: CreateAgentWorkloadOptions): Promise<AgentWorkloadResource>;\n getWorkload(name: string, namespace?: string): Promise<AgentWorkloadResource | null>;\n deleteWorkload(name: string, namespace?: string): Promise<void>;\n waitForWorkloadCondition(\n name: string,\n condition: AgentWorkloadCondition,\n options?: WaitForConditionOptions,\n ): Promise<{ observedResourceVersion: string; matched: true }>;\n\n createRun(options: CreateAgentRunOptions): Promise<AgentRunResource>;\n getRun(name: string, namespace?: string): Promise<AgentRunResource | null>;\n deleteRun(name: string, namespace?: string): Promise<void>;\n waitForRunCondition(\n name: string,\n condition: AgentRunCondition,\n options?: WaitForConditionOptions,\n ): Promise<{ observedResourceVersion: string; matched: true }>;\n}\n\nfunction requireName(name: string | undefined, generateName: string | undefined, label: string): string {\n if (name) return name;\n if (generateName) return `${generateName}${Math.random().toString(36).slice(2, 8)}`;\n throw new OrchestrationError({ code: 'INVALID', message: `${label} requires name or generateName`, retryable: false });\n}\n\nconst CANCELLATION_POLL_INTERVAL_MS = 50;\n\nfunction cancellationError(lastResourceVersion: string): OrchestrationError {\n return new OrchestrationError({\n code: 'CANCELLED',\n message: 'condition wait cancelled',\n retryable: false,\n details: { lastResourceVersion },\n });\n}\n\nfunction throwIfCancelled(options: WaitForConditionOptions, lastResourceVersion: string): void {\n if (options.signal?.aborted || options.isCancelled?.() === true) {\n throw cancellationError(lastResourceVersion);\n }\n}\n\nfunction abortableDelay(ms: number, signal: AbortSignal | undefined, lastResourceVersion: string): Promise<void> {\n if (!signal) {\n return new Promise((resolve) => {\n setTimeout(resolve, ms);\n });\n }\n\n return new Promise((resolve, reject) => {\n const onAbort = () => {\n clearTimeout(timeout);\n signal.removeEventListener('abort', onAbort);\n reject(cancellationError(lastResourceVersion));\n };\n const timeout = setTimeout(() => {\n signal.removeEventListener('abort', onAbort);\n resolve();\n }, ms);\n signal.addEventListener('abort', onAbort, { once: true });\n if (signal.aborted) onAbort();\n });\n}\n\nasync function waitInterval(ms: number, options: WaitForConditionOptions, lastResourceVersion: string): Promise<void> {\n if (!options.isCancelled) {\n await abortableDelay(ms, options.signal, lastResourceVersion);\n return;\n }\n\n for (let remaining = ms; remaining > 0; remaining -= CANCELLATION_POLL_INTERVAL_MS) {\n throwIfCancelled(options, lastResourceVersion);\n await abortableDelay(Math.min(remaining, CANCELLATION_POLL_INTERVAL_MS), options.signal, lastResourceVersion);\n }\n throwIfCancelled(options, lastResourceVersion);\n}\n\nexport async function waitForCondition<\n TResource extends { metadata?: { resourceVersion?: string }; status?: { conditions?: Array<{ type: string; status: 'True' | 'False' | 'Unknown' }> } },\n>(\n get: () => Promise<TResource | null>,\n condition: { type: string; status: 'True' | 'False' | 'Unknown' },\n options: WaitForConditionOptions,\n): Promise<{ observedResourceVersion: string; matched: true }> {\n const intervalMs = Math.max(100, options.interval ?? 1000);\n const timeoutMs = options.timeout ?? 30_000;\n const deadline = Date.now() + timeoutMs;\n let lastResourceVersion = '0';\n\n while (true) {\n throwIfCancelled(options, lastResourceVersion);\n const resource = await get();\n throwIfCancelled(options, lastResourceVersion);\n if (resource) {\n lastResourceVersion = resource.metadata?.resourceVersion ?? '0';\n const match = resource.status?.conditions?.find(\n (candidate) => candidate.type === condition.type && candidate.status === condition.status,\n );\n if (match) {\n return { observedResourceVersion: lastResourceVersion, matched: true };\n }\n }\n\n if (Date.now() + intervalMs > deadline) {\n throw new OrchestrationError({\n code: 'TIMEOUT',\n message: `condition ${condition.type}=${condition.status} not met within ${timeoutMs}ms`,\n retryable: true,\n details: { lastResourceVersion },\n });\n }\n\n await waitInterval(intervalMs, options, lastResourceVersion);\n }\n}\n\nexport function createAgentClient(client: AgentOrchestrationClient, defaultNamespace?: string): AgentClient {\n function resolveNamespace(namespace?: string): string | undefined {\n return namespace ?? defaultNamespace;\n }\n\n return {\n async createWorkload(options: CreateAgentWorkloadOptions): Promise<AgentWorkloadResource> {\n const name = requireName(options.name, options.generateName, 'AgentWorkload');\n const manifest: AgentWorkloadManifest = createAgentWorkloadManifest(name, {\n profileId: options.profileId,\n scriptReference: options.scriptReference,\n promptReference: options.promptReference,\n trust: options.trust,\n placement: options.placement,\n modelPolicy: options.modelPolicy,\n toolPolicy: options.toolPolicy,\n networkPolicy: options.networkPolicy,\n storagePolicy: options.storagePolicy,\n completionPolicy: options.completionPolicy,\n ownerReferences: options.ownerReferences,\n });\n const result = await client.apply(manifest, {\n idempotencyKey: options.idempotencyKey,\n fieldManager: 'memeloop-agent-client',\n });\n if (!isAgentWorkload(result)) {\n throw new OrchestrationError({ code: 'UNKNOWN_EFFECT', message: 'apply returned a non-AgentWorkload resource', retryable: false });\n }\n return result;\n },\n\n async getWorkload(name: string, namespace?: string): Promise<AgentWorkloadResource | null> {\n const result = await client.get(agentWorkloadReference(name, resolveNamespace(namespace)));\n return result && isAgentWorkload(result) ? result : null;\n },\n\n async deleteWorkload(name: string, namespace?: string): Promise<void> {\n await client.delete(agentWorkloadReference(name, resolveNamespace(namespace)));\n },\n\n async waitForWorkloadCondition(\n name: string,\n condition: AgentWorkloadCondition,\n options: WaitForConditionOptions = {},\n ): Promise<{ observedResourceVersion: string; matched: true }> {\n return waitForCondition(\n () => this.getWorkload(name, defaultNamespace),\n condition,\n options,\n );\n },\n\n async createRun(options: CreateAgentRunOptions): Promise<AgentRunResource> {\n const name = requireName(options.name, options.generateName, 'AgentRun');\n const manifest: AgentRunManifest = createAgentRunManifest(name, {\n workloadRef: agentWorkloadReference(options.workloadName, options.workloadNamespace ?? defaultNamespace),\n promptReference: options.promptReference,\n retry: options.retry,\n timeoutMs: options.timeoutMs,\n });\n const result = await client.apply(manifest, {\n idempotencyKey: options.idempotencyKey,\n fieldManager: 'memeloop-agent-client',\n });\n if (!isAgentRun(result)) {\n throw new OrchestrationError({ code: 'UNKNOWN_EFFECT', message: 'apply returned a non-AgentRun resource', retryable: false });\n }\n return result;\n },\n\n async getRun(name: string, namespace?: string): Promise<AgentRunResource | null> {\n const result = await client.get(agentRunReference(name, resolveNamespace(namespace)));\n return result && isAgentRun(result) ? result : null;\n },\n\n async deleteRun(name: string, namespace?: string): Promise<void> {\n await client.delete(agentRunReference(name, resolveNamespace(namespace)));\n },\n\n async waitForRunCondition(\n name: string,\n condition: AgentRunCondition,\n options: WaitForConditionOptions = {},\n ): Promise<{ observedResourceVersion: string; matched: true }> {\n return waitForCondition(\n () => this.getRun(name, defaultNamespace),\n condition,\n options,\n );\n },\n };\n}\n","import { zodToJsonSchema } from 'zod-to-json-schema';\n\nconst toolSchemas = new Map<string, unknown>();\nconst toolMetadata = new Map<string, { displayName: string; description: string }>();\n\n/**\n * Convert either a legacy host's Zod 3 schema, a current Zod 4 schema,\n * schema, or an already portable JSON Schema without silently widening a\n * registered tool to an unconstrained object.\n */\nexport function toolSchemaToJsonSchema(value: unknown): Record<string, unknown> {\n const native = (\n value as { toJSONSchema?: () => Record<string, unknown> } | undefined\n )?.toJSONSchema?.();\n if (native) return structuredClone(native);\n\n if (value !== null && typeof value === 'object' && '_def' in value) {\n const converted = zodToJsonSchema(value as never, {\n $refStrategy: 'none',\n });\n return structuredClone(converted as Record<string, unknown>);\n }\n\n if (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n ('type' in value ||\n 'properties' in value ||\n '$ref' in value ||\n 'oneOf' in value ||\n 'anyOf' in value)\n ) {\n return structuredClone(value as Record<string, unknown>);\n }\n\n throw new TypeError(\n 'Tool parameter schema must be a Zod schema or a portable JSON Schema',\n );\n}\n\nexport function registerToolParameterSchema(\n toolId: string,\n schema: unknown,\n metadata?: { displayName: string; description: string },\n): void {\n toolSchemas.set(toolId, schema);\n if (metadata) {\n toolMetadata.set(toolId, metadata);\n }\n}\n\nexport function getToolParameterSchema(toolId: string): unknown {\n return toolSchemas.get(toolId);\n}\n\nexport function getToolMetadata(\n toolId: string,\n): { displayName: string; description: string } | undefined {\n return toolMetadata.get(toolId);\n}\n","/**\n * Script sandbox/runtime selection (plan 24.18) and remote deployment (plan 24.14).\n *\n * - RuntimeClass: declares module isolation, resource limits, cancellation,\n * and supported trust classes for generated scripts.\n * - Sandbox selection: maps script trust class to appropriate RuntimeClass.\n * - Remote deployment: script declares placement desires; scheduler picks node.\n *\n * Scripts cannot silently run in an unrestricted controller process.\n */\n\nimport type { ScriptTrustClass } from './scriptAdmission.js';\n\n// ─── RuntimeClass ──────────────────────────────────────────────────────\n\nexport interface RuntimeClassSpec {\n /** Module isolation level. */\n isolation: 'none' | 'process' | 'container';\n /** CPU limit in millicores (1000 = 1 core). */\n cpuLimitMillis?: number;\n /** Memory limit in bytes. */\n memoryLimitBytes?: number;\n /** Wall-clock time limit in milliseconds. */\n timeLimitMs?: number;\n /** Whether the runtime supports cancellation signals. */\n supportsCancellation: boolean;\n /** Supported trust classes for this runtime. */\n supportedTrustClasses: ScriptTrustClass[];\n /** Whether network access is allowed (outbound-only for quarantine). */\n networkAccess: 'none' | 'outbound-only' | 'full';\n}\n\nexport interface RuntimeClassResource {\n apiVersion: 'execution.memeloop.io/v1alpha1';\n kind: 'RuntimeClass';\n metadata: {\n name: string;\n namespace?: string;\n };\n spec: RuntimeClassSpec;\n}\n\n// ─── Built-in Runtime Classes ──────────────────────────────────────────\n\nexport const BUILTIN_RUNTIME_CLASSES: Record<string, RuntimeClassSpec> = {\n 'trusted-process': {\n isolation: 'process',\n cpuLimitMillis: 2000,\n memoryLimitBytes: 512 * 1024 * 1024, // 512 MiB\n timeLimitMs: 300_000, // 5 min\n supportsCancellation: true,\n supportedTrustClasses: ['trusted'],\n networkAccess: 'full',\n },\n 'restricted-process': {\n isolation: 'process',\n cpuLimitMillis: 1000,\n memoryLimitBytes: 128 * 1024 * 1024, // 128 MiB\n timeLimitMs: 120_000, // 2 min\n supportsCancellation: true,\n supportedTrustClasses: ['trusted', 'restricted'],\n networkAccess: 'outbound-only',\n },\n 'quarantine-process': {\n isolation: 'process',\n cpuLimitMillis: 500,\n // A Node VM plus the trusted worker bootstrap needs more than 32 MiB RSS;\n // the Linux host enforces this value as cgroup MemoryMax, not only V8 heap.\n memoryLimitBytes: 96 * 1024 * 1024, // 96 MiB\n timeLimitMs: 30_000, // 30 sec\n supportsCancellation: true,\n supportedTrustClasses: ['quarantine'],\n networkAccess: 'none',\n },\n};\n\n// ─── Sandbox Selection ─────────────────────────────────────────────────\n\nexport interface SandboxSelectionResult {\n runtimeClass: string;\n isolation: RuntimeClassSpec['isolation'];\n cpuLimitMillis: number;\n memoryLimitBytes: number;\n timeLimitMs: number;\n networkAccess: RuntimeClassSpec['networkAccess'];\n}\n\n/**\n * Select the most restrictive RuntimeClass capable of hosting the given\n * trust class. Throws when no available RuntimeClass supports the trust\n * class — there is no silent fallback (24.18).\n */\nexport function selectRuntimeClass(trustClass: ScriptTrustClass, available: string[] = Object.keys(BUILTIN_RUNTIME_CLASSES)): SandboxSelectionResult {\n // Prefer exact match by trust class.\n const exact = available.find((name) => {\n const spec = BUILTIN_RUNTIME_CLASSES[name];\n return spec?.supportedTrustClasses.includes(trustClass);\n });\n\n if (!exact) {\n throw new Error('No RuntimeClass available for trust class: ' + trustClass);\n }\n const name = exact;\n const spec = BUILTIN_RUNTIME_CLASSES[name];\n\n return {\n runtimeClass: name,\n isolation: spec.isolation,\n cpuLimitMillis: spec.cpuLimitMillis ?? 500,\n memoryLimitBytes: spec.memoryLimitBytes ?? 32 * 1024 * 1024,\n timeLimitMs: spec.timeLimitMs ?? 30_000,\n networkAccess: spec.networkAccess,\n };\n}\n\n// ─── Remote Deployment Descriptor ──────────────────────────────────────\n\n/**\n * Reference to a content-addressed ArtifactRecord holding the script source\n * (plan 24.15/24.47). Remote deployments never carry raw script source\n * strings; the target node resolves the artifact by identity and verifies\n * it against `contentDigest` before loading.\n */\nexport interface ScriptArtifactReference {\n /** API version of the artifact resource (`artifacts.memeloop.io/v1alpha1`). */\n apiVersion: string;\n /** Resource kind; always `ArtifactRecord`. */\n kind: 'ArtifactRecord';\n /** Artifact resource name. */\n name: string;\n /** Artifact namespace, if any. */\n namespace?: string;\n /**\n * Content digest (`sha256:<hex>`) of the NORMALIZED script source. The\n * remote node must verify the fetched artifact content against this\n * digest before admission.\n */\n contentDigest: string;\n}\n\nexport interface RemoteDeploymentRequest {\n /**\n * Content-addressed reference to the script artifact. Raw script source\n * is never transported inside a deployment request.\n */\n artifactRef: ScriptArtifactReference;\n /** Trust class assigned by admission. */\n trustClass: ScriptTrustClass;\n /** Desired lifecycle. */\n lifecycle: 'run-once' | 'service' | 'schedule';\n /** Runtime class to use. */\n runtimeClass: string;\n /** Node selector for scheduling. */\n nodeSelector?: Record<string, string>;\n /** Environment variables (never credentials). */\n env?: Record<string, string>;\n /** Network attachment requirements enforced before the script starts. */\n networkPolicy?: import('../resources.js').AgentWorkloadNetworkPolicy;\n /** Existing claims to publish before the script starts. */\n storagePolicy?: import('../resources.js').AgentWorkloadStoragePolicy;\n}\n\nexport interface RemoteDeploymentResult {\n /** Workload name created on the target node. */\n workloadName: string;\n /** Node the workload was placed on. */\n nodeName: string;\n /** When the deployment was requested. */\n requestedAt: string;\n}\n","/**\n * Script admission policy and checkpoint compatibility (plan 24.17, 24.19).\n *\n * - Admission: trust class, author, imports, resource limits, approval\n * - Compatibility: script digest/API version vs checkpoint schema\n *\n * Quarantine scripts cannot enable arbitrary network imports or plugin loading.\n * A changed script cannot resume an incompatible checkpoint without explicit\n * converter or restart policy.\n */\n\nimport type { ScriptValidationResult } from './scriptValidation.js';\n\nexport type ScriptTrustClass = 'trusted' | 'restricted' | 'quarantine';\n\nexport interface ScriptAdmissionRequest {\n /** The validated script result. */\n script: ScriptValidationResult;\n /** Trust class of the author (e.g., the Agent that generated the script). */\n authorTrust: ScriptTrustClass;\n /** Requested interfaces the script wants to use. */\n requestedInterfaces: string[];\n /** Optional checkpoint digest the script expects to resume from. */\n expectedCheckpointDigest?: string;\n /** The checkpoint's API version (for compatibility check). */\n checkpointApiVersion?: string;\n}\n\nexport interface ScriptAdmissionDecision {\n admitted: boolean;\n reason: string;\n /** Which interfaces are approved for this script. */\n approvedInterfaces: string[];\n /** Whether the checkpoint is compatible. */\n checkpointCompatible: boolean;\n /** If not admitted, whether the author can retry with changes. */\n retryable: boolean;\n}\n\ninterface TrustProfile {\n maxScriptBytes: number;\n allowedInterfaces: string[];\n forbiddenImports: string[];\n requireDefaultExport: boolean;\n allowUntrustedInputs: boolean;\n}\n\nconst TRUST_PROFILES: Record<ScriptTrustClass, TrustProfile> = {\n trusted: {\n maxScriptBytes: 1_048_576, // 1 MiB\n allowedInterfaces: ['resource', 'loop-runtime', 'tool-execution', 'model-provider', 'network', 'storage', 'credential-broker', 'artifact'],\n forbiddenImports: [],\n requireDefaultExport: true,\n allowUntrustedInputs: false,\n },\n restricted: {\n maxScriptBytes: 256_000, // 256 KiB\n allowedInterfaces: ['resource', 'loop-runtime', 'model-provider'],\n forbiddenImports: ['node:fs', 'node:child_process', 'node:net', 'node:http', 'node:https'],\n requireDefaultExport: true,\n allowUntrustedInputs: false,\n },\n quarantine: {\n maxScriptBytes: 64_000, // 64 KiB\n allowedInterfaces: ['loop-runtime'], // No network, no file system, no model provider\n forbiddenImports: ['node:fs', 'node:child_process', 'node:net', 'node:http', 'node:https', 'node:os', 'node:crypto'],\n requireDefaultExport: true,\n allowUntrustedInputs: false,\n },\n};\n\nconst COMPATIBLE_CHECKPOINT_VERSIONS = new Set(['loops.memeloop.io/v1alpha1']);\n\n/**\n * The full interface set a host may grant to scripts authored under the\n * given trust class — a defensive copy of the trust profile's allowlist.\n *\n * Hosts wiring a {@link ../loopAPI/types.ScriptLoadGate} or a deployment\n * pipeline should pass these as `requestedInterfaces`; {@link admitScript}\n * rejects any request outside the trust profile, so this is the widest set\n * that can ever be approved for that class. Callers may pass a narrower\n * subset to further restrict a specific runtime.\n */\nexport function defaultRequestedInterfacesForTrustClass(trustClass: ScriptTrustClass): string[] {\n return [...TRUST_PROFILES[trustClass].allowedInterfaces];\n}\n\n/** Maximum script size in bytes admitted for the given trust class. */\nexport function maxScriptBytesForTrustClass(trustClass: ScriptTrustClass): number {\n return TRUST_PROFILES[trustClass].maxScriptBytes;\n}\n\n/**\n * Decide whether a generated script may be admitted for execution.\n */\nexport function admitScript(request: ScriptAdmissionRequest): ScriptAdmissionDecision {\n const profile = TRUST_PROFILES[request.authorTrust];\n const approvedInterfaces: string[] = [];\n\n // 1. Size check.\n if (request.script.sizeBytes > profile.maxScriptBytes) {\n return {\n admitted: false,\n reason: `Script size ${request.script.sizeBytes} exceeds ${request.authorTrust} limit ${profile.maxScriptBytes}`,\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: true,\n };\n }\n\n // 2. Syntax check.\n if (!request.script.valid) {\n return {\n admitted: false,\n reason: `Script validation failed: ${request.script.errors.join('; ')}`,\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: true,\n };\n }\n\n // 3. Export check.\n if (profile.requireDefaultExport && !request.script.hasDefaultExport) {\n return {\n admitted: false,\n reason: 'Script must export a default async generator',\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: true,\n };\n }\n\n // 4. Import policy.\n for (const imp of request.script.imports) {\n // Forbidden imports per trust profile.\n if (profile.forbiddenImports.includes(imp) || profile.forbiddenImports.includes(imp.replace(/^node:/, ''))) {\n return {\n admitted: false,\n reason: `Import '${imp}' not allowed for ${request.authorTrust} scripts`,\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: false,\n };\n }\n }\n\n // 5. Interface policy.\n for (const iface of request.requestedInterfaces) {\n if (!profile.allowedInterfaces.includes(iface)) {\n return {\n admitted: false,\n reason: `Interface '${iface}' not allowed for ${request.authorTrust} scripts`,\n approvedInterfaces: [],\n checkpointCompatible: false,\n retryable: false,\n };\n }\n approvedInterfaces.push(iface);\n }\n\n // 6. Checkpoint compatibility.\n let checkpointCompatible = true;\n if (request.expectedCheckpointDigest && request.checkpointApiVersion) {\n if (!COMPATIBLE_CHECKPOINT_VERSIONS.has(request.checkpointApiVersion)) {\n checkpointCompatible = false;\n }\n // Changed script digest cannot resume old checkpoint without explicit converter.\n if (request.expectedCheckpointDigest !== request.script.digest) {\n checkpointCompatible = false;\n }\n }\n\n return {\n admitted: true,\n reason: `Admitted as ${request.authorTrust}`,\n approvedInterfaces,\n checkpointCompatible,\n retryable: false,\n };\n}\n","/**\n * Generated-script validation and normalization (plan 24.16).\n *\n * Validates Agent-generated .mjs scripts before they are scheduled:\n * - Syntax check via a real JavaScript parser (Acorn) — regexes could be\n * fooled by comments/strings/regex literals; an AST cannot.\n * - Required export shape: the default export must be an async generator\n * function (inline or via an identifier bound to one in the same module).\n * - Import extraction from the AST: static `import` declarations, re-exports\n * (`export ... from`), and string-literal dynamic `import()` arguments.\n * Non-literal dynamic imports are rejected because they defeat admission.\n * - Forbidden imports: no Node builtins except 'node:events'.\n * - Size limits.\n * - Canonical SHA-256 digest for provenance. The digest commits to the\n * NORMALIZED source (see {@link normalizeScript}), so semantically\n * identical scripts with different line endings share one digest.\n *\n * Security note: this runs in the controller process, but never executes\n * the script. Execution is delegated to the sandbox from plan 24.48.\n */\n\nimport { parse } from 'acorn';\n\nconst MAX_SCRIPT_BYTES = 1_048_576; // 1 MiB\n\nexport interface ScriptValidationResult {\n valid: boolean;\n /**\n * Canonical SHA-256 hex digest of the NORMALIZED source\n * (`normalizeScript(source)`). The digest commits to the normalized form,\n * not the raw bytes, so CRLF/LF variants of the same script are equal.\n */\n digest: string;\n /** Detected imports, from the AST (static, re-export, literal dynamic). */\n imports: string[];\n /** Whether the script's default export is an async generator function. */\n hasDefaultExport: boolean;\n /**\n * Whether the script contains a dynamic `import()` whose argument is not\n * a string literal. Such scripts are always invalid: the import target\n * cannot be known statically, which defeats admission control.\n */\n hasNonLiteralDynamicImport: boolean;\n /** Human-readable errors if invalid. */\n errors: string[];\n /** Normalized source size in bytes. */\n sizeBytes: number;\n}\n\n/** Minimal structural type for generic AST traversal. */\ninterface AstNode {\n type: string;\n [key: string]: unknown;\n}\n\nfunction isAstNode(value: unknown): value is AstNode {\n return typeof value === 'object' && value !== null && typeof (value as AstNode).type === 'string';\n}\n\n/**\n * Recursively visit every node in an ESTree AST. Only properties holding\n * node-like values (objects/arrays of objects with a string `type`) are\n * traversed, so scalar fields (names, literals, ranges) are skipped.\n */\nfunction walkAst(node: AstNode, visit: (node: AstNode) => void): void {\n visit(node);\n for (const key of Object.keys(node)) {\n const value: unknown = node[key];\n if (Array.isArray(value)) {\n for (const child of value as unknown[]) {\n if (isAstNode(child)) walkAst(child, visit);\n }\n } else if (isAstNode(value)) {\n walkAst(value, visit);\n }\n }\n}\n\nfunction isAsyncGeneratorFunction(node: AstNode | null | undefined): boolean {\n if (!node) return false;\n return (\n (node.type === 'FunctionDeclaration' || node.type === 'FunctionExpression') &&\n node.async === true &&\n node.generator === true\n );\n}\n\nfunction getStaticImportSource(node: AstNode): string | undefined {\n const source = node.source as AstNode | null | undefined;\n if (source && source.type === 'Literal' && typeof source.value === 'string') {\n return source.value;\n }\n return undefined;\n}\n\n/** Detect `module.exports = ...` or `exports.foo = ...` assignments. */\nfunction isCommonJsExportAssignment(node: AstNode): boolean {\n if (node.type !== 'AssignmentExpression') return false;\n const left = node.left as AstNode | undefined;\n if (!left || left.type !== 'MemberExpression' || left.computed === true) return false;\n const object = left.object as AstNode | undefined;\n const property = left.property as AstNode | undefined;\n if (!object || object.type !== 'Identifier' || !property || property.type !== 'Identifier') {\n return false;\n }\n if (object.name === 'exports') return true;\n return object.name === 'module' && property.name === 'exports';\n}\n\n/**\n * Compute the canonical SHA-256 hex digest of an already-normalized script.\n * Callers with raw source must pass it through {@link normalizeScript} first\n * (or use {@link validateScript}, which normalizes internally).\n */\nexport async function digestNormalizedScript(normalizedSource: string): Promise<string> {\n const encoded = new TextEncoder().encode(normalizedSource);\n const hash = await crypto.subtle.digest('SHA-256', encoded);\n return Array.from(new Uint8Array(hash)).map((b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/**\n * Validate a script string using a real AST parse (Acorn).\n * Returns a structured result; never throws.\n */\nexport async function validateScript(source: string): Promise<ScriptValidationResult> {\n const errors: string[] = [];\n const imports: string[] = [];\n let hasDefaultExport = false;\n let hasNonLiteralDynamicImport = false;\n\n const normalized = normalizeScript(source);\n const encoded = new TextEncoder().encode(normalized);\n\n // Size check (on the canonical form the digest commits to).\n if (encoded.length > MAX_SCRIPT_BYTES) {\n errors.push(`Script exceeds ${MAX_SCRIPT_BYTES} bytes (got ${encoded.length})`);\n }\n if (normalized.trim().length === 0) {\n errors.push('Script is empty');\n }\n\n // The digest commits to the normalized source, never the raw bytes.\n const digest = await digestNormalizedScript(normalized);\n\n // Parse with a real JavaScript parser. Comments, strings, template\n // literals, and regex literals cannot smuggle fake imports/exports.\n let program: AstNode | undefined;\n if (normalized.trim().length > 0) {\n try {\n program = parse(normalized, { ecmaVersion: 'latest', sourceType: 'module' }) as unknown as AstNode;\n } catch (error) {\n errors.push(`Syntax error: ${error instanceof Error ? error.message : String(error)}`);\n }\n }\n\n if (program) {\n const topLevel = Array.isArray(program.body) ? (program.body as AstNode[]) : [];\n\n // 1. Default export shape (top-level statements only).\n for (const statement of topLevel) {\n if (statement.type !== 'ExportDefaultDeclaration') continue;\n const declaration = statement.declaration as AstNode | undefined;\n if (isAsyncGeneratorFunction(declaration)) {\n hasDefaultExport = true;\n } else if (declaration?.type === 'Identifier') {\n // Disguised default export: `async function* run() {} export default run;`\n const identifier = declaration;\n hasDefaultExport = topLevel.some((candidate) => {\n if (isAsyncGeneratorFunction(candidate) && (candidate.id as AstNode | undefined)?.name === identifier.name) {\n return true;\n }\n if (candidate.type === 'VariableDeclaration' && Array.isArray(candidate.declarations)) {\n return (candidate.declarations as AstNode[]).some(\n (declarator) =>\n (declarator.id as AstNode | undefined)?.name === identifier.name &&\n isAsyncGeneratorFunction(declarator.init as AstNode | undefined),\n );\n }\n return false;\n });\n }\n }\n\n // 2. Imports, re-exports, dynamic imports, and CommonJS (full AST walk).\n walkAst(program, (node) => {\n if (node.type === 'ImportDeclaration') {\n const specifier = getStaticImportSource(node);\n if (specifier !== undefined) imports.push(specifier);\n } else if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') {\n // Re-exports (`export { x } from '...'`, `export * from '...'`) import too.\n const specifier = getStaticImportSource(node);\n if (specifier !== undefined) imports.push(specifier);\n } else if (node.type === 'ImportExpression') {\n const specifier = getStaticImportSource(node);\n if (specifier !== undefined) {\n imports.push(specifier);\n } else {\n hasNonLiteralDynamicImport = true;\n }\n } else if (isCommonJsExportAssignment(node)) {\n errors.push('CommonJS module.exports not supported (use ESM export)');\n }\n });\n }\n\n // 3. Forbidden imports.\n for (const specifier of imports) {\n if (isForbiddenImport(specifier)) {\n errors.push(`Forbidden import: ${specifier}`);\n }\n }\n\n // 4. Non-literal dynamic imports defeat admission control.\n if (hasNonLiteralDynamicImport) {\n errors.push('Dynamic import() with a non-literal argument is not allowed (defeats admission control)');\n }\n\n // 5. Required export shape.\n if (!hasDefaultExport) {\n errors.push('Script must export a default async generator function');\n }\n\n return {\n valid: errors.length === 0,\n digest,\n imports,\n hasDefaultExport,\n hasNonLiteralDynamicImport,\n errors,\n sizeBytes: encoded.length,\n };\n}\n\n/**\n * Normalize a script to a canonical form for digest stability.\n * Strips BOM, normalizes line endings to LF, and trims trailing whitespace.\n * Idempotent: `normalizeScript(normalizeScript(s)) === normalizeScript(s)`.\n * The canonical digest in {@link validateScript} commits to this form.\n */\nexport function normalizeScript(source: string): string {\n return source\n .replace(/^\\uFEFF/, '') // BOM\n .replace(/\\r\\n/g, '\\n') // CRLF → LF\n .replace(/\\r/g, '\\n') // CR → LF\n .split('\\n')\n .map((line) => line.trimEnd())\n .join('\\n')\n .trim() + '\\n';\n}\n\nfunction isForbiddenImport(spec: string): boolean {\n // Node builtins are forbidden except 'events'.\n const builtins = new Set([\n 'fs',\n 'path',\n 'child_process',\n 'net',\n 'http',\n 'https',\n 'os',\n 'crypto',\n 'tls',\n 'dgram',\n 'dns',\n 'readline',\n 'repl',\n 'stream',\n 'timers',\n 'tty',\n 'url',\n 'util',\n 'v8',\n 'vm',\n 'worker_threads',\n 'zlib',\n 'assert',\n 'buffer',\n 'querystring',\n 'string_decoder',\n ]);\n const base = spec.replace(/^node:/, '');\n if (builtins.has(base) && spec !== 'node:events') return true;\n\n // Libp2p imports are forbidden.\n if (spec.startsWith('@libp2p/') || spec.startsWith('@chainsafe/libp2p') || spec === 'libp2p') {\n return true;\n }\n\n // Process/tool-specific: scripts cannot import the host runtime.\n if (spec === 'memeloop' || spec.startsWith('memeloop/')) return true;\n\n return false;\n}\n","/**\n * Generated-script deployment pipeline (plans 24.14–24.19, 24.47).\n *\n * Connects the full security chain for remote/generated scripts:\n *\n * normalizeScript → validateScript (Acorn AST) → admitScript (trust-class\n * policy) → ArtifactRecord manifest (content-addressed) → persist via the\n * injected artifact store port → selectRuntimeClass →\n * RemoteDeploymentRequest (artifactRef only — raw source is never carried).\n *\n * Also provides {@link createScriptLoadGate}, the production\n * {@link ScriptLoadGate} implementation for the in-process script loading\n * path (`loopAPI/scriptLoader`): validate (AST) → admit → assign\n * trustClass/RuntimeClass before any `import()` executes.\n *\n * Everything here is pure and portable; artifact persistence sits behind the\n * {@link ScriptArtifactStore} port so the CLI can back it with real storage.\n */\n\nimport type { ScriptLoadGate, ScriptLoadGateDecision } from '../../loopAPI/types.js';\nimport { waitForCondition, type WaitForConditionOptions } from '../agentClient.js';\nimport type { AgentOrchestrationClient, OrchestrationOwnerReference } from '../client.js';\nimport { OrchestrationError } from '../errors.js';\nimport {\n AGENT_WORKLOAD_API_VERSION,\n AGENT_WORKLOAD_KIND,\n type AgentWorkloadCompletionPolicy,\n type AgentWorkloadManifest,\n type AgentWorkloadNetworkPolicy,\n type AgentWorkloadResource,\n type AgentWorkloadStoragePolicy,\n type ArtifactRecordManifest,\n createAgentWorkloadManifest,\n createArtifactRecordManifest,\n} from '../resources.js';\nimport { containsSecrets } from '../security/secretRedaction.js';\nimport { admitScript, defaultRequestedInterfacesForTrustClass, type ScriptAdmissionDecision, type ScriptTrustClass } from './scriptAdmission.js';\nimport { type RemoteDeploymentRequest, type SandboxSelectionResult, selectRuntimeClass } from './scriptRuntime.js';\nimport { normalizeScript, type ScriptValidationResult, validateScript } from './scriptValidation.js';\n\n// ─── Artifact persistence port ─────────────────────────────────────────\n\n/**\n * Port: persists a script ArtifactRecord manifest plus its normalized\n * content. Implementations (e.g. CLI storage) must store content addressed\n * by `manifest.spec.contentHash` and must not trust content whose hash does\n * not match the manifest.\n */\nexport interface ScriptArtifactStore {\n putArtifact(manifest: ArtifactRecordManifest, normalizedContent: string): Promise<void> | void;\n}\n\n// ─── Deployment pipeline ───────────────────────────────────────────────\n\n/** Input for {@link deployGeneratedScript}. */\nexport interface ScriptDeploymentRequest {\n /** Raw generated `.mjs` source (normalized internally). */\n source: string;\n /** Trust class of the author (the Agent that generated the script). */\n authorTrust: ScriptTrustClass;\n /** Interfaces the script requests (loop-runtime, model-provider, ...). */\n requestedInterfaces: string[];\n /** Desired lifecycle for the remote workload. */\n lifecycle: 'run-once' | 'service' | 'schedule';\n /** Node selector for scheduling. */\n nodeSelector?: Record<string, string>;\n /** Environment variables (never credentials). */\n env?: Record<string, string>;\n /** Network attachment requirements for the deployed workload. */\n networkPolicy?: AgentWorkloadNetworkPolicy;\n /** Existing volume claims required by the deployed workload. */\n storagePolicy?: AgentWorkloadStoragePolicy;\n /** Optional checkpoint digest the script expects to resume from. */\n expectedCheckpointDigest?: string;\n /** API version of the expected checkpoint (plan 24.19). */\n checkpointApiVersion?: string;\n /** Namespace for the ArtifactRecord and deployment. */\n namespace?: string;\n}\n\n/** Tunables for {@link deployGeneratedScript}. */\nexport interface ScriptDeploymentPipelineOptions {\n /** Artifact persistence port; when omitted the manifest is built but not persisted. */\n artifactStore?: ScriptArtifactStore;\n /** RuntimeClass names available for selection (defaults to all built-ins). */\n availableRuntimeClasses?: string[];\n}\n\n/** Result of {@link deployGeneratedScript}; `deployed` gates artifact/deployment presence. */\nexport interface ScriptDeploymentResult {\n /** Whether a deployment request was produced. */\n deployed: boolean;\n /** Human-readable outcome (validation/admission/enforcement reason). */\n reason: string;\n /** AST validation outcome (always present). */\n validation: ScriptValidationResult;\n /** Admission decision (present once validation passed). */\n admission?: ScriptAdmissionDecision;\n /** Content-addressed artifact manifest (present when deployed). */\n artifact?: ArtifactRecordManifest;\n /** Selected RuntimeClass (present when deployed). */\n runtimeClass?: SandboxSelectionResult;\n /** Deployment request referencing the artifact by digest (present when deployed). */\n deployment?: RemoteDeploymentRequest;\n /** Applied AgentWorkload (present when deployed through an orchestration facade). */\n workload?: AgentWorkloadResource;\n}\n\n// ─── Scheduler consumption (plan 24.14) ────────────────────────────────\n\n/** Lifecycle declared by the script → workload completion policy. */\nconst LIFECYCLE_TO_COMPLETION_POLICY: Record<RemoteDeploymentRequest['lifecycle'], AgentWorkloadCompletionPolicy> = {\n 'run-once': 'complete',\n service: 'daemon',\n schedule: 'detach',\n};\n\nexport interface RemoteDeploymentWorkloadOptions {\n /** Workload name (defaults to the content-addressed artifact name). */\n name?: string;\n namespace?: string;\n ownerReferences?: OrchestrationOwnerReference[];\n}\n\n/**\n * Translate a {@link RemoteDeploymentRequest} into an AgentWorkload manifest\n * the binding controller (24.56) can schedule. The script declares placement\n * and lifecycle; the scheduler — never the script — selects the node.\n */\nexport function remoteDeploymentToWorkloadManifest(\n deployment: RemoteDeploymentRequest,\n options: RemoteDeploymentWorkloadOptions = {},\n): AgentWorkloadManifest {\n const manifest = createAgentWorkloadManifest(options.name ?? deployment.artifactRef.name, {\n scriptReference: deployment.artifactRef.contentDigest,\n trust: deployment.trustClass,\n runtimeClass: deployment.runtimeClass,\n completionPolicy: LIFECYCLE_TO_COMPLETION_POLICY[deployment.lifecycle],\n ...(deployment.nodeSelector ? { placement: { nodeSelector: deployment.nodeSelector } } : {}),\n ...(deployment.env ? { env: deployment.env } : {}),\n ...(deployment.networkPolicy ? { networkPolicy: deployment.networkPolicy } : {}),\n ...(deployment.storagePolicy ? { storagePolicy: deployment.storagePolicy } : {}),\n ...(options.ownerReferences ? { ownerReferences: options.ownerReferences } : {}),\n });\n const namespace = options.namespace ?? deployment.artifactRef.namespace;\n if (namespace !== undefined) {\n manifest.metadata.namespace = namespace;\n }\n return manifest;\n}\n\n/**\n * Run the full generated-script security chain and produce a remote\n * deployment request. Never throws for script-content problems — invalid or\n * inadmissible scripts yield `deployed: false` with a structured reason.\n *\n * Checkpoint compatibility (plan 24.19) is enforced here: when the caller\n * expects to resume a checkpoint and admission found it incompatible, no\n * deployment is produced (an explicit converter or restart policy would be\n * required first).\n */\nexport async function deployGeneratedScript(\n request: ScriptDeploymentRequest,\n options: ScriptDeploymentPipelineOptions = {},\n): Promise<ScriptDeploymentResult> {\n // 1. Normalize + validate (Acorn AST, canonical digest).\n const validation = await validateScript(request.source);\n if (!validation.valid) {\n return {\n deployed: false,\n reason: `Script validation failed: ${validation.errors.join('; ')}`,\n validation,\n };\n }\n\n // 2. Admission (trust-class policy, plan 24.17/24.19).\n const admission = admitScript({\n script: validation,\n authorTrust: request.authorTrust,\n requestedInterfaces: request.requestedInterfaces,\n expectedCheckpointDigest: request.expectedCheckpointDigest,\n checkpointApiVersion: request.checkpointApiVersion,\n });\n if (!admission.admitted) {\n return { deployed: false, reason: admission.reason, validation, admission };\n }\n if (request.expectedCheckpointDigest !== undefined && !admission.checkpointCompatible) {\n return {\n deployed: false,\n reason: 'Checkpoint is incompatible with this script digest/API version; an explicit converter or restart policy is required',\n validation,\n admission,\n };\n }\n\n // 2b. env guard (plan 24.35): workload env is persisted in the ControlStore\n // spec, so secret-shaped values are rejected here rather than redacted.\n for (const [name, value] of Object.entries(request.env ?? {})) {\n if (containsSecrets(value)) {\n return {\n deployed: false,\n reason: `Environment variable '${name}' carries a secret-shaped value; workload env must never contain credentials (plan 24.35)`,\n validation,\n admission,\n };\n }\n }\n\n // 3. Content-addressed ArtifactRecord manifest (plan 24.15/24.47).\n const contentDigest = `sha256:${validation.digest}`;\n const artifactName = `script-${validation.digest}`;\n const artifact = createArtifactRecordManifest(artifactName, {\n contentHash: contentDigest,\n sizeBytes: validation.sizeBytes,\n mimeType: 'text/javascript',\n producer: { trust: request.authorTrust },\n trust: request.authorTrust,\n });\n if (request.namespace !== undefined) {\n artifact.metadata.namespace = request.namespace;\n }\n await options.artifactStore?.putArtifact(artifact, normalizeScript(request.source));\n\n // 4. RuntimeClass selection (plan 24.18).\n const runtimeClass = selectRuntimeClass(request.authorTrust, options.availableRuntimeClasses);\n\n // 5. Deployment request referencing the artifact by digest — never raw source.\n const deployment: RemoteDeploymentRequest = {\n artifactRef: {\n apiVersion: artifact.apiVersion,\n kind: 'ArtifactRecord',\n name: artifactName,\n namespace: artifact.metadata.namespace,\n contentDigest,\n },\n trustClass: request.authorTrust,\n lifecycle: request.lifecycle,\n runtimeClass: runtimeClass.runtimeClass,\n nodeSelector: request.nodeSelector,\n env: request.env,\n networkPolicy: request.networkPolicy,\n storagePolicy: request.storagePolicy,\n };\n\n return {\n deployed: true,\n reason: admission.reason,\n validation,\n admission,\n artifact,\n runtimeClass,\n deployment,\n };\n}\n\n// ─── Script load gate (production admission for in-process loading) ────\n\n/** Configuration for {@link createScriptLoadGate}. */\nexport interface ScriptLoadGateConfig {\n /** Trust class to assign admitted scripts (plan 24.17). */\n authorTrust: ScriptTrustClass;\n /** Interfaces admitted scripts may request. */\n requestedInterfaces: string[];\n /** RuntimeClass names available for selection (defaults to all built-ins). */\n availableRuntimeClasses?: string[];\n /** Optional checkpoint digest admitted scripts expect to resume from. */\n expectedCheckpointDigest?: string;\n /** API version of the expected checkpoint (plan 24.19). */\n checkpointApiVersion?: string;\n}\n\n/**\n * Create the production {@link ScriptLoadGate}: every non-builtin source is\n * validated (Acorn AST), admitted under the configured trust-class policy,\n * and assigned a RuntimeClass before the loader is allowed to `import()` it.\n * The gate verifies that the digest computed by the loader matches the\n * digest of the source it validated, so the admitted bytes are exactly the\n * imported bytes.\n */\nexport function createScriptLoadGate(config: ScriptLoadGateConfig): ScriptLoadGate {\n return {\n async admitScriptLoad(request): Promise<ScriptLoadGateDecision> {\n const validation = await validateScript(request.normalizedSource);\n if (!validation.valid) {\n return { allowed: false, reason: `Script validation failed: ${validation.errors.join('; ')}` };\n }\n if (validation.digest !== request.digest) {\n return { allowed: false, reason: 'Digest mismatch between loader and validated source' };\n }\n const admission = admitScript({\n script: validation,\n authorTrust: config.authorTrust,\n requestedInterfaces: config.requestedInterfaces,\n expectedCheckpointDigest: config.expectedCheckpointDigest,\n checkpointApiVersion: config.checkpointApiVersion,\n });\n if (!admission.admitted) {\n return { allowed: false, reason: admission.reason };\n }\n if (config.expectedCheckpointDigest !== undefined && !admission.checkpointCompatible) {\n return {\n allowed: false,\n reason: 'Checkpoint is incompatible with this script digest/API version; an explicit converter or restart policy is required',\n };\n }\n const runtimeClass = selectRuntimeClass(config.authorTrust, config.availableRuntimeClasses);\n return {\n allowed: true,\n trustClass: config.authorTrust,\n runtimeClass: runtimeClass.runtimeClass,\n checkpointCompatible: admission.checkpointCompatible,\n };\n },\n };\n}\n\n// ─── Agent-facing deployment client (plan 24.14) ───────────────────────\n\n/**\n * Host-bound configuration for {@link createScriptDeploymentClient}.\n * Trust and interface ceilings come from the host, never from the calling\n * script — a script cannot elevate its own trust class or widen the\n * interface set beyond what the host configured.\n */\nexport interface ScriptDeploymentClientConfig {\n /** Trust class the host assigns to deployments from this context. */\n authorTrust: ScriptTrustClass;\n /**\n * Interface ceiling for deployments (defaults to the widest set\n * admissible for `authorTrust`). Scripts may request a narrower subset;\n * anything wider is rejected by admission.\n */\n requestedInterfaces?: string[];\n /** RuntimeClass names available for selection (defaults to all built-ins). */\n availableRuntimeClasses?: string[];\n /** Artifact persistence port; when omitted manifests are built but not persisted. */\n artifactStore?: ScriptArtifactStore;\n /** Default namespace for produced ArtifactRecords and deployments. */\n namespace?: string;\n /**\n * Orchestration facade. When present, `deploy` also applies an\n * AgentWorkload so the scheduler binds a node (plan 24.14); when absent,\n * `deploy` only produces the deployment request and the readiness/deletion\n * methods reject with UNSUPPORTED.\n */\n orchestration?: AgentOrchestrationClient;\n /** Field manager for applied workloads (default `memeloop/script-deployment`). */\n fieldManager?: string;\n}\n\n/** Request a script makes through the deployment client. */\nexport interface ScriptDeploymentClientRequest {\n /** Raw generated `.mjs` source (normalized internally). */\n source: string;\n /** Desired lifecycle for the remote workload. */\n lifecycle: 'run-once' | 'service' | 'schedule';\n /** Optional narrower interface subset (must stay within the host ceiling). */\n requestedInterfaces?: string[];\n /** Node selector for scheduling. */\n nodeSelector?: Record<string, string>;\n /** Environment variables (never credentials). */\n env?: Record<string, string>;\n /** Network attachment requirements for the deployed workload. */\n networkPolicy?: AgentWorkloadNetworkPolicy;\n /** Existing volume claims required by the deployed workload. */\n storagePolicy?: AgentWorkloadStoragePolicy;\n /** Optional checkpoint digest the script expects to resume from. */\n expectedCheckpointDigest?: string;\n /** API version of the expected checkpoint (plan 24.19). */\n checkpointApiVersion?: string;\n /** Namespace override (defaults to the configured namespace). */\n namespace?: string;\n}\n\n/** Agent-facing handle for declarative script deployment (plan 24.14). */\nexport interface ScriptDeploymentClient {\n /**\n * Validate, admit, persist, and package a generated script as a\n * {@link RemoteDeploymentRequest} referencing its ArtifactRecord by\n * digest. When an orchestration facade is configured, also applies the\n * AgentWorkload so the scheduler binds a node. Never throws for\n * script-content problems — inadmissible scripts yield `deployed: false`\n * with a structured reason.\n */\n deploy(request: ScriptDeploymentClientRequest): Promise<ScriptDeploymentResult>;\n /**\n * Wait until the scheduler has bound the deployment's workload\n * (`Scheduled=True` condition written by the binding controller).\n */\n waitForScheduled(\n name: string,\n options?: WaitForConditionOptions & { namespace?: string },\n ): Promise<{ observedResourceVersion: string; matched: true }>;\n /** Delete the deployment's workload. */\n deleteDeployment(name: string, namespace?: string): Promise<void>;\n}\n\n/**\n * Create the Agent-facing deployment client injected into `.mjs` scripts\n * as `ctx.scriptClient` (plan 24.14). The script declares placement and\n * lifecycle; trust, interface ceilings, and persistence are bound by the\n * host. The scheduler — not the script — selects the target node.\n */\nexport function createScriptDeploymentClient(config: ScriptDeploymentClientConfig): ScriptDeploymentClient {\n const interfaceCeiling = config.requestedInterfaces ?? defaultRequestedInterfacesForTrustClass(config.authorTrust);\n\n function requireOrchestration(): AgentOrchestrationClient {\n if (!config.orchestration) {\n throw new OrchestrationError({\n code: 'UNSUPPORTED',\n message: 'script deployment scheduling requires a host-configured orchestration facade',\n retryable: false,\n });\n }\n return config.orchestration;\n }\n\n return {\n async deploy(request) {\n const result = await deployGeneratedScript(\n {\n source: request.source,\n authorTrust: config.authorTrust,\n requestedInterfaces: request.requestedInterfaces ?? interfaceCeiling,\n lifecycle: request.lifecycle,\n nodeSelector: request.nodeSelector,\n env: request.env,\n networkPolicy: request.networkPolicy,\n storagePolicy: request.storagePolicy,\n expectedCheckpointDigest: request.expectedCheckpointDigest,\n checkpointApiVersion: request.checkpointApiVersion,\n namespace: request.namespace ?? config.namespace,\n },\n {\n artifactStore: config.artifactStore,\n availableRuntimeClasses: config.availableRuntimeClasses,\n },\n );\n\n if (result.deployed && result.deployment && config.orchestration) {\n const manifest = remoteDeploymentToWorkloadManifest(result.deployment, {\n namespace: request.namespace ?? config.namespace,\n });\n const workload = await config.orchestration.apply<typeof manifest.spec>(manifest, {\n idempotencyKey: result.deployment.artifactRef.contentDigest,\n fieldManager: config.fieldManager ?? 'memeloop/script-deployment',\n });\n return { ...result, workload: workload as AgentWorkloadResource };\n }\n return result;\n },\n\n async waitForScheduled(name, options = {}) {\n const orchestration = requireOrchestration();\n const { namespace, ...waitOptions } = options;\n return waitForCondition(\n () =>\n orchestration.get({\n apiVersion: AGENT_WORKLOAD_API_VERSION,\n kind: AGENT_WORKLOAD_KIND,\n name,\n namespace: namespace ?? config.namespace,\n }),\n { type: 'Scheduled', status: 'True' },\n waitOptions,\n );\n },\n\n async deleteDeployment(name, namespace) {\n const orchestration = requireOrchestration();\n await orchestration.delete({\n apiVersion: AGENT_WORKLOAD_API_VERSION,\n kind: AGENT_WORKLOAD_KIND,\n name,\n namespace: namespace ?? config.namespace,\n });\n },\n };\n}\n","// Generated by scripts/generate-loop-sources.mjs. Edit the sibling .mjs files instead.\n\nexport const AgentAgentLoopArtifactResourceLifecycleScriptId = 'builtin:agent-agent-loop/artifact-resource-lifecycle';\nexport const AgentAgentLoopDeclarativeAgentRunScriptId = 'builtin:agent-agent-loop/declarative-agent-run';\nexport const AgentAgentLoopQualityGateScriptId = 'builtin:agent-agent-loop/quality-gate';\n\nexport const BUILTIN_AGENT_AGENT_LOOP_ARTIFACT_RESOURCE_LIFECYCLE_SCRIPT_ID = AgentAgentLoopArtifactResourceLifecycleScriptId;\nexport const BUILTIN_AGENT_AGENT_LOOP_DECLARATIVE_AGENT_RUN_SCRIPT_ID = AgentAgentLoopDeclarativeAgentRunScriptId;\nexport const BUILTIN_AGENT_AGENT_LOOP_QUALITY_GATE_SCRIPT_ID = AgentAgentLoopQualityGateScriptId;\n\nexport const builtinAgentAgentLoopSources: Readonly<Record<string, string>> = {\n [AgentAgentLoopArtifactResourceLifecycleScriptId]: [\n '// @ts-check',\n '',\n 'function resourceName(value) {',\n ' const normalized = value.toLowerCase().replace(/[^a-z0-9-]+/g, \"-\").replace(/^-+|-+$/g, \"\");',\n ' return (normalized || \"artifact\").slice(0, 56);',\n '}',\n '',\n \"/** @param {import('../../loopAPI/agent-agent-loop/loop.js').AgentAgentScriptContext} ctx */\",\n 'export default async function run(ctx) {',\n ' if (!ctx.orchestration) {',\n ' throw new Error(\"artifact-resource-lifecycle requires the orchestration resource facade\");',\n ' }',\n '',\n ' const metadata = ctx.profile?.metadata ?? {};',\n ' const contentHash = typeof metadata.contentHash === \"string\"',\n ' ? metadata.contentHash',\n ' : \"sha256:0000000000000000000000000000000000000000000000000000000000000000\";',\n ' const artifactName = resourceName(`script-${ctx.input.conversationId}`);',\n ' const query = {',\n ' apiVersion: \"artifacts.memeloop.io/v1alpha1\",',\n ' kind: \"ArtifactRecord\",',\n ' namespace: \"default\",',\n ' };',\n ' const abortController = new AbortController();',\n ' const events = ctx.orchestration.watch(query, {',\n ' resourceVersion: \"0\",',\n ' sendInitialEvents: true,',\n ' allowBookmarks: true,',\n ' timeoutMs: 5_000,',\n ' signal: abortController.signal,',\n ' })[Symbol.asyncIterator]();',\n ' const nextEvent = events.next();',\n '',\n ' try {',\n ' const artifact = await ctx.orchestration.apply({',\n ' apiVersion: query.apiVersion,',\n ' kind: query.kind,',\n ' metadata: {',\n ' name: artifactName,',\n ' namespace: query.namespace,',\n ' labels: { \"memeloop.io/artifact-purpose\": \"generated-script\" },',\n ' },',\n ' spec: {',\n ' contentHash,',\n ' mimeType: \"text/javascript\",',\n ' producer: { trust: \"restricted\" },',\n ' trust: \"restricted\",',\n ' },',\n ' }, {',\n ' fieldManager: \"agent-agent-script-example\",',\n ' idempotencyKey: `${ctx.input.conversationId}:artifact`,',\n ' });',\n '',\n ' const observed = await nextEvent;',\n ' if (observed.done || observed.value.type !== \"ADDED\") {',\n ' throw new Error(\"artifact watch ended before observing the created resource\");',\n ' }',\n '',\n ' const reference = {',\n ' apiVersion: artifact.apiVersion,',\n ' kind: artifact.kind,',\n ' name: artifact.metadata.name,',\n ' namespace: artifact.metadata.namespace,',\n ' uid: artifact.metadata.uid,',\n ' };',\n ' const fetched = await ctx.orchestration.get(reference, {',\n ' resourceVersion: artifact.metadata.resourceVersion,',\n ' });',\n ' const listed = await ctx.orchestration.list(query, {',\n ' resourceVersion: artifact.metadata.resourceVersion,',\n ' resourceVersionMatch: \"not-older-than\",',\n ' limit: 10,',\n ' });',\n ' if (!fetched || !listed.items.some((item) => item.metadata.uid === artifact.metadata.uid)) {',\n ' throw new Error(\"created artifact was not readable through the resource facade\");',\n ' }',\n '',\n ' await ctx.orchestration.delete(reference, {',\n ' idempotencyKey: `${ctx.input.conversationId}:artifact-delete`,',\n ' preconditions: {',\n ' uid: artifact.metadata.uid,',\n ' resourceVersion: artifact.metadata.resourceVersion,',\n ' },',\n ' });',\n ' ctx.finish(`verified artifact lifecycle ${artifact.metadata.name}@${observed.value.resourceVersion}`);',\n ' } finally {',\n ' abortController.abort();',\n ' await events.return?.();',\n ' }',\n '}',\n '',\n ].join('\\n'),\n [AgentAgentLoopDeclarativeAgentRunScriptId]: [\n '// @ts-check',\n '',\n 'function resourceName(value) {',\n ' const normalized = value.toLowerCase().replace(/[^a-z0-9-]+/g, \"-\").replace(/^-+|-+$/g, \"\");',\n ' return (normalized || \"agent-run\").slice(0, 48);',\n '}',\n '',\n \"/** @param {import('../../loopAPI/agent-agent-loop/loop.js').AgentAgentScriptContext} ctx */\",\n 'export default async function run(ctx) {',\n ' if (!ctx.agentClient) {',\n ' throw new Error(\"declarative-agent-run requires the orchestration resource facade\");',\n ' }',\n '',\n ' const metadata = ctx.profile?.metadata ?? {};',\n ' const childProfileId = typeof metadata.childProfileId === \"string\"',\n ' ? metadata.childProfileId',\n ' : ctx.agents[0]?.profileId;',\n ' if (!childProfileId) {',\n ' throw new Error(\"declarative-agent-run requires metadata.childProfileId or one configured agent\");',\n ' }',\n '',\n ' const baseName = resourceName(`child-${ctx.input.conversationId}`);',\n ' const workloadName = `${baseName}-workload`;',\n ' const runName = `${baseName}-run`;',\n ' const workload = await ctx.agentClient.createWorkload({',\n ' name: workloadName,',\n ' profileId: childProfileId,',\n ' promptReference: `conversation:${ctx.input.conversationId}:input`,',\n ' trust: \"restricted\",',\n ' placement: {',\n ' nodeSelector: { \"memeloop.io/worker-pool\": \"restricted\" },',\n ' antiAffinity: [ctx.input.conversationId],',\n ' },',\n ' modelPolicy: {',\n ' modelClass: \"local-model\",',\n ' budget: { maxTokens: 8_192 },',\n ' },',\n ' toolPolicy: {',\n ' defaultAction: \"deny\",',\n ' allowedToolClasses: [\"read-only\"],',\n ' },',\n ' networkPolicy: {',\n ' networkClass: \"restricted-egress\",',\n ' egress: \"restricted\",',\n ' },',\n ' storagePolicy: {',\n ' storageClass: \"ephemeral\",',\n ' },',\n ' completionPolicy: \"complete\",',\n ' idempotencyKey: `${ctx.input.conversationId}:workload`,',\n ' });',\n ' const agentRun = await ctx.agentClient.createRun({',\n ' name: runName,',\n ' workloadName: workload.metadata.name,',\n ' workloadNamespace: workload.metadata.namespace,',\n ' promptReference: `conversation:${ctx.input.conversationId}:input`,',\n ' timeoutMs: 120_000,',\n ' idempotencyKey: `${ctx.input.conversationId}:run`,',\n ' });',\n '',\n ' if (metadata.waitForCompletion === true) {',\n ' await ctx.agentClient.waitForRunCondition(',\n ' agentRun.metadata.name,',\n ' { type: \"Completed\", status: \"True\" },',\n ' { timeout: 5_000, interval: 100 },',\n ' );',\n ' }',\n '',\n ' ctx.finish(`scheduled ${workload.metadata.name}/${agentRun.metadata.name}`);',\n '}',\n '',\n ].join('\\n'),\n [AgentAgentLoopQualityGateScriptId]: [\n '// @ts-check',\n '',\n 'function positiveInteger(value, fallback) {',\n ' const number = Number(value);',\n ' return Number.isFinite(number) && number > 0 ? Math.floor(number) : fallback;',\n '}',\n '',\n 'function asEntries(value, fallback) {',\n ' return Array.isArray(value) && value.length > 0 ? value : fallback;',\n '}',\n '',\n 'function withConversationIds(ctx, entries, phase, iteration) {',\n ' return entries.map((entry, index) => {',\n ' const record = typeof entry === \"string\" ? { profile: entry } : entry;',\n ' return {',\n ' ...record,',\n ' conversationId:',\n ' record.conversationId ?? `${ctx.input.conversationId}:${phase}:${iteration}:${index}`,',\n ' };',\n ' });',\n '}',\n '',\n 'function resultText(ctx, result) {',\n ' return result.text || ctx.formatAgentResults(result, { includeFailureSection: true });',\n '}',\n '',\n 'function reviewText(ctx, result) {',\n ' return ctx.formatAgentResults(result, { includeFailureSection: true });',\n '}',\n '',\n 'function approved(result) {',\n ' return (',\n ' result.failures.length === 0 &&',\n ' result.results.length > 0 &&',\n ' result.results.every((item) => /^\\\\s*APPROVED\\\\b/imu.test(item.text))',\n ' );',\n '}',\n '',\n 'function feedbackBlock(ctx, history) {',\n ' if (history.length === 0) return \"No prior review feedback.\";',\n ' return history',\n ' .map((entry) =>',\n ' [',\n ' `Iteration ${entry.iteration}`,',\n ' `Attempt:\\\\n${resultText(ctx, entry.attempt)}`,',\n ' `Review:\\\\n${reviewText(ctx, entry.review)}`,',\n ' ].join(\"\\\\n\\\\n\"),',\n ' )',\n ' .join(\"\\\\n\\\\n---\\\\n\\\\n\");',\n '}',\n '',\n 'function workerPrompt(ctx, goal, iteration, previousAttempt, history) {',\n ' if (!previousAttempt) return goal;',\n ' return [',\n ' \"Continue working on the original goal until the reviewer can approve it.\",',\n ' \"Do not summarize the review. Produce the corrected deliverable itself.\",',\n ' `Original goal:\\\\n${goal}`,',\n ' `Previous deliverable:\\\\n${resultText(ctx, previousAttempt)}`,',\n ' `Review history:\\\\n${feedbackBlock(ctx, history)}`,',\n ' `This is revision attempt ${iteration}.`,',\n ' ].join(\"\\\\n\\\\n\");',\n '}',\n '',\n 'function reviewPrompt(ctx, goal, attempt, history) {',\n ' return [',\n ' \"You are the quality gate for this delegated agent run.\",',\n ' \"Return APPROVED on the first line only when the deliverable fully satisfies the original goal and is ready to send to the user.\",',\n ' \"Return REVISE on the first line when more work is required, followed by concrete blocking issues and exact changes needed.\",',\n ' \"Do not approve partial progress.\",',\n ' `Original goal:\\\\n${goal}`,',\n ' `Candidate deliverable:\\\\n${resultText(ctx, attempt)}`,',\n ' `Earlier review history:\\\\n${feedbackBlock(ctx, history)}`,',\n ' ].join(\"\\\\n\\\\n\");',\n '}',\n '',\n 'async function runBatch(ctx, mode, input) {',\n ' return mode === \"sequential\" ? ctx.runSequential(input) : ctx.runParallel(input);',\n '}',\n '',\n \"/** @param {import('../../loopAPI/agent-agent-loop/loop.js').AgentAgentScriptContext} ctx */\",\n 'export default async function run(ctx) {',\n ' const metadata = ctx.profile?.metadata ?? {};',\n ' const goal = ctx.input.message;',\n ' const maxIterations = positiveInteger(metadata.maxIterations, 4);',\n ' const mode = metadata.mode === \"sequential\" ? \"sequential\" : \"parallel\";',\n ' const reviewMode = metadata.reviewMode === \"sequential\" ? \"sequential\" : \"parallel\";',\n ' const defaultAgents = ctx.getAgentEntries(\"agents\");',\n ' const workers = asEntries(',\n ' ctx.getAgentEntries(\"workers\"),',\n ' asEntries(ctx.getAgentEntries(\"draftAgents\"), defaultAgents),',\n ' );',\n ' const reviewers = asEntries(',\n ' ctx.getAgentEntries(\"reviewers\"),',\n ' asEntries(ctx.getAgentEntries(\"reviewAgents\"), defaultAgents),',\n ' );',\n ' const fixers = asEntries(',\n ' ctx.getAgentEntries(\"fixers\"),',\n ' asEntries(ctx.getAgentEntries(\"revisionAgents\"), workers),',\n ' );',\n ' const history = [];',\n ' let attempt;',\n '',\n ' if (workers.length === 0 || reviewers.length === 0) {',\n ' ctx.finish(',\n ' \"AgentAgent quality gate requires worker and reviewer agents. Configure metadata.workers/reviewers or metadata.agents.\",',\n ' );',\n ' return;',\n ' }',\n '',\n ' for (let iteration = 1; iteration <= maxIterations; iteration += 1) {',\n ' if (ctx.isCancelled()) break;',\n ' const activeWorkers = iteration === 1 ? workers : fixers;',\n ' const attemptKey = `quality-gate:${iteration}:attempt`;',\n ' const previousAttempt = attempt;',\n ' const savedAttempt = await ctx.loadCheckpoint(attemptKey);',\n ' if (savedAttempt) {',\n ' attempt = savedAttempt;',\n ' } else {',\n ' ctx.emit({',\n ' type: \"thinking\",',\n ' data: { status: \"quality-gate-work\", conversationId: ctx.input.conversationId, iteration },',\n ' });',\n ' attempt = await runBatch(ctx, mode, {',\n ' agents: withConversationIds(ctx, activeWorkers, \"work\", iteration),',\n ' prompt: workerPrompt(ctx, goal, iteration, previousAttempt, history),',\n ' });',\n ' await ctx.checkpoint(attemptKey, attempt);',\n ' }',\n '',\n ' if (attempt.failures.length > 0 && attempt.results.length === 0) {',\n ' history.push({',\n ' iteration,',\n ' attempt,',\n ' review: { results: [], failures: attempt.failures, text: \"\" },',\n ' });',\n ' continue;',\n ' }',\n '',\n ' const reviewKey = `quality-gate:${iteration}:review`;',\n ' let review = await ctx.loadCheckpoint(reviewKey);',\n ' if (!review) {',\n ' ctx.emit({',\n ' type: \"thinking\",',\n ' data: {',\n ' status: \"quality-gate-review\",',\n ' conversationId: ctx.input.conversationId,',\n ' iteration,',\n ' },',\n ' });',\n ' review = await runBatch(ctx, reviewMode, {',\n ' agents: withConversationIds(ctx, reviewers, \"review\", iteration),',\n ' prompt: reviewPrompt(ctx, goal, attempt, history),',\n ' });',\n ' await ctx.checkpoint(reviewKey, review);',\n ' }',\n ' history.push({ iteration, attempt, review });',\n '',\n ' if (approved(review)) {',\n ' ctx.finish(resultText(ctx, attempt));',\n ' return;',\n ' }',\n ' }',\n '',\n ' ctx.finish(',\n ' [',\n ' \"Quality gate did not approve the delegated work before the iteration limit.\",',\n ' attempt ? resultText(ctx, attempt) : \"No deliverable was produced.\",',\n ' \"Review trail:\",',\n ' feedbackBlock(ctx, history),',\n ' ]',\n ' .filter(Boolean)',\n ' .join(\"\\\\n\\\\n\"),',\n ' );',\n '}',\n '',\n ].join('\\n'),\n};\n\nexport function getBuiltinAgentAgentLoopSource(id: string): string | undefined {\n return builtinAgentAgentLoopSources[id];\n}\n","/**\n * Agent loop script loader (plan 24.15: source is never imported directly\n * from an LLM string without passing the admission chain).\n *\n * Loading rules:\n * - Builtin loop sources are allowlisted by content digest at startup\n * ({@link registerBuiltinScriptSources}); they load with zero gate overhead.\n * - Any other source-bearing reference (`source` refs and `data:` URLs) must\n * pass the host-injected {@link ScriptLoadGate}: validate (AST) → admit\n * (trust-class policy) → only then `import()`.\n * - When no gate is configured, all non-builtin sources are DENIED\n * (fail-closed) with a structured {@link ScriptLoadDeniedError}.\n *\n * Admission results (trust class, RuntimeClass, checkpoint compatibility)\n * are attached to the loaded script via {@link LOADED_SCRIPT_METADATA} so\n * hosts can enforce sandboxing.\n */\n\nimport { digestNormalizedScript, normalizeScript } from '../orchestration/scripts/scriptValidation.js';\nimport type { AgentLoopScriptPolicy, LoopProfileScriptReference, ScriptLoadGate } from './types.js';\n\nexport type AgentLoopScriptReference = string | LoopProfileScriptReference;\n\nexport interface LoadAgentLoopScriptOptions extends AgentLoopScriptPolicy {\n getBuiltinScriptSource?: (id: string) => string | undefined;\n scriptType?: string;\n}\n\nconst DEFAULT_POLICY = {\n allowBuiltin: true,\n allowFile: false,\n allowNetwork: false,\n allowSource: false,\n allowSpecifier: true,\n} as const;\n\n// ─── Loaded-script admission metadata ──────────────────────────────────\n\n/** Symbol under which the admission result is attached to a loaded script. */\nexport const LOADED_SCRIPT_METADATA: unique symbol = Symbol('memeloop.loadedScriptMetadata');\n\n/** Admission metadata attached to every source-loaded script. */\nexport interface LoadedScriptMetadata {\n /** Canonical SHA-256 hex digest of the normalized source. */\n digest: string;\n /** True when the digest matched the builtin allowlist (first-party code). */\n builtin: boolean;\n /** Trust class assigned by admission (plan 24.17). */\n trustClass?: string;\n /** RuntimeClass name the host must enforce for this script (plan 24.18). */\n runtimeClass?: string;\n /** Whether the script may resume its expected checkpoint (plan 24.19). */\n checkpointCompatible?: boolean;\n}\n\ntype LoadedScriptFunction = (...arguments_: never[]) => unknown;\n\nfunction isLoadedScriptFunction(value: unknown): value is LoadedScriptFunction {\n return typeof value === 'function';\n}\n\n/**\n * Read the admission metadata attached to a loaded script, or `undefined`\n * when the script was provided directly (not loaded through this module).\n */\nexport function getLoadedScriptMetadata(script: unknown): LoadedScriptMetadata | undefined {\n if (!isLoadedScriptFunction(script)) return undefined;\n return (script as unknown as Record<PropertyKey, unknown>)[LOADED_SCRIPT_METADATA] as LoadedScriptMetadata | undefined;\n}\n\nfunction attachLoadedScriptMetadata(script: LoadedScriptFunction, metadata: LoadedScriptMetadata): void {\n // Module-level caching means the same function object can be returned for\n // repeated loads of an identical specifier; the metadata is derived from\n // the source digest, so re-attaching is unnecessary.\n if (getLoadedScriptMetadata(script) !== undefined) return;\n Object.defineProperty(script, LOADED_SCRIPT_METADATA, {\n value: metadata,\n enumerable: false,\n configurable: false,\n writable: false,\n });\n}\n\n// ─── Builtin digest allowlist ──────────────────────────────────────────\n\nconst builtinScriptDigests = new Set<string>();\n\n/**\n * Register pre-computed digests of first-party builtin loop sources.\n * Idempotent; hosts typically use {@link registerBuiltinScriptSources}.\n */\nexport function registerBuiltinScriptDigests(digests: Iterable<string>): void {\n for (const digest of digests) {\n builtinScriptDigests.add(digest);\n }\n}\n\n/**\n * Compute canonical digests for builtin loop sources and register them in\n * the startup allowlist. Returns the registered digests.\n */\nexport async function registerBuiltinScriptSources(sources: Record<string, string>): Promise<string[]> {\n const digests: string[] = [];\n for (const source of Object.values(sources)) {\n digests.push(await digestNormalizedScript(normalizeScript(source)));\n }\n registerBuiltinScriptDigests(digests);\n return digests;\n}\n\n/** Check whether a canonical digest belongs to a registered builtin source. */\nexport function isRegisteredBuiltinScriptDigest(digest: string): boolean {\n return builtinScriptDigests.has(digest);\n}\n\n// ─── Denial error ──────────────────────────────────────────────────────\n\n/** Structured error thrown when the script load gate denies a source. */\nexport class ScriptLoadDeniedError extends Error {\n readonly code = 'SCRIPT_LOAD_DENIED' as const;\n\n constructor(\n /** Canonical digest of the denied script. */\n readonly digest: string,\n /** Reason reported by the gate. */\n readonly gateReason: string,\n ) {\n super(`Agent loop script load denied (sha256:${digest}): ${gateReason}`);\n this.name = 'ScriptLoadDeniedError';\n }\n}\n\n/**\n * Default gate used when the host provides none: denies every non-builtin\n * script source (fail-closed, plan 24.15).\n */\nexport const FAIL_CLOSED_SCRIPT_LOAD_GATE: ScriptLoadGate = {\n admitScriptLoad: () => ({\n allowed: false,\n reason: 'No script load gate configured; non-builtin script sources are denied by default (fail-closed)',\n }),\n};\n\n// ─── Helpers ───────────────────────────────────────────────────────────\n\nfunction getExportedScript(moduleExports: unknown): unknown {\n if (typeof moduleExports === 'function') return moduleExports;\n if (!moduleExports || typeof moduleExports !== 'object') return undefined;\n\n const record = moduleExports as Record<string, unknown>;\n return record.default ?? record.run;\n}\n\nfunction sourceToDataSpecifier(source: string, name = 'agent-loop-script.mjs'): string {\n return `data:text/javascript;charset=utf-8,${encodeURIComponent(`${source}\\n//# sourceURL=${name}`)}`;\n}\n\nfunction normalizeScriptReference(scriptReference: AgentLoopScriptReference): LoopProfileScriptReference {\n if (typeof scriptReference !== 'string') return scriptReference;\n if (scriptReference.startsWith('builtin:')) return { kind: 'builtin', id: scriptReference };\n return { kind: 'specifier', specifier: scriptReference };\n}\n\nfunction isFileSpecifier(specifier: string): boolean {\n return specifier.startsWith('file:') || specifier.startsWith('/') || specifier.startsWith('./') || specifier.startsWith('../');\n}\n\nfunction isNetworkSpecifier(specifier: string): boolean {\n return specifier.startsWith('http:') || specifier.startsWith('https:');\n}\n\nfunction isSourceSpecifier(specifier: string): boolean {\n return specifier.startsWith('data:text/javascript') || specifier.startsWith('data:application/javascript');\n}\n\n/**\n * Decode the source carried by a `data:` script specifier. Returns\n * `undefined` when the payload cannot be decoded; callers must treat an\n * undecodable data URL as a denial (fail-closed).\n */\nfunction decodeDataScriptSpecifier(specifier: string): string | undefined {\n const commaIndex = specifier.indexOf(',');\n if (commaIndex < 0) return undefined;\n const metadata = specifier.slice('data:'.length, commaIndex);\n const payload = specifier.slice(commaIndex + 1);\n try {\n if (metadata.split(';').includes('base64')) {\n // atob is available in browsers and Node ≥ 16; no Buffer needed.\n return atob(payload);\n }\n return decodeURIComponent(payload);\n } catch {\n return undefined;\n }\n}\n\nfunction assertSpecifierAllowed(specifier: string, policy: Required<Pick<LoadAgentLoopScriptOptions, 'allowFile' | 'allowNetwork' | 'allowSource' | 'allowSpecifier'>>): void {\n if (!policy.allowSpecifier) {\n throw new Error('Agent loop script import specifiers are disabled by policy.');\n }\n if (isSourceSpecifier(specifier) && !policy.allowSource) {\n throw new Error('Agent loop script source/data URLs are disabled by policy.');\n }\n if (isFileSpecifier(specifier) && !policy.allowFile) {\n throw new Error('Agent loop script file imports are disabled by policy.');\n }\n if (isNetworkSpecifier(specifier) && !policy.allowNetwork) {\n throw new Error('Agent loop script network imports are disabled by policy.');\n }\n}\n\n/**\n * Load an agent loop script. Source-bearing references (builtin sources,\n * `source` refs, `data:` URLs) are admitted by content digest before\n * `import()`: builtin digests load directly, everything else must pass the\n * host's {@link ScriptLoadGate} and is denied when no gate is configured.\n */\nexport async function loadAgentLoopScript<TScript>(\n scriptReference: AgentLoopScriptReference,\n options: LoadAgentLoopScriptOptions = {},\n): Promise<TScript> {\n const policy = { ...DEFAULT_POLICY, ...options };\n const importModule = options.importModule ?? ((specifier: string) => import(specifier));\n const normalized = normalizeScriptReference(scriptReference);\n const scriptType = options.scriptType ?? 'Agent loop script';\n let scriptSpecifier: string;\n let sourceForAdmission: string | undefined;\n\n if (normalized.kind === 'builtin') {\n if (!policy.allowBuiltin) {\n throw new Error('Built-in agent loop scripts are disabled by policy.');\n }\n const source = options.getBuiltinScriptSource?.(normalized.id);\n if (!source) throw new Error(`Unknown built-in agent loop script: ${normalized.id}`);\n sourceForAdmission = source;\n scriptSpecifier = sourceToDataSpecifier(source, normalized.id);\n } else if (normalized.kind === 'source') {\n if (!policy.allowSource) {\n throw new Error('Agent loop script source strings are disabled by policy.');\n }\n sourceForAdmission = normalized.source;\n scriptSpecifier = sourceToDataSpecifier(normalized.source, normalized.name);\n } else {\n scriptSpecifier = normalized.specifier;\n assertSpecifierAllowed(scriptSpecifier, policy);\n if (isSourceSpecifier(scriptSpecifier)) {\n sourceForAdmission = decodeDataScriptSpecifier(scriptSpecifier);\n if (sourceForAdmission === undefined) {\n throw new ScriptLoadDeniedError('undecodable', 'data: script specifier payload could not be decoded');\n }\n }\n }\n\n // Admit source-bearing scripts by content digest before import().\n let metadata: LoadedScriptMetadata | undefined;\n if (sourceForAdmission !== undefined) {\n const normalizedSource = normalizeScript(sourceForAdmission);\n const digest = await digestNormalizedScript(normalizedSource);\n if (isRegisteredBuiltinScriptDigest(digest)) {\n // First-party builtin source: allowlisted by digest at startup.\n metadata = { digest, builtin: true, trustClass: 'trusted' };\n } else {\n const gate = options.scriptLoadGate ?? FAIL_CLOSED_SCRIPT_LOAD_GATE;\n const decision = await gate.admitScriptLoad({ normalizedSource, digest, reference: normalized, scriptType });\n if (!decision.allowed) {\n throw new ScriptLoadDeniedError(digest, decision.reason ?? 'denied by script load gate');\n }\n metadata = {\n digest,\n builtin: false,\n trustClass: decision.trustClass,\n runtimeClass: decision.runtimeClass,\n checkpointCompatible: decision.checkpointCompatible,\n };\n }\n }\n\n const moduleExports: unknown = await importModule(scriptSpecifier);\n const exportedScript = getExportedScript(moduleExports);\n\n if (!isLoadedScriptFunction(exportedScript)) {\n throw new TypeError(\n `${scriptType} \"${scriptSpecifier}\" must export a default function or named run function.`,\n );\n }\n\n if (metadata) {\n attachLoadedScriptMetadata(exportedScript, metadata);\n }\n\n return exportedScript as TScript;\n}\n","import { builtinAgentAgentLoopSources, getBuiltinAgentAgentLoopSource } from '../../loops/agent-agent-loop/builtinLoopSources.js';\nimport { type AgentLoopScriptReference, loadAgentLoopScript, registerBuiltinScriptSources } from '../scriptLoader.js';\nimport type { AgentLoopScriptPolicy } from '../types.js';\nimport type { AgentAgentLoopScript } from './loop.js';\n\nexport type LoadAgentAgentLoopScriptOptions = AgentLoopScriptPolicy;\n\nexport type AgentAgentLoopScriptReference = AgentLoopScriptReference;\n\nlet builtinDigestsRegistered: Promise<unknown> | undefined;\n\n/**\n * Register the first-party builtin loop sources in the digest allowlist\n * once, so builtin scripts load without gate overhead while every other\n * source must pass the script load gate (plan 24.15).\n */\nfunction ensureBuiltinDigestsRegistered(): Promise<unknown> {\n builtinDigestsRegistered ??= registerBuiltinScriptSources(builtinAgentAgentLoopSources);\n return builtinDigestsRegistered;\n}\n\nexport async function loadAgentAgentLoopScript(\n scriptReference: AgentAgentLoopScriptReference,\n options: LoadAgentAgentLoopScriptOptions = {},\n): Promise<AgentAgentLoopScript> {\n await ensureBuiltinDigestsRegistered();\n return loadAgentLoopScript<AgentAgentLoopScript>(scriptReference, {\n ...options,\n getBuiltinScriptSource: getBuiltinAgentAgentLoopSource,\n scriptType: 'AgentAgentLoop script',\n });\n}\n","/**\n * AgentAgent_Loop — a loop that orchestrates child agents.\n *\n * This loop does NOT call the LLM directly. Instead it coordinates child agents:\n * - running a child agent and feeding its result to another child agent (review / verify)\n * - splitting work across multiple parallel child agents\n * - looping back to a child agent with feedback when a reviewer rejects the output\n *\n * The loop script (.mjs) holds the orchestration logic. This file provides the\n * runtime that invokes the script and manages child agent runs.\n */\n\nimport type { AgentClient, AgentOrchestrationClient, ScriptDeploymentClient } from '../../orchestration/index.js';\nimport { createAgentClient, createScriptDeploymentClient } from '../../orchestration/index.js';\nimport type { AgentLoopDefinition, AgentLoopGenerator, AgentLoopInput, AgentLoopRuntime, AgentLoopStep, LoopProfile } from '../types.js';\nimport { type AgentAgentLoopScriptReference, loadAgentAgentLoopScript, type LoadAgentAgentLoopScriptOptions } from './scriptLoader.js';\n\nconst LOOP_ID = 'agent-agent-loop';\nconst LOOP_NAME = 'AgentAgent Loop';\nconst LOOP_DESC = 'Orchestrates child agents to collaborate on a task. Supports sequential chaining, parallel execution, and feedback loops.';\n\n/**\n * Typed API passed to a AgentAgent `.mjs` script.\n *\n * The API is intentionally primitive: scripts decide the workflow shape, role\n * names, approval rules, retry limits, and delivery gates. This runtime only\n * handles child-agent execution, progress events, cancellation, state, and\n * checkpoints.\n */\nexport interface AgentAgentLoopScriptArguments {\n /** The parent turn input. `input.message` is the user's original goal. */\n input: AgentLoopInput;\n /** Host/runtime context for advanced integrations. Prefer the typed helpers below when possible. */\n context: AgentAgentLoopContext;\n /** Active profile. Scripts may define their own workflow-specific metadata keys here. */\n profile?: LoopProfile;\n /** Normalized worker agents read from `context.agents` or `profile.metadata.agents`. */\n agents: AgentAgentDescriptor[];\n /**\n * Read raw agent entries from `profile.metadata[key]`; defaults to `agents`.\n * This is deliberately generic so scripts can choose names like `critics`,\n * `builders`, `verifiers`, or any other workflow-specific role.\n */\n getAgentEntries: (key?: string) => AgentAgentConfigEntry[];\n /** Low-level runtime hooks. Prefer `state`, `checkpoint`, `emit`, and run helpers first. */\n runtime?: Partial<AgentLoopRuntime>;\n /** Policy-scoped declarative manager facade. It never exposes raw infrastructure drivers or secrets. */\n orchestration?: AgentOrchestrationClient;\n /** Typed convenience client for creating, reading, and deleting Agent workloads and runs. */\n agentClient?: AgentClient;\n /**\n * Declarative generated-script deployment (plan 24.14). The script declares\n * placement and lifecycle; trust, interface ceilings, and persistence are\n * host-bound. Undefined when the host provides no deployment configuration.\n */\n scriptClient?: ScriptDeploymentClient;\n /** Run one child agent and collect all yielded steps into a text result. */\n runAgent: (input: AgentAgentRunAgentInput) => Promise<AgentAgentRunAgentResult>;\n /** Run child agents concurrently. Use `runSequential` when order matters. */\n runAgents: (inputs: AgentAgentRunAgentInput[]) => Promise<AgentAgentRunAgentResult[]>;\n /** Run a batch of agents in order, aggregating successful output and failures. */\n runSequential: (input?: AgentAgentBatchRunInput) => Promise<AgentAgentBatchRunResult>;\n /** Run a batch of agents concurrently, aggregating successful output and failures. */\n runParallel: (input?: AgentAgentBatchRunInput) => Promise<AgentAgentBatchRunResult>;\n /** Format a batch result for final delivery or an intermediate report. */\n formatAgentResults: (result: AgentAgentBatchRunResult, options?: AgentAgentFormatResultsOptions) => string;\n /** Emit a formatted batch result as the parent loop's final/user-visible message. */\n finishAgentResults: (result: AgentAgentBatchRunResult, options?: AgentAgentFormatResultsOptions) => void;\n /** Emit a raw loop step upstream. Use sparingly; helpers already emit progress. */\n emit: (step: AgentLoopStep) => void;\n /** Emit a user-visible message or step and end the script's work. */\n finish: (message: string | AgentLoopStep) => void;\n /** True when the host cancelled this parent run. Long-running scripts should check this between phases. */\n isCancelled: () => boolean;\n /** Write an observability event through the host runtime logger. */\n log: (event: string, data?: Record<string, unknown>) => void;\n /** Per-run persistent state scoped by the host runtime. */\n state: AgentLoopRuntime['state'];\n /** Record a resumable milestone for long workflows. */\n checkpoint: AgentLoopRuntime['checkpoint'];\n /** Read a milestone recorded by an earlier process and skip completed work. */\n loadCheckpoint: AgentLoopRuntime['loadCheckpoint'];\n}\n\nexport type AgentAgentScriptContext = AgentAgentLoopScriptArguments;\n\nexport type AgentAgentContext = AgentAgentScriptContext;\n\nexport interface AgentAgentDescriptor {\n /** Child profile id to run. */\n profileId: string;\n /** Prompt override for this child run. Defaults to the parent input message. */\n prompt?: string;\n /** Conversation id override. Defaults to `${parent}:child:${index}` for batch helpers. */\n conversationId?: string;\n /** Optional human-readable role label, e.g. \"implementer\" or \"reviewer\". */\n label?: string;\n [key: string]: unknown;\n}\n\nexport type AgentAgentConfigEntry =\n | string\n | ({\n profileId?: string;\n profile?: string;\n prompt?: string;\n conversationId?: string;\n label?: string;\n } & Record<string, unknown>);\n\nexport interface AgentAgentRunAgentInput {\n /** Child profile id. `profile` is accepted as an ergonomic alias for scripts. */\n profileId?: string;\n profile?: string;\n /** Defaults to the parent input message. */\n prompt?: string;\n conversationId?: string;\n label?: string;\n}\n\nexport interface AgentAgentRunAgentResult {\n profileId: string;\n conversationId: string;\n steps: AgentLoopStep[];\n text: string;\n}\n\nexport interface AgentAgentRunAgentFailure {\n profileId: string;\n conversationId?: string;\n error: string;\n}\n\nexport interface AgentAgentBatchRunInput {\n /** Agents to run. Defaults to `ctx.agents`. */\n agents?: AgentAgentConfigEntry[];\n /** Prompt shared by every agent in this batch. Defaults to the parent input message. */\n prompt?: string;\n /** When false, the first child failure rejects the batch. Defaults to true. */\n continueOnError?: boolean;\n}\n\nexport interface AgentAgentBatchRunResult {\n results: AgentAgentRunAgentResult[];\n failures: AgentAgentRunAgentFailure[];\n text: string;\n}\n\nexport interface AgentAgentFormatResultsOptions {\n emptyMessage?: string;\n failureHeader?: string;\n includeFailureSection?: boolean;\n}\n\nexport type AgentAgentLoopScriptResult =\n | AgentLoopGenerator\n | AgentLoopStep\n | AgentLoopStep[]\n | string\n | undefined;\n\nexport type AgentAgentLoopScript = (\n scriptArguments: AgentAgentLoopScriptArguments,\n) => AgentAgentLoopScriptResult | Promise<AgentAgentLoopScriptResult>;\n\nexport interface AgentAgentLoopContext {\n [key: string]: unknown;\n profile?: LoopProfile;\n runtime?: Partial<AgentLoopRuntime>;\n agents?: AgentAgentConfigEntry[];\n script?: AgentAgentLoopScript;\n loadScript?: (\n script: AgentAgentLoopScriptReference,\n context: AgentAgentLoopContext,\n ) => AgentAgentLoopScript | Promise<AgentAgentLoopScript>;\n scriptPolicy?: LoadAgentAgentLoopScriptOptions;\n}\n\nfunction isAsyncIterable(value: unknown): value is AgentLoopGenerator {\n return Boolean(value && typeof value === 'object' && Symbol.asyncIterator in value);\n}\n\nfunction messageStep(message: string): AgentLoopStep {\n return { type: 'message', data: message };\n}\n\nfunction stepText(step: AgentLoopStep): string | undefined {\n if (step.type !== 'message') return undefined;\n if (typeof step.data === 'string') return step.data;\n if (step.data && typeof step.data === 'object' && 'content' in step.data) {\n const content = (step.data as { content?: unknown }).content;\n return typeof content === 'string' ? content : undefined;\n }\n return undefined;\n}\n\nfunction profileIdFromEntry(entry: AgentAgentConfigEntry): string | undefined {\n if (typeof entry === 'string') return entry;\n return entry.profileId ?? entry.profile;\n}\n\nfunction readProfileAgentEntries(profile?: LoopProfile, key = 'agents'): AgentAgentConfigEntry[] | undefined {\n const metadata = profile?.metadata;\n if (!metadata) return undefined;\n\n const entries = metadata[key];\n if (Array.isArray(entries)) return entries as AgentAgentConfigEntry[];\n\n return undefined;\n}\n\nfunction normalizeAgentAgents(\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n entries?: AgentAgentConfigEntry[],\n prompt?: string,\n): AgentAgentDescriptor[] {\n const configuredEntries = entries ?? context.agents ?? readProfileAgentEntries(context.profile) ?? [];\n return configuredEntries.flatMap((entry, index) => {\n const profileId = profileIdFromEntry(entry);\n if (!profileId) return [];\n const record = typeof entry === 'string' ? {} : entry;\n return {\n ...record,\n profileId,\n prompt: prompt ?? record.prompt,\n conversationId: record.conversationId ?? `${input.conversationId}:child:${index}`,\n label: record.label,\n };\n });\n}\n\nfunction formatAgentResults(\n result: AgentAgentBatchRunResult,\n options: AgentAgentFormatResultsOptions = {},\n): string {\n const emptyMessage = options.emptyMessage ?? 'No child agent output.';\n const failureHeader = options.failureHeader ?? 'Failed child agents:';\n const includeFailureSection = options.includeFailureSection !== false;\n const sections = [result.text || emptyMessage];\n\n if (includeFailureSection && result.failures.length > 0) {\n sections.push(`${failureHeader}\\n${result.failures.map(failure => `${failure.profileId}: ${failure.error}`).join('\\n')}`);\n }\n\n return sections.filter(Boolean).join('\\n\\n');\n}\n\nfunction createScriptArguments(\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n emittedSteps: AgentLoopStep[],\n): AgentAgentLoopScriptArguments {\n const agentEntries = context.agents ?? readProfileAgentEntries(context.profile) ?? [];\n const agents = normalizeAgentAgents(input, context, agentEntries);\n const getAgentEntries = (key = 'agents'): AgentAgentConfigEntry[] => {\n if (key === 'agents') return agentEntries;\n return readProfileAgentEntries(context.profile, key) ?? [];\n };\n\n const emit = (step: AgentLoopStep): void => {\n emittedSteps.push(step);\n context.runtime?.emit?.(step);\n };\n\n const log = (event: string, data?: Record<string, unknown>): void => {\n context.runtime?.log?.(event, data);\n };\n\n const isCancelled = (): boolean => context.runtime?.signal?.cancelled === true;\n\n // Monotonic counter for unique child conversation IDs across concurrent runs\n // of the same profile (24.57 collision fix).\n let childCounter = 0;\n\n const runAgent = async (childInput: AgentAgentRunAgentInput): Promise<AgentAgentRunAgentResult> => {\n if (isCancelled()) throw new Error('AgentAgent_Loop cancelled before child agent start');\n const profileId = childInput.profileId ?? childInput.profile;\n if (!profileId) throw new Error('ctx.runAgent requires profileId or profile');\n if (!context.runtime?.runChildAgent) throw new Error('ctx.runAgent requires runtime.runChildAgent');\n\n const childConversationId = childInput.conversationId ?? `${input.conversationId}:child:${profileId}:${++childCounter}`;\n const prompt = childInput.prompt ?? input.message;\n emit({\n type: 'thinking',\n data: { status: 'child-agent-started', profileId, conversationId: childConversationId },\n });\n\n const steps: AgentLoopStep[] = [];\n const chunks: string[] = [];\n try {\n for await (\n const step of context.runtime.runChildAgent({\n profileId,\n prompt,\n conversationId: childConversationId,\n })\n ) {\n if (isCancelled()) throw new Error('AgentAgent_Loop cancelled during child agent run');\n steps.push(step);\n const text = stepText(step);\n if (text) chunks.push(text);\n emit({\n type: 'thinking',\n data: { status: 'child-agent-step', profileId, conversationId: childConversationId, step },\n });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emit({\n type: 'thinking',\n data: { status: 'child-agent-failed', profileId, conversationId: childConversationId, error: message },\n });\n throw error;\n }\n\n emit({\n type: 'thinking',\n data: { status: 'child-agent-completed', profileId, conversationId: childConversationId },\n });\n return { profileId, conversationId: childConversationId, steps, text: chunks.join('').trim() };\n };\n\n const runBatch = async (\n batchInput: AgentAgentBatchRunInput | undefined,\n mode: 'parallel' | 'sequential',\n ): Promise<AgentAgentBatchRunResult> => {\n const batchAgents = normalizeAgentAgents(input, context, batchInput?.agents, batchInput?.prompt);\n const continueOnError = batchInput?.continueOnError !== false;\n const results: AgentAgentRunAgentResult[] = [];\n const failures: AgentAgentRunAgentFailure[] = [];\n\n const runOne = async (agent: AgentAgentDescriptor): Promise<void> => {\n if (isCancelled()) {\n emit({\n type: 'thinking',\n data: { status: 'cancelled', conversationId: input.conversationId },\n });\n return;\n }\n try {\n const result = await runAgent(agent);\n results.push(result);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n failures.push({ profileId: agent.profileId, conversationId: agent.conversationId, error: message });\n if (!continueOnError) throw error;\n }\n };\n\n if (mode === 'parallel') {\n await Promise.all(batchAgents.map(agent => runOne(agent)));\n } else {\n for (const agent of batchAgents) {\n await runOne(agent);\n if (isCancelled()) break;\n }\n }\n\n return { results, failures, text: results.map(result => result.text).filter(Boolean).join('\\n\\n') };\n };\n\n const agentClient = context.runtime?.orchestration ? createAgentClient(context.runtime.orchestration) : undefined;\n const scriptClient = context.runtime?.scriptDeployment ? createScriptDeploymentClient(context.runtime.scriptDeployment) : undefined;\n\n return {\n input,\n context,\n profile: context.profile,\n agents,\n getAgentEntries,\n runtime: context.runtime,\n orchestration: context.runtime?.orchestration,\n agentClient,\n scriptClient,\n runAgent,\n runAgents: inputs => Promise.all(inputs.map(runAgent)),\n runSequential: batchInput => runBatch(batchInput, 'sequential'),\n runParallel: batchInput => runBatch(batchInput, 'parallel'),\n formatAgentResults,\n finishAgentResults: (result, options) => {\n emit(messageStep(formatAgentResults(result, options)));\n },\n emit,\n finish: message => {\n emit(typeof message === 'string' ? messageStep(message) : message);\n },\n isCancelled,\n log,\n state: context.runtime?.state ?? {\n get: async () => undefined,\n set: async () => undefined,\n update: async () => undefined,\n },\n checkpoint: context.runtime?.checkpoint ?? (async () => undefined),\n loadCheckpoint: context.runtime?.loadCheckpoint ?? (async () => undefined),\n };\n}\n\nasync function* drainEmittedSteps(steps: AgentLoopStep[]): AgentLoopGenerator {\n while (steps.length > 0) {\n const step = steps.shift();\n if (step) yield step;\n }\n}\n\nasync function* runScript(\n script: AgentAgentLoopScript,\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n): AgentLoopGenerator {\n const emittedSteps: AgentLoopStep[] = [];\n const scriptArguments = createScriptArguments(input, context, emittedSteps);\n const result = await script(scriptArguments);\n\n yield* drainEmittedSteps(emittedSteps);\n if (isAsyncIterable(result)) {\n yield* result;\n yield* drainEmittedSteps(emittedSteps);\n } else if (typeof result === 'string') {\n yield messageStep(result);\n } else if (Array.isArray(result)) {\n yield* result;\n } else if (result) {\n yield result;\n }\n}\n\nfunction asAgentAgentContext(context: { [key: string]: unknown }): AgentAgentLoopContext {\n return context as AgentAgentLoopContext;\n}\n\nasync function resolveScript(\n context: AgentAgentLoopContext,\n): Promise<AgentAgentLoopScript | undefined> {\n if (context.script) return context.script;\n const scriptReference = context.profile?.scriptReference ?? context.profile?.scriptRef ?? context.profile?.script;\n if (scriptReference) {\n if (context.loadScript) return context.loadScript(scriptReference, context);\n return loadAgentAgentLoopScript(scriptReference, context.scriptPolicy);\n }\n return undefined;\n}\n\n/**\n * Create the AgentAgent_Loop definition and register it with the loop registry.\n */\nexport function createAgentAgentLoopDefinition(): AgentLoopDefinition {\n return {\n id: LOOP_ID,\n name: LOOP_NAME,\n description: LOOP_DESC,\n createRunner: (rawContext) => {\n return async function* agentAgentLoop(input) {\n const context = asAgentAgentContext(rawContext);\n const script = await resolveScript(context);\n\n yield {\n type: 'thinking',\n data: { status: 'agent-agent-loop-loop-started', conversationId: input.conversationId },\n };\n context.runtime?.log?.('agent-agent-loop-loop-started', {\n conversationId: input.conversationId,\n profileId: context.profile?.id,\n });\n\n if (script) {\n yield* runScript(script, input, context);\n yield {\n type: 'thinking',\n data: { status: 'completed', conversationId: input.conversationId },\n };\n return;\n }\n\n yield {\n type: 'thinking',\n data: { status: 'script-missing', conversationId: input.conversationId },\n };\n yield {\n type: 'message',\n data: 'AgentAgentLoop requires an explicit loop script. Configure profile.scriptReference or provide context.script.',\n };\n yield {\n type: 'thinking',\n data: { status: 'completed', conversationId: input.conversationId },\n };\n };\n },\n };\n}\n\n/** Export loop id for consumers. */\nexport function getAgentAgentLoopId(): string {\n return LOOP_ID;\n}\n","// Generated by scripts/generate-loop-sources.mjs. Edit the sibling .mjs files instead.\n\nexport const AgentToolLoopDefaultScriptId = 'builtin:agent-tool-loop/default';\n\nexport const BUILTIN_AGENT_TOOL_LOOP_DEFAULT_SCRIPT_ID = AgentToolLoopDefaultScriptId;\n\nexport const builtinAgentToolLoopSources: Readonly<Record<string, string>> = {\n [AgentToolLoopDefaultScriptId]: [\n '// @ts-check',\n '',\n \"/** @param {import('../../loopAPI/agent-tool-loop/loop.js').AgentToolLoopScriptContext} ctx */\",\n 'export default async function* run(ctx) {',\n ' const state = ctx.createState();',\n '',\n ' try {',\n ' const start = await ctx.startTurn(state);',\n ' if (start.step) yield start.step;',\n \" if (start.action === 'stop') return;\",\n '',\n ' while (true) {',\n ' const result = yield* ctx.runIteration(state);',\n \" if (result.action === 'stop') return;\",\n ' }',\n ' } catch (error) {',\n \" await ctx.stopTurn(state, 'error');\",\n ' throw error;',\n ' } finally {',\n ' await ctx.stopTurn(state);',\n ' }',\n '}',\n ].join('\\n'),\n};\n\nexport function getBuiltinAgentToolLoopSource(id: string): string | undefined {\n return builtinAgentToolLoopSources[id];\n}\n","import { builtinAgentToolLoopSources, getBuiltinAgentToolLoopSource } from '../../loops/agent-tool-loop/builtinLoopSources.js';\nimport { type AgentLoopScriptReference, loadAgentLoopScript, registerBuiltinScriptSources } from '../scriptLoader.js';\nimport type { AgentLoopScriptPolicy } from '../types.js';\nimport type { AgentToolLoopScript } from './loop.js';\n\nexport type LoadAgentToolLoopScriptOptions = AgentLoopScriptPolicy;\n\nexport type AgentToolLoopScriptReference = AgentLoopScriptReference;\n\nlet builtinDigestsRegistered: Promise<unknown> | undefined;\n\n/**\n * Register the first-party builtin loop sources in the digest allowlist\n * once, so builtin scripts load without gate overhead while every other\n * source must pass the script load gate (plan 24.15).\n */\nfunction ensureBuiltinDigestsRegistered(): Promise<unknown> {\n builtinDigestsRegistered ??= registerBuiltinScriptSources(builtinAgentToolLoopSources);\n return builtinDigestsRegistered;\n}\n\nexport async function loadAgentToolLoopScript(\n scriptReference: AgentToolLoopScriptReference,\n options: LoadAgentToolLoopScriptOptions = {},\n): Promise<AgentToolLoopScript> {\n await ensureBuiltinDigestsRegistered();\n return loadAgentLoopScript<AgentToolLoopScript>(scriptReference, {\n ...options,\n getBuiltinScriptSource: getBuiltinAgentToolLoopSource,\n scriptType: 'AgentToolLoop script',\n });\n}\n","import type { AgentLoopGenerator, AgentLoopInput, AgentLoopStep } from '../types.js';\nimport type { AgentToolLoopContext, AgentToolLoopScript, AgentToolLoopScriptContext } from './contracts.js';\nimport { loadAgentToolLoopScript } from './scriptLoader.js';\nimport { createAgentToolLoopState, runAgentToolLoopIteration, startAgentToolLoopTurn, stopAgentToolLoopTurn } from './turnPrimitives.js';\n\nfunction isAsyncIterable(value: unknown): value is AgentLoopGenerator {\n return Boolean(value && typeof value === 'object' && Symbol.asyncIterator in value);\n}\n\nfunction messageStep(message: string): AgentLoopStep {\n return { type: 'message', data: message };\n}\n\nasync function* drainEmittedSteps(steps: AgentLoopStep[]): AgentLoopGenerator {\n while (steps.length > 0) {\n const step = steps.shift();\n if (step) yield step;\n }\n}\n\nexport function asAgentToolLoopContext(rawContext: { [key: string]: unknown }): AgentToolLoopContext {\n return rawContext as unknown as AgentToolLoopContext;\n}\n\nexport async function resolveAgentToolLoopScript(context: AgentToolLoopContext): Promise<AgentToolLoopScript | undefined> {\n if (context.script) return context.script;\n const scriptReference = context.profile?.scriptReference ?? context.profile?.scriptRef ?? context.profile?.script;\n if (!scriptReference) return undefined;\n if (context.loadScript) return context.loadScript(scriptReference, context);\n return loadAgentToolLoopScript(scriptReference, context.scriptPolicy);\n}\n\nfunction createAgentToolLoopScriptContext(\n input: AgentLoopInput,\n context: AgentToolLoopContext,\n emittedSteps: AgentLoopStep[],\n): AgentToolLoopScriptContext {\n const emit = (step: AgentLoopStep): void => {\n emittedSteps.push(step);\n context.runtime?.emit?.(step);\n };\n return {\n input,\n context,\n profile: context.profile,\n createState: () => createAgentToolLoopState(context),\n startTurn: state => startAgentToolLoopTurn(context, input, state),\n runIteration: state => runAgentToolLoopIteration(context, input, state),\n stopTurn: (state, reason) => stopAgentToolLoopTurn(context, input, state, reason),\n emit,\n finish: message => {\n emit(typeof message === 'string' ? messageStep(message) : message);\n },\n isCancelled: () => context.runtime?.signal?.cancelled === true || context.agentToolLoop?.isCancelled?.(input.conversationId) === true,\n log: (event, data) => {\n context.runtime?.log?.(event, data);\n context.logger?.debug?.(event, data);\n },\n };\n}\n\nexport async function* runAgentToolLoopScript(\n script: AgentToolLoopScript,\n input: AgentLoopInput,\n context: AgentToolLoopContext,\n): AgentLoopGenerator {\n const emittedSteps: AgentLoopStep[] = [];\n const result = await script(createAgentToolLoopScriptContext(input, context, emittedSteps));\n\n yield* drainEmittedSteps(emittedSteps);\n if (isAsyncIterable(result)) {\n yield* result;\n yield* drainEmittedSteps(emittedSteps);\n } else if (typeof result === 'string') {\n yield messageStep(result);\n } else if (Array.isArray(result)) {\n yield* result;\n } else if (result) {\n yield result;\n }\n}\n","import type { AgentLoopDefinition } from '../types.js';\nimport { createAgentToolLoopRunner } from './directRunner.js';\nimport { asAgentToolLoopContext, resolveAgentToolLoopScript, runAgentToolLoopScript } from './scriptRunner.js';\n\nexport type {\n AgentToolLoopContext,\n AgentToolLoopIterationGenerator,\n AgentToolLoopIterationResult,\n AgentToolLoopScript,\n AgentToolLoopScriptContext,\n AgentToolLoopScriptReference,\n AgentToolLoopState,\n AgentToolLoopTurnStartResult,\n LoadAgentToolLoopScriptOptions,\n} from './contracts.js';\n\nexport { createAgentToolLoopRunner } from './directRunner.js';\n\nexport function createAgentToolLoopDefinition(name = 'AgentToolLoop'): AgentLoopDefinition {\n return {\n id: 'agent-tool-loop',\n name,\n description: 'Agent/tool loop that alternates between LLM output and external tool execution.',\n createRunner: (rawContext) => {\n const context = asAgentToolLoopContext(rawContext);\n return async function* agentToolLoop(input) {\n const script = await resolveAgentToolLoopScript(context);\n if (script) {\n yield* runAgentToolLoopScript(script, input, context);\n return;\n }\n yield* createAgentToolLoopRunner(context)(input);\n };\n },\n };\n}\n","/**\n * Built-in loop registrations — installed at startup so getLoopRegistry().createRunner('agent-tool-loop') works.\n *\n * This module allows hosts to skip manual registerLoop() for the built-in loop types.\n * Hosts can still override by calling registerLoop() with the same id after.\n */\n\nimport { createAgentAgentLoopDefinition, getAgentAgentLoopId } from '../agent-agent-loop/loop.js';\nimport { createAgentToolLoopDefinition } from '../agent-tool-loop/loop.js';\nimport { getLoopRegistry } from '../registry.js';\n\nexport const AGENT_TOOL_LOOP_ID = 'agent-tool-loop';\nexport const AGENT_AGENT_LOOP_ID = getAgentAgentLoopId();\n\n/**\n * Register the default built-in loops (agent-tool-loop and agent-agent-loop) with the loop registry.\n * Safe to call multiple times — skips already-registered loops.\n */\nexport function registerBuiltinLoops(): void {\n const registry = getLoopRegistry();\n\n if (!registry.getLoop(AGENT_TOOL_LOOP_ID)) {\n registry.registerLoop(createAgentToolLoopDefinition('AgentToolLoop'));\n }\n\n if (!registry.getLoop(AGENT_AGENT_LOOP_ID)) {\n registry.registerLoop(createAgentAgentLoopDefinition());\n }\n}\n","import { z } from 'zod';\n\nimport { waitForQuestionAnswer } from './questionWaitRegistry.js';\nimport type { BuiltinToolContext } from './types.js';\n\nexport const askQuestionConfigSchema = z.object({\n question: z.string().min(1),\n /**\n * Desktop / TidGi 的 LLM 工具参数里通常不会显式携带 conversationId,\n * 由宿主侧上下文负责关联;这里允许缺省,交给宿主回调侧做路由。\n */\n conversationId: z.string().min(1).optional(),\n timeoutMs: z.number().int().positive().max(3_600_000).optional(),\n inputType: z.enum(['single-select', 'multi-select', 'text']).optional(),\n options: z\n .array(\n z.object({\n label: z.string(),\n description: z.string().optional(),\n }),\n )\n .optional(),\n allowFreeform: z.boolean().optional().default(true),\n});\n\n/**\n * Must match `tool_use name=\"ask-question\"` extracted by responsePatternUtility.\n */\nexport const ASK_QUESTION_TOOL_ID = 'ask-question';\n\nexport async function askQuestionImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = askQuestionConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: 'invalid_askQuestion_args' };\n }\n const { question, conversationId, timeoutMs, inputType, options, allowFreeform } = parsed.data;\n const questionId = crypto.randomUUID();\n const timeout = timeoutMs ?? 300_000;\n context.notifyAskQuestion?.({\n questionId,\n question,\n conversationId,\n inputType,\n options,\n allowFreeform,\n });\n try {\n const answer = await waitForQuestionAnswer(questionId, timeout);\n return { result: answer };\n } catch (error) {\n return { error: error instanceof Error ? error.message : 'askQuestion_failed' };\n }\n}\n","type Pending = {\n resolve: (answer: string) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst pending = new Map<string, Pending>();\n\nexport function resolveQuestionAnswer(questionId: string, answer: string): boolean {\n const p = pending.get(questionId);\n if (!p) return false;\n clearTimeout(p.timer);\n pending.delete(questionId);\n p.resolve(answer);\n return true;\n}\n\nexport function waitForQuestionAnswer(questionId: string, timeoutMs: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(questionId);\n reject(new Error('askQuestion_timeout'));\n }, timeoutMs);\n pending.set(questionId, { resolve, reject, timer });\n });\n}\n","/**\n * AskUserQuestion Tool — Pause agent execution and ask user for input.\n *\n * Uses the existing askQuestion pattern (notifyAskQuestion + waitForQuestionAnswer)\n * but provides a dedicated tool ID for explicit user question prompting.\n */\nimport { z } from 'zod';\n\nimport { waitForQuestionAnswer } from './questionWaitRegistry.js';\nimport type { BuiltinToolContext } from './types.js';\n\nexport const askUserQuestionConfigSchema = z.object({\n question: z.string().min(1).describe('The question to ask the user'),\n inputType: z\n .enum(['text', 'single-select', 'multi-select'])\n .optional()\n .default('text')\n .describe('Type of input expected: text, single-select, or multi-select'),\n options: z\n .array(\n z.object({\n label: z.string().min(1),\n description: z.string().optional(),\n }),\n )\n .optional()\n .describe('Options for single-select or multi-select input types'),\n allowFreeform: z\n .boolean()\n .optional()\n .default(true)\n .describe('Allow free-text input even for select types'),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .max(3_600_000)\n .optional()\n .default(300_000)\n .describe('Timeout in milliseconds (default 5 minutes)'),\n});\n\nexport const ASK_USER_QUESTION_TOOL_ID = 'askUserQuestion';\n\nexport async function askUserQuestionImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = askUserQuestionConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: `invalid_askUserQuestion_args: ${parsed.error.message}` };\n }\n\n const { question, inputType, options, allowFreeform, timeoutMs } = parsed.data;\n const questionId = crypto.randomUUID();\n const conversationId = context.agent?.id ?? context.activeToolConversationId;\n\n context.notifyAskQuestion?.({\n questionId,\n question,\n conversationId,\n inputType,\n options,\n allowFreeform,\n });\n\n try {\n const answer = await waitForQuestionAnswer(questionId, timeoutMs);\n return { result: answer };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'askUserQuestion_failed';\n return { error: message };\n }\n}\n","import type { BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'mcpClient';\n\nexport const mcpClientConfigSchema = {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Target node ID' },\n serverName: { type: 'string', description: 'MCP server name on that node' },\n toolName: { type: 'string', description: 'Tool to invoke' },\n args: { type: 'object', description: 'Tool arguments' },\n },\n required: ['nodeId', 'serverName', 'toolName'],\n} as const;\n\nexport const mcpClientImpl: BuiltinToolImpl = async (arguments_, context) => {\n const nodeId = arguments_.nodeId as string | undefined;\n const serverName = arguments_.serverName as string | undefined;\n const toolName = arguments_.toolName as string | undefined;\n const toolArguments = (arguments_.args as Record<string, unknown>) ?? {};\n\n if (!nodeId || !serverName || !toolName) {\n return {\n error: 'mcpClient requires nodeId, serverName, and toolName',\n };\n }\n\n if (!context.mcpCallRemote) {\n return {\n error: 'MCP proxy not configured (no mcpCallRemote in context). Connect to nodes that expose MCP.',\n };\n }\n\n try {\n const result = await context.mcpCallRemote(nodeId, serverName, toolName, toolArguments);\n return { result };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { error: `MCP call failed: ${message}` };\n }\n};\n\nexport function getMcpClientToolId(): string {\n return TOOL_ID;\n}\n","import type { BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'mcpForward';\n\nexport const mcpForwardConfigSchema = {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['list', 'listTools'],\n description: \"Action: 'list' returns nodes with MCP servers, 'listTools' returns all available MCP tools across nodes\",\n },\n },\n} as const;\n\ninterface McpServerInfo {\n name: string;\n}\n\ninterface McpToolInfo {\n nodeId: string;\n serverName: string;\n name: string;\n description?: string;\n}\n\n/**\n * MCP forwarding tool: discover MCP servers and tools on connected nodes.\n * - action=list: returns nodes with their MCP servers\n * - action=listTools: returns all available MCP tools across all nodes\n */\nexport const mcpForwardImpl: BuiltinToolImpl = async (arguments_, context) => {\n const action = (arguments_.action as string | undefined) ?? 'list';\n\n if (!context.getPeers) {\n return { error: 'Peer list not configured (no getPeers).' };\n }\n\n if (!context.sendRpcToNode) {\n return { error: 'Remote node RPC not configured (no sendRpcToNode).' };\n }\n\n const peers = await context.getPeers();\n const online = peers.filter((p) => p.reachability.state === 'online');\n\n if (action === 'list') {\n // List devices with their MCP servers\n const result: Array<{ nodeId: string; name: string; mcpServers: McpServerInfo[] }> = [];\n\n for (const node of online) {\n try {\n const response = (await context.sendRpcToNode(\n node.peerId,\n 'memeloop.mcp.listServers',\n {},\n )) as {\n servers?: McpServerInfo[];\n };\n const servers = Array.isArray(response?.servers) ? response.servers : [];\n if (servers.length > 0) {\n result.push({\n nodeId: node.peerId,\n name: node.displayName,\n mcpServers: servers,\n });\n }\n } catch {\n // Skip devices that don't support MCP or fail to respond\n }\n }\n\n return { nodes: result };\n }\n\n if (action === 'listTools') {\n // List all MCP tools across all devices\n const allTools: McpToolInfo[] = [];\n\n for (const node of online) {\n try {\n const response = (await context.sendRpcToNode(\n node.peerId,\n 'memeloop.mcp.listTools',\n {},\n )) as {\n tools?: Array<{ serverName: string; name: string; description?: string }>;\n };\n const tools = Array.isArray(response?.tools) ? response.tools : [];\n for (const tool of tools) {\n allTools.push({\n nodeId: node.peerId,\n serverName: tool.serverName,\n name: tool.name,\n description: tool.description,\n });\n }\n } catch {\n // Skip devices that don't support MCP or fail to respond\n }\n }\n\n return { tools: allTools };\n }\n\n return { error: `Unknown action: ${action}` };\n};\n\nexport function getMcpForwardToolId(): string {\n return TOOL_ID;\n}\n","import type {\n AgentOrchestrationClient,\n OrchestrationApplyOptions,\n OrchestrationConditionStatus,\n OrchestrationDeleteOptions,\n OrchestrationGetOptions,\n OrchestrationListOptions,\n OrchestrationManifestMetadata,\n OrchestrationPreconditions,\n OrchestrationResourceManifest,\n OrchestrationResourceQuery,\n OrchestrationResourceReference,\n} from '../../orchestration/index.js';\nimport { OrchestrationError, toOrchestrationErrorData, waitForCondition } from '../../orchestration/index.js';\nimport type { BuiltinToolImpl } from './types.js';\n\nexport const ORCHESTRATION_TOOL_ID = 'orchestration';\n\nexport const orchestrationConfigSchema = {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['capabilities', 'apply', 'get', 'list', 'wait', 'delete'],\n description: 'Declarative orchestration resource operation.',\n },\n resource: {\n type: 'object',\n description: 'Resource manifest for apply. status and actor fields are not accepted.',\n },\n reference: {\n type: 'object',\n description: 'Resource reference for get, wait, or delete.',\n },\n query: {\n type: 'object',\n description: 'Resource query for list.',\n },\n condition: {\n type: 'object',\n description: 'Condition to wait for. Required when action is wait.',\n },\n options: {\n type: 'object',\n description: 'Operation options. Only documented fields are forwarded.',\n },\n },\n required: ['action'],\n} as const;\n\nfunction objectValue(value: unknown, field: string): Record<string, unknown> {\n if (!value || typeof value !== 'object' || Array.isArray(value)) {\n throw invalidError(`${field} must be an object`);\n }\n return value as Record<string, unknown>;\n}\n\nfunction invalidError(message: string): OrchestrationError {\n return new OrchestrationError({ code: 'INVALID', message, retryable: false });\n}\n\nfunction optionalString(value: unknown): string | undefined {\n return typeof value === 'string' && value.length > 0 ? value : undefined;\n}\n\nfunction optionalBoolean(value: unknown): boolean | undefined {\n return typeof value === 'boolean' ? value : undefined;\n}\n\nfunction stringRecord(value: unknown): Record<string, string> | undefined {\n if (value === undefined) return undefined;\n const record = objectValue(value, 'record');\n const entries = Object.entries(record);\n if (entries.some(([, entry]) => typeof entry !== 'string')) {\n throw invalidError('record values must be strings');\n }\n return Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction metadataValue(value: unknown): OrchestrationManifestMetadata {\n const metadata = objectValue(value, 'resource.metadata');\n return {\n name: optionalString(metadata.name),\n generateName: optionalString(metadata.generateName),\n namespace: optionalString(metadata.namespace),\n labels: stringRecord(metadata.labels),\n annotations: stringRecord(metadata.annotations),\n };\n}\n\nfunction resourceValue(value: unknown): OrchestrationResourceManifest {\n const resource = objectValue(value, 'resource');\n const apiVersion = optionalString(resource.apiVersion);\n const kind = optionalString(resource.kind);\n if (!apiVersion || !kind) throw invalidError('resource requires apiVersion and kind');\n return {\n apiVersion,\n kind,\n metadata: metadataValue(resource.metadata),\n spec: objectValue(resource.spec, 'resource.spec'),\n };\n}\n\nfunction referenceValue(value: unknown): OrchestrationResourceReference {\n const reference = objectValue(value, 'reference');\n const apiVersion = optionalString(reference.apiVersion);\n const kind = optionalString(reference.kind);\n const name = optionalString(reference.name);\n const uid = optionalString(reference.uid);\n if (!apiVersion || !kind || (!name && !uid)) {\n throw invalidError('reference requires apiVersion, kind, and name or uid');\n }\n return {\n apiVersion,\n kind,\n name,\n namespace: optionalString(reference.namespace),\n uid,\n };\n}\n\nfunction queryValue(value: unknown): OrchestrationResourceQuery {\n const query = objectValue(value, 'query');\n const kind = optionalString(query.kind);\n if (!kind) throw invalidError('query requires kind');\n return {\n apiVersion: optionalString(query.apiVersion),\n kind,\n namespace: optionalString(query.namespace),\n labels: stringRecord(query.labels),\n };\n}\n\nfunction preconditionsValue(value: unknown): OrchestrationPreconditions | undefined {\n if (value === undefined) return undefined;\n const preconditions = objectValue(value, 'options.preconditions');\n return {\n uid: optionalString(preconditions.uid),\n resourceVersion: optionalString(preconditions.resourceVersion),\n generation: typeof preconditions.generation === 'number' ? preconditions.generation : undefined,\n };\n}\n\nfunction applyOptions(value: unknown): OrchestrationApplyOptions | undefined {\n if (value === undefined) return undefined;\n const options = objectValue(value, 'options');\n return {\n idempotencyKey: optionalString(options.idempotencyKey),\n fieldManager: optionalString(options.fieldManager),\n force: optionalBoolean(options.force),\n dryRun: optionalBoolean(options.dryRun),\n preconditions: preconditionsValue(options.preconditions),\n };\n}\n\nfunction getOptions(value: unknown): OrchestrationGetOptions | undefined {\n if (value === undefined) return undefined;\n const options = objectValue(value, 'options');\n return { resourceVersion: optionalString(options.resourceVersion) };\n}\n\nfunction listOptions(value: unknown): OrchestrationListOptions | undefined {\n if (value === undefined) return undefined;\n const options = objectValue(value, 'options');\n return {\n resourceVersion: optionalString(options.resourceVersion),\n resourceVersionMatch: options.resourceVersionMatch === 'exact' || options.resourceVersionMatch === 'not-older-than'\n ? options.resourceVersionMatch\n : undefined,\n limit: typeof options.limit === 'number' ? options.limit : undefined,\n continueToken: optionalString(options.continueToken),\n };\n}\n\nfunction deleteOptions(value: unknown): OrchestrationDeleteOptions | undefined {\n if (value === undefined) return undefined;\n const options = objectValue(value, 'options');\n const propagationPolicy = options.propagationPolicy;\n const validPropagationPolicy = propagationPolicy === 'orphan' || propagationPolicy === 'background' || propagationPolicy === 'foreground'\n ? propagationPolicy\n : undefined;\n return {\n idempotencyKey: optionalString(options.idempotencyKey),\n preconditions: preconditionsValue(options.preconditions),\n propagationPolicy: validPropagationPolicy,\n dryRun: optionalBoolean(options.dryRun),\n };\n}\n\nfunction waitConditionValue(value: unknown): { type: string; status: OrchestrationConditionStatus } {\n const condition = objectValue(value, 'condition');\n const type = optionalString(condition.type);\n if (!type) throw invalidError('condition requires type');\n const status = condition.status === 'True' || condition.status === 'False' || condition.status === 'Unknown'\n ? condition.status\n : 'True';\n return { type, status };\n}\n\nfunction waitOptions(value: unknown): { timeout?: number; interval?: number } {\n if (value === undefined) return {};\n const options = objectValue(value, 'options');\n const timeout = typeof options.timeout === 'number' ? options.timeout : undefined;\n const interval = typeof options.interval === 'number' ? options.interval : undefined;\n if (timeout !== undefined && timeout <= 0) throw invalidError('timeout must be positive');\n if (interval !== undefined && interval <= 0) throw invalidError('interval must be positive');\n return { timeout, interval };\n}\n\nasync function waitForResourceCondition(\n context: Parameters<BuiltinToolImpl>[1],\n client: AgentOrchestrationClient,\n reference: OrchestrationResourceReference,\n condition: { type: string; status: OrchestrationConditionStatus },\n options: { timeout?: number; interval?: number },\n): Promise<{ observedResourceVersion: string; matched: true }> {\n return waitForCondition(\n () => client.get(reference, { resourceVersion: undefined }),\n condition,\n {\n ...options,\n isCancelled: () =>\n context.isCancelled?.() === true ||\n (context.activeToolConversationId !== undefined && context.conversationCancellation?.has(context.activeToolConversationId) === true),\n },\n );\n}\n\nexport const orchestrationImpl: BuiltinToolImpl = async (arguments_, context) => {\n const client = context.orchestration;\n if (!client) {\n return {\n error: {\n code: 'UNSUPPORTED',\n message: 'Orchestration manager not configured.',\n retryable: false,\n },\n };\n }\n\n try {\n switch (arguments_.action) {\n case 'capabilities':\n return await client.getCapabilities();\n case 'apply':\n return await client.apply(resourceValue(arguments_.resource), applyOptions(arguments_.options));\n case 'get':\n return await client.get(referenceValue(arguments_.reference), getOptions(arguments_.options));\n case 'list':\n return await client.list(queryValue(arguments_.query), listOptions(arguments_.options));\n case 'wait':\n return await waitForResourceCondition(\n context,\n client,\n referenceValue(arguments_.reference),\n waitConditionValue(arguments_.condition),\n waitOptions(arguments_.options),\n );\n case 'delete':\n return await client.delete(referenceValue(arguments_.reference), deleteOptions(arguments_.options));\n default:\n throw invalidError('orchestration requires a supported action');\n }\n } catch (error) {\n return { error: toOrchestrationErrorData(error) };\n }\n};\n","import { createAgentClient } from '../../orchestration/index.js';\nimport type { AgentOrchestrationClient } from '../../orchestration/index.js';\nimport { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'remoteAgent';\nconst REMOTE_LOG_POLL_INTERVAL_MS = 500;\nconst REMOTE_LOG_IDLE_POLLS = 2;\n\ntype RemoteConversationMessage = {\n messageId?: string;\n role?: string;\n content?: unknown;\n};\n\nfunction messageContentToText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (content == null) return '';\n try {\n return JSON.stringify(content);\n } catch {\n return Object.prototype.toString.call(content);\n }\n}\n\nfunction getRemoteStreamChunkContent(chunk: unknown): unknown {\n if (chunk != null && typeof chunk === 'object' && 'content' in chunk) {\n return Reflect.get(chunk, 'content');\n }\n\n return undefined;\n}\n\nfunction summarizeRemoteMessages(messages: RemoteConversationMessage[]): string {\n const relevant = messages.filter((message) => message.role && message.role !== 'user');\n if (relevant.length === 0) {\n return '(task dispatched; waiting for remote output)';\n }\n const joined = relevant\n .map((message) => {\n const role = typeof message.role === 'string' ? message.role : 'message';\n const content = messageContentToText(message.content).trim();\n return content.length > 0 ? `[${role}] ${content}` : '';\n })\n .filter((line) => line.length > 0)\n .join('\\n');\n return joined.trim() || '(task dispatched; remote messages had no readable content)';\n}\n\nasync function collectRemoteConversationSummary(\n sendRpc: NonNullable<BuiltinToolContext['sendRpcToNode']>,\n nodeId: string,\n conversationId: string,\n timeoutMs: number,\n): Promise<string> {\n const startedAt = Date.now();\n const knownMessageIds = new Set<string>();\n const collectedMessages: RemoteConversationMessage[] = [];\n let idlePolls = 0;\n\n while (Date.now() - startedAt < timeoutMs) {\n const response = (await sendRpc(nodeId, 'memeloop.chat.pullAgentRunLog', {\n conversationId,\n knownMessageIds: [...knownMessageIds],\n })) as { messages?: RemoteConversationMessage[] };\n const newMessages = Array.isArray(response?.messages) ? response.messages : [];\n\n if (newMessages.length > 0) {\n idlePolls = 0;\n for (const message of newMessages) {\n if (typeof message.messageId === 'string' && message.messageId.length > 0) {\n knownMessageIds.add(message.messageId);\n }\n collectedMessages.push(message);\n }\n } else if (collectedMessages.some((message) => message.role && message.role !== 'user')) {\n idlePolls += 1;\n if (idlePolls >= REMOTE_LOG_IDLE_POLLS) {\n break;\n }\n }\n\n await new Promise((resolve) => setTimeout(resolve, REMOTE_LOG_POLL_INTERVAL_MS));\n }\n\n return summarizeRemoteMessages(collectedMessages);\n}\n\nasync function supportsAgentWorkload(client: AgentOrchestrationClient): Promise<boolean> {\n try {\n const caps = await client.getCapabilities();\n return caps.operations.includes('apply') && caps.resourceKinds.includes('AgentWorkload');\n } catch {\n return false;\n }\n}\n\nasync function runRemoteAgentViaOrchestration(\n client: AgentOrchestrationClient,\n nodeId: string,\n definitionId: string,\n message: string,\n localNodeId: string | undefined,\n): Promise<Record<string, unknown>> {\n const timestamp = Date.now().toString(36);\n const conversationId = `remote:${nodeId}:${definitionId}:${timestamp}`;\n const agents = createAgentClient(client);\n const workload = await agents.createWorkload({\n name: conversationId,\n profileId: definitionId,\n promptReference: message,\n completionPolicy: 'complete',\n placement: { requiredNode: nodeId },\n });\n const run = await agents.createRun({\n name: `${conversationId}-run`,\n workloadName: workload.metadata.name,\n promptReference: message,\n });\n const result = await agents.waitForRunCondition(\n run.metadata.name,\n { type: 'Completed', status: 'True' },\n { timeout: 30_000, interval: 1000 },\n );\n const finalRun = await agents.getRun(run.metadata.name);\n const summary = finalRun?.status?.summary ?? '(no summary)';\n const shortSummary = truncateToolSummary(summary);\n const resolvedNodeId = localNodeId?.trim() || 'local';\n return {\n summary,\n remoteNodeId: nodeId,\n remoteConversationId: conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId: resolvedNodeId,\n resourceVersion: result.observedResourceVersion,\n },\n },\n };\n}\n\nexport const remoteAgentConfigSchema = {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Target node ID to run the agent-run on' },\n definitionId: { type: 'string', description: 'Agent definition ID on that node' },\n message: { type: 'string', description: 'Task message for the remote agent' },\n },\n required: ['nodeId', 'definitionId', 'message'],\n} as const;\n\n/** List policy-filtered execution targets and capabilities. No direct peer enumeration. */\nexport const remoteAgentListImpl: BuiltinToolImpl = async (_arguments, context) => {\n if (context.orchestration) {\n try {\n const caps = await context.orchestration.getCapabilities();\n const targets = caps.resourceKinds.map((kind) => ({\n kind,\n interfaces: caps.interfaces,\n operations: caps.operations,\n }));\n return {\n targets,\n capabilities: caps.interfaces,\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n targets: [],\n error: `Orchestration target discovery failed: ${message}`,\n };\n }\n }\n\n return {\n targets: [],\n error: 'Direct peer enumeration is disabled. Configure an orchestration manager to discover execution targets.',\n };\n};\n\nexport const remoteAgentImpl: BuiltinToolImpl = async (arguments_, context) => {\n const nodeId = arguments_.nodeId as string | undefined;\n const definitionId = arguments_.definitionId as string | undefined;\n const message = arguments_.message as string | undefined;\n\n if (!nodeId || !definitionId || typeof message !== 'string') {\n return remoteAgentListImpl(arguments_, context);\n }\n\n try {\n if (context.orchestration && (await supportsAgentWorkload(context.orchestration))) {\n return await runRemoteAgentViaOrchestration(context.orchestration, nodeId, definitionId, message, context.localNodeId);\n }\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : messageContentToText(error);\n return { error: `remoteAgent failed: ${errorMessage}` };\n }\n\n const sendRpc = context.sendRpcToNode\n ? async (nodeId: string, method: string, parameters: unknown) => context.sendRpcToNode?.(nodeId, method, parameters)\n : undefined;\n if (!sendRpc) {\n return {\n error: 'Remote node RPC not configured (no sendRpcToNode). Connect to peer nodes first.',\n };\n }\n\n try {\n const createResult = (await sendRpc(nodeId, 'memeloop.agent.create', {\n definitionId,\n })) as { conversationId?: string };\n const conversationId = createResult?.conversationId;\n if (!conversationId) {\n return { error: 'Remote agent.create did not return conversationId', raw: createResult };\n }\n\n await sendRpc(nodeId, 'memeloop.agent.send', {\n conversationId,\n message,\n });\n\n const subscribeStream = (\n context as BuiltinToolContext & {\n subscribeRemoteStream?: (\n nodeId: string,\n conversationId: string,\n onChunk: (chunk: unknown) => void,\n ) => () => void;\n }\n ).subscribeRemoteStream;\n const streamWaitMs = context.remoteAgentStreamTimeoutMs ?? 30_000;\n const chunks: string[] = [];\n if (subscribeStream) {\n await new Promise<void>((resolve) => {\n const unsub = subscribeStream(nodeId, conversationId, (chunk) => {\n if (typeof chunk === 'string') chunks.push(chunk);\n else {\n const chunkContent = getRemoteStreamChunkContent(chunk);\n if (chunkContent !== undefined) {\n chunks.push(messageContentToText(chunkContent));\n }\n }\n });\n setTimeout(() => {\n unsub();\n resolve();\n }, streamWaitMs);\n });\n }\n\n const fullSummary = chunks.length > 0\n ? chunks.join('').trim()\n : await collectRemoteConversationSummary(sendRpc, nodeId, conversationId, streamWaitMs);\n const shortSummary = truncateToolSummary(fullSummary);\n return {\n summary: fullSummary,\n remoteNodeId: nodeId,\n remoteConversationId: conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId,\n },\n },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : messageContentToText(error);\n return { error: `remoteAgent failed: ${message}` };\n }\n};\n\nexport function getRemoteAgentToolId(): string {\n return TOOL_ID;\n}\n","import { createAgentClient } from '../../orchestration/index.js';\nimport type { AgentOrchestrationClient } from '../../orchestration/index.js';\nimport { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'spawnAgent';\n\nasync function supportsAgentWorkload(client: AgentOrchestrationClient): Promise<boolean> {\n try {\n const caps = await client.getCapabilities();\n return caps.operations.includes('apply') && caps.resourceKinds.includes('AgentWorkload');\n } catch {\n return false;\n }\n}\n\nasync function runSpawnAgentViaOrchestration(\n client: AgentOrchestrationClient,\n definitionId: string,\n message: string,\n conversationId: string,\n localNodeId: string | undefined,\n): Promise<Record<string, unknown>> {\n const agents = createAgentClient(client);\n const workload = await agents.createWorkload({\n name: conversationId,\n profileId: definitionId,\n completionPolicy: 'complete',\n });\n const run = await agents.createRun({\n name: `${conversationId}-run`,\n workloadName: workload.metadata.name,\n promptReference: message,\n });\n const result = await agents.waitForRunCondition(\n run.metadata.name,\n { type: 'Completed', status: 'True' },\n { timeout: 30_000, interval: 1000 },\n );\n const finalRun = await agents.getRun(run.metadata.name);\n const summary = finalRun?.status?.summary ?? '(no summary)';\n const shortSummary = truncateToolSummary(summary);\n const nodeId = localNodeId?.trim() || 'local';\n return {\n summary,\n conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId,\n resourceVersion: result.observedResourceVersion,\n },\n },\n };\n}\n\nasync function runSpawnAgentLocally(\n runLocalAgent: NonNullable<BuiltinToolContext['runLocalAgent']>,\n definitionId: string,\n message: string,\n conversationId: string,\n localNodeId: string | undefined,\n): Promise<Record<string, unknown>> {\n const chunks: string[] = [];\n for await (const step of runLocalAgent({ conversationId, message })) {\n if (step.type === 'message' && typeof step.data === 'string') {\n chunks.push(step.data);\n }\n if (\n step.type === 'message' &&\n step.data != null &&\n typeof step.data === 'object' &&\n 'content' in step.data\n ) {\n const c = (step.data as { content?: string }).content;\n if (typeof c === 'string') chunks.push(c);\n }\n }\n const fullSummary = chunks.join('').trim() || '(no text output)';\n const shortSummary = truncateToolSummary(fullSummary);\n const nodeId = localNodeId?.trim() || 'local';\n return {\n summary: fullSummary,\n conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId,\n },\n },\n };\n}\n\nexport const spawnAgentConfigSchema = {\n type: 'object',\n properties: {\n definitionId: { type: 'string', description: 'Agent definition ID to use for the agent-run' },\n message: { type: 'string', description: 'User message / task for the agent-run' },\n },\n required: ['definitionId', 'message'],\n} as const;\n\nexport const spawnAgentImpl: BuiltinToolImpl = async (arguments_, context) => {\n const definitionId = arguments_.definitionId as string | undefined;\n const message = arguments_.message as string | undefined;\n\n if (!definitionId || typeof message !== 'string') {\n return { error: 'spawnAgent requires definitionId and message' };\n }\n\n const conversationId = `spawn:${definitionId}:${Date.now().toString(36)}`;\n\n try {\n if (context.orchestration && (await supportsAgentWorkload(context.orchestration))) {\n return await runSpawnAgentViaOrchestration(context.orchestration, definitionId, message, conversationId, context.localNodeId);\n }\n\n if (!context.runLocalAgent) {\n return {\n error: 'Local agent runner not configured (no runLocalAgent in context).',\n };\n }\n return await runSpawnAgentLocally(\n (input) => context.runLocalAgent!(input),\n definitionId,\n message,\n conversationId,\n context.localNodeId,\n );\n } catch (error) {\n const errorMessage = error instanceof Error ? error.message : String(error);\n return { error: `spawnAgent failed: ${errorMessage}`, conversationId };\n }\n};\n\nexport function getSpawnAgentToolId(): string {\n return TOOL_ID;\n}\n","import type { AgentDefinition as ProtocolAgentDefinition } from './types.js';\n\n/**\n * Extended agent definition used by the agent profile registry.\n * Wraps the protocol-level AgentDefinition with additional runtime metadata.\n */\nexport interface AgentProfile {\n /** Unique ID for this agent (matches protocol id convention like \"memeloop:build\") */\n id: string;\n /** Display name */\n name: string;\n /** Agent type / role */\n type: AgentProfileType;\n /** System prompt / instructions for the agent */\n prompt: string;\n /** Tool permission rules (mutually exclusive with permissive defaults) */\n permissions: ToolPermissionRules;\n /** Optional model override (provider/model string) */\n model?: string;\n /** Underlying protocol-compatible definition for framework integration */\n protocolDef: ProtocolAgentDefinition;\n}\n\nexport type AgentProfileType = 'build' | 'plan' | 'explore' | 'oracle' | 'librarian';\n\nexport interface ToolPermissionRules {\n /** Default action for tools not matching any rule */\n default: 'allow' | 'ask' | 'deny';\n /** Per-tool or wildcard rules */\n rules: Array<{ pattern: string; action: 'allow' | 'ask' | 'deny' }>;\n}\n\nfunction makeBuiltinDefinition(\n id: string,\n name: string,\n type: AgentProfileType,\n prompt: string,\n permissions: ToolPermissionRules,\n model?: string,\n): AgentProfile {\n const systemPrompt = prompt;\n const tools: string[] = []; // runtime tools; permissions govern access\n return {\n id,\n name,\n type,\n prompt,\n permissions,\n model,\n protocolDef: {\n id,\n name,\n description: prompt.slice(0, 200),\n systemPrompt,\n tools,\n version: '1.0.0',\n modelConfig: model\n ? {\n provider: model.split('/')[0] ?? 'memeloop',\n model: model.split('/').slice(1).join('/') || model,\n }\n : undefined,\n },\n };\n}\n\n/**\n * Build agent: full access, default model.\n * Primary agent for executing tasks, writing code, running commands.\n */\nexport const buildAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:build',\n 'Build Agent',\n 'build',\n \"You are a build agent capable of executing tasks, writing and editing files, running commands, and making changes. Use tools to accomplish the user's goals efficiently.\",\n { default: 'allow', rules: [] },\n);\n\n/**\n * Plan agent: read-only, denies file edits and terminal execution.\n * Used for high-level planning and task decomposition.\n */\nexport const planAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:plan',\n 'Plan Agent',\n 'plan',\n 'You are a planning agent. Your role is to analyze requirements, decompose tasks, and create structured plans. You CANNOT write files or execute terminal commands. Only use read and search tools.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Explore agent: read + search tools only.\n * Fast search and codebase exploration without modification.\n */\nexport const exploreAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:explore',\n 'Explore Agent',\n 'explore',\n 'You are an exploration agent specialized in fast codebase search and discovery. You have read and search tools. Do NOT modify files or run terminal commands. Focus on finding relevant code, files, and patterns.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n { pattern: 'lsp.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Oracle agent: read-only, for architecture consultation and code review.\n */\nexport const oracleAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:oracle',\n 'Oracle Agent',\n 'oracle',\n 'You are an oracle agent specialized in architecture analysis, code review, and constraint verification. You have read access only. Review code, identify issues, and provide expert architectural guidance.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n { pattern: 'lsp.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Librarian agent: read + web search tools only.\n * External documentation lookup and context gathering.\n */\nexport const librarianAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:librarian',\n 'Librarian Agent',\n 'librarian',\n 'You are a librarian agent specialized in external documentation lookup, web search, and context gathering. Use web search tools to find relevant documentation, APIs, and examples. Do NOT modify files or run terminal commands.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'web.*', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n ],\n },\n);\n\n/** Built-in agent profiles used by the task delegation tool. */\nexport const BUILTIN_AGENT_PROFILES: AgentProfile[] = [\n buildAgent,\n planAgent,\n exploreAgent,\n oracleAgent,\n librarianAgent,\n];\n","import type { AgentProfile, AgentProfileType } from './agentProfiles.js';\nimport { BUILTIN_AGENT_PROFILES } from './agentProfiles.js';\n\n/**\n * Registry for agent profiles used by task delegation.\n * Pre-seeded with built-in profiles (build, plan, explore, oracle, librarian).\n */\nexport class AgentProfileRegistry {\n private readonly profiles = new Map<string, AgentProfile>();\n\n constructor() {\n this.seedDefaults();\n }\n\n /** Seed the registry with built-in agent profiles. */\n private seedDefaults(): void {\n for (const profile of BUILTIN_AGENT_PROFILES) {\n this.profiles.set(profile.id, profile);\n }\n }\n\n /**\n * Register a new agent profile or override an existing one.\n * Throws if the profile is invalid.\n */\n registerAgentProfile(profile: AgentProfile): void {\n if (!profile.id || typeof profile.id !== 'string' || profile.id.trim().length === 0) {\n throw new Error('Agent profile must have a non-empty id');\n }\n if (!profile.name || typeof profile.name !== 'string') {\n throw new Error('Agent profile must have a name');\n }\n if (!profile.type || typeof profile.type !== 'string') {\n throw new Error('Agent profile must have a type');\n }\n if (!profile.prompt || typeof profile.prompt !== 'string') {\n throw new Error('Agent profile must have a prompt');\n }\n if (!profile.permissions || typeof profile.permissions.default !== 'string') {\n throw new Error('Agent profile must have valid permissions');\n }\n this.profiles.set(profile.id, profile);\n }\n\n /**\n * Get an agent profile by ID.\n * Returns undefined if not found.\n */\n getAgentProfile(id: string): AgentProfile | undefined {\n return this.profiles.get(id);\n }\n\n /**\n * List all registered agent profiles.\n */\n listAgentProfiles(): AgentProfile[] {\n return Array.from(this.profiles.values());\n }\n\n /**\n * List agent profiles filtered by type.\n */\n listAgentProfilesByType(type: AgentProfileType): AgentProfile[] {\n return this.listAgentProfiles().filter((profile) => profile.type === type);\n }\n\n /**\n * Remove an agent profile by ID.\n */\n unregisterAgentProfile(id: string): boolean {\n return this.profiles.delete(id);\n }\n\n /**\n * Reset the registry to only built-in defaults.\n */\n reset(): void {\n this.profiles.clear();\n this.seedDefaults();\n }\n}\n\n/** Shared singleton instance for convenience. */\nlet defaultRegistry: AgentProfileRegistry | null = null;\n\nexport function getAgentProfileRegistry(): AgentProfileRegistry {\n if (!defaultRegistry) {\n defaultRegistry = new AgentProfileRegistry();\n }\n return defaultRegistry;\n}\n\nexport function resetAgentProfileRegistry(): void {\n if (defaultRegistry) {\n defaultRegistry.reset();\n }\n defaultRegistry = null;\n}\n","import { getAgentProfileRegistry } from '../../agent/agentProfileRegistry.js';\nimport { createAgentClient } from '../../orchestration/index.js';\nimport type { AgentOrchestrationClient } from '../../orchestration/index.js';\nimport { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'task';\n\nasync function supportsAgentWorkload(client: AgentOrchestrationClient): Promise<boolean> {\n try {\n const caps = await client.getCapabilities();\n return caps.operations.includes('apply') && caps.resourceKinds.includes('AgentWorkload');\n } catch {\n return false;\n }\n}\n\nasync function runTaskViaOrchestration(\n client: AgentOrchestrationClient,\n agentId: string,\n prompt: string,\n background: boolean | undefined,\n localNodeId: string | undefined,\n conversationId: string,\n permissions: { default: 'allow' | 'ask' | 'deny'; rules: Array<{ pattern: string; action: 'allow' | 'ask' | 'deny' }> },\n): Promise<Record<string, unknown>> {\n const agents = createAgentClient(client);\n const workload = await agents.createWorkload({\n name: conversationId,\n profileId: agentId,\n promptReference: prompt,\n completionPolicy: background ? 'detach' : 'complete',\n toolPolicy: {\n defaultAction: permissions.default,\n rules: permissions.rules,\n },\n });\n const run = await agents.createRun({\n name: `${conversationId}-run`,\n workloadName: workload.metadata.name,\n promptReference: prompt,\n });\n\n const nodeId = localNodeId?.trim() || 'local';\n\n if (background) {\n return {\n summary: `Background task \"${agentId}\" launched. Task ID: ${conversationId}`,\n conversationId,\n agentId,\n taskId: conversationId,\n background: true,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: `[bg-task] ${agentId}: ${conversationId}`,\n detailRef: {\n type: 'agent-run' as const,\n conversationId,\n nodeId,\n resourceVersion: run.metadata.resourceVersion,\n },\n },\n };\n }\n\n const result = await agents.waitForRunCondition(\n run.metadata.name,\n { type: 'Completed', status: 'True' },\n { timeout: 30_000, interval: 1000 },\n );\n const finalRun = await agents.getRun(run.metadata.name);\n const text = finalRun?.status?.summary ?? '(no summary)';\n const shortSummary = truncateToolSummary(text);\n return {\n result: text,\n conversationId,\n agentId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run' as const,\n conversationId,\n nodeId,\n resourceVersion: result.observedResourceVersion,\n },\n },\n };\n}\n\nasync function runTaskLocally(\n runLocalAgent: NonNullable<BuiltinToolContext['runLocalAgent']>,\n context: BuiltinToolContext,\n agentId: string,\n prompt: string,\n background: boolean | undefined,\n conversationId: string,\n): Promise<Record<string, unknown>> {\n async function collectOutput(\n gen: AsyncIterable<{ type: string; data?: unknown }>,\n ): Promise<{ text: string; conversationId: string }> {\n const chunks: string[] = [];\n for await (const step of gen) {\n if (step.type === 'message') {\n if (typeof step.data === 'string') {\n chunks.push(step.data);\n } else if (step.data != null && typeof step.data === 'object' && 'content' in step.data) {\n const c = (step.data as { content?: string }).content;\n if (typeof c === 'string') chunks.push(c);\n }\n }\n }\n return { text: chunks.join('').trim() || '(no text output)', conversationId };\n }\n\n if (background) {\n const gen = runLocalAgent({ conversationId, message: prompt });\n void collectOutput(gen).catch(() => {\n /* background errors are non-fatal */\n });\n\n const nodeId = context.localNodeId?.trim() || 'local';\n return {\n summary: `Background task \"${agentId}\" launched. Task ID: ${conversationId}`,\n conversationId,\n agentId,\n taskId: conversationId,\n background: true,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: `[bg-task] ${agentId}: ${conversationId}`,\n detailRef: {\n type: 'agent-run' as const,\n conversationId,\n nodeId,\n },\n },\n };\n }\n\n const gen = runLocalAgent({ conversationId, message: prompt });\n const { text, conversationId: cid } = await collectOutput(gen);\n\n const shortSummary = truncateToolSummary(text);\n const nodeId = context.localNodeId?.trim() || 'local';\n return {\n result: text,\n conversationId: cid,\n agentId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run' as const,\n conversationId: cid,\n nodeId,\n },\n },\n };\n}\n\nexport const taskToolConfigSchema = {\n type: 'object',\n properties: {\n agent: {\n type: 'string',\n description: \"Agent ID to delegate to (e.g. 'memeloop:build', 'memeloop:explore')\",\n },\n prompt: {\n type: 'string',\n description: 'Task prompt / instructions for the delegated agent',\n },\n background: {\n type: 'boolean',\n description: 'If true, runs asynchronously and returns a task ID immediately',\n },\n },\n required: ['agent', 'prompt'],\n} as const;\n\n/**\n * Check if we're already nested too deep in agent-runs.\n * The conversationId format for agent-runs is `agentId:timestamp`.\n * We check the current conversation for nesting depth heuristics.\n */\nfunction isTooDeeplyNested(context: { activeToolConversationId?: string }): boolean {\n const cid = context.activeToolConversationId;\n if (!cid) return false;\n // Count how many colons indicate nesting depth\n const depth = cid.split(':').length - 1;\n // Allow up to 2 levels of nesting (agent:sub:timestamp = 2 colons)\n return depth > 2;\n}\n\n/**\n * Set up per-agent tool permissions on the framework context so that\n * the AgentToolLoop's resolveToolPermission picks up the agent's restrictions.\n */\nfunction applyAgentPermissions(\n context: { agentToolLoop?: { toolPermissions?: Record<string, unknown> } },\n agentId: string,\n defaultAction: 'allow' | 'ask' | 'deny',\n rules: Array<{ pattern: string; action: 'allow' | 'ask' | 'deny' }>,\n): void {\n const tp = context.agentToolLoop ?? (context.agentToolLoop = {});\n const tperm = (tp.toolPermissions ?? (tp.toolPermissions = {})) as {\n perAgent?: Record<\n string,\n { default?: string; rules?: Array<{ pattern: string; action: string }> }\n >;\n };\n const perAgent = tperm.perAgent ?? (tperm.perAgent = {});\n perAgent[agentId] = { default: defaultAction, rules };\n}\n\nexport const taskToolImpl: BuiltinToolImpl = async (arguments_, context) => {\n const agentId = arguments_.agent as string | undefined;\n const prompt = arguments_.prompt as string | undefined;\n const background = arguments_.background as boolean | undefined;\n\n if (!agentId || typeof prompt !== 'string' || prompt.trim().length === 0) {\n return { error: \"task requires 'agent' (string) and 'prompt' (non-empty string)\" };\n }\n\n if (isTooDeeplyNested(context)) {\n return {\n error: 'Maximum agent nesting depth exceeded. Cannot delegate further.',\n };\n }\n\n const registry = getAgentProfileRegistry();\n const agentProfile = registry.getAgentProfile(agentId);\n if (!agentProfile) {\n const available = registry\n .listAgentProfiles()\n .map((a) => a.id)\n .join(', ');\n return {\n error: `Agent \"${agentId}\" not found in registry. Available: [${available}]`,\n };\n }\n\n const permissions = {\n default: agentProfile.permissions.default,\n rules: agentProfile.permissions.rules,\n };\n\n const timestamp = Date.now().toString(36);\n const conversationId = `${agentProfile.id}:${timestamp}`;\n\n try {\n if (context.orchestration && (await supportsAgentWorkload(context.orchestration))) {\n return await runTaskViaOrchestration(\n context.orchestration,\n agentProfile.id,\n prompt,\n background,\n context.localNodeId,\n conversationId,\n permissions,\n );\n }\n\n if (!context.runLocalAgent) {\n return {\n error: 'Local agent runner not configured (no runLocalAgent in context).',\n };\n }\n\n applyAgentPermissions(\n context as { agentToolLoop?: { toolPermissions?: Record<string, unknown> } },\n agentProfile.id,\n permissions.default,\n permissions.rules,\n );\n\n return await runTaskLocally(\n (input) => context.runLocalAgent!(input),\n context,\n agentProfile.id,\n prompt,\n background,\n conversationId,\n );\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n error: `Task execution failed: ${message}`,\n conversationId,\n agentId: agentProfile.id,\n };\n }\n};\n\nexport function getTaskToolId(): string {\n return TOOL_ID;\n}\n","/**\n * TodoWrite Tool — Manage structured todo lists stored in conversation context.\n *\n * Supports operations: create, update, complete, list, remove.\n * Todo state is stored in-memory per conversation, keyed by conversationId.\n */\nimport { z } from 'zod';\n\nimport type { BuiltinToolContext } from './types.js';\n\nexport const todoWriteConfigSchema = z.object({\n action: z\n .enum(['create', 'update', 'complete', 'list', 'remove'])\n .describe('Action: create, update, complete, list, or remove'),\n id: z.string().min(1).optional().describe('Todo item ID (required for update/complete/remove)'),\n content: z.string().min(1).optional().describe('Todo item content (required for create/update)'),\n status: z\n .enum(['pending', 'in_progress', 'completed', 'cancelled'])\n .optional()\n .describe(\"Status (defaults to 'pending' for create)\"),\n priority: z\n .enum(['high', 'medium', 'low'])\n .optional()\n .default('medium')\n .describe('Priority level'),\n});\n\nexport const TODO_WRITE_TOOL_ID = 'todoWrite';\n\ninterface TodoItem {\n id: string;\n content: string;\n status: 'pending' | 'in_progress' | 'completed' | 'cancelled';\n priority: 'high' | 'medium' | 'low';\n createdAt: number;\n updatedAt: number;\n}\n\n/**\n * In-memory per-conversation todo store.\n * In production this could be backed by IAgentStorage for persistence.\n */\nconst conversationTodos = new Map<string, Map<string, TodoItem>>();\n\n/** Exported for test cleanup. */\nexport function __clearTodoStore(): void {\n conversationTodos.clear();\n}\n\nfunction getConversationTodos(\n conversationId: string,\n): Map<string, TodoItem> {\n let todos = conversationTodos.get(conversationId);\n if (!todos) {\n todos = new Map<string, TodoItem>();\n conversationTodos.set(conversationId, todos);\n }\n return todos;\n}\n\nfunction formatTodoList(todos: Map<string, TodoItem>): string {\n if (todos.size === 0) {\n return '(No todos)';\n }\n\n const statusOrder: Record<string, number> = {\n in_progress: 0,\n pending: 1,\n completed: 2,\n cancelled: 3,\n };\n\n const sorted = [...todos.values()].sort(\n (a, b) =>\n (statusOrder[a.status] ?? 99) - (statusOrder[b.status] ?? 99) ||\n b.updatedAt - a.updatedAt,\n );\n\n const statusIcons: Record<string, string> = {\n pending: '○',\n in_progress: '◉',\n completed: '✓',\n cancelled: '✗',\n };\n\n return sorted\n .map(\n (t) => `${statusIcons[t.status] ?? '?'} [${t.priority}] ${t.content} (id: ${t.id})`,\n )\n .join('\\n');\n}\n\nfunction getConversationId(context: BuiltinToolContext): string {\n return context.agent?.id ?? context.activeToolConversationId ?? 'default';\n}\n\nexport async function todoWriteImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = todoWriteConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: `invalid_todoWrite_args: ${parsed.error.message}` };\n }\n\n const { action, id, content, status, priority } = parsed.data;\n const conversationId = getConversationId(context);\n const todos = getConversationTodos(conversationId);\n const now = Date.now();\n\n switch (action) {\n case 'create': {\n if (!content) {\n return { error: 'content is required for create action' };\n }\n const newId = id ?? crypto.randomUUID();\n if (todos.has(newId)) {\n return { error: `Todo with id '${newId}' already exists. Use update action.` };\n }\n const item: TodoItem = {\n id: newId,\n content,\n status: status ?? 'pending',\n priority,\n createdAt: now,\n updatedAt: now,\n };\n todos.set(newId, item);\n return {\n result: `Todo created: [${item.priority}] ${item.content} (id: ${item.id})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'update': {\n if (!id) {\n return { error: 'id is required for update action' };\n }\n const existing = todos.get(id);\n if (!existing) {\n return { error: `Todo with id '${id}' not found` };\n }\n if (content !== undefined) existing.content = content;\n if (status !== undefined) existing.status = status;\n existing.priority = priority ?? existing.priority;\n existing.updatedAt = now;\n return {\n result: `Todo updated: [${existing.priority}] ${existing.content} (id: ${existing.id}, status: ${existing.status})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'complete': {\n if (!id) {\n return { error: 'id is required for complete action' };\n }\n const existing = todos.get(id);\n if (!existing) {\n return { error: `Todo with id '${id}' not found` };\n }\n existing.status = 'completed';\n existing.updatedAt = now;\n return {\n result: `Todo completed: [${existing.priority}] ${existing.content} (id: ${existing.id})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'remove': {\n if (!id) {\n // Remove all completed/cancelled todos\n let removed = 0;\n for (const [key, item] of todos) {\n if (item.status === 'completed' || item.status === 'cancelled') {\n todos.delete(key);\n removed++;\n }\n }\n return {\n result: `Removed ${removed} completed/cancelled todo(s)\\n\\n${formatTodoList(todos)}`,\n };\n }\n const removed = todos.delete(id);\n return {\n result: removed\n ? `Todo removed: ${id}\\n\\n${formatTodoList(todos)}`\n : `Todo with id '${id}' not found\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'list':\n default: {\n return {\n result: `Todo list (${todos.size} items):\\n\\n${formatTodoList(todos)}`,\n };\n }\n }\n}\n","/**\n * Builtin tool plugins — registers core tools as LoopPlugin entries.\n *\n * Each tool is a separate LoopPlugin that can be overridden by user/host plugins\n * with the same id. The plugin.install callback calls the tool registry to\n * register the tool implementation.\n *\n * These are registered in the loop registry at startup and loaded by\n * `registerBuiltinTools` via plugin discovery.\n */\n\nimport type { ToolOperationEffect } from '../../orchestration/resources.js';\nimport { registerToolParameterSchema } from '../../tools/schemaRegistry.js';\nimport type { IToolRegistry } from '../../types.js';\nimport { getLoopRegistry } from '../registry.js';\nimport type { LoopPlugin } from '../types.js';\n\n// ─── Import tool implementations ─────────────────────────────────────\n\nimport { ASK_QUESTION_TOOL_ID, askQuestionConfigSchema, askQuestionImpl } from '../../tools/builtins/askQuestion.js';\nimport { ASK_USER_QUESTION_TOOL_ID, askUserQuestionConfigSchema, askUserQuestionImpl } from '../../tools/builtins/askUserQuestion.js';\nimport { getMcpClientToolId, mcpClientConfigSchema, mcpClientImpl } from '../../tools/builtins/mcpClient.js';\nimport { getMcpForwardToolId, mcpForwardConfigSchema, mcpForwardImpl } from '../../tools/builtins/mcpForward.js';\nimport { ORCHESTRATION_TOOL_ID, orchestrationConfigSchema, orchestrationImpl } from '../../tools/builtins/orchestration.js';\nimport { getRemoteAgentToolId, remoteAgentConfigSchema, remoteAgentImpl } from '../../tools/builtins/remoteAgent.js';\nimport { getSpawnAgentToolId, spawnAgentConfigSchema, spawnAgentImpl } from '../../tools/builtins/spawnAgent.js';\nimport { getTaskToolId, taskToolConfigSchema, taskToolImpl } from '../../tools/builtins/task.js';\nimport { TODO_WRITE_TOOL_ID, todoWriteConfigSchema, todoWriteImpl } from '../../tools/builtins/todoWrite.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from '../../tools/builtins/types.js';\n\n// ─── Plugin id constants ───────────────────────────────────────────\n\nexport const PLUGIN_MCP_CLIENT = 'builtin:mcp-client';\nexport const PLUGIN_MCP_FORWARD = 'builtin:mcp-forward';\nexport const PLUGIN_ORCHESTRATION = 'builtin:orchestration';\nexport const PLUGIN_SPAWN_AGENT = 'builtin:spawn-agent';\nexport const PLUGIN_REMOTE_AGENT = 'builtin:remote-agent';\nexport const PLUGIN_ASK_QUESTION = 'builtin:ask-question';\nexport const PLUGIN_TODO_WRITE = 'builtin:todo-write';\nexport const PLUGIN_ASK_USER_QUESTION = 'builtin:ask-user-question';\nexport const PLUGIN_TASK = 'builtin:task';\n\nexport const BUILTIN_TOOL_PLUGIN_IDS = [\n PLUGIN_MCP_CLIENT,\n PLUGIN_MCP_FORWARD,\n PLUGIN_ORCHESTRATION,\n PLUGIN_SPAWN_AGENT,\n PLUGIN_REMOTE_AGENT,\n PLUGIN_ASK_QUESTION,\n PLUGIN_TODO_WRITE,\n PLUGIN_ASK_USER_QUESTION,\n PLUGIN_TASK,\n] as const;\n\ninterface BuiltinToolPluginOptions {\n id: string;\n toolId: string;\n schema: unknown;\n metadata: { displayName: string; description: string };\n implementation: BuiltinToolImpl;\n effect?: ToolOperationEffect;\n}\n\nfunction getToolRegistry(context: { [key: string]: unknown }): IToolRegistry | undefined {\n return context.toolRegistry as IToolRegistry | undefined;\n}\n\nfunction createBuiltinToolPlugin(options: BuiltinToolPluginOptions): LoopPlugin {\n return {\n id: options.id,\n targetLoopId: '*',\n install: (context) => {\n const registry = getToolRegistry(context);\n if (!registry) return;\n\n const builtinContext = context as unknown as BuiltinToolContext;\n const implementation = (arguments_: Record<string, unknown>) => options.implementation(arguments_, builtinContext);\n if (options.effect === undefined) {\n registry.registerTool(options.toolId, implementation, options.schema);\n } else {\n registry.registerTool(\n options.toolId,\n implementation,\n options.schema,\n options.effect,\n );\n }\n registerToolParameterSchema(options.toolId, options.schema, options.metadata);\n },\n };\n}\n\nconst builtinToolPlugins: LoopPlugin[] = [\n createBuiltinToolPlugin({\n id: PLUGIN_MCP_CLIENT,\n toolId: getMcpClientToolId(),\n schema: mcpClientConfigSchema,\n metadata: {\n displayName: 'MCP Client',\n description: 'Call a tool on a remote MCP server (transparent proxy). Requires nodeId, serverName, toolName, and optional args.',\n },\n implementation: mcpClientImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_MCP_FORWARD,\n toolId: getMcpForwardToolId(),\n schema: mcpForwardConfigSchema,\n metadata: {\n displayName: 'MCP Forward',\n description: \"Discover MCP servers and tools on connected nodes. Use action='list' for nodes with servers, action='listTools' for all available tools.\",\n },\n implementation: mcpForwardImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_ORCHESTRATION,\n toolId: ORCHESTRATION_TOOL_ID,\n schema: orchestrationConfigSchema,\n metadata: {\n displayName: 'Orchestration',\n description: 'Discover and manage declarative resources through the policy-scoped orchestration manager.',\n },\n implementation: orchestrationImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_SPAWN_AGENT,\n toolId: getSpawnAgentToolId(),\n schema: spawnAgentConfigSchema,\n metadata: {\n displayName: 'Spawn Agent',\n description: 'Run a local agent-agent-loop with the given definition and message. Returns summary.',\n },\n implementation: spawnAgentImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_REMOTE_AGENT,\n toolId: getRemoteAgentToolId(),\n schema: remoteAgentConfigSchema,\n metadata: {\n displayName: 'Remote Agent',\n description: 'Create and run a agent-agent-loop on a remote node. Requires nodeId, definitionId, message. List nodes with no args.',\n },\n implementation: remoteAgentImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_ASK_QUESTION,\n toolId: ASK_QUESTION_TOOL_ID,\n schema: askQuestionConfigSchema,\n metadata: {\n displayName: 'Ask Question',\n description: 'Block until the user answers (via memeloop.agent.resolveQuestion RPC). Args: question, conversationId, optional timeoutMs.',\n },\n implementation: askQuestionImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_TODO_WRITE,\n toolId: TODO_WRITE_TOOL_ID,\n effect: 'update',\n schema: todoWriteConfigSchema,\n metadata: {\n displayName: 'Todo Write',\n description: 'Manage structured todo lists: create, update, complete, list, remove. Todos scoped per conversation.',\n },\n implementation: todoWriteImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_ASK_USER_QUESTION,\n toolId: ASK_USER_QUESTION_TOOL_ID,\n schema: askUserQuestionConfigSchema,\n metadata: {\n displayName: 'Ask User Question',\n description: 'Pause agent and ask user a question. Supports text, single-select, and multi-select input types. Blocks until answered.',\n },\n implementation: askUserQuestionImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_TASK,\n toolId: getTaskToolId(),\n schema: taskToolConfigSchema,\n metadata: {\n displayName: 'Task Delegation',\n description: 'Delegate a task to a specialized agent-agent-loop (build, plan, explore, oracle, librarian). Supports sync (default) and background modes.',\n },\n implementation: taskToolImpl,\n }),\n];\n\nexport function getBuiltinToolPlugins(): LoopPlugin[] {\n return builtinToolPlugins;\n}\n\n/** Register all builtin tool plugins with the loop registry. */\nexport function registerBuiltinToolPlugins(): void {\n const loopRegistry = getLoopRegistry();\n\n for (const plugin of builtinToolPlugins) {\n if (loopRegistry.getPlugin(plugin.id)) continue;\n loopRegistry.registerPlugin(plugin);\n }\n}\n","import { getActivePluginRegistry } from '../tools/pluginRegistry.js';\nimport type { PromptConcatHooks, PromptConcatTool } from '../tools/types.js';\n\nimport type { PromptNode } from './types.js';\n\nexport const FULL_REPLACEMENT_PLUGIN_TOOL_ID = 'fullReplacement';\nexport const DYNAMIC_POSITION_PLUGIN_TOOL_ID = 'dynamicPosition';\n\nfunction registerFullReplacement(reg: Map<string, PromptConcatTool>): void {\n if (reg.has(FULL_REPLACEMENT_PLUGIN_TOOL_ID)) return;\n reg.set(FULL_REPLACEMENT_PLUGIN_TOOL_ID, (hooks: PromptConcatHooks) => {\n hooks.processPrompts.tapAsync(\n 'fullReplacementLite',\n (context: { messages: unknown[]; maxReplacementChars?: number }, callback) => {\n const msgs = context.messages;\n if (!Array.isArray(msgs)) {\n callback();\n return;\n }\n const maxChars = context?.maxReplacementChars ?? 48_000;\n if (!Number.isFinite(maxChars) || maxChars <= 0) {\n callback();\n return;\n }\n let total = 0;\n const kept: unknown[] = [];\n for (let index = msgs.length - 1; index >= 0; index--) {\n const m = msgs[index] as { content?: unknown };\n const c = typeof m?.content === 'string'\n ? m.content\n : m?.content != null\n ? JSON.stringify(m.content)\n : '';\n total += c.length;\n if (total > maxChars) break;\n kept.push(m);\n }\n kept.reverse();\n context.messages = kept;\n callback();\n },\n );\n });\n}\n\n/**\n * TidGi `dynamicPosition` 极简版:根级 `prompt` 若带 `dynamicPosition: \"deferToEnd\"`,\n * 在用户轮次 ≥2 时将该节点移到同级列表末尾(多轮后再强调尾部 system/user 块)。\n */\nfunction registerDynamicPosition(reg: Map<string, PromptConcatTool>): void {\n if (reg.has(DYNAMIC_POSITION_PLUGIN_TOOL_ID)) return;\n reg.set(DYNAMIC_POSITION_PLUGIN_TOOL_ID, (hooks: PromptConcatHooks) => {\n hooks.processPrompts.tapAsync(\n 'dynamicPositionLite',\n (context: { messages: unknown[]; prompts?: PromptNode[] }, callback) => {\n const prompts = context.prompts;\n const messages = context.messages;\n if (!Array.isArray(prompts) || prompts.length < 2 || !Array.isArray(messages)) {\n callback();\n return;\n }\n const userTurns = messages.filter((m) => (m as { role?: string })?.role === 'user').length;\n if (userTurns < 2) {\n callback();\n return;\n }\n const deferred: PromptNode[] = [];\n const rest: PromptNode[] = [];\n for (const n of prompts) {\n if (n?.dynamicPosition === 'deferToEnd') deferred.push(n);\n else rest.push(n);\n }\n if (deferred.length === 0) {\n callback();\n return;\n }\n context.prompts = [...rest, ...deferred] as typeof context.prompts;\n callback();\n },\n );\n });\n}\n\n/**\n * 注册内置 prompt 插件(fullReplacement、dynamicPosition)。\n * @param target 若传入(如节点 `ToolRegistry` 上的 Map),只写入该表;否则写入活动注册表(全局或 ALS)。\n */\nexport function registerBuiltinPromptPlugins(target?: Map<string, PromptConcatTool>): void {\n const reg = target ?? getActivePluginRegistry();\n registerFullReplacement(reg);\n registerDynamicPosition(reg);\n}\n","import type { ChatMessage } from './conversation/index.js';\nimport type { ConversationMeta } from './sync/protocol.js';\n\nimport { registerBuiltinLoops } from './loopAPI/plugins/builtinLoopsPlugin.js';\nimport { registerBuiltinToolPlugins } from './loopAPI/plugins/builtinToolsPlugin.js';\nimport { getLoopRegistry } from './loopAPI/registry.js';\nimport type { AgentLoopGenerator, AgentLoopInput, AgentLoopRuntime, LoopProfile } from './loopAPI/types.js';\nimport { getBuiltinLoopProfile } from './loopProfiles/loadBuiltins.js';\nimport { registerBuiltinPromptPlugins } from './promptUtilities/builtinPromptPlugins.js';\nimport { nextLamportClockForConversation } from './storage/nextLamport.js';\nimport type { AgentFrameworkContext } from './types.js';\n\nexport interface CreateAgentOptions {\n definitionId: string;\n initialMessage?: string;\n}\n\nexport interface SendMessageOptions {\n conversationId: string;\n message: string;\n definitionId?: string;\n userMessage?: AgentLoopInput['userMessage'];\n resumeSession?: ChatMessage[];\n}\n\nexport interface MemeLoopRuntime {\n createAgent(options: CreateAgentOptions): Promise<{ conversationId: string }>;\n sendMessage(options: SendMessageOptions): Promise<void>;\n cancelAgent(conversationId: string): Promise<void>;\n subscribeToUpdates(conversationId: string, listener: (update: unknown) => void): () => void;\n}\n\nexport interface CreateAgentLoopRunnerOptions {\n definitionId: string;\n conversationId?: string;\n}\n\nasync function drainAgentLoop(\n gen: AgentLoopGenerator,\n conversationId: string,\n notify: (conversationId: string, update: unknown) => void,\n): Promise<void> {\n try {\n for await (const step of gen) {\n notify(conversationId, { type: 'agent-step', step });\n }\n notify(conversationId, { type: 'agent-done' });\n } catch (error) {\n notify(conversationId, {\n type: 'agent-error',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nfunction inferDefinitionIdFromConversationId(conversationId: string): string {\n const parts = conversationId.split(':');\n if (parts.length >= 2) return parts.slice(0, -1).join(':');\n return conversationId;\n}\n\nasync function resolveDefinitionId(\n context: AgentFrameworkContext,\n conversationId: string,\n): Promise<string> {\n try {\n const meta = await context.storage.getConversationMeta(conversationId);\n if (meta?.definitionId) return meta.definitionId;\n } catch {\n /* optional for old storage adapters */\n }\n return inferDefinitionIdFromConversationId(conversationId);\n}\n\nasync function resolveLoopProfile(\n context: AgentFrameworkContext,\n definitionId: string,\n): Promise<LoopProfile | null> {\n const definition = (context.resolveAgentDefinition ? await context.resolveAgentDefinition(definitionId) : null) ??\n (await context.storage.getAgentDefinition(definitionId)) ??\n getBuiltinLoopProfile(definitionId) ??\n null;\n if (!definition) return null;\n return definition as unknown as LoopProfile;\n}\n\nasync function createProfileRunner(\n context: AgentFrameworkContext,\n definitionId: string,\n runtime?: Partial<AgentLoopRuntime>,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n const profile = await resolveLoopProfile(context, definitionId);\n if (!profile) return null;\n return createAgentProfileRunner(context, profile, runtime);\n}\n\n/**\n * Create a loop runner for an already-resolved profile. Registers builtin\n * loops/tools/prompts and threads the host script policy through, exactly\n * like the definition-based path.\n */\nexport async function createAgentProfileRunner(\n context: AgentFrameworkContext,\n profile: LoopProfile,\n runtime?: Partial<AgentLoopRuntime>,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n registerBuiltinLoops();\n registerBuiltinToolPlugins();\n registerBuiltinPromptPlugins(context.tools.getPromptPlugins?.());\n\n const runnerContext = {\n ...context,\n runtime,\n scriptPolicy: context.loopScriptPolicy,\n toolRegistry: context.tools,\n } as { [key: string]: unknown };\n return getLoopRegistry().createRunnerForProfile(profile, runnerContext);\n}\n\n/**\n * Create a loop runner for a profile with a fresh per-conversation script\n * runtime (state, checkpoints, cancellation, child propagation). Used by the\n * workload execution path (plan 24.14) where the profile is synthesized from\n * a resource rather than resolved from the definition store.\n */\nexport async function createAgentLoopScriptRunner(\n context: AgentFrameworkContext,\n profile: LoopProfile,\n conversationId: string,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n const cancellation = context.conversationCancellation ?? new Set<string>();\n context.conversationCancellation ??= cancellation;\n const scriptState = new Map<string, unknown>();\n return createAgentProfileRunner(\n context,\n profile,\n createScriptRuntime(context, cancellation, scriptState, conversationId),\n );\n}\n\nfunction createScriptRuntime(\n context: AgentFrameworkContext,\n cancellation: Set<string>,\n scriptState: Map<string, unknown>,\n conversationId: string,\n parentConversationId?: string,\n): Partial<AgentLoopRuntime> {\n const stateKey = (key: string): string => `${conversationId}:${key}`;\n return {\n orchestration: context.orchestration,\n scriptDeployment: context.scriptDeployment,\n runChildAgent: async function*(input) {\n const childRuntime = createScriptRuntime(\n context,\n cancellation,\n scriptState,\n input.conversationId,\n conversationId,\n );\n const run = await createProfileRunner(context, input.profileId, childRuntime);\n if (!run) {\n yield {\n type: 'message',\n data: `Child agent profile not found: ${input.profileId}`,\n };\n return;\n }\n yield* run({ conversationId: input.conversationId, message: input.prompt });\n },\n log: (event, data) => context.logger?.debug?.(event, data),\n emit: () => undefined,\n signal: {\n get cancelled() {\n return cancellation.has(conversationId) || (parentConversationId ? cancellation.has(parentConversationId) : false);\n },\n },\n state: {\n get: async <T>(key: string) => {\n const local = scriptState.get(stateKey(key)) as T | undefined;\n if (local !== undefined) return local;\n const persisted = await context.loopCheckpoints?.loadCheckpoint<T>(conversationId, `state:${key}`);\n if (persisted !== undefined) scriptState.set(stateKey(key), persisted);\n return persisted;\n },\n set: async (key, value) => {\n scriptState.set(stateKey(key), value);\n await context.loopCheckpoints?.saveCheckpoint(conversationId, `state:${key}`, value);\n },\n update: async (key, updater) => {\n const fullKey = stateKey(key);\n const previous = scriptState.get(fullKey);\n const next = updater(previous);\n scriptState.set(fullKey, next);\n await context.loopCheckpoints?.saveCheckpoint(conversationId, `state:${key}`, next);\n },\n },\n checkpoint: async (key, result) => {\n scriptState.set(stateKey(`checkpoint:${key}`), result);\n await context.loopCheckpoints?.saveCheckpoint(conversationId, key, result);\n },\n loadCheckpoint: async <T>(key: string) => {\n const memoryKey = stateKey(`checkpoint:${key}`);\n if (scriptState.has(memoryKey)) return scriptState.get(memoryKey) as T;\n const result = await context.loopCheckpoints?.loadCheckpoint<T>(conversationId, key);\n if (result !== undefined) scriptState.set(memoryKey, result);\n return result;\n },\n };\n}\n\nexport async function createAgentLoopRunner(\n context: AgentFrameworkContext,\n options: CreateAgentLoopRunnerOptions,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n const cancellation = context.conversationCancellation ?? new Set<string>();\n context.conversationCancellation ??= cancellation;\n const scriptState = new Map<string, unknown>();\n const conversationId = options.conversationId ?? options.definitionId;\n return createProfileRunner(\n context,\n options.definitionId,\n createScriptRuntime(context, cancellation, scriptState, conversationId),\n );\n}\n\nexport function createMemeLoopRuntime(context: AgentFrameworkContext): MemeLoopRuntime {\n const listeners = new Map<string, Set<(update: unknown) => void>>();\n const cancellation = context.conversationCancellation ?? new Set<string>();\n const scriptState = new Map<string, unknown>();\n context.conversationCancellation ??= cancellation;\n\n function notify(conversationId: string, update: unknown) {\n const set = listeners.get(conversationId);\n if (!set) return;\n for (const listener of set) {\n listener(update);\n }\n }\n\n async function runAgentLoop(input: AgentLoopInput, definitionId: string): Promise<boolean> {\n const run = context.runAgentToolLoop ?? await createProfileRunner(\n context,\n definitionId,\n createScriptRuntime(context, cancellation, scriptState, input.conversationId),\n );\n if (!run) return false;\n void drainAgentLoop(run(input), input.conversationId, notify);\n return true;\n }\n\n async function* runChildAgent(input: Parameters<NonNullable<AgentFrameworkContext['runChildAgent']>>[0]): AgentLoopGenerator {\n const run = await createProfileRunner(\n context,\n input.profileId,\n createScriptRuntime(context, cancellation, scriptState, input.conversationId),\n );\n if (!run) {\n yield {\n type: 'message',\n data: `Child agent profile not found: ${input.profileId}`,\n };\n return;\n }\n yield* run({ conversationId: input.conversationId, message: input.prompt });\n }\n\n context.runChildAgent ??= runChildAgent;\n\n return {\n async createAgent(options) {\n const now = Date.now();\n const conversationId = `${options.definitionId}:${now.toString(36)}`;\n cancellation?.delete(conversationId);\n\n const meta: ConversationMeta = {\n conversationId,\n title: options.definitionId,\n lastMessagePreview: context.runAgentToolLoop ? '' : options.initialMessage ?? '',\n lastMessageTimestamp: now,\n messageCount: context.runAgentToolLoop || !options.initialMessage ? 0 : 1,\n originNodeId: 'local',\n originClock: 1,\n definitionId: options.definitionId,\n isUserInitiated: true,\n };\n await context.storage.upsertConversationMetadata(meta);\n\n if (options.initialMessage) {\n const started = await runAgentLoop(\n { conversationId, message: options.initialMessage },\n options.definitionId,\n );\n if (started) {\n notify(conversationId, { type: 'created', conversationId });\n return { conversationId };\n }\n }\n\n if (options.initialMessage) {\n const message: ChatMessage = {\n messageId: `${conversationId}:m1`,\n conversationId,\n originNodeId: meta.originNodeId,\n timestamp: now,\n lamportClock: 1,\n role: 'user',\n content: options.initialMessage,\n };\n await context.storage.appendMessage(message);\n }\n\n notify(conversationId, { type: 'created', conversationId });\n return { conversationId };\n },\n async sendMessage(options) {\n cancellation?.delete(options.conversationId);\n const definitionId = options.definitionId ?? await resolveDefinitionId(context, options.conversationId);\n const started = await runAgentLoop(\n {\n conversationId: options.conversationId,\n message: options.message,\n userMessage: options.userMessage,\n resumeSession: options.resumeSession,\n },\n definitionId,\n );\n if (started) {\n notify(options.conversationId, { type: 'message-queued' });\n return;\n }\n\n if (options.resumeSession && options.resumeSession.length > 0) {\n await context.storage.insertMessagesIfAbsent(options.resumeSession);\n }\n\n const now = Date.now();\n const lamportClock = await nextLamportClockForConversation(\n context.storage,\n options.conversationId,\n );\n const hostUserMessage = options.userMessage;\n const message: ChatMessage = {\n ...hostUserMessage,\n messageId: hostUserMessage?.messageId ?? `${options.conversationId}:${now.toString(36)}`,\n conversationId: options.conversationId,\n originNodeId: hostUserMessage?.originNodeId ?? 'local',\n timestamp: hostUserMessage?.timestamp ?? now,\n lamportClock: hostUserMessage?.lamportClock ?? lamportClock,\n role: 'user',\n content: hostUserMessage?.content ?? options.message,\n };\n await context.storage.appendMessage(message);\n notify(options.conversationId, { type: 'message-queued' });\n },\n async cancelAgent(conversationId) {\n cancellation?.add(conversationId);\n notify(conversationId, { type: 'cancelled' });\n },\n subscribeToUpdates(conversationId, listener) {\n const set = listeners.get(conversationId) ?? new Set();\n set.add(listener);\n listeners.set(conversationId, set);\n return () => {\n const current = listeners.get(conversationId);\n if (!current) return;\n current.delete(listener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A;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AAAA,EACX,CAAC,yCAAyC,GAAG;AAAA,IAC3C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AAAA,EACX,CAAC,iCAAiC,GAAG;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA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iB,gBAAgB;AAAA,QAC/C,MAAM;AAAA,QACN,SAAS,iBAAiB,WAAW,QAAQ;AAAA,MAC/C;AACA,YAAM,QAAQ,QAAQ,cAAc,OAAO;AAC3C,aAAO,QAAQ,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAAA,IAC3D;AAAA,IACA,MAAM,YAAY,gBAAgB;AAChC,oBAAc,IAAI,cAAc;AAChC,aAAO,gBAAgB,EAAE,MAAM,YAAY,CAAC;AAAA,IAC9C;AAAA,IACA,mBAAmB,gBAAgB,UAAU;AAC3C,YAAM,MAAM,UAAU,IAAI,cAAc,KAAK,oBAAI,IAAI;AACrD,UAAI,IAAI,QAAQ;AAChB,gBAAU,IAAI,gBAAgB,GAAG;AACjC,aAAO,MAAM;AACX,cAAM,UAAU,UAAU,IAAI,cAAc;AAC5C,YAAI,CAAC,QAAS;AACd,gBAAQ,OAAO,QAAQ;AACvB,YAAI,QAAQ,SAAS,GAAG;AACtB,oBAAU,OAAO,cAAc;AAAA,QACjC;AAAA,MACF;AAAA,IACF;AAAA,EACF;AACF;","names":["name","spec","waitOptions","builtinDigestsRegistered","ensureBuiltinDigestsRegistered","isAsyncIterable","messageStep","drainEmittedSteps","z","z","TOOL_ID","TOOL_ID","nodeId","message","TOOL_ID","supportsAgentWorkload","TOOL_ID","supportsAgentWorkload","gen","nodeId","z","removed"]}
|