@tangle-network/agent-runtime 0.91.0 → 0.92.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/README.md +4 -2
- package/dist/agent.d.ts +3 -3
- package/dist/agent.js +88 -9
- package/dist/agent.js.map +1 -1
- package/dist/{mcp-serve-verifier-XsX8rkB9.d.ts → agentic-generator-B8oeE2Yv.d.ts} +6 -33
- package/dist/analyst-loop.d.ts +1 -1
- package/dist/candidate-execution/index.d.ts +104 -0
- package/dist/candidate-execution/index.js +34 -0
- package/dist/candidate-execution/index.js.map +1 -0
- package/dist/chunk-3BE7KTMU.js +1229 -0
- package/dist/chunk-3BE7KTMU.js.map +1 -0
- package/dist/chunk-3D2RHC4K.js +73 -0
- package/dist/chunk-3D2RHC4K.js.map +1 -0
- package/dist/chunk-3MDZX7YU.js +125 -0
- package/dist/chunk-3MDZX7YU.js.map +1 -0
- package/dist/{chunk-NC66AM3S.js → chunk-6O5USWVH.js} +32 -1413
- package/dist/chunk-6O5USWVH.js.map +1 -0
- package/dist/chunk-6O73TRHW.js +142 -0
- package/dist/chunk-6O73TRHW.js.map +1 -0
- package/dist/{chunk-JRS3YSRZ.js → chunk-7VJJJ2T2.js} +2 -2
- package/dist/chunk-A62TP7SK.js +4784 -0
- package/dist/chunk-A62TP7SK.js.map +1 -0
- package/dist/chunk-APVPRF4Y.js +2166 -0
- package/dist/chunk-APVPRF4Y.js.map +1 -0
- package/dist/{chunk-DWWII6N2.js → chunk-AUEIDTR3.js} +2 -2
- package/dist/{chunk-FF77IBQM.js → chunk-FRBHUNQ7.js} +2 -141
- package/dist/chunk-FRBHUNQ7.js.map +1 -0
- package/dist/{chunk-7ON74BQO.js → chunk-GDAQUFG6.js} +2 -2
- package/dist/{chunk-AD7JW4QG.js → chunk-I7WVPJBZ.js} +23 -1231
- package/dist/chunk-I7WVPJBZ.js.map +1 -0
- package/dist/{chunk-IOUUITQA.js → chunk-IGGZGKJD.js} +3 -3
- package/dist/chunk-PH65PR4F.js +860 -0
- package/dist/chunk-PH65PR4F.js.map +1 -0
- package/dist/chunk-RSWM2ZKM.js +659 -0
- package/dist/chunk-RSWM2ZKM.js.map +1 -0
- package/dist/{chunk-BZF3KQ6G.js → chunk-VSWBYWFK.js} +4 -122
- package/dist/chunk-VSWBYWFK.js.map +1 -0
- package/dist/{completion-gate-DkAnUmpb.d.ts → completion-gate-BLaiN0-X.d.ts} +1 -1
- package/dist/{coordination-rRj5hjJK.d.ts → coordination-DxJ83oZA.d.ts} +12 -5
- package/dist/environment-provider.d.ts +2 -2
- package/dist/environment-provider.js +2 -1
- package/dist/improve-CUVCq7xg.d.ts +152 -0
- package/dist/{improvement-adapter-CDR8QNVM.d.ts → improvement-adapter-BieWeK5J.d.ts} +16 -0
- package/dist/index.d.ts +27 -1092
- package/dist/index.js +108 -6491
- package/dist/index.js.map +1 -1
- package/dist/intelligence.d.ts +160 -13
- package/dist/intelligence.js +535 -59
- package/dist/intelligence.js.map +1 -1
- package/dist/knowledge.d.ts +6 -6
- package/dist/knowledge.js +6 -4
- package/dist/lifecycle.d.ts +2 -1
- package/dist/lifecycle.js +5 -3
- package/dist/lifecycle.js.map +1 -1
- package/dist/{loop-runner-bin-DTbZVGfM.d.ts → loop-runner-bin-kKUNGLyV.d.ts} +2 -2
- package/dist/loop-runner-bin.d.ts +5 -5
- package/dist/loop-runner-bin.js +8 -5
- package/dist/loops.d.ts +16 -16
- package/dist/loops.js +47 -41
- package/dist/mcp/bin.js +6 -4
- package/dist/mcp/bin.js.map +1 -1
- package/dist/mcp/index.d.ts +8 -8
- package/dist/mcp/index.js +9 -6
- package/dist/mcp/index.js.map +1 -1
- package/dist/mcp-serve-verifier-Bg4C3p5S.d.ts +34 -0
- package/dist/{openai-tools-C4ZfUD4L.d.ts → openai-tools-E3woykz9.d.ts} +1 -1
- package/dist/prepare-Z08a4heC.d.ts +713 -0
- package/dist/profiles.d.ts +1 -1
- package/dist/{router-client-DJImUDlm.d.ts → sanitize-C9go6tXj.d.ts} +113 -1
- package/dist/{structural-rollout-MwlpgQ-6.d.ts → structural-rollout-DHGDbhvR.d.ts} +3 -3
- package/dist/{supervise-DPmYPk0j.d.ts → supervise-T2pazU3G.d.ts} +4 -4
- package/dist/{types-SyuwunY_.d.ts → types-B00NtbCs.d.ts} +1 -1
- package/dist/{types-eMNgWgFi.d.ts → types-DAdIm4AC.d.ts} +1 -1
- package/dist/{worktree-fanout-BDFQIO-Y.d.ts → worktree-fanout-BUb2Ag02.d.ts} +3 -3
- package/package.json +26 -35
- package/skills/build-with-agent-runtime/SKILL.md +1 -1
- package/dist/chunk-AD7JW4QG.js.map +0 -1
- package/dist/chunk-BZF3KQ6G.js.map +0 -1
- package/dist/chunk-FF77IBQM.js.map +0 -1
- package/dist/chunk-IVGYLCFH.js +0 -381
- package/dist/chunk-IVGYLCFH.js.map +0 -1
- package/dist/chunk-NC66AM3S.js.map +0 -1
- /package/dist/{chunk-JRS3YSRZ.js.map → chunk-7VJJJ2T2.js.map} +0 -0
- /package/dist/{chunk-DWWII6N2.js.map → chunk-AUEIDTR3.js.map} +0 -0
- /package/dist/{chunk-7ON74BQO.js.map → chunk-GDAQUFG6.js.map} +0 -0
- /package/dist/{chunk-IOUUITQA.js.map → chunk-IGGZGKJD.js.map} +0 -0
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/runtime/util.ts","../src/runtime/environment-provider.ts"],"sourcesContent":["/**\n *\n * Internal loop-kernel utilities shared across the kernel, drivers, and the\n * sandbox-acquire layer. Not part of the public barrel surface.\n *\n * @experimental\n */\n\nimport type { SandboxInstance } from '@tangle-network/sandbox'\nimport type { LoopTokenUsage } from './types'\n\n/**\n * Best-effort sandbox delete. Skips instances without a `delete` (test fakes);\n * swallows errors (the platform reaps on expiry). Returns `false` when delete\n * threw, `true` otherwise, so callers can surface a leak if they choose.\n */\nexport async function deleteBoxSafe(box: SandboxInstance | undefined): Promise<boolean> {\n if (!box || typeof (box as { delete?: unknown }).delete !== 'function') return true\n try {\n await box.delete()\n return true\n } catch {\n return false\n }\n}\n\n/** Short base36 id for trace correlation. Not cryptographic, not collision-free. */\nexport function randomSuffix(len = 8): string {\n return Math.random()\n .toString(36)\n .slice(2, 2 + len)\n}\n\n/** Collision-resistant id for sandbox naming (find-by-name recovery must be unique). */\nexport function randomUuid(): string {\n return crypto.randomUUID()\n}\n\n/** Construct an AbortError. Downstream code pattern-matches on `err.name`. */\nexport function abortError(): Error {\n const err = new Error('aborted')\n err.name = 'AbortError'\n return err\n}\n\n/** Throw an AbortError. */\nexport function throwAbort(): never {\n throw abortError()\n}\n\n/** Throw if the signal is already aborted; otherwise no-op. */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) throw abortError()\n}\n\n/** True for any error whose `name` is `AbortError` (the cross-kernel abort contract). */\nexport function isAbortError(err: unknown): boolean {\n return err instanceof Error && err.name === 'AbortError'\n}\n\n/**\n * Sleep that resolves early on abort and always clears its timer so it never\n * keeps the event loop alive. Resolves (does not reject) on abort — callers\n * re-check the signal explicitly after the sleep.\n */\nexport function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal?.aborted) {\n resolve()\n return\n }\n let onAbort: (() => void) | undefined\n const timer = setTimeout(() => {\n if (onAbort && signal) signal.removeEventListener('abort', onAbort)\n resolve()\n }, ms)\n if (signal) {\n onAbort = () => {\n clearTimeout(timer)\n resolve()\n }\n signal.addEventListener('abort', onAbort, { once: true })\n }\n })\n}\n\n/**\n * Race a promise against a timeout. Resolves with the value if it settles in\n * time, otherwise resolves with `undefined`. Always clears the timer.\n */\nexport function withTimeout<T>(promise: Promise<T>, ms: number): Promise<T | undefined> {\n return new Promise<T | undefined>((resolve) => {\n const timer = setTimeout(() => resolve(undefined), ms)\n promise.then(\n (value) => {\n clearTimeout(timer)\n resolve(value)\n },\n () => {\n clearTimeout(timer)\n resolve(undefined)\n },\n )\n })\n}\n\ninterface StringifyOptions {\n /** Pretty-print with 2-space indent. Default false (compact). */\n pretty?: boolean\n /** Truncate to this many chars, appending `…`. Default unbounded. */\n max?: number\n}\n\n/**\n * `JSON.stringify` with a `String()` fallback on throw (cyclic / non-JSON).\n * Strings pass through unstringified so a preview of a string output is the\n * string itself, not a quoted re-encoding.\n */\nexport function stringifySafe(value: unknown, opts: StringifyOptions = {}): string {\n let s: string\n try {\n if (typeof value === 'string') {\n s = value\n } else {\n const json = opts.pretty ? JSON.stringify(value, null, 2) : JSON.stringify(value)\n s = json ?? String(value)\n }\n } catch {\n s = String(value)\n }\n if (opts.max !== undefined && s.length > opts.max) return `${s.slice(0, opts.max)}…`\n return s\n}\n\n/** A fresh zero token-usage accumulator. */\nexport function zeroTokenUsage(): LoopTokenUsage {\n return { input: 0, output: 0 }\n}\n\n/** Add `delta` into `acc` in place. Missing fields count as zero. */\nexport function addTokenUsage(acc: LoopTokenUsage, delta: Partial<LoopTokenUsage>): void {\n acc.input += delta.input ?? 0\n acc.output += delta.output ?? 0\n}\n\n/**\n * Map `items` through `fn` with at most `limit` calls in flight at once,\n * preserving input order in the result. On the first `fn` rejection no NEW\n * items are picked up; already-in-flight calls are awaited, then the first\n * error is rethrown. `limit` is clamped to ≥ 1.\n *\n * Used where a burst of provisioning (e.g. forking N child boxes) must respect\n * the loop's concurrency bound instead of firing all N at once.\n */\nexport async function mapWithConcurrency<T, R>(\n items: readonly T[],\n limit: number,\n fn: (item: T, index: number) => Promise<R>,\n): Promise<R[]> {\n const bound = Math.max(1, Math.floor(limit))\n const results = new Array<R>(items.length)\n let next = 0\n let failed = false\n const worker = async (): Promise<void> => {\n while (!failed) {\n const i = next\n next += 1\n if (i >= items.length) return\n try {\n results[i] = await fn(items[i] as T, i)\n } catch (err) {\n failed = true\n throw err\n }\n }\n }\n const workerCount = Math.min(bound, items.length)\n await Promise.all(Array.from({ length: workerCount }, () => worker()))\n return results\n}\n","import type {\n AgentProfile,\n AgentProfileValidationResult,\n InputPart,\n TokenUsage,\n} from '@tangle-network/agent-interface'\nimport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentEvent,\n AgentEnvironmentProvider,\n AgentEnvironmentQuery,\n AgentEnvironmentStatus,\n AgentEnvironmentSummary,\n AgentProfileRef,\n AgentSession,\n AgentSessionRef,\n AgentSessionStatus,\n AgentTurnInput,\n AgentTurnResult,\n CheckpointRef,\n CheckpointRequest,\n CreateAgentEnvironmentInput,\n ExecRequest,\n ExecResult,\n ForkRequest,\n PlacementInfo,\n ResourceRequest,\n} from '@tangle-network/agent-interface/environment-provider'\nimport type {\n BackendType,\n CreateSandboxOptions,\n PromptOptions,\n PromptResult,\n SandboxEvent,\n ExecResult as SandboxExecResult,\n SandboxInstance,\n} from '@tangle-network/sandbox'\nimport type {\n Executor,\n ExecutorContext,\n ExecutorFactory,\n ExecutorResult,\n Runtime,\n Spend,\n UsageEvent,\n} from './supervise/types'\nimport type { LoopSandboxPlacement, SandboxClient } from './types'\nimport { zeroTokenUsage } from './util'\n\n// Keep this file loadable from the lean `./environment-provider` export without agent-eval installed.\nclass ValidationError extends Error {\n constructor(message: string, options?: { cause?: unknown }) {\n super(message, options)\n this.name = 'ValidationError'\n }\n}\n\nexport type {\n AgentEnvironment,\n AgentEnvironmentCapabilities,\n AgentEnvironmentEvent,\n AgentEnvironmentProvider,\n AgentEnvironmentQuery,\n AgentEnvironmentStatus,\n AgentEnvironmentSummary,\n AgentProfileRef,\n AgentSession,\n AgentSessionRef,\n AgentSessionStatus,\n AgentTurnInput,\n AgentTurnResult,\n CheckpointRef,\n CheckpointRequest,\n CreateAgentEnvironmentInput,\n ExecRequest,\n ExecResult,\n ForkRequest,\n PlacementInfo,\n ResourceRequest,\n WorkspaceRequest,\n} from '@tangle-network/agent-interface/environment-provider'\n\n/** Provider object or registry name accepted by runtime provider adapters.\n * @experimental */\nexport type AgentEnvironmentProviderRef = AgentEnvironmentProvider | string\n\n/** In-memory registry for named `AgentEnvironmentProvider` instances.\n * @experimental */\nexport interface AgentEnvironmentProviderRegistry {\n register(provider: AgentEnvironmentProvider, options?: { replace?: boolean }): void\n has(name: string): boolean\n get(name: string): AgentEnvironmentProvider | undefined\n require(name: string): AgentEnvironmentProvider\n names(): string[]\n providers(): AgentEnvironmentProvider[]\n capabilities(name: string): Promise<AgentEnvironmentCapabilities>\n}\n\n/** Create a registry that resolves provider names to concrete provider instances.\n * @experimental */\nexport function createAgentEnvironmentProviderRegistry(\n providers: Iterable<AgentEnvironmentProvider> = [],\n): AgentEnvironmentProviderRegistry {\n const entries = new Map<string, AgentEnvironmentProvider>()\n\n const registry: AgentEnvironmentProviderRegistry = {\n register(provider, options = {}): void {\n if (!provider.name) {\n throw new ValidationError('agent environment provider registry: provider.name required')\n }\n if (!options.replace && entries.has(provider.name)) {\n throw new ValidationError(\n `agent environment provider registry: provider \"${provider.name}\" already registered`,\n )\n }\n entries.set(provider.name, provider)\n },\n has(name): boolean {\n return entries.has(name)\n },\n get(name): AgentEnvironmentProvider | undefined {\n return entries.get(name)\n },\n require(name): AgentEnvironmentProvider {\n const provider = entries.get(name)\n if (!provider) {\n const available = Array.from(entries.keys()).sort()\n const suffix = available.length > 0 ? `; available: ${available.join(', ')}` : ''\n throw new ValidationError(\n `agent environment provider registry: provider \"${name}\" is not registered${suffix}`,\n )\n }\n return provider\n },\n names(): string[] {\n return Array.from(entries.keys()).sort()\n },\n providers(): AgentEnvironmentProvider[] {\n return registry.names().map((name) => registry.require(name))\n },\n async capabilities(name): Promise<AgentEnvironmentCapabilities> {\n return registry.require(name).capabilities()\n },\n }\n\n for (const provider of providers) registry.register(provider)\n return registry\n}\n\n/** Resolve a provider instance or registry name, failing loudly when a name is unknown.\n * @experimental */\nexport function resolveAgentEnvironmentProvider(\n provider: AgentEnvironmentProviderRef,\n registry?: AgentEnvironmentProviderRegistry,\n): AgentEnvironmentProvider {\n if (typeof provider !== 'string') return provider\n if (!registry) {\n throw new ValidationError(\n `agent environment provider \"${provider}\" requires an AgentEnvironmentProviderRegistry`,\n )\n }\n return registry.require(provider)\n}\n\n/** Options for exposing an `AgentEnvironmentProvider` through the legacy sandbox client port.\n * @experimental */\nexport interface ProviderAsSandboxClientOptions {\n defaults?: Partial<CreateAgentEnvironmentInput>\n requireTerminalEvent?: boolean\n mapCreateOptions?: (\n options: CreateSandboxOptions | undefined,\n ) => Partial<CreateAgentEnvironmentInput>\n}\n\n/** Adapt a neutral environment provider to the `SandboxClient` interface used by existing loop paths.\n * @experimental */\nexport function providerAsSandboxClient(\n provider: AgentEnvironmentProvider,\n options: ProviderAsSandboxClientOptions = {},\n): SandboxClient {\n return {\n async create(createOptions?: CreateSandboxOptions): Promise<SandboxInstance> {\n const mapped = {\n ...(options.defaults ?? {}),\n ...createInputFromSandboxOptions(createOptions),\n ...(options.mapCreateOptions?.(createOptions) ?? {}),\n }\n if (mapped.profile === undefined) {\n throw new ValidationError(\n `providerAsSandboxClient(${provider.name}): profile required in defaults or CreateSandboxOptions.backend.profile`,\n )\n }\n const environment = await provider.create(mapped as CreateAgentEnvironmentInput)\n return environmentAsSandboxInstance(environment, {\n requireTerminalEvent: options.requireTerminalEvent ?? true,\n })\n },\n }\n}\n\n/** Options for wrapping the current Tangle sandbox client as an environment provider.\n * @experimental */\nexport interface SandboxClientProviderOptions {\n name?: string\n defaultBackend?: BackendType\n capabilities?:\n | AgentEnvironmentCapabilities\n | (() => AgentEnvironmentCapabilities | Promise<AgentEnvironmentCapabilities>)\n validateProfile?: (\n profile: AgentProfileRef,\n ) => AgentProfileValidationResult | Promise<AgentProfileValidationResult>\n mapCreateInput?: (input: CreateAgentEnvironmentInput) => CreateSandboxOptions\n}\n\n/** Adapt a `SandboxClient` into the shared `AgentEnvironmentProvider` contract.\n * @experimental */\nexport function sandboxClientAsProvider(\n client: SandboxClient,\n options: SandboxClientProviderOptions = {},\n): AgentEnvironmentProvider {\n const providerName = options.name ?? 'tangle-sandbox'\n return {\n name: providerName,\n capabilities: async () => {\n if (options.capabilities) {\n return typeof options.capabilities === 'function'\n ? options.capabilities()\n : options.capabilities\n }\n return defaultTangleSandboxCapabilities()\n },\n ...(options.validateProfile ? { validateProfile: options.validateProfile } : {}),\n async create(input: CreateAgentEnvironmentInput): Promise<AgentEnvironment> {\n const createOptions =\n options.mapCreateInput?.(input) ??\n sandboxOptionsFromCreateInput(input, options.defaultBackend ?? 'opencode')\n const box = await client.create(createOptions)\n return sandboxInstanceAsEnvironment(box, providerName, client)\n },\n ...(hasGet(client)\n ? {\n async get(id: string): Promise<AgentEnvironment | null> {\n const box = await client.get(id)\n return box ? sandboxInstanceAsEnvironment(box, providerName, client) : null\n },\n }\n : {}),\n ...(hasList(client)\n ? {\n async list(query?: AgentEnvironmentQuery): Promise<AgentEnvironmentSummary[]> {\n const boxes = await client.list(query?.providerOptions)\n return boxes.map((box) => ({\n id: String(box.id),\n provider: providerName,\n name: typeof box.name === 'string' ? box.name : undefined,\n status: statusFromUnknown(readBoxStatus(box)),\n metadata: readBoxMetadata(box),\n }))\n },\n }\n : {}),\n }\n}\n\n/** Options for running a provider as a supervise-mode executor.\n * @experimental */\nexport interface ProviderExecutorOptions {\n defaults?: Partial<CreateAgentEnvironmentInput>\n runtime?: Runtime\n destroyOnSettle?: boolean\n requireTerminalEvent?: boolean\n taskToTurn?: (task: unknown, specProfile: AgentProfile) => AgentTurnInput\n}\n\n/** Adapt an environment provider into an `ExecutorFactory` for `createExecutor`.\n * @experimental */\nexport function providerAsExecutor(\n provider: AgentEnvironmentProvider,\n options: ProviderExecutorOptions = {},\n): ExecutorFactory<unknown> {\n return (spec, ctx) => createProviderExecutor(provider, spec.profile, ctx, options)\n}\n\nfunction createProviderExecutor(\n provider: AgentEnvironmentProvider,\n profile: AgentProfile,\n ctx: ExecutorContext,\n options: ProviderExecutorOptions,\n): Executor<unknown> {\n const controller = new AbortController()\n const abortIfSignalled = () => {\n if (ctx.signal.aborted) controller.abort()\n }\n abortIfSignalled()\n if (!ctx.signal.aborted) ctx.signal.addEventListener('abort', abortIfSignalled, { once: true })\n\n let environment: AgentEnvironment | undefined\n let artifact: ExecutorResult<unknown> | undefined\n\n return {\n runtime: options.runtime ?? (provider.name as Runtime),\n execute(task, signal): AsyncIterable<UsageEvent> {\n return streamProviderExecutor({\n provider,\n profile,\n task,\n signal,\n controller,\n options,\n onEnvironment: (env) => {\n environment = env\n },\n onArtifact: (next) => {\n artifact = next\n },\n })\n },\n async teardown(_grace): Promise<{ destroyed: boolean }> {\n controller.abort()\n await environment?.destroy?.()\n return { destroyed: true }\n },\n resultArtifact(): ExecutorResult<unknown> {\n if (!artifact) {\n throw new ValidationError(\n `providerAsExecutor(${provider.name}): resultArtifact() read before stream drained`,\n )\n }\n return artifact\n },\n }\n}\n\ninterface StreamProviderExecutorArgs {\n provider: AgentEnvironmentProvider\n profile: AgentProfile\n task: unknown\n signal: AbortSignal\n controller: AbortController\n options: ProviderExecutorOptions\n onEnvironment: (environment: AgentEnvironment) => void\n onArtifact: (artifact: ExecutorResult<unknown>) => void\n}\n\nasync function* streamProviderExecutor(\n args: StreamProviderExecutorArgs,\n): AsyncIterable<UsageEvent> {\n const started = Date.now()\n const linked = mergeAbortSignals(args.signal, args.controller.signal)\n const environment = await args.provider.create({\n ...(args.options.defaults ?? {}),\n profile: args.profile,\n signal: linked,\n })\n args.onEnvironment(environment)\n\n const turn =\n args.options.taskToTurn?.(args.task, args.profile) ?? taskToTurnInput(args.task, linked)\n const events: AgentEnvironmentEvent[] = []\n const tokens = zeroTokenUsage()\n let usd = 0\n let text = ''\n let terminal = false\n try {\n for await (const event of environment.stream({ ...turn, signal: linked })) {\n events.push(event)\n text += textFromEnvironmentEvent(event)\n const usage = usageFromEnvironmentEvent(event)\n if (usage.input || usage.output) {\n tokens.input += usage.input\n tokens.output += usage.output\n yield { kind: 'tokens', input: usage.input, output: usage.output }\n }\n if (usage.usd) {\n usd += usage.usd\n yield { kind: 'cost', usd: usage.usd }\n }\n if (isTerminalEnvironmentEvent(event)) terminal = true\n }\n if ((args.options.requireTerminalEvent ?? true) && !terminal) {\n throw new ValidationError(\n `providerAsExecutor(${args.provider.name}): stream ended without a terminal result/done/status event`,\n )\n }\n yield { kind: 'iteration' }\n const result = resultFromEvents(events, text)\n const spent: Spend = {\n iterations: 1,\n tokens,\n usd,\n ms: Date.now() - started,\n }\n args.onArtifact({\n outRef: contentRef(`provider:${args.provider.name}`, result),\n out: result,\n spent,\n })\n } finally {\n if (args.options.destroyOnSettle ?? true) await environment.destroy?.()\n }\n}\n\nfunction createInputFromSandboxOptions(\n options: CreateSandboxOptions | undefined,\n): Partial<CreateAgentEnvironmentInput> {\n const profile = options?.backend?.profile as AgentProfileRef | undefined\n const backend = options?.backend?.type\n return {\n ...(profile !== undefined ? { profile } : {}),\n ...(backend ? { backend } : {}),\n workspace: {\n ...(options?.environment ? { environment: options.environment } : {}),\n ...(options?.image ? { image: options.image } : {}),\n ...(options?.git?.url ? { repoUrl: options.git.url } : {}),\n ...(options?.git?.ref ? { gitRef: options.git.ref } : {}),\n },\n ...(options?.resources ? { resources: options.resources as ResourceRequest } : {}),\n ...(options?.env ? { env: options.env } : {}),\n ...(options?.secrets ? { secrets: options.secrets } : {}),\n ...(options?.metadata ? { metadata: options.metadata } : {}),\n ...(options?.name ? { name: options.name } : {}),\n ...(options?.idempotencyKey ? { idempotencyKey: options.idempotencyKey } : {}),\n providerOptions: { sandboxCreateOptions: options ?? {} },\n }\n}\n\nfunction sandboxOptionsFromCreateInput(\n input: CreateAgentEnvironmentInput,\n defaultBackend: BackendType,\n): CreateSandboxOptions {\n const backendType = (input.backend ?? defaultBackend) as BackendType\n const workspace = input.workspace ?? {}\n const providerOptions = input.providerOptions?.sandboxCreateOptions\n const base =\n providerOptions && typeof providerOptions === 'object'\n ? ({ ...(providerOptions as CreateSandboxOptions) } as CreateSandboxOptions)\n : ({} satisfies CreateSandboxOptions)\n return {\n ...base,\n ...(workspace.environment ? { environment: workspace.environment } : {}),\n ...(workspace.image ? { image: workspace.image } : {}),\n ...(workspace.repoUrl ? { git: { url: workspace.repoUrl, ref: workspace.gitRef } } : {}),\n ...(input.resources ? { resources: input.resources as CreateSandboxOptions['resources'] } : {}),\n ...(input.env ? { env: input.env } : {}),\n ...(Array.isArray(input.secrets) ? { secrets: input.secrets } : {}),\n ...(input.metadata ? { metadata: input.metadata } : {}),\n ...(input.name ? { name: input.name } : {}),\n ...(input.idempotencyKey ? { idempotencyKey: input.idempotencyKey } : {}),\n backend: {\n ...(base.backend ?? {}),\n type: backendType,\n profile: input.profile,\n },\n }\n}\n\nfunction environmentAsSandboxInstance(\n environment: AgentEnvironment,\n options: { requireTerminalEvent: boolean },\n): SandboxInstance {\n const box = {\n id: environment.id,\n name: environment.name,\n status: 'running',\n async refresh(): Promise<void> {\n await environment.refresh?.()\n },\n async *streamPrompt(\n message: string | InputPart[],\n promptOptions?: PromptOptions,\n ): AsyncGenerator<SandboxEvent> {\n let terminal = false\n const input = turnInputFromPrompt(message, promptOptions)\n for await (const event of environment.stream(input)) {\n if (isTerminalEnvironmentEvent(event)) terminal = true\n const usageEvent = usageSandboxEvent(event)\n if (usageEvent) yield usageEvent\n yield sandboxEventFromEnvironmentEvent(event)\n }\n if (options.requireTerminalEvent && !terminal) {\n throw new ValidationError(\n `providerAsSandboxClient(${environment.provider}): stream ended without a terminal result/done/status event`,\n )\n }\n },\n async prompt(\n message: string | InputPart[],\n promptOptions?: PromptOptions,\n ): Promise<PromptResult> {\n const events: AgentEnvironmentEvent[] = []\n let text = ''\n let usage: TokenUsage | undefined\n let terminal = false\n for await (const event of environment.stream(turnInputFromPrompt(message, promptOptions))) {\n events.push(event)\n if (isTerminalEnvironmentEvent(event)) terminal = true\n text += textFromEnvironmentEvent(event)\n usage = mergeTokenUsage(usage, event.usage)\n }\n if (options.requireTerminalEvent && !terminal) {\n throw new ValidationError(\n `providerAsSandboxClient(${environment.provider}): prompt ended without a terminal result/done/status event`,\n )\n }\n return promptResultCompat(\n {\n response: resultFromEvents(events, text).content,\n success: true,\n durationMs: 0,\n ...(usage ? { usage } : {}),\n },\n 'success',\n )\n },\n ...(environment.dispatch\n ? {\n async dispatchPrompt(message: string | InputPart[], promptOptions?: PromptOptions) {\n const session = await environment.dispatch?.(\n turnInputFromPrompt(message, promptOptions),\n )\n if (!session)\n throw new ValidationError('providerAsSandboxClient: dispatch returned no session')\n return sandboxDispatchResultFromSessionRef(session)\n },\n }\n : {}),\n ...(environment.session\n ? {\n session(id: string) {\n return sessionAsSandboxSession(environment.session?.(id))\n },\n }\n : {}),\n ...(environment.read ? { read: environment.read.bind(environment) } : {}),\n ...(environment.write ? { write: environment.write.bind(environment) } : {}),\n ...(environment.exec\n ? {\n exec: environment.exec.bind(environment),\n }\n : {}),\n ...(environment.checkpoint\n ? {\n async checkpoint(checkpointOptions?: CheckpointRequest) {\n const checkpoint = await environment.checkpoint?.(checkpointOptions)\n return { checkpointId: checkpoint?.id, id: checkpoint?.id }\n },\n }\n : {}),\n ...(environment.fork\n ? {\n async fork(checkpointId: string, forkOptions?: ForkRequest) {\n const forked = await environment.fork?.({ id: checkpointId }, forkOptions)\n if (!forked)\n throw new ValidationError('providerAsSandboxClient: fork returned no environment')\n return environmentAsSandboxInstance(forked, options)\n },\n }\n : {}),\n async delete(): Promise<void> {\n await environment.destroy?.()\n },\n }\n return box as unknown as SandboxInstance\n}\n\nfunction sandboxInstanceAsEnvironment(\n box: SandboxInstance,\n providerName: string,\n client: SandboxClient,\n): AgentEnvironment {\n const environment: AgentEnvironment = {\n id: String(box.id),\n provider: providerName,\n ...(typeof box.name === 'string' ? { name: box.name } : {}),\n async status(): Promise<AgentEnvironmentStatus> {\n await maybeRefresh(box)\n return statusFromUnknown(readBoxStatus(box))\n },\n async *stream(input: AgentTurnInput): AsyncIterable<AgentEnvironmentEvent> {\n for await (const event of box.streamPrompt(\n promptFromTurnInput(input),\n promptOptionsFromTurnInput(input),\n )) {\n yield environmentEventFromSandboxEvent(event)\n }\n },\n ...(hasDispatchPrompt(box)\n ? {\n async dispatch(input: AgentTurnInput): Promise<AgentSessionRef> {\n const dispatched = await box.dispatchPrompt(\n promptFromTurnInput(input),\n promptOptionsFromTurnInput(input),\n )\n return sessionRefFromSandboxDispatch(dispatched, providerName)\n },\n }\n : {}),\n ...(hasSession(box)\n ? {\n session(id: string): AgentSession {\n return sandboxSessionAsAgentSession(box.session(id))\n },\n }\n : {}),\n ...(hasRead(box) ? { read: box.read.bind(box) } : {}),\n ...(hasWrite(box) ? { write: box.write.bind(box) } : {}),\n ...(hasExec(box)\n ? {\n async exec(command: string, options?: ExecRequest): Promise<ExecResult> {\n return execResultFromSandboxExecResult(await box.exec(command, options as never))\n },\n }\n : {}),\n ...(hasCheckpoint(box)\n ? {\n async checkpoint(options?: CheckpointRequest): Promise<CheckpointRef> {\n const result = await box.checkpoint(options as never)\n return { id: checkpointIdFromResult(result), provider: providerName }\n },\n }\n : {}),\n ...(hasFork(box)\n ? {\n async fork(checkpoint: CheckpointRef, options?: ForkRequest): Promise<AgentEnvironment> {\n const forked = await box.fork(checkpoint.id, options as never)\n return sandboxInstanceAsEnvironment(forked, providerName, client)\n },\n }\n : {}),\n async placement(): Promise<PlacementInfo> {\n return placementInfoFromLoopPlacement(client.describePlacement?.(box), box)\n },\n async refresh(): Promise<void> {\n await maybeRefresh(box)\n },\n async destroy(): Promise<void> {\n await destroyBox(box)\n },\n }\n return environment\n}\n\nfunction sandboxSessionAsAgentSession(session: SandboxSessionLike): AgentSession {\n return {\n id: session.id,\n async status(): Promise<AgentSessionStatus | null> {\n const status = await session.status()\n if (!status) return null\n return sessionStatusFromUnknown((status as { status?: unknown }).status)\n },\n async *events(options?: {\n since?: string\n signal?: AbortSignal\n }): AsyncIterable<AgentEnvironmentEvent> {\n for await (const event of session.events(options))\n yield environmentEventFromSandboxEvent(event)\n },\n async result(): Promise<AgentTurnResult> {\n return agentTurnResultFromPromptResult(await session.result())\n },\n async prompt(input: AgentTurnInput): Promise<AgentTurnResult> {\n return agentTurnResultFromPromptResult(\n await session.prompt(promptFromTurnInput(input), promptOptionsFromTurnInput(input)),\n )\n },\n cancel(): Promise<void> {\n return session.cancel()\n },\n }\n}\n\nfunction sessionAsSandboxSession(session: AgentSession | undefined): unknown {\n if (!session) throw new ValidationError('providerAsSandboxClient: session(id) returned undefined')\n return {\n id: session.id,\n status: session.status.bind(session),\n async *events(options?: {\n since?: string\n signal?: AbortSignal\n }): AsyncGenerator<SandboxEvent> {\n for await (const event of session.events(options))\n yield sandboxEventFromEnvironmentEvent(event)\n },\n async result(): Promise<PromptResult> {\n return promptResultFromAgentTurnResult(await session.result())\n },\n async prompt(message: string | InputPart[], options?: PromptOptions): Promise<PromptResult> {\n return promptResultFromAgentTurnResult(\n await session.prompt(turnInputFromPrompt(message, options)),\n )\n },\n cancel: session.cancel.bind(session),\n }\n}\n\nfunction environmentEventFromSandboxEvent(event: SandboxEvent): AgentEnvironmentEvent {\n const data =\n event.data && typeof event.data === 'object'\n ? (event.data as Record<string, unknown>)\n : ({} as Record<string, unknown>)\n return {\n type: String(event.type),\n data,\n ...(event.id ? { id: event.id } : {}),\n usage: tokenUsageFromData(data),\n providerEvent: event,\n }\n}\n\nfunction sandboxEventFromEnvironmentEvent(event: AgentEnvironmentEvent): SandboxEvent {\n return {\n type: event.type,\n data: {\n ...event.data,\n ...(event.usage ? { usage: tokenUsageData(event.usage) } : {}),\n },\n ...(event.id ? { id: event.id } : {}),\n }\n}\n\nfunction usageSandboxEvent(event: AgentEnvironmentEvent): SandboxEvent | undefined {\n if (!event.usage || isUsageType(event.type)) return undefined\n const usage = tokenUsageData(event.usage)\n if (\n usage.inputTokens === undefined &&\n usage.outputTokens === undefined &&\n usage.totalCostUsd === undefined\n ) {\n return undefined\n }\n return { type: 'llm_call', data: usage }\n}\n\nfunction tokenUsageData(usage: TokenUsage): Record<string, number | undefined> {\n return {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n totalCostUsd: usage.cost,\n }\n}\n\nfunction turnInputFromPrompt(\n message: string | InputPart[],\n options?: PromptOptions,\n): AgentTurnInput {\n return {\n ...(typeof message === 'string' ? { prompt: message } : { parts: message }),\n ...(options?.sessionId ? { sessionId: options.sessionId } : {}),\n ...(options?.model ? { model: options.model } : {}),\n ...(options?.timeoutMs ? { timeoutMs: options.timeoutMs } : {}),\n ...(options?.executionId ? { executionId: options.executionId } : {}),\n ...(options?.lastEventId ? { lastEventId: options.lastEventId } : {}),\n ...(options?.turnId ? { turnId: options.turnId } : {}),\n ...(options?.detach !== undefined ? { detach: options.detach } : {}),\n ...(options?.context ? { context: options.context } : {}),\n ...(options?.signal ? { signal: options.signal } : {}),\n ...(options?.backend ? { providerOptions: { backend: options.backend } } : {}),\n }\n}\n\nfunction promptFromTurnInput(input: AgentTurnInput): string | InputPart[] {\n if (input.parts) return input.parts\n return input.prompt ?? ''\n}\n\nfunction promptOptionsFromTurnInput(input: AgentTurnInput): PromptOptions {\n return {\n ...(input.sessionId ? { sessionId: input.sessionId } : {}),\n ...(input.model ? { model: input.model } : {}),\n ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}),\n ...(input.context ? { context: input.context } : {}),\n ...(input.signal ? { signal: input.signal } : {}),\n ...(input.executionId ? { executionId: input.executionId } : {}),\n ...(input.lastEventId ? { lastEventId: input.lastEventId } : {}),\n ...(input.turnId ? { turnId: input.turnId } : {}),\n ...(input.detach !== undefined ? { detach: input.detach } : {}),\n }\n}\n\nfunction taskToTurnInput(task: unknown, signal: AbortSignal): AgentTurnInput {\n return { prompt: taskToPrompt(task), signal }\n}\n\nfunction taskToPrompt(task: unknown): string {\n if (typeof task === 'string') return task\n if (task && typeof task === 'object') {\n const record = task as Record<string, unknown>\n for (const key of ['prompt', 'content', 'task', 'message']) {\n if (typeof record[key] === 'string') return record[key]\n }\n }\n return JSON.stringify(task)\n}\n\nfunction resultFromEvents(\n events: AgentEnvironmentEvent[],\n fallbackText: string,\n): { content: string; events: AgentEnvironmentEvent[] } {\n for (let i = events.length - 1; i >= 0; i -= 1) {\n const event = events[i]\n const text = event ? resultTextFromData(event.data) : undefined\n if (text !== undefined) return { content: text, events }\n }\n return { content: fallbackText, events }\n}\n\nfunction textFromEnvironmentEvent(event: AgentEnvironmentEvent): string {\n if (\n typeof event.normalized === 'object' &&\n event.normalized &&\n event.normalized.type === 'message.part.updated'\n ) {\n return typeof event.normalized.delta === 'string' ? event.normalized.delta : ''\n }\n const data = event.data\n for (const key of ['delta', 'chunk', 'content', 'text']) {\n if (typeof data[key] === 'string' && !isTerminalEnvironmentEvent(event)) return data[key]\n }\n return ''\n}\n\nfunction resultTextFromData(data: Record<string, unknown>): string | undefined {\n for (const key of ['finalText', 'text', 'response', 'resultSummary', 'content']) {\n if (typeof data[key] === 'string') return data[key]\n }\n return undefined\n}\n\nfunction isTerminalEnvironmentEvent(event: AgentEnvironmentEvent): boolean {\n if (event.type === 'result' || event.type === 'done' || event.type === 'final') return true\n if (event.type.endsWith('.completed') || event.type.endsWith('.failed')) return true\n if (event.type === 'status') {\n const status = event.data.status\n return status === 'completed' || status === 'failed' || status === 'cancelled'\n }\n return false\n}\n\nfunction isUsageType(type: string): boolean {\n return type === 'llm_call' || type === 'usage' || type === 'cost.usage'\n}\n\nfunction usageFromEnvironmentEvent(event: AgentEnvironmentEvent): {\n input: number\n output: number\n usd: number\n} {\n const usage = event.usage ?? tokenUsageFromData(event.data)\n return {\n input: finiteNumber(usage?.inputTokens) ?? 0,\n output: finiteNumber(usage?.outputTokens) ?? 0,\n usd:\n finiteNumber(usage?.cost) ??\n finiteNumber(event.data.costUsd) ??\n finiteNumber(event.data.totalCostUsd) ??\n 0,\n }\n}\n\nfunction tokenUsageFromData(data: Record<string, unknown>): TokenUsage | undefined {\n const usageRecord =\n data.usage && typeof data.usage === 'object'\n ? (data.usage as Record<string, unknown>)\n : data.tokenUsage && typeof data.tokenUsage === 'object'\n ? (data.tokenUsage as Record<string, unknown>)\n : data\n const inputTokens =\n finiteNumber(usageRecord.inputTokens) ??\n finiteNumber(usageRecord.tokensIn) ??\n finiteNumber(usageRecord.prompt_tokens)\n const outputTokens =\n finiteNumber(usageRecord.outputTokens) ??\n finiteNumber(usageRecord.tokensOut) ??\n finiteNumber(usageRecord.completion_tokens)\n const cost =\n finiteNumber(usageRecord.cost) ??\n finiteNumber(usageRecord.costUsd) ??\n finiteNumber(usageRecord.totalCostUsd) ??\n finiteNumber(data.costUsd) ??\n finiteNumber(data.totalCostUsd)\n if (inputTokens === undefined && outputTokens === undefined && cost === undefined)\n return undefined\n return {\n inputTokens: inputTokens ?? 0,\n outputTokens: outputTokens ?? 0,\n ...(cost !== undefined ? { cost } : {}),\n }\n}\n\nfunction mergeTokenUsage(\n left: TokenUsage | undefined,\n right: TokenUsage | undefined,\n): TokenUsage | undefined {\n if (!left) return right\n if (!right) return left\n return {\n inputTokens: left.inputTokens + right.inputTokens,\n outputTokens: left.outputTokens + right.outputTokens,\n ...(left.cost !== undefined || right.cost !== undefined\n ? { cost: (left.cost ?? 0) + (right.cost ?? 0) }\n : {}),\n }\n}\n\nfunction finiteNumber(value: unknown): number | undefined {\n return typeof value === 'number' && Number.isFinite(value) ? value : undefined\n}\n\ntype PromptResultCompatInput = {\n response?: string\n success: boolean\n error?: string\n traceId?: string\n durationMs: number\n usage?: PromptResult['usage']\n}\n\nfunction promptResultCompat(\n input: PromptResultCompatInput,\n status: 'success' | 'failed',\n): PromptResult {\n // sandbox 0.8 omitted `status`; sandbox 0.9 requires it. Emit it at runtime\n // while keeping this adapter type-checkable across the supported peer range.\n return { ...input, status } as unknown as PromptResult\n}\n\nfunction promptResultFromAgentTurnResult(result: AgentTurnResult): PromptResult {\n return promptResultCompat(\n {\n response: result.text,\n success: result.success,\n durationMs: 0,\n ...(result.error ? { error: result.error } : {}),\n ...(result.usage ? { usage: result.usage } : {}),\n },\n result.success ? 'success' : 'failed',\n )\n}\n\nfunction agentTurnResultFromPromptResult(result: PromptResult): AgentTurnResult {\n const record = result as unknown as Record<string, unknown>\n const text =\n typeof record.response === 'string'\n ? record.response\n : typeof record.text === 'string'\n ? record.text\n : typeof record.finalText === 'string'\n ? record.finalText\n : ''\n const success = typeof record.success === 'boolean' ? record.success : true\n return {\n text,\n success,\n ...(typeof record.error === 'string' ? { error: record.error } : {}),\n usage: tokenUsageFromData(record),\n }\n}\n\nfunction sandboxDispatchResultFromSessionRef(session: AgentSessionRef): Record<string, unknown> {\n const hasStatus = session.metadata && Object.hasOwn(session.metadata, 'status')\n const status = hasStatus ? sessionStatusFromUnknown(session.metadata?.status) : 'running'\n return {\n sessionId: session.id,\n status,\n alreadyExisted: session.metadata?.alreadyExisted === true,\n }\n}\n\nfunction sessionRefFromSandboxDispatch(dispatched: unknown, providerName: string): AgentSessionRef {\n const record =\n dispatched && typeof dispatched === 'object'\n ? (dispatched as Record<string, unknown>)\n : undefined\n const id = record?.sessionId ?? record?.id\n if (typeof id !== 'string' || id.length === 0) {\n throw new ValidationError('sandboxClientAsProvider: dispatch returned no session id')\n }\n if (!record) {\n throw new ValidationError('sandboxClientAsProvider: dispatch returned no session record')\n }\n return {\n id,\n provider: providerName,\n metadata: {\n ...(record.status ? { status: record.status } : {}),\n ...(record.alreadyExisted !== undefined ? { alreadyExisted: record.alreadyExisted } : {}),\n },\n }\n}\n\nfunction execResultFromSandboxExecResult(result: SandboxExecResult): ExecResult {\n const record = result as unknown as Record<string, unknown>\n const exitCode = finiteNumber(record.exitCode) ?? finiteNumber(record.code)\n if (exitCode === undefined) {\n throw new ValidationError('sandboxClientAsProvider: exec returned no exit code')\n }\n return {\n exitCode,\n stdout: typeof record.stdout === 'string' ? record.stdout : '',\n stderr: typeof record.stderr === 'string' ? record.stderr : '',\n }\n}\n\nfunction statusFromUnknown(status: unknown): AgentEnvironmentStatus {\n if (status === 'pending' || status === 'provisioning' || status === 'running') return status\n if (status === 'stopped' || status === 'failed' || status === 'expired') return status\n if (status === 'completed') return 'stopped'\n if (status === 'cancelled') return 'stopped'\n return 'unknown'\n}\n\nfunction sessionStatusFromUnknown(status: unknown): AgentSessionStatus | null {\n if (status === 'completed' || status === 'cancelled') return status\n return statusFromUnknown(status)\n}\n\nfunction readBoxStatus(box: SandboxInstance): unknown {\n return (box as unknown as { status?: unknown }).status\n}\n\nfunction readBoxMetadata(box: SandboxInstance): Record<string, unknown> | undefined {\n const metadata = (box as unknown as { metadata?: unknown }).metadata\n return metadata && typeof metadata === 'object'\n ? (metadata as Record<string, unknown>)\n : undefined\n}\n\nasync function maybeRefresh(box: SandboxInstance): Promise<void> {\n const refresh = (box as unknown as { refresh?: () => Promise<void> }).refresh\n if (typeof refresh === 'function') await refresh.call(box)\n}\n\nasync function destroyBox(box: SandboxInstance): Promise<void> {\n const deleteBox = (box as unknown as { delete?: () => Promise<void> }).delete\n if (typeof deleteBox === 'function') await deleteBox.call(box)\n}\n\nfunction placementInfoFromLoopPlacement(\n placement: LoopSandboxPlacement | undefined,\n box: SandboxInstance,\n): PlacementInfo {\n if (!placement) return { kind: 'sandbox', sandboxId: String(box.id) }\n return {\n kind: placement.kind === 'fleet' ? 'fleet' : 'sandbox',\n ...(placement.sandboxId ? { sandboxId: placement.sandboxId } : { sandboxId: String(box.id) }),\n ...(placement.fleetId ? { fleetId: placement.fleetId } : {}),\n ...(placement.machineId ? { machineId: placement.machineId } : {}),\n }\n}\n\nfunction checkpointIdFromResult(result: unknown): string {\n const record = result && typeof result === 'object' ? (result as Record<string, unknown>) : {}\n const id = record.checkpointId ?? record.id\n if (typeof id !== 'string' || id.length === 0) {\n throw new ValidationError('sandboxClientAsProvider: checkpoint returned no checkpoint id')\n }\n return id\n}\n\nfunction defaultTangleSandboxCapabilities(): AgentEnvironmentCapabilities {\n return {\n profile: {\n namedProfiles: true,\n systemPrompt: true,\n instructions: true,\n tools: true,\n permissions: true,\n mcp: true,\n subagents: true,\n resources: {\n files: true,\n instructions: true,\n tools: true,\n skills: true,\n agents: true,\n commands: true,\n },\n hooks: true,\n modes: true,\n runtimeUpdate: true,\n validation: true,\n },\n streaming: { live: true, replay: true, detach: true, turnIdempotency: true },\n sessions: { continue: true, list: true, messages: true },\n workspace: { read: true, write: true, exec: true, git: true, upload: true, download: true },\n branching: { checkpoint: true, fork: true },\n placement: true,\n usage: true,\n confidential: true,\n }\n}\n\nfunction mergeAbortSignals(a: AbortSignal, b: AbortSignal): AbortSignal {\n const controller = new AbortController()\n const abort = () => controller.abort()\n if (a.aborted || b.aborted) controller.abort()\n else {\n a.addEventListener('abort', abort, { once: true })\n b.addEventListener('abort', abort, { once: true })\n }\n return controller.signal\n}\n\nfunction contentRef(prefix: string, value: unknown): string {\n let str: string\n try {\n str = JSON.stringify(value) ?? String(value)\n } catch {\n str = String(value)\n }\n let hash = 0x811c9dc5\n for (let i = 0; i < str.length; i += 1) {\n hash ^= str.charCodeAt(i)\n hash = Math.imul(hash, 0x01000193)\n }\n return `${prefix}:${(hash >>> 0).toString(16).padStart(8, '0')}`\n}\n\nfunction hasGet(\n client: SandboxClient,\n): client is SandboxClient & { get(id: string): Promise<SandboxInstance | null> } {\n return typeof (client as { get?: unknown }).get === 'function'\n}\n\nfunction hasList(\n client: SandboxClient,\n): client is SandboxClient & { list(options?: unknown): Promise<SandboxInstance[]> } {\n return typeof (client as { list?: unknown }).list === 'function'\n}\n\nfunction hasDispatchPrompt(box: SandboxInstance): box is SandboxInstance & {\n dispatchPrompt(message: string | InputPart[], options?: PromptOptions): Promise<unknown>\n} {\n return typeof (box as { dispatchPrompt?: unknown }).dispatchPrompt === 'function'\n}\n\nfunction hasSession(\n box: SandboxInstance,\n): box is SandboxInstance & { session(id: string): SandboxSessionLike } {\n return typeof (box as { session?: unknown }).session === 'function'\n}\n\nfunction hasRead(box: SandboxInstance): box is SandboxInstance & {\n read(path: string, options?: { sessionId?: string }): Promise<string>\n} {\n return typeof (box as { read?: unknown }).read === 'function'\n}\n\nfunction hasWrite(\n box: SandboxInstance,\n): box is SandboxInstance & { write(path: string, content: string): Promise<void> } {\n return typeof (box as { write?: unknown }).write === 'function'\n}\n\nfunction hasExec(box: SandboxInstance): box is SandboxInstance & {\n exec(command: string, options?: unknown): Promise<SandboxExecResult>\n} {\n return typeof (box as { exec?: unknown }).exec === 'function'\n}\n\nfunction hasCheckpoint(\n box: SandboxInstance,\n): box is SandboxInstance & { checkpoint(options?: unknown): Promise<unknown> } {\n return typeof (box as { checkpoint?: unknown }).checkpoint === 'function'\n}\n\nfunction hasFork(box: SandboxInstance): box is SandboxInstance & {\n fork(checkpointId: string, options?: unknown): Promise<SandboxInstance>\n} {\n return typeof (box as { fork?: unknown }).fork === 'function'\n}\n\ninterface SandboxSessionLike {\n readonly id: string\n status(): Promise<unknown | null>\n events(options?: { since?: string; signal?: AbortSignal }): AsyncIterable<SandboxEvent>\n result(): Promise<PromptResult>\n prompt(message: string | InputPart[], options?: PromptOptions): Promise<PromptResult>\n cancel(): Promise<void>\n}\n"],"mappings":";AAgBA,eAAsB,cAAc,KAAoD;AACtF,MAAI,CAAC,OAAO,OAAQ,IAA6B,WAAW,WAAY,QAAO;AAC/E,MAAI;AACF,UAAM,IAAI,OAAO;AACjB,WAAO;AAAA,EACT,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAGO,SAAS,aAAa,MAAM,GAAW;AAC5C,SAAO,KAAK,OAAO,EAChB,SAAS,EAAE,EACX,MAAM,GAAG,IAAI,GAAG;AACrB;AAGO,SAAS,aAAqB;AACnC,SAAO,OAAO,WAAW;AAC3B;AAGO,SAAS,aAAoB;AAClC,QAAM,MAAM,IAAI,MAAM,SAAS;AAC/B,MAAI,OAAO;AACX,SAAO;AACT;AAGO,SAAS,aAAoB;AAClC,QAAM,WAAW;AACnB;AAGO,SAAS,eAAe,QAAuC;AACpE,MAAI,QAAQ,QAAS,OAAM,WAAW;AACxC;AAGO,SAAS,aAAa,KAAuB;AAClD,SAAO,eAAe,SAAS,IAAI,SAAS;AAC9C;AAOO,SAAS,MAAM,IAAY,QAAqC;AACrE,SAAO,IAAI,QAAQ,CAAC,YAAY;AAC9B,QAAI,QAAQ,SAAS;AACnB,cAAQ;AACR;AAAA,IACF;AACA,QAAI;AACJ,UAAM,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AAK,UAAU,KAAK,KAAK,OAAO,KAAK;AAAA,EAC7C,QAAQ;AACN,UAAM,OAAO,KAAK;AAAA,EACpB;AACA,MAAI,OAAO;AACX,WAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,GAAG;AACtC,YAAQ,IAAI,WAAW,CAAC;AACxB,WAAO,KAAK,KAAK,MAAM,QAAU;AAAA,EACnC;AACA,SAAO,GAAG,MAAM,KAAK,SAAS,GAAG,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG,CAAC;AAChE;AAEA,SAAS,OACP,QACgF;AAChF,SAAO,OAAQ,OAA6B,QAAQ;AACtD;AAEA,SAAS,QACP,QACmF;AACnF,SAAO,OAAQ,OAA8B,SAAS;AACxD;AAEA,SAAS,kBAAkB,KAEzB;AACA,SAAO,OAAQ,IAAqC,mBAAmB;AACzE;AAEA,SAAS,WACP,KACsE;AACtE,SAAO,OAAQ,IAA8B,YAAY;AAC3D;AAEA,SAAS,QAAQ,KAEf;AACA,SAAO,OAAQ,IAA2B,SAAS;AACrD;AAEA,SAAS,SACP,KACkF;AAClF,SAAO,OAAQ,IAA4B,UAAU;AACvD;AAEA,SAAS,QAAQ,KAEf;AACA,SAAO,OAAQ,IAA2B,SAAS;AACrD;AAEA,SAAS,cACP,KAC8E;AAC9E,SAAO,OAAQ,IAAiC,eAAe;AACjE;AAEA,SAAS,QAAQ,KAEf;AACA,SAAO,OAAQ,IAA2B,SAAS;AACrD;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/improvement/agentic-generator.ts","../src/improvement/build-prompts.ts","../src/improvement/mcp-serve-verifier.ts"],"sourcesContent":["/**\n *\n * `agenticGenerator` — the full-agentic `CandidateGenerator`: the\n * `shots=N, sandbox=on` setting of the one `improvementDriver`. It runs a real\n * coding harness (claude / codex / opencode) inside the candidate worktree the\n * driver already created, letting the agent read the codebase + the research\n * report and make the change in place. The driver then commits the worktree\n * into a `CodeSurface`.\n *\n * Mechanism: identical to the proven Phase-2.8 in-process executor — spawn the\n * harness as a subprocess with `cwd` = the worktree, on the same filesystem,\n * so edits land in place (no sandbox-mount round-trip). `runLocalHarness` is\n * the verified primitive. The OUTER sandbox is the improvement loop's own\n * execution context; the generator does not nest a second sandbox per\n * candidate (which would reintroduce a host↔sandbox worktree-transport\n * problem that does not need solving here).\n *\n * `maxShots` is the DEPTH dial — a multi-shot verify-in-session loop, NOT the\n * kernel `runLoop`. Each shot runs one full harness session in the (persistent)\n * worktree; between shots the loop refines based on what the last shot produced:\n * - empty tree → \"you changed nothing, make the edits\" → retry\n * - dirty + `verify` fails → feed the verifier's failure into the next shot\n * (the worktree persists, so the harness RESUMES atop its own failing\n * edits with the error in hand — no `--resume` session plumbing needed,\n * and harness-agnostic across claude/codex/opencode)\n * - dirty + `verify` ok (or no verifier configured) → return the candidate\n * A candidate that never verifies within `maxShots` is discarded (`applied:\n * false`), never shipped — if you configured a verifier, a non-passing tree is\n * not a candidate. With no verifier the legacy behavior holds: first dirty shot\n * is the candidate.\n *\n * @experimental\n */\n\nimport { spawnSync } from 'node:child_process'\nimport { existsSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\nimport { type LocalHarness, runLocalHarness } from '../mcp/local-harness'\nimport type { CandidateGenerator } from './improvement-driver'\n\nconst RAW_TRACE_ANALYST_ID = 'raw-trace-distiller'\nconst RAW_TRACE_AREA = 'raw-trace-context'\nconst RAW_TRACE_DIAGNOSIS_PATH = '.improve/raw-trace-diagnosis.md'\n\n/** Outcome of verifying a candidate worktree. `feedback` (compiler errors,\n * failing test output) is fed into the next shot when `ok` is false. */\nexport interface VerifyResult {\n ok: boolean\n feedback?: string\n}\n\n/** Verifies the edited worktree. Sync or async; throws only on a setup fault\n * (a candidate that fails verification returns `{ok:false}`, it does not\n * throw). */\nexport type Verifier = (worktreePath: string) => Promise<VerifyResult> | VerifyResult\n\nexport interface AgenticGeneratorOptions {\n /** Local coding harness to run in the worktree. Default `claude`. */\n harness?: LocalHarness\n /** Per-shot wall-clock timeout (ms). Default = `runLocalHarness` default (5m). */\n timeoutMs?: number\n /** Build the harness task prompt from the report + findings. Override for\n * domain phrasing; the default turns findings into a concrete coder task. */\n buildPrompt?: (args: { report: unknown; findings: AnalystFinding[] }) => string\n /** Verify the worktree after each dirtying shot. When set, a candidate that\n * fails verification is NOT returned — the failure feeds the next shot\n * (verify-in-session), up to `maxShots`; a candidate that never verifies is\n * discarded (`applied:false`), never shipped. Omitted ⇒ legacy behavior:\n * the first dirty shot is the candidate. See `commandVerifier`. */\n verify?: Verifier\n /** Test seam — inject the harness runner (defaults to `runLocalHarness`). */\n runHarness?: typeof runLocalHarness\n /** Test seam — inject the worktree-dirty check (defaults to `git status`). */\n isDirty?: (worktreePath: string) => boolean\n}\n\n/** Full-agentic `CandidateGenerator` (the `shots=N, sandbox=on` setting): run a real coding harness inside the candidate worktree so the agent makes the change in place. */\nexport function agenticGenerator(opts: AgenticGeneratorOptions = {}): CandidateGenerator {\n const harness = opts.harness ?? 'claude'\n const buildPrompt = opts.buildPrompt ?? defaultBuildPrompt\n const run = opts.runHarness ?? runLocalHarness\n const dirty = opts.isDirty ?? worktreeDirty\n const verify = opts.verify\n\n return {\n kind: `agentic:${harness}`,\n // The seed repo + (in rawTraceContext mode) the raw-trace filesystem context\n // are the change signal — an agentic coder proposes from them even when the\n // distiller yielded zero findings. Without this, the improvementDriver's\n // empty-findings guard short-circuits and generates ZERO candidates on the\n // first (and, for a single-generation run, only) proposal round.\n proposesWithoutFindings: true,\n async generate({ worktreePath, report, findings, maxShots, signal }) {\n const basePrompt = buildPrompt({ report, findings })\n const needsRawTraceEvidence = requiresRawTraceEvidence(findings)\n const shots = Math.max(1, maxShots)\n // Feedback appended to the base prompt for the NEXT shot — empty on shot 0.\n let attemptNote = ''\n\n for (let shot = 0; shot < shots; shot++) {\n if (signal.aborted) break\n await run({\n harness,\n cwd: worktreePath,\n taskPrompt: attemptNote ? `${basePrompt}\\n\\n${attemptNote}` : basePrompt,\n // The candidate worktree is isolated and must be editable without an\n // interactive permission prompt. Other runLocalHarness callers remain\n // permission-safe by default.\n dangerouslySkipPermissions: harness === 'claude',\n timeoutMs: opts.timeoutMs,\n signal,\n })\n\n // The worktree IS the signal: no edits ⇒ tell the next shot to act.\n if (!dirty(worktreePath)) {\n attemptNote = EMPTY_TREE_NOTE\n continue\n }\n\n if (needsRawTraceEvidence) {\n const problem = rawTraceEvidenceProblem(worktreePath, findings)\n if (problem) {\n attemptNote = problem\n continue\n }\n }\n\n // Dirty: with no verifier the diff IS the candidate (we trust the diff,\n // not the harness's stdout). With a verifier the candidate must pass it.\n if (!verify) {\n return { applied: true, summary: summarize(findings) }\n }\n const result = await verify(worktreePath)\n if (result.ok) {\n return { applied: true, summary: summarize(findings) }\n }\n // Dirty but failing — resume next shot atop these edits with the error.\n attemptNote = failureNote(result.feedback)\n }\n\n // Shots exhausted: no verified candidate (or, sans verifier, no edits).\n return { applied: false, summary: '' }\n },\n }\n}\n\n/** Turn the analyst's findings (+ optional report) into a concrete coder task. */\nfunction defaultBuildPrompt(args: { report: unknown; findings: AnalystFinding[] }): string {\n const lines: string[] = [\n 'You are improving this codebase based on an evaluation analysis.',\n 'Make the smallest set of edits that addresses the findings below, then stop.',\n 'Do not change unrelated code. Do not commit — leave changes in the working tree.',\n '',\n 'Findings:',\n ]\n for (const f of args.findings) {\n const where = f.subject ? ` [${f.subject}]` : ''\n lines.push(`- (${f.severity})${where} ${f.claim}`)\n if (f.recommended_action) lines.push(` → ${f.recommended_action}`)\n }\n if (requiresRawTraceEvidence(args.findings)) {\n lines.push(\n '',\n 'Raw trace evidence requirement:',\n `- Inspect at least one raw trace path named above before editing.`,\n `- Write ${RAW_TRACE_DIAGNOSIS_PATH} in this worktree.`,\n '- Include the exact trace path(s) inspected, the failure mechanism, and the code change made.',\n '- A candidate without this file, or with only this file changed, is discarded.',\n )\n }\n return lines.join('\\n')\n}\n\nconst EMPTY_TREE_NOTE =\n 'NOTE: your previous attempt left the working tree unchanged. Make the concrete file edits now.'\n\n/** Next-shot feedback when the worktree is dirty but failed verification. The\n * edits persist on disk, so the harness resumes atop them — tell it to fix in\n * place, not start over. Verifier detail is truncated to keep the prompt bounded. */\nfunction failureNote(feedback?: string): string {\n const detail = feedback?.trim()\n return [\n 'NOTE: your edits are in the working tree but verification FAILED.',\n 'Fix the problem in place — build on your existing edits, do not revert them.',\n detail ? `Verifier output:\\n${truncate(detail, 4000)}` : 'No verifier detail was captured.',\n ].join('\\n')\n}\n\nfunction rawTraceEvidenceProblem(worktreePath: string, findings: AnalystFinding[]): string | null {\n const changedPaths = worktreeChangedPaths(worktreePath)\n const substantive = changedPaths.filter((path) => path !== RAW_TRACE_DIAGNOSIS_PATH)\n if (substantive.length === 0) {\n return [\n `NOTE: raw-trace mode requires a real code/config edit in addition to ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Your previous attempt only changed the diagnosis artifact. Inspect the cited traces and make the causal code change.',\n ].join('\\n')\n }\n\n const diagnosisPath = join(worktreePath, RAW_TRACE_DIAGNOSIS_PATH)\n if (!existsSync(diagnosisPath)) {\n return [\n `NOTE: raw-trace mode requires ${RAW_TRACE_DIAGNOSIS_PATH}.`,\n 'Before retrying, inspect at least one cited spans.jsonl/cached-result.json/artifact path, then write the diagnosis file with the exact path, failure mechanism, and code change.',\n ].join('\\n')\n }\n\n const body = readFileSync(diagnosisPath, 'utf8')\n const evidencePaths = traceEvidencePaths(findings)\n if (evidencePaths.length > 0 && !evidencePaths.some((path) => body.includes(path))) {\n return [\n `${RAW_TRACE_DIAGNOSIS_PATH} exists, but it does not cite any exact raw trace path from the findings.`,\n `Cite at least one of these inspected paths exactly: ${evidencePaths.slice(0, 5).join(', ')}`,\n ].join('\\n')\n }\n\n return null\n}\n\nfunction requiresRawTraceEvidence(findings: AnalystFinding[]): boolean {\n return findings.some((finding) => {\n const f = finding as unknown as Record<string, unknown>\n return f.analyst_id === RAW_TRACE_ANALYST_ID || f.area === RAW_TRACE_AREA\n })\n}\n\nfunction traceEvidencePaths(findings: AnalystFinding[]): string[] {\n const out: string[] = []\n for (const finding of findings) {\n const refs = (finding as unknown as { evidence_refs?: unknown }).evidence_refs\n if (!Array.isArray(refs)) continue\n for (const ref of refs) {\n if (!ref || typeof ref !== 'object') continue\n const uri = (ref as { uri?: unknown }).uri\n if (typeof uri === 'string' && uri.length > 0) out.push(uri)\n }\n }\n return [...new Set(out)]\n}\n\n/** A `Verifier` that runs a command in the worktree: exit 0 ⇒ ok, any other\n * exit ⇒ failed with stdout+stderr as feedback. The common case — verify by\n * `tsc --noEmit`, `pnpm build`, or a test command. A timeout is treated as a\n * FAILED candidate (a change that hangs the build is a bad change); a missing\n * binary or spawn fault throws (a setup bug, not a failed candidate — no\n * silent fallback). */\nexport function commandVerifier(\n command: string,\n args: string[] = [],\n timeoutMs = 300_000,\n): Verifier {\n return (worktreePath: string): VerifyResult => {\n const result = spawnSync(command, args, {\n cwd: worktreePath,\n encoding: 'utf-8',\n timeout: timeoutMs,\n })\n if (result.signal) {\n return {\n ok: false,\n feedback: `verifier '${command}' killed by ${result.signal} (likely timeout after ${timeoutMs}ms)`,\n }\n }\n if (result.error) {\n const code = (result.error as NodeJS.ErrnoException).code\n if (code === 'ENOENT') {\n throw new Error(\n `commandVerifier: '${command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n }\n throw new Error(`commandVerifier: '${command}' failed to spawn: ${result.error.message}`)\n }\n if (result.status === 0) return { ok: true }\n const out = `${result.stdout ?? ''}${result.stderr ?? ''}`.trim()\n return { ok: false, feedback: out.length > 0 ? out : `exit ${result.status}` }\n }\n}\n\n/** A one-line summary for the commit message, derived from the findings. */\nfunction summarize(findings: AnalystFinding[]): string {\n if (findings.length === 0) return 'agentic improvement'\n if (findings.length === 1) return `agentic: ${truncate(findings[0]!.claim, 64)}`\n return `agentic: ${findings.length} findings addressed`\n}\n\nfunction truncate(s: string, n: number): string {\n return s.length <= n ? s : `${s.slice(0, n - 1)}…`\n}\n\n/** Non-empty `git status --porcelain` ⇒ the harness changed the worktree.\n * Fails loud: the worktree is a fresh checkout, so a git error here means\n * something is genuinely broken (git missing, corrupt index, killed mid-run).\n * Folding that into `false` would silently discard a candidate and mask the\n * real failure — forbidden by the no-silent-fallbacks doctrine. */\nfunction worktreeDirty(worktreePath: string): boolean {\n return worktreeChangedPaths(worktreePath).length > 0\n}\n\nfunction worktreeChangedPaths(worktreePath: string): string[] {\n const result = spawnSync('git', ['status', '--porcelain', '--untracked-files=all'], {\n cwd: worktreePath,\n encoding: 'utf-8',\n })\n if (result.error) {\n throw new Error(\n `agenticGenerator: git status failed to spawn in ${worktreePath}: ${result.error.message}`,\n )\n }\n if (result.status !== 0) {\n throw new Error(\n `agenticGenerator: git status exited ${result.status} in ${worktreePath}: ${result.stderr.trim()}`,\n )\n }\n return result.stdout\n .split('\\n')\n .map((line) => line.trim())\n .filter((line) => line.length > 0)\n .map((line) => line.slice(3).trim())\n}\n","/**\n * Build-prompt starting points for the two buildable artifact types. There is\n * NO `toolGenerator`/`mcpGenerator` wrapper — the factory is `agenticGenerator`\n * + a verifier (docs/artifact-lifecycle-frontier.md), so a tool or an MCP\n * server is built by composing the pieces directly:\n *\n * // a tool:\n * agenticGenerator({ buildPrompt: toolBuildPrompt, verify: commandVerifier('pnpm', ['test']) })\n * // an MCP server:\n * agenticGenerator({ buildPrompt: mcpBuildPrompt, verify: mcpServeVerifier({ command: 'node', args: ['server.mjs'] }) })\n *\n * These are the only type-specific bit (the phrasing that points the agent at a\n * tool vs. an MCP); the worktree, resume-on-failure loop, and improvement-loop\n * wrapper are shared. MCP is the load-bearing target — it is how a harness\n * acquires tools; raw tools matter where we control the loader.\n */\n\nimport type { AnalystFinding } from '@tangle-network/agent-eval'\n\ntype FindingsArg = { report: unknown; findings: AnalystFinding[] }\n\nfunction findingLines(findings: AnalystFinding[]): string[] {\n return findings.map((f) => {\n const where = f.subject ? ` [${f.subject}]` : ''\n const action = f.recommended_action ? ` → ${f.recommended_action}` : ''\n return `- (${f.severity})${where} ${f.claim}${action}`\n })\n}\n\n/** Build the starting instruction for a coder agent tasked with implementing a new tool. */\nexport function toolBuildPrompt(args: FindingsArg): string {\n return [\n 'You are building a new TOOL for this codebase to address the gaps below.',\n 'Write the tool as a small, self-contained module PLUS tests that exercise it.',\n 'The tool must compile and its tests must pass — they will be run automatically;',\n 'if verification fails you will get the error and another attempt. Do not commit;',\n 'leave the changes in the working tree.',\n '',\n 'Gaps the tool should close:',\n ...findingLines(args.findings),\n ].join('\\n')\n}\n\n/** Build the starting instruction for a coder agent tasked with implementing a new MCP server. */\nexport function mcpBuildPrompt(args: FindingsArg): string {\n return [\n 'You are building a new MCP SERVER (Model Context Protocol) that exposes',\n 'tool(s) addressing the gaps below, so any harness can mount it.',\n 'Requirements that WILL be checked by booting the server:',\n '- it starts over stdio and answers the MCP `initialize` handshake,',\n '- `tools/list` returns at least one tool with a valid input schema.',\n 'Newline-delimited JSON-RPC 2.0, protocol version 2024-11-05. Include a start',\n 'command (e.g. a package.json `start` script or a clear entrypoint). If the',\n 'boot-and-probe fails you will get the error and another attempt. Do not',\n 'commit; leave the changes in the working tree.',\n '',\n 'Capabilities the server should provide:',\n ...findingLines(args.findings),\n ].join('\\n')\n}\n","/**\n * `mcpServeVerifier` — the intrinsic verifier for a built MCP server: the\n * boot-and-probe checker named in docs/artifact-lifecycle-frontier.md. A\n * generated MCP server is only a candidate if it actually *serves* — so this\n * boots it over stdio (the default local MCP transport) and runs the real\n * handshake: `initialize` → `notifications/initialized` → `tools/list`, and\n * asserts the server answers with at least `minTools` tools.\n *\n * Outcomes follow the `Verifier` contract: a server that fails to start, exits\n * early, errors the handshake, times out, or exposes no tools is a FAILED\n * candidate (`{ok:false}`, fed back into the next generation shot); a missing\n * start binary or spawn fault THROWS (a setup bug, never a silent fallback).\n *\n * Protocol matches the runtime's own stdio MCP server (src/mcp/server.ts):\n * newline-delimited JSON-RPC 2.0, protocol version 2024-11-05.\n */\n\nimport { spawn } from 'node:child_process'\nimport { createInterface } from 'node:readline'\nimport type { Verifier, VerifyResult } from './agentic-generator'\n\nconst PROTOCOL_VERSION = '2024-11-05'\n\nexport interface McpServeSpec {\n /** Command that starts the built MCP server in the worktree (stdio transport). */\n command: string\n args?: string[]\n /** Extra env for the server process (merged over `process.env`). */\n env?: Record<string, string>\n /** Handshake timeout (ms). Default 30s. */\n timeoutMs?: number\n /** Minimum tools the server must expose to pass. Default 1. */\n minTools?: number\n}\n\ninterface JsonRpcResponse {\n jsonrpc?: string\n id?: number | string | null\n result?: unknown\n error?: { code: number; message: string }\n}\n\n/** Build a `Verifier` that boots a generated MCP server over stdio and checks it exposes tools. */\nexport function mcpServeVerifier(spec: McpServeSpec): Verifier {\n const timeoutMs = spec.timeoutMs ?? 30_000\n const minTools = spec.minTools ?? 1\n\n return (worktreePath: string): Promise<VerifyResult> =>\n new Promise<VerifyResult>((resolve, reject) => {\n const child = spawn(spec.command, spec.args ?? [], {\n cwd: worktreePath,\n stdio: ['pipe', 'pipe', 'pipe'],\n env: { ...process.env, ...spec.env },\n })\n\n const stderr: string[] = []\n let settled = false\n let nextId = 1\n const initId = nextId++\n let listId = -1\n\n const settle = (fn: () => void) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n rl.close()\n child.kill('SIGKILL')\n fn()\n }\n const withStderr = (msg: string) =>\n stderr.length > 0 ? `${msg}\\nstderr:\\n${stderr.join('').slice(-2000)}` : msg\n const pass = () => settle(() => resolve({ ok: true }))\n const failCandidate = (msg: string) =>\n settle(() => resolve({ ok: false, feedback: withStderr(msg) }))\n const setupFault = (err: Error) => settle(() => reject(err))\n const failStdin = (err: Error) =>\n failCandidate(`writing to MCP server stdin failed: ${err.message}`)\n\n const send = (msg: Record<string, unknown>): boolean => {\n try {\n child.stdin.write(`${JSON.stringify(msg)}\\n`)\n return true\n } catch (err) {\n // EPIPE: the server died mid-handshake — a failed candidate, not a fault.\n failStdin(err as Error)\n return false\n }\n }\n\n child.on('error', (err) => {\n const code = (err as NodeJS.ErrnoException).code\n setupFault(\n code === 'ENOENT'\n ? new Error(\n `mcpServeVerifier: '${spec.command}' not found in PATH (setup bug, not a failed candidate)`,\n )\n : new Error(`mcpServeVerifier: '${spec.command}' failed to spawn: ${err.message}`),\n )\n })\n child.on('exit', (code, signal) => {\n // An exit before the handshake completes is a failed candidate (the\n // server crashed on boot); after we settle, our own SIGKILL fires here.\n failCandidate(`MCP server exited (code ${code}, signal ${signal}) before serving`)\n })\n // Pipe failures normally arrive asynchronously, outside send()'s try/catch.\n child.stdin.on('error', failStdin)\n child.stderr.on('data', (d) => stderr.push(String(d)))\n\n const rl = createInterface({ input: child.stdout })\n rl.on('line', (line) => {\n let msg: JsonRpcResponse | undefined\n try {\n msg = JSON.parse(line) as JsonRpcResponse\n } catch {\n return // servers log to stdout too; skip non-JSON lines\n }\n if (!msg || typeof msg !== 'object') return\n\n if (msg.id === initId) {\n if (msg.error) return failCandidate(`initialize errored: ${JSON.stringify(msg.error)}`)\n if (!send({ jsonrpc: '2.0', method: 'notifications/initialized' })) return\n listId = nextId++\n send({ jsonrpc: '2.0', id: listId, method: 'tools/list' })\n return\n }\n if (msg.id === listId) {\n if (msg.error) return failCandidate(`tools/list errored: ${JSON.stringify(msg.error)}`)\n const tools = (msg.result as { tools?: unknown[] } | undefined)?.tools\n if (!Array.isArray(tools)) return failCandidate('tools/list result has no tools array')\n if (tools.length < minTools) {\n return failCandidate(`tools/list returned ${tools.length} tool(s), need >= ${minTools}`)\n }\n return pass()\n }\n })\n\n const timer = setTimeout(\n () => failCandidate(`MCP server did not complete the handshake within ${timeoutMs}ms`),\n timeoutMs,\n )\n\n send({\n jsonrpc: '2.0',\n id: initId,\n method: 'initialize',\n params: {\n protocolVersion: PROTOCOL_VERSION,\n capabilities: {},\n clientInfo: { name: 'agent-runtime-mcp-verify', version: '0' },\n },\n })\n })\n}\n"],"mappings":";;;;;AAkCA,SAAS,iBAAiB;AAC1B,SAAS,YAAY,oB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iBAAiB;AAAA,QACjB,cAAc,CAAC;AAAA,QACf,YAAY,EAAE,MAAM,4BAA4B,SAAS,IAAI;AAAA,MAC/D;AAAA,IACF,CAAC;AAAA,EACH,CAAC;AACL;","names":[]}
|
package/dist/chunk-IVGYLCFH.js
DELETED
|
@@ -1,381 +0,0 @@
|
|
|
1
|
-
// src/otel-export.ts
|
|
2
|
-
var SCOPE = { name: "@tangle-network/agent-runtime", version: "0.83.0" };
|
|
3
|
-
var GEN_AI = {
|
|
4
|
-
operation: "gen_ai.operation.name",
|
|
5
|
-
agentName: "gen_ai.agent.name",
|
|
6
|
-
conversationId: "gen_ai.conversation.id",
|
|
7
|
-
inputTokens: "gen_ai.usage.input_tokens",
|
|
8
|
-
outputTokens: "gen_ai.usage.output_tokens"
|
|
9
|
-
};
|
|
10
|
-
function createOtelExporter(config) {
|
|
11
|
-
const resolvedEndpoint = config?.endpoint ?? (typeof process !== "undefined" ? process.env.OTEL_EXPORTER_OTLP_ENDPOINT : void 0);
|
|
12
|
-
if (!resolvedEndpoint) return void 0;
|
|
13
|
-
const endpoint = resolvedEndpoint;
|
|
14
|
-
const headers = config?.headers ?? parseHeadersFromEnv();
|
|
15
|
-
const batchSize = config?.batchSize ?? 64;
|
|
16
|
-
const flushIntervalMs = config?.flushIntervalMs ?? 5e3;
|
|
17
|
-
const serviceName = config?.serviceName ?? "agent-runtime";
|
|
18
|
-
const resourceAttrs = config?.resourceAttributes ?? {};
|
|
19
|
-
const pending = [];
|
|
20
|
-
let timer;
|
|
21
|
-
let stopped = false;
|
|
22
|
-
const exporter = {
|
|
23
|
-
exportSpan(span) {
|
|
24
|
-
if (stopped) return;
|
|
25
|
-
pending.push(span);
|
|
26
|
-
if (pending.length >= batchSize) {
|
|
27
|
-
void doFlush();
|
|
28
|
-
}
|
|
29
|
-
},
|
|
30
|
-
async flush() {
|
|
31
|
-
await doFlush();
|
|
32
|
-
},
|
|
33
|
-
async shutdown() {
|
|
34
|
-
stopped = true;
|
|
35
|
-
if (timer !== void 0) {
|
|
36
|
-
clearInterval(timer);
|
|
37
|
-
timer = void 0;
|
|
38
|
-
}
|
|
39
|
-
await doFlush();
|
|
40
|
-
}
|
|
41
|
-
};
|
|
42
|
-
timer = setInterval(() => {
|
|
43
|
-
if (pending.length > 0) void doFlush();
|
|
44
|
-
}, flushIntervalMs);
|
|
45
|
-
if (typeof timer === "object" && "unref" in timer) {
|
|
46
|
-
;
|
|
47
|
-
timer.unref();
|
|
48
|
-
}
|
|
49
|
-
async function doFlush() {
|
|
50
|
-
if (pending.length === 0) return;
|
|
51
|
-
const batch = pending.splice(0);
|
|
52
|
-
const body = {
|
|
53
|
-
resourceSpans: [
|
|
54
|
-
{
|
|
55
|
-
resource: {
|
|
56
|
-
attributes: toAttributes({
|
|
57
|
-
"service.name": serviceName,
|
|
58
|
-
...resourceAttrs
|
|
59
|
-
})
|
|
60
|
-
},
|
|
61
|
-
scopeSpans: [{ scope: SCOPE, spans: batch }]
|
|
62
|
-
}
|
|
63
|
-
]
|
|
64
|
-
};
|
|
65
|
-
const url = `${endpoint.replace(/\/+$/, "")}/v1/traces`;
|
|
66
|
-
try {
|
|
67
|
-
await fetch(url, {
|
|
68
|
-
method: "POST",
|
|
69
|
-
headers: { "content-type": "application/json", ...headers },
|
|
70
|
-
body: JSON.stringify(body)
|
|
71
|
-
});
|
|
72
|
-
} catch {
|
|
73
|
-
}
|
|
74
|
-
}
|
|
75
|
-
return exporter;
|
|
76
|
-
}
|
|
77
|
-
function loopEventToOtelSpan(event, traceId, parentSpanId) {
|
|
78
|
-
const spanId = generateSpanId();
|
|
79
|
-
const attrs = {
|
|
80
|
-
"loop.event_kind": event.kind,
|
|
81
|
-
"loop.run_id": event.runId
|
|
82
|
-
};
|
|
83
|
-
for (const [k, v] of Object.entries(event.payload)) {
|
|
84
|
-
if (typeof v === "string" || typeof v === "number" || typeof v === "boolean") {
|
|
85
|
-
attrs[`loop.${k}`] = v;
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
const ts = msToNs(event.timestamp);
|
|
89
|
-
return {
|
|
90
|
-
traceId: padTraceId(traceId),
|
|
91
|
-
spanId,
|
|
92
|
-
parentSpanId: parentSpanId ? padSpanId(parentSpanId) : void 0,
|
|
93
|
-
name: event.kind,
|
|
94
|
-
kind: 1,
|
|
95
|
-
startTimeUnixNano: ts,
|
|
96
|
-
endTimeUnixNano: ts,
|
|
97
|
-
attributes: toAttributes(attrs),
|
|
98
|
-
status: { code: 1 }
|
|
99
|
-
};
|
|
100
|
-
}
|
|
101
|
-
function flatOtelSpan(name, attributes, traceId, timestampMs, parentSpanId) {
|
|
102
|
-
const ts = msToNs(timestampMs);
|
|
103
|
-
return {
|
|
104
|
-
traceId: padTraceId(traceId),
|
|
105
|
-
spanId: generateSpanId(),
|
|
106
|
-
parentSpanId: parentSpanId ? padSpanId(parentSpanId) : void 0,
|
|
107
|
-
name,
|
|
108
|
-
kind: 1,
|
|
109
|
-
startTimeUnixNano: ts,
|
|
110
|
-
endTimeUnixNano: ts,
|
|
111
|
-
attributes: toAttributes(attributes),
|
|
112
|
-
status: { code: 1 }
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
function buildLoopOtelSpans(events, traceId, rootParentSpanId) {
|
|
116
|
-
const tid = padTraceId(traceId);
|
|
117
|
-
return buildLoopSpanNodes(events).map((node) => ({
|
|
118
|
-
traceId: tid,
|
|
119
|
-
spanId: node.spanId,
|
|
120
|
-
parentSpanId: node.parentSpanId ? padSpanId(node.parentSpanId) : rootParentSpanId ? padSpanId(rootParentSpanId) : void 0,
|
|
121
|
-
name: node.name,
|
|
122
|
-
kind: 1,
|
|
123
|
-
startTimeUnixNano: msToNs(node.startMs),
|
|
124
|
-
endTimeUnixNano: msToNs(node.endMs),
|
|
125
|
-
attributes: toAttributes(node.attrs),
|
|
126
|
-
status: { code: node.error ? 2 : 1 }
|
|
127
|
-
}));
|
|
128
|
-
}
|
|
129
|
-
function buildLoopSpanNodes(events) {
|
|
130
|
-
if (events.length === 0) return [];
|
|
131
|
-
const out = [];
|
|
132
|
-
const num = (v) => typeof v === "number" && Number.isFinite(v) ? v : void 0;
|
|
133
|
-
const str = (v) => typeof v === "string" && v.length > 0 ? v : void 0;
|
|
134
|
-
const rec = (v) => v && typeof v === "object" ? v : {};
|
|
135
|
-
const started = events.find((e) => e.kind === "loop.started");
|
|
136
|
-
const ended = events.find((e) => e.kind === "loop.ended");
|
|
137
|
-
const runId = events[0]?.runId ?? "";
|
|
138
|
-
const rootStart = started?.timestamp ?? events[0].timestamp;
|
|
139
|
-
const rootEnd = ended?.timestamp ?? events[events.length - 1].timestamp;
|
|
140
|
-
const rootId = generateSpanId();
|
|
141
|
-
const make = (spanId, parentSpanId, name, kind, startMs, endMs, attrs, error = false) => ({
|
|
142
|
-
spanId,
|
|
143
|
-
parentSpanId,
|
|
144
|
-
name,
|
|
145
|
-
kind,
|
|
146
|
-
startMs,
|
|
147
|
-
endMs,
|
|
148
|
-
attrs,
|
|
149
|
-
error
|
|
150
|
-
});
|
|
151
|
-
const sp = rec(started?.payload);
|
|
152
|
-
const rootAttrs = {
|
|
153
|
-
[GEN_AI.operation]: "invoke_workflow",
|
|
154
|
-
[GEN_AI.conversationId]: runId,
|
|
155
|
-
// Explicit run identity under the tangle namespace so a consuming system of
|
|
156
|
-
// record (Tangle Intelligence's run spine) maps this span tree to one run
|
|
157
|
-
// deterministically, instead of inferring it from the conversation id.
|
|
158
|
-
"tangle.run.id": runId,
|
|
159
|
-
"tangle.loop.driver": str(sp.driver) ?? "driver"
|
|
160
|
-
};
|
|
161
|
-
if (Array.isArray(sp.agentRunNames) && sp.agentRunNames.length > 0) {
|
|
162
|
-
rootAttrs["tangle.loop.agents"] = sp.agentRunNames.map(String).join(",");
|
|
163
|
-
rootAttrs["tangle.subject.key"] = String(sp.agentRunNames[0]);
|
|
164
|
-
}
|
|
165
|
-
if (ended) {
|
|
166
|
-
const ep = rec(ended.payload);
|
|
167
|
-
const win = num(ep.winnerIterationIndex);
|
|
168
|
-
if (win !== void 0) rootAttrs["tangle.loop.winner.iteration_index"] = win;
|
|
169
|
-
const cost = num(ep.totalCostUsd);
|
|
170
|
-
if (cost !== void 0) rootAttrs["tangle.cost.usd"] = cost;
|
|
171
|
-
const dur = num(ep.durationMs);
|
|
172
|
-
if (dur !== void 0) rootAttrs["tangle.loop.duration_ms"] = dur;
|
|
173
|
-
const iters = num(ep.iterations);
|
|
174
|
-
if (iters !== void 0) rootAttrs["tangle.loop.iterations"] = iters;
|
|
175
|
-
}
|
|
176
|
-
out.push(make(rootId, void 0, "loop", "loop", rootStart, rootEnd, rootAttrs));
|
|
177
|
-
const iterStartTs = /* @__PURE__ */ new Map();
|
|
178
|
-
const placementByIdx = /* @__PURE__ */ new Map();
|
|
179
|
-
let currentRoundId;
|
|
180
|
-
let pendingRound;
|
|
181
|
-
const flushRound = (endMs) => {
|
|
182
|
-
if (!pendingRound) return;
|
|
183
|
-
out.push(
|
|
184
|
-
make(
|
|
185
|
-
pendingRound.id,
|
|
186
|
-
rootId,
|
|
187
|
-
"loop.round",
|
|
188
|
-
"round",
|
|
189
|
-
pendingRound.start,
|
|
190
|
-
endMs,
|
|
191
|
-
pendingRound.attrs
|
|
192
|
-
)
|
|
193
|
-
);
|
|
194
|
-
pendingRound = void 0;
|
|
195
|
-
};
|
|
196
|
-
for (const e of events) {
|
|
197
|
-
const p = rec(e.payload);
|
|
198
|
-
switch (e.kind) {
|
|
199
|
-
case "loop.plan": {
|
|
200
|
-
flushRound(e.timestamp);
|
|
201
|
-
const id = generateSpanId();
|
|
202
|
-
const roundIdx = num(p.roundIndex) ?? 0;
|
|
203
|
-
const attrs = {
|
|
204
|
-
[GEN_AI.operation]: "invoke_workflow",
|
|
205
|
-
"tangle.loop.round.index": roundIdx,
|
|
206
|
-
"tangle.loop.move.kind": str(p.moveKind) ?? "unknown",
|
|
207
|
-
"tangle.loop.move.round": roundIdx,
|
|
208
|
-
"tangle.loop.move.width": num(p.plannedCount) ?? 0
|
|
209
|
-
};
|
|
210
|
-
const r = str(p.rationale);
|
|
211
|
-
if (r) attrs["tangle.loop.move.rationale"] = r;
|
|
212
|
-
const parent = num(p.parentIndex);
|
|
213
|
-
if (parent !== void 0) attrs["tangle.loop.move.parent_index"] = parent;
|
|
214
|
-
if (Array.isArray(p.childIndices) && p.childIndices.length > 0) {
|
|
215
|
-
attrs["tangle.loop.move.child_indices"] = p.childIndices.map(String).join(",");
|
|
216
|
-
}
|
|
217
|
-
pendingRound = { id, start: e.timestamp, attrs };
|
|
218
|
-
currentRoundId = id;
|
|
219
|
-
break;
|
|
220
|
-
}
|
|
221
|
-
case "loop.iteration.started": {
|
|
222
|
-
const idx = num(p.iterationIndex);
|
|
223
|
-
if (idx !== void 0) iterStartTs.set(idx, e.timestamp);
|
|
224
|
-
break;
|
|
225
|
-
}
|
|
226
|
-
case "loop.iteration.dispatch": {
|
|
227
|
-
const idx = num(p.iterationIndex);
|
|
228
|
-
if (idx === void 0) break;
|
|
229
|
-
const place = {};
|
|
230
|
-
const kind = str(p.placement);
|
|
231
|
-
if (kind) place["tangle.loop.placement.kind"] = kind;
|
|
232
|
-
const sid = str(p.sandboxId);
|
|
233
|
-
if (sid) place["tangle.sandbox.id"] = sid;
|
|
234
|
-
const fid = str(p.fleetId);
|
|
235
|
-
if (fid) place["tangle.fleet.id"] = fid;
|
|
236
|
-
const mid = str(p.machineId);
|
|
237
|
-
if (mid) place["tangle.machine.id"] = mid;
|
|
238
|
-
placementByIdx.set(idx, place);
|
|
239
|
-
break;
|
|
240
|
-
}
|
|
241
|
-
case "loop.iteration.ended": {
|
|
242
|
-
const idx = num(p.iterationIndex) ?? 0;
|
|
243
|
-
const start = iterStartTs.get(idx) ?? e.timestamp;
|
|
244
|
-
const err = str(p.error);
|
|
245
|
-
const attrs = {
|
|
246
|
-
[GEN_AI.operation]: "invoke_agent",
|
|
247
|
-
"tangle.loop.iteration.index": idx
|
|
248
|
-
};
|
|
249
|
-
const agent = str(p.agentRunName);
|
|
250
|
-
if (agent) attrs[GEN_AI.agentName] = agent;
|
|
251
|
-
const tu = rec(p.tokenUsage);
|
|
252
|
-
const inTok = num(tu.input);
|
|
253
|
-
if (inTok !== void 0) attrs[GEN_AI.inputTokens] = inTok;
|
|
254
|
-
const outTok = num(tu.output);
|
|
255
|
-
if (outTok !== void 0) attrs[GEN_AI.outputTokens] = outTok;
|
|
256
|
-
const cost = num(p.costUsd);
|
|
257
|
-
if (cost !== void 0) attrs["tangle.cost.usd"] = cost;
|
|
258
|
-
const verdict = rec(p.verdict);
|
|
259
|
-
if (typeof verdict.valid === "boolean") attrs["tangle.loop.verdict.valid"] = verdict.valid;
|
|
260
|
-
const score = num(verdict.score);
|
|
261
|
-
if (score !== void 0) attrs["tangle.loop.verdict.score"] = score;
|
|
262
|
-
if (err) attrs["tangle.loop.error"] = err;
|
|
263
|
-
const gid = num(p.groupId);
|
|
264
|
-
if (gid !== void 0) attrs["tangle.loop.iteration.group_id"] = gid;
|
|
265
|
-
const par = num(p.parentIndex);
|
|
266
|
-
if (par !== void 0) attrs["tangle.loop.iteration.parent_index"] = par;
|
|
267
|
-
const dur = num(p.durationMs);
|
|
268
|
-
if (dur !== void 0) attrs["tangle.loop.iteration.duration_ms"] = dur;
|
|
269
|
-
const preview = str(p.outputPreview);
|
|
270
|
-
if (preview) attrs["tangle.loop.iteration.output_preview"] = preview;
|
|
271
|
-
Object.assign(attrs, placementByIdx.get(idx) ?? {});
|
|
272
|
-
out.push(
|
|
273
|
-
make(
|
|
274
|
-
generateSpanId(),
|
|
275
|
-
currentRoundId ?? rootId,
|
|
276
|
-
"loop.iteration",
|
|
277
|
-
"branch",
|
|
278
|
-
start,
|
|
279
|
-
e.timestamp,
|
|
280
|
-
attrs,
|
|
281
|
-
err !== void 0
|
|
282
|
-
)
|
|
283
|
-
);
|
|
284
|
-
break;
|
|
285
|
-
}
|
|
286
|
-
case "loop.decision": {
|
|
287
|
-
if (pendingRound) {
|
|
288
|
-
const dec = str(p.decision);
|
|
289
|
-
if (dec) pendingRound.attrs["tangle.loop.decision"] = dec;
|
|
290
|
-
flushRound(e.timestamp);
|
|
291
|
-
}
|
|
292
|
-
currentRoundId = void 0;
|
|
293
|
-
break;
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
}
|
|
297
|
-
flushRound(rootEnd);
|
|
298
|
-
return out;
|
|
299
|
-
}
|
|
300
|
-
function parseHeadersFromEnv() {
|
|
301
|
-
if (typeof process === "undefined") return {};
|
|
302
|
-
const raw = process.env.OTEL_EXPORTER_OTLP_HEADERS;
|
|
303
|
-
if (!raw) return {};
|
|
304
|
-
const out = {};
|
|
305
|
-
for (const pair of raw.split(",")) {
|
|
306
|
-
const eq = pair.indexOf("=");
|
|
307
|
-
if (eq < 0) continue;
|
|
308
|
-
const key = pair.slice(0, eq).trim();
|
|
309
|
-
const value = pair.slice(eq + 1).trim();
|
|
310
|
-
if (key) out[key] = value;
|
|
311
|
-
}
|
|
312
|
-
return out;
|
|
313
|
-
}
|
|
314
|
-
function toAttributes(record) {
|
|
315
|
-
return Object.entries(record).map(([key, value]) => ({
|
|
316
|
-
key,
|
|
317
|
-
value: typeof value === "number" ? Number.isInteger(value) ? { intValue: value.toString() } : { doubleValue: value } : typeof value === "boolean" ? { boolValue: value } : { stringValue: value }
|
|
318
|
-
}));
|
|
319
|
-
}
|
|
320
|
-
function msToNs(ms) {
|
|
321
|
-
return (BigInt(Math.floor(ms)) * 1000000n).toString();
|
|
322
|
-
}
|
|
323
|
-
function padSpanId(id) {
|
|
324
|
-
const cleaned = id.replace(/-/g, "");
|
|
325
|
-
return cleaned.slice(0, 16).padEnd(16, "0");
|
|
326
|
-
}
|
|
327
|
-
function padTraceId(id) {
|
|
328
|
-
const cleaned = id.replace(/-/g, "");
|
|
329
|
-
return cleaned.slice(0, 32).padEnd(32, "0");
|
|
330
|
-
}
|
|
331
|
-
function generateSpanId() {
|
|
332
|
-
const bytes = new Uint8Array(8);
|
|
333
|
-
if (typeof globalThis.crypto?.getRandomValues === "function") {
|
|
334
|
-
globalThis.crypto.getRandomValues(bytes);
|
|
335
|
-
} else {
|
|
336
|
-
for (let i = 0; i < 8; i++) bytes[i] = Math.floor(Math.random() * 256);
|
|
337
|
-
}
|
|
338
|
-
return Array.from(bytes).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
339
|
-
}
|
|
340
|
-
var INTELLIGENCE_WIRE_VERSION = "2026-05-26.v1";
|
|
341
|
-
var DEFAULT_INTELLIGENCE_BASE = "https://intelligence.tangle.tools";
|
|
342
|
-
async function exportEvalRuns(events, config) {
|
|
343
|
-
if (events.length === 0) return { ok: true, status: 0, accepted: 0, rejected: [] };
|
|
344
|
-
const apiKey = config?.apiKey ?? (typeof process !== "undefined" ? process.env.TANGLE_API_KEY : void 0);
|
|
345
|
-
if (!apiKey)
|
|
346
|
-
throw new Error("exportEvalRuns: apiKey required (pass config.apiKey or set TANGLE_API_KEY)");
|
|
347
|
-
const base = config?.base ?? (typeof process !== "undefined" ? process.env.TANGLE_INTELLIGENCE_URL : void 0) ?? DEFAULT_INTELLIGENCE_BASE;
|
|
348
|
-
const url = `${base.replace(/\/+$/, "")}/v1/ingest/eval-runs`;
|
|
349
|
-
const res = await fetch(url, {
|
|
350
|
-
method: "POST",
|
|
351
|
-
headers: {
|
|
352
|
-
"content-type": "application/json",
|
|
353
|
-
authorization: `Bearer ${apiKey}`,
|
|
354
|
-
"X-Tangle-Wire-Version": INTELLIGENCE_WIRE_VERSION,
|
|
355
|
-
...config?.idempotencyKey ? { "Idempotency-Key": config.idempotencyKey } : {}
|
|
356
|
-
},
|
|
357
|
-
body: JSON.stringify({ wireVersion: INTELLIGENCE_WIRE_VERSION, events })
|
|
358
|
-
});
|
|
359
|
-
let parsed = {};
|
|
360
|
-
try {
|
|
361
|
-
parsed = await res.json();
|
|
362
|
-
} catch {
|
|
363
|
-
}
|
|
364
|
-
return {
|
|
365
|
-
ok: res.ok,
|
|
366
|
-
status: res.status,
|
|
367
|
-
accepted: parsed.accepted ?? (res.ok ? events.length : 0),
|
|
368
|
-
rejected: parsed.rejected ?? []
|
|
369
|
-
};
|
|
370
|
-
}
|
|
371
|
-
|
|
372
|
-
export {
|
|
373
|
-
createOtelExporter,
|
|
374
|
-
loopEventToOtelSpan,
|
|
375
|
-
flatOtelSpan,
|
|
376
|
-
buildLoopOtelSpans,
|
|
377
|
-
buildLoopSpanNodes,
|
|
378
|
-
INTELLIGENCE_WIRE_VERSION,
|
|
379
|
-
exportEvalRuns
|
|
380
|
-
};
|
|
381
|
-
//# sourceMappingURL=chunk-IVGYLCFH.js.map
|