{"version":3,"file":"skills.mjs","names":[],"sources":["../../src/batteries/skills/contracts.ts","../../src/batteries/skills/middleware.ts","../../src/batteries/skills/artifacts.ts","../../src/batteries/skills/output.ts","../../src/batteries/skills/import.ts","../../src/batteries/skills/channels.ts","../../src/batteries/skills/isolated.ts","../../src/batteries/skills/scripts.ts","../../src/batteries/skills/manager.ts","../../src/batteries/skills/forge.ts"],"sourcesContent":["/** Structural contracts for skill sources. No ADK classes are required at this boundary. */\n\n/**\n * Discovery result. Carries the ROUTING METADATA — `name` and `description` — because that is\n * what `list_skills` shows the model and what it chooses on; requiring `descriptor()` to obtain\n * it would mean loading every skill's module just to list the catalog.\n */\nexport interface DiscoveredSkill {\n  /** Stable source-assigned identity used for catalog routing and load operations. */\n  id: string\n  /** Source version used to detect an available update without loading the descriptor. */\n  version: string\n  /** agentskills.io passthrough, surfaced pre-load. Optional: a source may not have them. */\n  license?: string\n  /** Client-specific agentskills.io properties surfaced before load for provenance and audit. */\n  metadata?: Readonly<Record<string, string>>\n  /** Free-form compatibility note; surfaced but deliberately not parsed or enforced. */\n  compatibility?: string\n  /** Human-facing name used in routing metadata. */\n  name: string\n  /** Routing text shown to the model without loading the skill body. */\n  description: string\n}\n\n/** A discovered skill plus manager-assigned provenance. This is what the battery passes around. */\nexport type SkillRef = DiscoveredSkill & { readonly sourceId: string }\n\n/** Controls whether a loaded body is represented by a handle or rendered inline per dispatch. */\nexport type SkillLoadChannel = 'handle' | 'inline'\n\n/** A model-selectable script bundled with a skill and invoked with declared arguments only. */\nexport interface SkillScriptSpec {\n  /** Enum member exposed to the model when selecting this script. */\n  readonly name: string\n  /** Source-relative bundled path; it must also be returned by {@link SkillSource.list}. */\n  readonly path: string\n  /** Instructions shown alongside the script choice. */\n  readonly description: string\n  /** Interpreter key resolved through the deployment's interpreter allowlist. */\n  readonly interpreter: string\n  /** Declared parameters, passed only in declaration order after the script path. */\n  readonly params?: readonly SkillScriptParam[]\n}\n\n/** One validated value in the fixed argv contract presented to a script. */\nexport interface SkillScriptParam {\n  /** Argument name used in validation and argv construction. */\n  readonly name: string\n  /** Argument guidance shown to the model. */\n  readonly description: string\n  /** Validation/rendering kind; enum values are constrained separately. */\n  readonly type: 'string' | 'number' | 'boolean' | 'enum'\n  /** Allowed values, required when {@link SkillScriptParam.type} is `enum`. */\n  readonly values?: readonly string[]\n  /** Whether omission is rejected before the child process is started. */\n  readonly required?: boolean\n  /** Rendered as `--flag value` when set, otherwise positionally in declaration order. */\n  readonly flag?: string\n}\n\n/** Runtime-neutral source seam for discovery, metadata, body bytes, and bundled files. */\nexport interface SkillSource {\n  /** Stable provenance label; the manager rejects duplicate source ids at configuration time. */\n  readonly id: string\n  /** Asynchronously yields discovery metadata; protocol conformance is checked by the suite, not the duck-guard. */\n  discover(o?: { signal?: AbortSignal }): AsyncIterable<DiscoveredSkill>\n  /** Resolves the live descriptor and tools only when a manager operation loads the skill. */\n  descriptor(ref: SkillRef, o?: { signal?: AbortSignal }): Promise<unknown>\n  /**\n   * Read a file from the skill. **An omitted `path` means the skill BODY** — the `SKILL.md`\n   * equivalent — whatever the source calls it internally. Every channel needs the body.\n   */\n  read(\n    ref: SkillRef,\n    path?: string,\n    o?: { signal?: AbortSignal }\n  ): Promise<ReadableStream<Uint8Array>>\n  /** Returns source size and version for a body or bundled file without returning its bytes. */\n  stat(ref: SkillRef, path?: string): Promise<{ size: number; version: string }>\n  /**\n   * Enumerate bundled files for materialization.\n   * MUST include every path named by a `SkillScriptSpec`, and MUST NOT include the body.\n   */\n  list?(ref: SkillRef): Promise<readonly string[]>\n}\n\n/**\n * Duck-guard for the synchronous portion of a source contract. `discover()` returns an async\n * iterable and cannot be duck-checked beyond \"is a function\", so a value passing this guard may\n * still violate the protocol. `runSkillSourceConformance`, from\n * `@nhtio/adk/batteries/skills/conformance`, is the real protocol check.\n */\nexport const implementsSkillSource = (value: unknown): value is SkillSource => {\n  if (value === null || typeof value !== 'object') return false\n  const candidate = value as Record<string, unknown>\n  return (\n    typeof candidate.id === 'string' &&\n    typeof candidate.discover === 'function' &&\n    typeof candidate.descriptor === 'function' &&\n    typeof candidate.read === 'function' &&\n    typeof candidate.stat === 'function'\n  )\n}\n","import { isError } from '@nhtio/adk/guards'\nimport type { Retrievable, Tool } from '@nhtio/adk/common'\nimport type { SkillManager, SkillMiddlewareSet, ProjectedSkill } from './types'\nimport type {\n  DispatchContext,\n  DispatchPipelineMiddlewareFn,\n  TurnContext,\n  TurnPipelineMiddlewareFn,\n} from '@nhtio/adk/types'\n\n/** Options for the standalone skills middleware factories. */\nexport interface SkillMiddlewareOptions {\n  /** Re-discover the catalog before hydrating each non-empty turn. */\n  readonly autoRefresh?: boolean\n}\n\ntype SkillContext = TurnContext | DispatchContext\n\n/**\n * Tracks only objects injected by this middleware. Context registries are deliberately not used\n * as a live-state store: their reads clone values.\n */\ninterface ProjectionState {\n  readonly retrievables: Set<Retrievable>\n  /**\n   * The exact `Tool` objects this battery registered, keyed by name. Cleanup compares identity\n   * against the live registry entry so it never unregisters a same-named tool that a later\n   * projection replaced ours with.\n   */\n  readonly tools: Map<string, Tool>\n}\n\ntype ProjectionStates = WeakMap<object, ProjectionState>\n\n/**\n * The four standalone factories must share projection state when composed by hand for the same\n * manager — otherwise the turn-output factory holds a different `WeakMap` than the turn-input one\n * and sees no projection to strip. Keyed by manager so each manager gets exactly one shared map,\n * matching what `createSkillMiddlewareSet` builds internally.\n */\nconst sharedProjectionStates = new WeakMap<SkillManager, ProjectionStates>()\nconst projectionStatesFor = (manager: SkillManager): ProjectionStates => {\n  let states = sharedProjectionStates.get(manager)\n  if (!states) {\n    states = new WeakMap<object, ProjectionState>()\n    sharedProjectionStates.set(manager, states)\n  }\n  return states\n}\n\nconst stateFor = (ctx: SkillContext, projectionStates: ProjectionStates): ProjectionState => {\n  let state = projectionStates.get(ctx)\n  if (!state) {\n    state = { retrievables: new Set(), tools: new Map() }\n    projectionStates.set(ctx, state)\n  }\n  return state\n}\n\nconst project = (\n  ctx: SkillContext,\n  projected: readonly ProjectedSkill[],\n  projectionStates: ProjectionStates\n): void => {\n  const state = stateFor(ctx, projectionStates)\n  for (const skill of projected) {\n    for (const tool of skill.tools) {\n      ctx.tools.register(tool, true)\n      state.tools.set(tool.name, tool)\n    }\n    if (skill.retrievable) {\n      ctx.turnRetrievables.add(skill.retrievable)\n      state.retrievables.add(skill.retrievable)\n    }\n  }\n}\n\nconst reconcile = (\n  ctx: SkillContext,\n  manager: SkillManager,\n  projectionStates: ProjectionStates\n): void => {\n  const loaded = new Set(manager.loaded())\n  const state = stateFor(ctx, projectionStates)\n  for (const [name, tool] of state.tools) {\n    const owner = tool.meta.get('skill')\n    if (typeof owner === 'string' && !loaded.has(owner)) {\n      // Only remove the entry if the registry still holds OUR object; a later projection may\n      // have replaced this name with a different tool that we must not clobber.\n      if (ctx.tools.get(name) === tool) ctx.tools.unregister(name)\n      state.tools.delete(name)\n    }\n  }\n\n  const projected = manager.projected(ctx)\n  const currentRetrievables = new Set(\n    projected.flatMap((skill) => (skill.retrievable ? [skill.retrievable] : []))\n  )\n  for (const retrievable of state.retrievables) {\n    if (!currentRetrievables.has(retrievable)) {\n      ctx.turnRetrievables.delete(retrievable)\n      state.retrievables.delete(retrievable)\n    }\n  }\n  project(ctx, projected, projectionStates)\n}\n\nconst failTurn = (ctx: TurnContext, error: unknown): void => {\n  // TurnContext has no nack/ack; abort(reason) preserves the projection failure and prevents\n  // an invalid turn from continuing.\n  ctx.abort(error)\n}\n\nconst failDispatch = (ctx: DispatchContext, error: unknown): void => {\n  ctx.nack(isError(error) ? error : new Error(String(error)))\n}\n\n/**\n * Hydrates loaded skills onto the fresh turn registry.\n *\n * @remarks\n * The registry exists before the turn input pipeline runs: `turn_runner.ts:309` constructs it,\n * `:311` constructs the `TurnContext`, and `:392` awaits the input pipeline. Projection here is\n * therefore sound and is the load-bearing turn-boundary operation. With `autoRefresh`, this calls\n * the catalog-only `refresh()`, never `refreshAndProject()`; an available update is not swapped\n * into a live conversation implicitly.\n *\n * Place this early, before middleware that reads `ctx.tools` or budgets context. A projection\n * failure aborts the turn: `TurnContext` has `abort()` but no `ack()`/`nack()`. The original\n * error is passed as `abort(reason)`, so the turn's abort signal retains the projection failure\n * for its runner/consumer rather than allowing an invalid turn to continue. Middleware is\n * skipped once `ctx.aborted` (the wrapper still calls `next()` but the body does not run), so\n * cleanup must never live only here; workspace disposal and other cleanup are reachable from\n * `manager.dispose()` as well.\n */\nconst createTurnInputMiddleware = (\n  manager: SkillManager,\n  options: SkillMiddlewareOptions,\n  projectionStates: ProjectionStates\n): TurnPipelineMiddlewareFn => {\n  const autoRefresh = options.autoRefresh === true\n  return async (ctx, next) => {\n    if (manager.loaded().length === 0) {\n      await next()\n      return\n    }\n    try {\n      if (autoRefresh) await manager.refresh()\n      project(ctx, manager.projected(ctx), projectionStates)\n    } catch (error) {\n      failTurn(ctx, error)\n      return\n    }\n    await next()\n  }\n}\n\n/** Create the turn-input middleware that refreshes and projects loaded skills. */\nexport const skillsTurnInputMiddleware = (\n  manager: SkillManager,\n  options: SkillMiddlewareOptions = {}\n): TurnPipelineMiddlewareFn =>\n  createTurnInputMiddleware(manager, options, projectionStatesFor(manager))\n\n/**\n * Strips skill projections at the head of the turn-output pipeline, before any downstream output\n * middleware observes the context.\n *\n * @remarks\n * The turn's answer is persisted at dispatch, before this pipeline runs; the strip removes the\n * projection **at the head of turn-output** — it runs before `next()`, so every downstream\n * turn-output middleware (a consumer's observation or secondary persistence) sees a context the\n * skill body and tools have ALREADY left. That omission is the guarantee, not a gap: \"the body\n * never leaves\" is the whole point, and running the strip after `next()` would expose the\n * projection to downstream persistence and reintroduce exactly the leak this battery exists to\n * prevent. Do not move the strip below `next()`.\n *\n * This is best-effort: `TurnRunner.run()` returns before the output pipeline on a failed or\n * aborted turn (`turn_runner.ts:470-473`). Nothing is corrupted when this strip is skipped because\n * projected state is ephemeral; the discarded turn context is not durable state. This middleware\n * never touches a skill workspace: workspace lifetime follows the skill, not the turn. The\n * per-set weak state records the exact tools and retrievables injected by this battery; cleanup\n * therefore cannot unregister a consumer-owned tool that merely has `meta.skill`. Strip is\n * deliberately subtractive: it never projects to fill missing state. A `load()` handler receives\n * a `DispatchContext` and settles its projection there; it is not a projection into this turn\n * context. In the normal path, `turnInput` records every turn-context injection before output\n * runs. Treating an unrecorded context as loaded state here would briefly inject a skill body and\n * tools into a context that the turn pipeline never hydrated, violating the strip boundary.\n */\nconst createTurnOutputMiddleware =\n  (\n    _manager: SkillManager,\n    _options: SkillMiddlewareOptions,\n    projectionStates: ProjectionStates\n  ): TurnPipelineMiddlewareFn =>\n  async (ctx, next) => {\n    const state = projectionStates.get(ctx)\n    for (const retrievable of state?.retrievables ?? []) ctx.turnRetrievables.delete(retrievable)\n    for (const [name, tool] of state?.tools ?? []) {\n      if (ctx.tools.get(name) === tool) ctx.tools.unregister(name)\n    }\n    state?.retrievables.clear()\n    state?.tools.clear()\n    await next()\n  }\n\n/** Create the turn-output middleware that removes this set's skill projections. */\nexport const skillsTurnOutputMiddleware = (\n  manager: SkillManager,\n  options: SkillMiddlewareOptions = {}\n): TurnPipelineMiddlewareFn =>\n  createTurnOutputMiddleware(manager, options, projectionStatesFor(manager))\n\n/**\n * Repairs per-iteration skill integrity before the budget/thrift pass.\n *\n * @remarks\n * `turn_runner.ts:425-426` hands `dispatchInputPipeline` to `DispatchRunner` as its\n * `turnInputPipeline`; the parameter names in this factory intentionally say dispatch to avoid\n * wiring those two seams backwards. Unloaded skill tools are removed and the current projection\n * is reasserted after a mid-turn load. Forged artifact readers are deliberately untouched:\n * `pruneEphemeral()` would remove readers for every artifact in the iteration, not just a skill.\n * A dispatch integrity failure nacks the iteration because `DispatchContext` has `nack()`; unlike\n * `TurnContext`, it also has `ack()`.\n */\nconst createDispatchInputMiddleware = (\n  manager: SkillManager,\n  _options: SkillMiddlewareOptions,\n  projectionStates: ProjectionStates\n): DispatchPipelineMiddlewareFn => {\n  return async (dispatchCtx, next) => {\n    if (manager.loaded().length === 0) {\n      await next()\n      return\n    }\n    try {\n      reconcile(dispatchCtx, manager, projectionStates)\n    } catch (error) {\n      failDispatch(dispatchCtx, error)\n      return\n    }\n    await next()\n  }\n}\n\n/** Create the dispatch-input middleware that reconciles skill projections. */\nexport const skillsDispatchInputMiddleware = (\n  manager: SkillManager,\n  options: SkillMiddlewareOptions = {}\n): DispatchPipelineMiddlewareFn =>\n  createDispatchInputMiddleware(manager, options, projectionStatesFor(manager))\n\n/**\n * Observes and reconciles skill state after execution, without committing anything.\n *\n * @remarks\n * Settlement is immediate: load/unload handlers mutate manager state and the registry before\n * returning, so this middleware is not a commit point. It runs after the executor and before\n * result persistence. It does not call `pruneEphemeral()` and does not touch forged artifact\n * readers. An empty initialized set is a deliberate no-op.\n */\nconst createDispatchOutputMiddleware = (\n  manager: SkillManager,\n  _options: SkillMiddlewareOptions,\n  projectionStates: ProjectionStates\n): DispatchPipelineMiddlewareFn => {\n  return async (dispatchCtx, next) => {\n    if (manager.loaded().length === 0) {\n      await next()\n      return\n    }\n    try {\n      reconcile(dispatchCtx, manager, projectionStates)\n    } catch (error) {\n      failDispatch(dispatchCtx, error)\n      return\n    }\n    await next()\n  }\n}\n\n/** Create the dispatch-output middleware that observes and reconciles skill state. */\nexport const skillsDispatchOutputMiddleware = (\n  manager: SkillManager,\n  options: SkillMiddlewareOptions = {}\n): DispatchPipelineMiddlewareFn =>\n  createDispatchOutputMiddleware(manager, options, projectionStatesFor(manager))\n\n/** Build the stable four-middleware skills integration surface. */\nexport const createSkillMiddlewareSet = (\n  manager: SkillManager,\n  options: SkillMiddlewareOptions = {}\n): SkillMiddlewareSet => {\n  const projectionStates = projectionStatesFor(manager)\n  return {\n    turnInput: createTurnInputMiddleware(manager, options, projectionStates),\n    turnOutput: createTurnOutputMiddleware(manager, options, projectionStates),\n    dispatchInput: createDispatchInputMiddleware(manager, options, projectionStates),\n    dispatchOutput: createDispatchOutputMiddleware(manager, options, projectionStates),\n  }\n}\n\nexport type { SkillMiddlewareSet }\n","/** Skill artifact-kind resolution and binding registry. */\nimport { SpooledArtifact } from '@nhtio/adk/common'\nimport { isError, isObject } from '@nhtio/adk/guards'\nimport { E_INVALID_SKILLS_CONFIG, E_SKILL_ARTIFACT_UNAVAILABLE } from './exceptions'\nimport type { SpooledArtifactConstructor } from '@nhtio/adk/common'\nimport type { SkillDescriptor, SkillManagerConfig, SpooledKindResolver } from './types'\n\n/** Resolved artifact kinds plus the consumer-owned skill/tool binding table. */\nexport interface SkillArtifactRegistry {\n  /** Constructors keyed by the kind name accepted in bindings and descriptors. */\n  readonly kinds: ReadonlyMap<string, SpooledArtifactConstructor>\n  /** Explicit skill-to-tool-to-kind mappings; these override descriptor advice. */\n  readonly bindings: Readonly<Record<string, Readonly<Record<string, string>>>>\n  /** Selects the binding, then descriptor advice, then the raw built-in kind. */\n  resolve(\n    skillId: string,\n    toolName: string,\n    descriptor?: Pick<SkillDescriptor, 'artifactKind'>\n  ): SpooledArtifactConstructor\n}\n\nconst unwrap = (value: unknown): unknown => {\n  if (isObject(value) && 'default' in value) return value.default\n  return value\n}\n\nconst resolveOne = async (resolver: SpooledKindResolver): Promise<SpooledArtifactConstructor> => {\n  const value =\n    typeof resolver === 'function' && !SpooledArtifact.isSpooledArtifactConstructor(resolver)\n      ? await resolver()\n      : resolver\n  const result = unwrap(value)\n  if (!SpooledArtifact.isSpooledArtifactConstructor(result)) {\n    throw new E_INVALID_SKILLS_CONFIG([\n      'artifact kind resolver did not return a SpooledArtifact constructor',\n    ])\n  }\n  return result\n}\n\n/**\n * Resolve all optional artifact classes eagerly. The built-in raw kind is always available;\n * optional artifact batteries are intentionally not imported here.\n */\nexport const createSkillArtifactRegistry = async (\n  config: Pick<SkillManagerConfig, 'artifactKinds' | 'artifactBindings'>\n): Promise<SkillArtifactRegistry> => {\n  const entries = Object.entries(config.artifactKinds ?? {})\n  const resolved = new Map<string, SpooledArtifactConstructor>([\n    ['SpooledArtifact', SpooledArtifact],\n  ])\n  await Promise.all(\n    entries.map(async ([key, resolver], index) => {\n      try {\n        resolved.set(key, await resolveOne(resolver))\n      } catch (error) {\n        throw new E_INVALID_SKILLS_CONFIG([\n          `artifactKinds[${index}] \"${key}\": ${isError(error) ? error.message : String(error)}`,\n        ])\n      }\n    })\n  )\n  const bindings = config.artifactBindings ?? {}\n  return {\n    kinds: resolved,\n    bindings,\n    resolve(skillId, toolName, descriptor) {\n      const kind = bindings[skillId]?.[toolName] ?? descriptor?.artifactKind ?? 'SpooledArtifact'\n      const constructor = resolved.get(kind)\n      if (!constructor) {\n        throw new E_SKILL_ARTIFACT_UNAVAILABLE([\n          `${kind}; registered keys: ${[...resolved.keys()].join(', ')}`,\n        ])\n      }\n      return constructor\n    },\n  }\n}\n\n/**\n * bedrock_converse and gemini_generate_content do not honour artifactConstructor: they coerce\n * every tool result through `new Tokenizable(JSON.stringify(raw))`. Their imported-tool output is\n * therefore inlined and no artifact readers are forged. The other adapters spool tool results.\n */\n","/**\n * Framework-agnostic typed output for skill tools.\n *\n * A skill tool is third-party code that should not have to import this library to describe what it\n * produced. Core's tool contract accepts `string | Uint8Array | Media | Media[]`, but constructing\n * a `Media` — let alone a `Retrievable` — means importing `@nhtio/adk/common`, which a tool written\n * against any other framework will not do. The wrapper is already the adaptation boundary for the\n * gate, errors and trust; this makes it the adaptation boundary for OUTPUT too.\n *\n * A tool may therefore return a plain-object DESCRIPTOR and the host builds the primitive:\n *\n * - `{ bytes, mimeType, filename? }` → a {@link Media}. The tool says what it produced (a PDF, a\n *   WAV); the host wraps the bytes in a reader via `ctx.storeMediaBytes`, infers `kind` and the\n *   conservative `modalityHazard` from the MIME type, and FLOORS the trust tier from the skill's own\n *   tier — a skill can never label its output first-party.\n * - `{ retrievable: { content, … } }` → a {@link Retrievable} the model can cite, search and hold a\n *   handle to. Its plain-string content is handed to `ctx.storeRetrievable`, which collision-checks,\n *   spools the text behind a handle, and PERSISTS the record DURABLY. It is durable work product —\n *   not the reclaimable instruction set a skill BODY is, nor the transient-within-dispatch stdout a\n *   SCRIPT produces — so it outlives the turn and an `unload_skill`.\n *\n * A prebuilt `SpooledArtifact` is still refused (it would bypass the deployer's artifact binding),\n * and anything not matching an accepted shape is still `E_SKILL_TOOL_BAD_RESPONSE`.\n */\nimport { v6 as uuidv6 } from 'uuid'\nimport { E_SKILL_TOOL_BAD_RESPONSE } from './exceptions'\nimport { isObject, isInstanceOf } from '@nhtio/adk/guards'\nimport { Media, Retrievable, SpooledArtifact } from '@nhtio/adk/common'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { RetrievableTrustTier } from '@nhtio/adk/common'\nimport type { MediaKind, MediaModalityHazard, MediaTrustTier } from '@nhtio/adk/common'\n\n/** The skill trust tiers the battery threads through, shared by scripts and typed output. */\nexport type SkillTrustTier = 'first-party' | 'third-party-public' | 'third-party-private'\n\n/**\n * Restriction rank of a trust tier: higher is MORE restricted. Mirrors the envelope renderer's own\n * ordering (`first-party` 0 < `third-party-public` 1 < `third-party-private` 2). Used to reject a\n * prebuilt primitive whose tier is MORE PRIVILEGED (lower rank) than the skill's floored output\n * tier — a skill must never elevate its output, but a stricter tier than the floor is fine.\n */\nconst tierRank: Record<MediaTrustTier & RetrievableTrustTier, number> = {\n  'first-party': 0,\n  'third-party-public': 1,\n  'third-party-private': 2,\n}\n\n/**\n * The output kind a descriptor may DECLARE for a tool. When present, a runtime shape that disagrees\n * is a detectable failure rather than a silent reinterpretation; when absent, the wrapper sniffs.\n */\nexport type SkillOutputKind = 'text' | 'binary' | 'media' | 'retrievable'\n\n/** Bytes-with-a-content-type: the framework-agnostic path to typed binary. */\nexport interface SkillBinaryOutput {\n  /** The raw bytes. The host wraps them in a reader via `ctx.storeMediaBytes`. */\n  readonly bytes: Uint8Array\n  /** MIME type of the bytes; the `MediaKind` and modality hazard are inferred from it. */\n  readonly mimeType: string\n  /** Optional filename; a stable default derived from the tool name is used when omitted. */\n  readonly filename?: string\n}\n\n/** A framework-agnostic retrievable descriptor. `content` is plain text; the host spools it. */\nexport interface SkillRetrievableOutput {\n  /** The retrievable to construct. Its text is spooled behind a handle and its tier is floored. */\n  readonly retrievable: {\n    /** Plain text the model can cite, search, and hold a handle to. */\n    readonly content: string\n    /** Optional provenance string (URL, document path, knowledge-base id). */\n    readonly source?: string\n    /** Optional semantic label (e.g. `'reference'`, `'policy'`); defaults to `'skill-tool'`. */\n    readonly kind?: string\n    /** Optional relevance score in `[0, 1]`. */\n    readonly score?: number\n    /** Render inline rather than as a handle; defaults to `false`. */\n    readonly inline?: boolean\n  }\n}\n\n/**\n * Floor a skill's trust tier onto its output, shared with tier-3 scripts: `first-party` becomes\n * `third-party-private`; both third-party tiers pass through. Program output from a first-party\n * skill is still program output, never deployer-authored prose, so it never gets the first-party\n * envelope.\n */\nexport const floorOutputTier = (\n  tier: SkillTrustTier | undefined\n): MediaTrustTier & RetrievableTrustTier =>\n  tier === 'first-party' ? 'third-party-private' : (tier ?? 'third-party-public')\n\nconst mediaKindOf = (mimeType: string): MediaKind => {\n  const mime = mimeType.toLowerCase()\n  if (mime.startsWith('image/')) return 'image'\n  if (mime.startsWith('audio/')) return 'audio'\n  if (mime.startsWith('video/')) return 'video'\n  return 'document'\n}\n\n/** Documents can carry hidden instructions; other modalities are opaque-perceptual. */\nconst hazardForKind = (kind: MediaKind): MediaModalityHazard =>\n  kind === 'document' ? 'extractable-instructions' : 'opaque-perceptual'\n\nconst isBinaryOutput = (value: unknown): value is SkillBinaryOutput =>\n  isObject(value) &&\n  isInstanceOf((value as { bytes?: unknown }).bytes, 'Uint8Array', Uint8Array) &&\n  typeof (value as { mimeType?: unknown }).mimeType === 'string'\n\nconst isRetrievableOutput = (value: unknown): value is SkillRetrievableOutput =>\n  isObject(value) &&\n  isObject((value as { retrievable?: unknown }).retrievable) &&\n  typeof (value as { retrievable: { content?: unknown } }).retrievable.content === 'string'\n\n/**\n * Build a {@link Media} from a framework-agnostic bytes descriptor. The reader is created via\n * `ctx.storeMediaBytes`, so the tool never supplies a `MediaReader` and never imports ADK.\n */\nconst buildMedia = async (\n  out: SkillBinaryOutput,\n  ctx: DispatchContext,\n  tier: SkillTrustTier | undefined,\n  toolName: string\n): Promise<Media> => {\n  // Validate the descriptor BEFORE storing bytes: `new Media` would otherwise reject an invalid\n  // filename only after `storeMediaBytes` has written the bytes, orphaning them in the store.\n  if (!out.mimeType)\n    throw new E_SKILL_TOOL_BAD_RESPONSE([`${toolName}: binary output missing mimeType`])\n  if (out.filename !== undefined && typeof out.filename !== 'string')\n    throw new E_SKILL_TOOL_BAD_RESPONSE([`${toolName}: binary output has a non-string filename`])\n  const kind = mediaKindOf(out.mimeType)\n  const id = uuidv6()\n  const reader = await ctx.storeMediaBytes(id, out.bytes)\n  return new Media({\n    id,\n    kind,\n    mimeType: out.mimeType,\n    filename: out.filename ?? `${toolName}-${id}`,\n    reader,\n    trustTier: floorOutputTier(tier),\n    modalityHazard: hazardForKind(kind),\n    source: toolName,\n  })\n}\n\n/**\n * Build a {@link Retrievable} from a framework-agnostic descriptor and PERSIST it through\n * `ctx.storeRetrievable`, following the canonical `retrievables` tool-battery pattern EXACTLY: hand\n * `storeRetrievable` a plain-STRING `content` and let core do the work. A skill tool's explicit\n * `{ retrievable }` is a declared knowledge record — durable work product, not the reclaimable\n * instruction set a skill BODY is, and not the transient-within-dispatch stdout a SCRIPT produces.\n *\n * Passing string content is what makes this atomic-in-order: `storeRetrievable` (core's\n * `#doStoreRetrievable`) runs its id-collision check FIRST, then `autoSpoolRetrievable` writes the\n * bytes through the consumer's own `storeRetrievableBytes` conduit, then registers the record and\n * fires the consumer's `storeRetrievable` callback. Nothing is written before the check, so a\n * collision throw stores nothing; and because the byte write is core's own (not a separate pre-write\n * of ours), there is no window where spooled bytes exist without a registered record on the paths\n * this battery controls.\n *\n * Byte cleanup after a rejecting persistence callback is DELIBERATELY OUT OF SCOPE for this library\n * — it is the consumer's to handle, and it must be, not merely a gap we tolerate. When the consumer's\n * `storeRetrievable` callback rejects, core has already spooled the bytes via the consumer's OWN\n * `storeRetrievableBytes` conduit under a known id; the consumer therefore holds both the id and the\n * store and is the only party that can reconcile a spooled id whose record write failed. The library\n * exposes no byte-delete conduit (`deleteRetrievable` removes the record, not the bytes) precisely\n * because adding one would push a failure the consumer already owns back across the boundary. Core\n * does not roll back for ANY `storeRetrievable` caller, and the canonical `retrievables` tool battery\n * makes the same choice; this battery is consistent with both. A consumer whose byte store must not\n * accumulate orphans on persistence failure cleans up in its own `storeRetrievable` callback.\n *\n * The tier is floored (a skill can never elevate its output) and the id is an unguessable UUID so\n * injected content cannot forge the closing tag. Returns the acknowledgement for the model.\n */\nconst addRetrievable = async (\n  out: SkillRetrievableOutput,\n  ctx: DispatchContext,\n  tier: SkillTrustTier | undefined,\n  toolName: string\n): Promise<string> => {\n  const { content, source, kind, score, inline } = out.retrievable\n  // Validate optional fields up front so an out-of-range score or a non-boolean inline fails as a\n  // clean bad-response rather than surfacing from the primitive constructor deeper in the stack.\n  if (\n    (source !== undefined && typeof source !== 'string') ||\n    (kind !== undefined && typeof kind !== 'string') ||\n    (score !== undefined &&\n      (typeof score !== 'number' || !Number.isFinite(score) || score < 0 || score > 1)) ||\n    (inline !== undefined && typeof inline !== 'boolean')\n  )\n    throw new E_SKILL_TOOL_BAD_RESPONSE([`${toolName}: invalid retrievable output`])\n  const id = uuidv6()\n  const byteLength = new TextEncoder().encode(content).byteLength\n  // Plain-string content: core collision-checks, THEN spools, THEN persists — no pre-write to orphan.\n  // If the consumer's storeRetrievable callback rejects after core spools, cleaning up the bytes is\n  // the consumer's responsibility (see the doc comment) — the rejection propagates unchanged.\n  await ctx.storeRetrievable(\n    new Retrievable({\n      id,\n      content,\n      trustTier: floorOutputTier(tier),\n      source: source ?? toolName,\n      kind: kind ?? 'skill-tool',\n      ...(score !== undefined ? { score } : {}),\n      inline: inline ?? false,\n      createdAt: new Date(),\n      updatedAt: new Date(),\n    })\n  )\n  return `Retrievable ${id} added (${byteLength} bytes)`\n}\n\n/**\n * Validate a raw skill-tool return and resolve it to a core-legal tool result, constructing typed\n * primitives from framework-agnostic descriptors host-side. `declared`, when the descriptor set it,\n * is enforced: a runtime shape that disagrees fails rather than being silently reinterpreted.\n */\nexport const resolveSkillToolOutput = async (o: {\n  raw: unknown\n  ctx: DispatchContext\n  toolName: string\n  trustTier: SkillTrustTier | undefined\n  declared?: SkillOutputKind\n}): Promise<string | Uint8Array | Media | Media[]> => {\n  const { raw, ctx, toolName, trustTier, declared } = o\n\n  // A prebuilt artifact is refused first and unconditionally: it would bypass the deployer's binding.\n  if (isInstanceOf(raw, 'SpooledArtifact', SpooledArtifact))\n    throw new E_SKILL_TOOL_BAD_RESPONSE([`${toolName} returned a SpooledArtifact`])\n\n  // Sniff by what the return PRODUCES: a raw Uint8Array is anonymous `'binary'`; a\n  // `{bytes, mimeType}` descriptor and a `Media`/`Media[]` all produce typed `'media'`; a\n  // retrievable descriptor is `'retrievable'`; a string is `'text'`.\n  const sniffed: SkillOutputKind | undefined =\n    typeof raw === 'string'\n      ? 'text'\n      : isInstanceOf(raw, 'Uint8Array', Uint8Array)\n        ? 'binary'\n        : isInstanceOf(raw, 'Media', Media) ||\n            // An empty array is a valid `Media[]` result — a tool reporting no media. `every` is\n            // vacuously true for `[]`, so no length guard: it stays 'media', not undefined/rejected.\n            (Array.isArray(raw) && raw.every((i) => isInstanceOf(i, 'Media', Media))) ||\n            isBinaryOutput(raw)\n          ? 'media'\n          : isRetrievableOutput(raw)\n            ? 'retrievable'\n            : undefined\n\n  if (sniffed === undefined) throw new E_SKILL_TOOL_BAD_RESPONSE([toolName])\n  // A declared kind that disagrees with the produced shape is a detectable bug.\n  if (declared !== undefined && declared !== sniffed)\n    throw new E_SKILL_TOOL_BAD_RESPONSE([\n      `${toolName}: declared ${declared} output but returned ${sniffed}`,\n    ])\n\n  if (typeof raw === 'string') return raw\n  if (isInstanceOf(raw, 'Uint8Array', Uint8Array)) return raw as Uint8Array\n  // A prebuilt Media must not carry a tier MORE PRIVILEGED than the skill's floored output tier:\n  // otherwise a skill constructing `Media.firstParty(...)` would render third-party content under a\n  // first-party envelope. Equal or stricter (higher rank) is fine — flooring only ever restricts.\n  const floor = floorOutputTier(trustTier)\n  if (isInstanceOf(raw, 'Media', Media)) {\n    if (tierRank[(raw as Media).trustTier] < tierRank[floor])\n      throw new E_SKILL_TOOL_BAD_RESPONSE([\n        `${toolName}: Media trust tier exceeds skill output tier`,\n      ])\n    return raw as Media\n  }\n  if (Array.isArray(raw)) {\n    if ((raw as Media[]).some((item) => tierRank[item.trustTier] < tierRank[floor]))\n      throw new E_SKILL_TOOL_BAD_RESPONSE([\n        `${toolName}: a Media in the array exceeds skill output tier`,\n      ])\n    return raw as Media[]\n  }\n  if (isBinaryOutput(raw)) return buildMedia(raw, ctx, trustTier, toolName)\n  return addRetrievable(raw as SkillRetrievableOutput, ctx, trustTier, toolName)\n}\n","/** Imported skill-tool wrapping and name preflight. */\nimport { isError } from '@nhtio/adk/guards'\nimport { resolveSkillToolOutput } from './output'\nimport { runToolGate } from '@nhtio/adk/batteries/tools/_shared'\nimport {\n  effectiveToolMethods,\n  SpooledArtifact,\n  SpooledMarkdownArtifact,\n  Tool,\n} from '@nhtio/adk/common'\nimport {\n  E_SKILL_MANIFEST_INVALID,\n  E_SKILL_NOT_LOADED,\n  E_SKILL_TOOL_COLLISION,\n  E_SKILL_TOOL_DUPLICATE,\n  E_SKILL_TOOL_FAILED,\n} from './exceptions'\nimport type { SkillRecord } from './manager'\nimport type { SkillOutputKind, SkillTrustTier } from './output'\nimport type { SpooledArtifactConstructor } from '@nhtio/adk/common'\nimport type { ToolGateFn } from '@nhtio/adk/batteries/tools/_shared'\n\n/**\n * Rebuild every imported tool; the original tool is never mutated.\n *\n * Error containment intentionally follows Tool.executor() on both sides. Error throws have the\n * four-level downstream/failed/downstream/original chain; non-Error throws have three levels and\n * an unrecoverable payload because the inner executor attaches no cause. This wrapper does not\n * race an in-process handler against ctx.abortSignal: a handler that never settles hangs the turn;\n * skills needing cancellation should ship a script.\n */\nexport const rewrapSkillTool = (o: {\n  /** The third-party tool exactly as the descriptor supplied it. */\n  original: Tool\n  /** Identity of the owning skill; becomes `meta.skill` / `meta.skillVersion`. */\n  skill: { readonly id: string; readonly version: string; readonly trustTier?: SkillTrustTier }\n  /** The loaded record. The wrapper closes over it for the liveness check (retired + refcount). */\n  record: SkillRecord\n  /** Undefined only when `unsafe.ungatedSkillTools` is set. */\n  gate: ToolGateFn | undefined\n  /** Resolves this tool's artifact kind. */\n  resolveArtifact: (skillId: string, toolName: string) => SpooledArtifactConstructor\n  /** Descriptor-declared output kind for this tool; enforced against the runtime shape when set. */\n  declaredOutput?: SkillOutputKind\n}): Tool => {\n  const { original, skill, record, gate, resolveArtifact, declaredOutput } = o\n  return new Tool({\n    name: original.name,\n    description: original.description,\n    inputSchema: original.inputSchema,\n    artifactConstructor: () => resolveArtifact(skill.id, original.name),\n    meta: { ...original.meta.all(), skill: skill.id, skillVersion: skill.version },\n    trusted: false,\n    handler: async (args, ctx) => {\n      if (!record.tryEnter()) throw new E_SKILL_NOT_LOADED([skill.id])\n      let raw: unknown\n      try {\n        await runToolGate(gate, ctx, original.name, args)\n        try {\n          raw = await original.executor(ctx)(args)\n        } catch (err) {\n          throw new E_SKILL_TOOL_FAILED([original.name, skill.id], {\n            cause: isError(err) ? err : undefined,\n          })\n        }\n      } finally {\n        record.exit()\n      }\n\n      // Output resolution runs after the executor (and its refcount exit): a legal string,\n      // Uint8Array, Media or Media[] passes through; a framework-agnostic bytes/retrievable\n      // descriptor is constructed into the real primitive host-side; a prebuilt SpooledArtifact\n      // and every other shape fail E_SKILL_TOOL_BAD_RESPONSE. Validation sits OUTSIDE the executor\n      // try/catch so an illegal return shape is not masked as E_SKILL_TOOL_FAILED.\n      return resolveSkillToolOutput({\n        raw,\n        ctx,\n        toolName: original.name,\n        trustTier: skill.trustTier,\n        declared: declaredOutput,\n      })\n    },\n  })\n}\n\nconst TOOL_NAME = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/\n\n/**\n * Check imported and generated names before reservations or registration. Artifact readers are\n * derived from core's live method registries, including the mandatory raw and markdown kinds.\n */\nexport const assertSkillToolNames = (o: {\n  candidates: readonly string[]\n  reserved: ReadonlySet<string>\n  registryNames: readonly string[]\n  registryOwners: ReadonlyMap<string, string | undefined>\n  skillId: string\n  artifactKinds: readonly unknown[]\n}): void => {\n  const seen = new Set<string>()\n  const readers = new Set<string>()\n  for (const ctor of [SpooledArtifact, SpooledMarkdownArtifact, ...o.artifactKinds]) {\n    for (const method of effectiveToolMethods(ctor)) readers.add(method.name)\n  }\n  for (const name of o.candidates) {\n    if (!TOOL_NAME.test(name)) throw new E_SKILL_MANIFEST_INVALID([`tool name \"${name}\"`])\n    if (seen.has(name)) throw new E_SKILL_TOOL_DUPLICATE([name])\n    seen.add(name)\n    if (o.reserved.has(name)) throw new E_SKILL_TOOL_COLLISION([name])\n    if (readers.has(name)) throw new E_SKILL_TOOL_COLLISION([name])\n    const index = o.registryNames.indexOf(name)\n    if (index >= 0 && o.registryOwners.get(name) !== o.skillId) {\n      throw new E_SKILL_TOOL_COLLISION([name])\n    }\n  }\n}\n","import { v6 as uuidv6 } from 'uuid'\nimport { Retrievable, SpooledMarkdownArtifact } from '@nhtio/adk/common'\nimport { autoSpoolRetrievable } from '../../lib/utils/retrievable_spool'\nimport type { SkillDescriptor } from './types'\nimport type { SkillLoadChannel, SkillRef } from './contracts'\nimport type { DispatchContext, TurnContext } from '@nhtio/adk/types'\n\n/** Resolve the per-skill projection channel. */\nexport const resolveSkillChannel = (\n  descriptor: SkillDescriptor,\n  defaultChannel: SkillLoadChannel | undefined\n): SkillLoadChannel => descriptor.channel ?? defaultChannel ?? 'handle'\n\n/** Spool a skill body exactly once for a loaded record. */\nexport const spoolSkillBody = async (\n  ctx: DispatchContext | TurnContext,\n  ref: SkillRef,\n  descriptor: SkillDescriptor,\n  body: string,\n  channel: SkillLoadChannel\n): Promise<Retrievable> => {\n  const now = new Date().toISOString()\n  return autoSpoolRetrievable(\n    ctx,\n    new Retrievable({\n      id: uuidv6(),\n      content: body,\n      artifactConstructor: () => SpooledMarkdownArtifact,\n      trustTier: descriptor.trustTier ?? 'third-party-public',\n      inline: channel === 'inline',\n      source: `${ref.sourceId}:${ref.id}`,\n      kind: 'skill',\n      createdAt: now,\n      updatedAt: now,\n    })\n  )\n}\n","import { Tool } from '@nhtio/adk/forge'\nimport { validator } from '@nhtio/validation'\nimport { isInstanceOf } from '@nhtio/adk/guards'\nimport { runToolGate } from '@nhtio/adk/batteries/tools/_shared'\nimport { E_INVALID_SKILLS_CONFIG, E_SKILL_NOT_LOADED } from './exceptions'\nimport {\n  E_SANDBOX_FAILED,\n  E_SES_EVALUATION_TIMEOUT,\n  createGuestRunner,\n  resolveGuestLimits,\n} from '@nhtio/adk/batteries/sandbox'\nimport type { SkillRecord } from './manager'\nimport type { SkillScriptParam } from './contracts'\nimport type { GuestRuntimeLike } from '../sandbox/js/ses_contracts'\nimport type { SkillIsolatedTool, SkillIsolationConfig } from './types'\n\nconst parameterShape = (params: readonly SkillScriptParam[] | undefined) => {\n  const shape: Record<string, ReturnType<typeof validator.any>> = {}\n  for (const param of params ?? []) {\n    const schema =\n      param.type === 'number'\n        ? validator.number()\n        : param.type === 'boolean'\n          ? validator.boolean()\n          : param.type === 'enum'\n            ? validator.string().valid(...(param.values ?? []))\n            : validator.string()\n    shape[param.name] = param.required ? schema.required() : schema.optional()\n  }\n  return shape\n}\n\n/** Forge the isolated (tier-2) tools belonging to one loaded skill. */\nexport const forgeIsolatedTools = (o: {\n  declarations: readonly SkillIsolatedTool[]\n  isolation: SkillIsolationConfig\n  gate: ((ctx: unknown, call: { tool: string; args: unknown }) => void | Promise<void>) | undefined\n  record: SkillRecord\n  skill: { readonly id: string; readonly version: string }\n}): Tool[] => {\n  const { declarations, isolation, gate, record, skill } = o\n  const limits = resolveGuestLimits(isolation.limits)\n  return declarations.map((declaration) => {\n    const inputSchema = validator\n      .object({\n        ...parameterShape(declaration.params),\n        timeout_seconds: validator\n          .number()\n          .min(1)\n          .max(isolation.maxTimeoutSeconds)\n          .default(isolation.defaultTimeoutSeconds),\n      })\n      .unknown(false)\n      .required()\n    return new Tool({\n      name: declaration.name,\n      description: declaration.description,\n      inputSchema,\n      trusted: false,\n      meta: { skill: skill.id, skillVersion: skill.version },\n      handler: async (raw, ctx) => {\n        if (!record.tryEnter()) throw new E_SKILL_NOT_LOADED([skill.id])\n        const value = raw as Record<string, unknown> & { timeout_seconds: number }\n        const { timeout_seconds: timeoutSeconds, ...validatedArgs } = value\n        try {\n          await runToolGate(gate, ctx, declaration.name, value)\n          if (ctx.abortSignal.aborted)\n            throw new DOMException('The operation was aborted', 'AbortError')\n          const runtime: GuestRuntimeLike = isolation.resolveGuest\n            ? await isolation.resolveGuest({\n                globals: isolation.globals ?? {},\n                modules: isolation.modules ?? {},\n                limits,\n                signal: ctx.abortSignal,\n              })\n            : await createGuestRunner(isolation.globals ?? {}, limits, isolation.modules ?? {})\n          const guest = await runtime.spawn({\n            modules: Object.keys(isolation.modules ?? {}),\n            globals: Object.keys(isolation.globals ?? {}).map((name) => ({\n              name,\n              kind: 'async-fn' as const,\n            })),\n            limits,\n            signal: ctx.abortSignal,\n          })\n          try {\n            return JSON.stringify(\n              await guest.evaluate(`(${declaration.source})(${JSON.stringify(validatedArgs)})`, {\n                timeoutMs: timeoutSeconds * 1000,\n              })\n            )\n          } catch (error) {\n            if (isInstanceOf(error, 'E_SES_EVALUATION_TIMEOUT', E_SES_EVALUATION_TIMEOUT)) {\n              await guest.kill()\n              throw new E_SANDBOX_FAILED([\n                `Evaluation timed out after ${timeoutSeconds} seconds (kind: timed-out).`,\n              ])\n            }\n            throw error\n          } finally {\n            // kill is idempotent for the stock compartment and releases conforming guests.\n            await guest.kill()\n          }\n        } finally {\n          record.exit()\n        }\n      },\n    })\n  })\n}\n\n/** Validate the structural safety choice before any skill descriptor is loaded. */\nexport const validateIsolationConfig = (config: {\n  isolation?: SkillIsolationConfig\n  unsafe?: { isolatedToolsInProcess?: true }\n}): void => {\n  if (\n    config.isolation &&\n    !config.isolation.resolveGuest &&\n    !config.unsafe?.isolatedToolsInProcess\n  ) {\n    throw new E_INVALID_SKILLS_CONFIG([\n      'isolation.resolveGuest is required unless unsafe.isolatedToolsInProcess is enabled',\n    ])\n  }\n  if (config.isolation && !config.isolation.resolveGuest && config.unsafe?.isolatedToolsInProcess) {\n    console.warn('Skill isolated tools are running in-process; cancellation is best-effort.')\n  }\n}\n","/** Gated, argv-only execution of skill-provided scripts under a per-call policy. */\nimport { v6 as uuidv6 } from 'uuid'\nimport { validator } from '@nhtio/validation'\nimport { isError, isInstanceOf } from '@nhtio/adk/guards'\nimport { E_TURN_GATE_ABORTED } from '@nhtio/adk/exceptions'\nimport { Tool, Retrievable, SpooledArtifact } from '@nhtio/adk/common'\nimport { runToolGate, type ToolGateFn } from '@nhtio/adk/batteries/tools/_shared'\nimport {\n  classifySandboxPathRejection,\n  createExistingSymlinkGuard,\n  normalizeSandboxPath,\n} from '../sandbox/paths'\nimport {\n  E_SKILL_MANIFEST_INVALID,\n  E_SKILL_NOT_LOADED,\n  E_SKILL_SCRIPT_DENIED,\n  E_SKILL_SCRIPT_FAILED,\n  E_SKILL_SCRIPT_GATE_UNAVAILABLE,\n  E_SKILL_SCRIPT_POLICY_WIDENED,\n  E_SKILL_SCRIPT_TIMEOUT,\n  E_SKILL_SOURCE_PATH_REJECTED,\n  E_SKILL_WORKSPACE_FAILED,\n} from './exceptions'\nimport type { SkillRecord } from './manager'\nimport type { SandboxPolicy } from '../sandbox/types'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { SkillScriptConfig, SkillWorkspace } from './types'\nimport type { SkillScriptParam, SkillScriptSpec } from './contracts'\n\nconst generatedName = /^[A-Za-z_][A-Za-z0-9_-]{0,63}$/\nconst encoder = new TextEncoder()\nconst truncation = '\\n[output truncated]'\n\n/** Validate a value before putting it in argv. Values are never shell-interpolated. */\nexport const assertArgvValue = (value: unknown, name: string): string => {\n  const text = String(value)\n  if (text.startsWith('-') || text.includes('\\0'))\n    throw new E_SKILL_MANIFEST_INVALID([`${name}: unsafe argv value`])\n  return text\n}\n\nconst slashPath = (value: string): string => {\n  if (value.startsWith('/') || value.startsWith('\\\\'))\n    throw new E_SKILL_SOURCE_PATH_REJECTED([value])\n  const reason = classifySandboxPathRejection(value)\n  if (reason !== undefined) throw new E_SKILL_SOURCE_PATH_REJECTED([`${value} (${reason})`])\n  try {\n    const normal = normalizeSandboxPath(value)\n    if (!normal || normal === '.' || normal.startsWith('../') || normal.includes('/../'))\n      throw new Error('outside skill subtree')\n    return normal\n  } catch {\n    throw new E_SKILL_SOURCE_PATH_REJECTED([value])\n  }\n}\n\n/** Validate and normalise a source-owned filename. Leading separators are rejected first. */\nexport const validateSkillSourcePath = (value: string): string => slashPath(value)\n\nconst descendant = (child: string, parent: string): boolean => {\n  const c = child.replaceAll('\\\\', '/').replace(/\\/+/g, '/').replace(/\\/$/, '') || '/'\n  const p = parent.replaceAll('\\\\', '/').replace(/\\/+/g, '/').replace(/\\/$/, '') || '/'\n  return p === '/' ? c.startsWith('/') : c === p || c.startsWith(`${p}/`)\n}\nconst concrete = (value: string): boolean => !/[!*?{}[\\]]/.test(value)\nconst list = (value: readonly string[] | undefined): readonly string[] => value ?? []\nconst authorised = (path: string, rules: readonly string[]): boolean =>\n  rules.some((rule) =>\n    concrete(rule) ? descendant(path, rule) : descendant(path, rule.replace(/[!*?{}[\\]]/g, ''))\n  )\nconst covered = (deny: string, by: string): boolean =>\n  concrete(deny) && concrete(by) && descendant(deny, by)\n\n/**\n * Check the battery's path-aware policy subset relation. This is intentionally conservative:\n * globs supplied by a per-call policy are undecidable and fail closed.\n */\nexport const assertPolicySubset = (perCall: SandboxPolicy, session: SandboxPolicy): void => {\n  if (perCall.filesystem.disabled || session.filesystem.disabled)\n    throw new E_SKILL_SCRIPT_POLICY_WIDENED(['filesystem.disabled'])\n  if (perCall.network.disabled || session.network.disabled)\n    throw new E_SKILL_SCRIPT_POLICY_WIDENED(['network.disabled'])\n  for (const path of list(perCall.filesystem.allowRead)) {\n    if (!concrete(path) || !authorised(path, list(session.filesystem.allowRead)))\n      throw new E_SKILL_SCRIPT_POLICY_WIDENED([`filesystem.allowRead:${path}`])\n  }\n  for (const deny of list(session.filesystem.denyRead)) {\n    if (!list(perCall.filesystem.denyRead).some((candidate) => covered(deny, candidate)))\n      throw new E_SKILL_SCRIPT_POLICY_WIDENED([`filesystem.denyRead:${deny}`])\n  }\n  for (const path of list(perCall.filesystem.allowWrite)) {\n    if (!concrete(path) || !authorised(path, list(session.filesystem.allowWrite)))\n      throw new E_SKILL_SCRIPT_POLICY_WIDENED([`filesystem.allowWrite:${path}`])\n    if (list(perCall.filesystem.denyWrite).some((deny) => descendant(path, deny))) continue\n    if (list(session.filesystem.denyWrite).some((deny) => descendant(path, deny)))\n      throw new E_SKILL_SCRIPT_POLICY_WIDENED([`filesystem.allowWrite:${path}`])\n  }\n  for (const domain of list(perCall.network.allowedDomains)) {\n    // A per-call `*` is the WIDEST possible request, so it must clear the same membership test as\n    // any named domain: it is authorised only when the session itself permits `*`. Special-casing\n    // `domain !== '*'` here would let the one value that widens the most bypass the check entirely.\n    if (\n      !list(session.network.allowedDomains).includes(domain) &&\n      !list(session.network.allowedDomains).includes('*')\n    )\n      throw new E_SKILL_SCRIPT_POLICY_WIDENED([`network:${domain}`])\n  }\n}\n\nconst validateParam = (param: SkillScriptParam): void => {\n  if (!param.name || !param.description)\n    throw new E_SKILL_MANIFEST_INVALID([`parameter ${param.name}`])\n  if (!param.required && !param.flag)\n    throw new E_SKILL_MANIFEST_INVALID([`optional positional ${param.name}`])\n  if (param.type === 'enum' && (!param.values || param.values.length === 0))\n    throw new E_SKILL_MANIFEST_INVALID([`enum ${param.name}`])\n}\n\n/** Validate a declaration, including the provider-safe generated tool name. */\nexport const validateSkillScript = (skillId: string, spec: SkillScriptSpec): string => {\n  const name = `run_${skillId}_${spec.name}`\n  if (!generatedName.test(name)) throw new E_SKILL_MANIFEST_INVALID([`${skillId}/${spec.name}`])\n  for (const param of spec.params ?? []) validateParam(param)\n  return name\n}\n\nconst schemaFor = (spec: SkillScriptSpec, config: SkillScriptConfig) => {\n  const shape: Record<string, unknown> = {}\n  for (const param of spec.params ?? []) {\n    let schema =\n      param.type === 'number'\n        ? validator.number()\n        : param.type === 'boolean'\n          ? validator.boolean()\n          : validator.string()\n    if (param.type === 'enum') schema = schema.valid(...(param.values ?? []))\n    shape[param.name] = (param.required ? schema.required() : schema.optional()).description(\n      param.description\n    )\n  }\n  shape.timeout_seconds = validator\n    .number()\n    .min(1)\n    .max(config.maxTimeoutSeconds)\n    .default(config.defaultTimeoutSeconds)\n  return validator.object(shape as Record<string, ReturnType<typeof validator.string>>)\n}\n\nconst gateScript = async (\n  gate: ToolGateFn,\n  ctx: DispatchContext,\n  name: string,\n  args: unknown\n): Promise<void> => {\n  try {\n    await runToolGate(gate, ctx, name, args)\n  } catch (error) {\n    if (isInstanceOf(error, 'E_TURN_GATE_ABORTED', E_TURN_GATE_ABORTED)) {\n      if (ctx.abortSignal.aborted) throw error\n      throw new E_SKILL_SCRIPT_GATE_UNAVAILABLE([name])\n    }\n    const outcome =\n      isError(error) || typeof error === 'object'\n        ? (error as { outcome?: { kind?: string }; kind?: string })\n        : {}\n    if (outcome.outcome?.kind === 'gate-declined' || outcome.kind === 'gate-declined')\n      throw new E_SKILL_SCRIPT_DENIED([name])\n    throw new E_SKILL_SCRIPT_GATE_UNAVAILABLE([name])\n  }\n}\n\nconst argvFor = (\n  spec: SkillScriptSpec,\n  raw: Record<string, unknown>,\n  interpreter: readonly string[]\n): string[] => {\n  const argv = [...interpreter]\n  argv.push(spec.path)\n  for (const param of spec.params ?? []) {\n    const value = raw[param.name]\n    if (value === undefined) continue\n    const flag = param.flag && assertArgvValue(param.flag, `${param.name}.flag`)\n    if (param.type === 'boolean' && flag) {\n      if (value) argv.push(flag)\n      continue\n    }\n    if (flag) argv.push(flag)\n    argv.push(assertArgvValue(value, param.name))\n  }\n  return argv\n}\n\nconst drain = async (\n  stream: ReadableStream<Uint8Array>,\n  state: { bytes: number; chunks: Uint8Array[]; truncated: boolean },\n  cap: number\n): Promise<void> => {\n  const reader = stream.getReader()\n  try {\n    for (;;) {\n      const item = await reader.read()\n      if (item.done) return\n      if (state.bytes < cap) {\n        const take = item.value.slice(0, Math.max(0, cap - state.bytes))\n        if (take.length) state.chunks.push(take)\n        state.bytes += take.length\n        if (take.length < item.value.length) state.truncated = true\n      } else state.truncated = true\n    }\n  } finally {\n    reader.releaseLock()\n  }\n}\n\n/** Forge one fixed-schema script tool. The record liveness check is synchronous and precedes all awaits. */\nexport const forgeSkillScriptTool = (o: {\n  skill: {\n    readonly id: string\n    readonly version: string\n    readonly trustTier?: 'first-party' | 'third-party-public' | 'third-party-private'\n  }\n  record: SkillRecord\n  spec: SkillScriptSpec\n  config: SkillScriptConfig\n  sessionPolicy: SandboxPolicy\n  gate?: ToolGateFn\n  materializedRoot: string\n}): Tool => {\n  const name = validateSkillScript(o.skill.id, o.spec)\n  const policyFor = (): SandboxPolicy => ({\n    filesystem: {\n      denyRead: ['/'],\n      allowRead: [o.materializedRoot, ...o.config.interpreterReadPaths],\n      allowWrite: [`${o.materializedRoot}/tmp`],\n    },\n    network: {},\n  })\n  const outputTier =\n    o.skill.trustTier === 'first-party'\n      ? 'third-party-private'\n      : (o.skill.trustTier ?? 'third-party-public')\n  return new Tool({\n    name,\n    description: o.spec.description,\n    inputSchema: schemaFor(o.spec, o.config),\n    trusted: false,\n    meta: { skill: o.skill.id, skillVersion: o.skill.version },\n    handler: async (raw, ctx) => {\n      if (!o.record.tryEnter()) throw new E_SKILL_NOT_LOADED([o.skill.id])\n      let timer: ReturnType<typeof setTimeout> | undefined\n      try {\n        const args = raw as Record<string, unknown>\n        if (o.gate) await gateScript(o.gate, ctx, name, args)\n        const policy = policyFor()\n        assertPolicySubset(policy, o.sessionPolicy)\n        const guard = createExistingSymlinkGuard(o.materializedRoot, o.config.workspace.fileSystem)\n        const relative = validateSkillSourcePath(o.spec.path)\n        await guard(relative)\n        const controller = new AbortController()\n        const requested = Number(args.timeout_seconds)\n        const timeout = Math.min(requested, o.config.maxTimeoutSeconds)\n        timer = setTimeout(() => controller.abort(), timeout * 1000)\n        // The child must die on EITHER our timeout OR the enclosing turn/dispatch\n        // aborting. Passing controller.signal alone left an aborted turn's script\n        // running until its own timeout. AbortSignal.any forwards both.\n        const runSignal = AbortSignal.any([controller.signal, ctx.abortSignal])\n        const correlationId = uuidv6()\n        const execution = await o.config.handle.run({\n          argv: argvFor(\n            { ...o.spec, path: relative },\n            args,\n            o.config.interpreters[o.spec.interpreter] ?? []\n          ),\n          policy,\n          correlationId,\n          cwd: o.materializedRoot,\n          env: {},\n          signal: runSignal,\n        })\n        const state = { bytes: 0, chunks: [] as Uint8Array[], truncated: false }\n        let completed: { exitCode: number; failed: boolean }\n        try {\n          await Promise.all([\n            drain(execution.stdout, state, o.config.maxOutputBytes),\n            drain(execution.stderr, state, o.config.maxOutputBytes),\n          ])\n          completed = await execution.completed\n        } finally {\n          clearTimeout(timer)\n          timer = undefined\n        }\n        if (controller.signal.aborted && !ctx.abortSignal.aborted)\n          throw new E_SKILL_SCRIPT_TIMEOUT([name])\n        const bytes = state.chunks.slice()\n        if (state.truncated) bytes.push(encoder.encode(truncation))\n        const body = bytes.reduce((all, value) => {\n          const next = new Uint8Array(all.length + value.length)\n          next.set(all)\n          next.set(value, all.length)\n          return next\n        }, new Uint8Array())\n        const id = uuidv6()\n        const reader = await ctx.storeRetrievableBytes(\n          id,\n          new ReadableStream({\n            start(c) {\n              c.enqueue(body)\n              c.close()\n            },\n          })\n        )\n        ctx.turnRetrievables.add(\n          new Retrievable({\n            id,\n            content: new SpooledArtifact(reader),\n            trustTier: outputTier,\n            source: `${o.skill.id}:${o.spec.name}`,\n            kind: 'skill-script',\n            createdAt: new Date(),\n            updatedAt: new Date(),\n          })\n        )\n        // Default (failOnNonzeroExit !== false): a nonzero exit is a host-detectable failure, so\n        // a broken or rejected script is not presented to the model as a successful run. Output is\n        // already spooled; the error carries the retrievable id so it stays inspectable. Set\n        // failOnNonzeroExit: false to receive the acknowledgement string for any completed run.\n        const acknowledgement = `Script ${name} exited ${completed.exitCode}; captured ${state.bytes} bytes; truncated=${state.truncated}; retrievable=${id}`\n        if (o.config.failOnNonzeroExit !== false && (completed.failed || completed.exitCode !== 0))\n          throw new E_SKILL_SCRIPT_FAILED([name, acknowledgement])\n        return acknowledgement\n      } catch (error) {\n        if (isInstanceOf(error, 'E_SKILL_SCRIPT_TIMEOUT', E_SKILL_SCRIPT_TIMEOUT)) throw error\n        // An enclosing turn/dispatch abort reaches here as the run/completed promise's rejection,\n        // whose name is not E_SKILL_*. Propagate it as the abort it is rather than mislabelling\n        // cancellation as a workspace failure (matches gateScript's own abort handling above).\n        if (\n          isInstanceOf(error, 'E_TURN_GATE_ABORTED', E_TURN_GATE_ABORTED) ||\n          ctx.abortSignal.aborted\n        )\n          throw error\n        if (isError(error) && error.name.startsWith('E_SKILL_')) throw error\n        throw new E_SKILL_WORKSPACE_FAILED([isError(error) ? error.message : String(error)])\n      } finally {\n        if (timer) clearTimeout(timer)\n        o.record.exit()\n      }\n    },\n  })\n}\n\n/** Materialise a source file list after validating every source-owned path. */\nexport const validateMaterializedPaths = (paths: readonly string[]): readonly string[] =>\n  paths.map(validateSkillSourcePath)\n\n/** Keep the workspace type visible to consumers implementing the materialisation seam. */\nexport type { SkillWorkspace }\n","import { DateTime } from 'luxon'\nimport { isObject } from '@nhtio/adk/guards'\nimport { createSkillMiddlewareSet } from './middleware'\nimport { createSkillArtifactRegistry } from './artifacts'\nimport { rewrapSkillTool, assertSkillToolNames } from './import'\nimport { resolveSkillChannel, spoolSkillBody } from './channels'\nimport { forgeIsolatedTools, validateIsolationConfig } from './isolated'\nimport { Retrievable, Tool, SpooledMarkdownArtifact } from '@nhtio/adk/common'\nimport { forgeSkillScriptTool, validateSkillScript, validateSkillSourcePath } from './scripts'\nimport {\n  E_INVALID_SKILLS_CONFIG,\n  E_SKILL_MANIFEST_INVALID,\n  E_SKILL_NOT_FOUND,\n  E_SKILL_ALREADY_LOADED,\n  E_SKILL_NOT_LOADED,\n} from './exceptions'\nimport type { SkillRef, SkillSource } from './contracts'\nimport type { DispatchContext, TurnContext } from '@nhtio/adk/types'\nimport type {\n  SkillDescriptor,\n  SkillManager,\n  SkillManagerConfig,\n  SkillSourceResolver,\n  LoadResult,\n  RefreshResult,\n  ProjectedSkill,\n  SkillWorkspace,\n} from './types'\n\n/**\n * The live ownership record captured by every skill-owned tool wrapper. `tryEnter()` performs\n * the retired check and active-call increment in one synchronous operation; `exit()` decrements\n * it and releases a retired workspace when the last call finishes. Retirement is synchronous and\n * is performed only while the manager mutex is held. Every skill-owned tool wrapper — module\n * tools, isolated JS tools and scripts alike — must close over this exact record rather than\n * consulting a registry, because hydrated wrappers can outlive the context they were registered\n * in: unregistering reaches only the context that requested the unload, so the record is the\n * authority on liveness and the registry is not.\n */\nexport interface SkillRecord {\n  readonly id: string\n  readonly version: string\n  readonly retired: boolean\n  tryEnter(): boolean\n  exit(): void\n}\n\ntype LiveRecord = SkillRecord & {\n  ref: SkillRef\n  descriptor: SkillDescriptor\n  tools: Tool[]\n  retrievable?: Retrievable\n  /** Tool-call timestamp after which body-reader calls belong to this loaded record. */\n  loadedAt: DateTime\n  root?: string\n  workspace?: SkillWorkspace\n  waitForDisposal(): Promise<void>\n  retire(): void\n  activeCalls(): number\n  forceDispose(): void\n}\n\ntype Candidate = { ref: SkillRef; shadowedBy?: SkillRef }\n\nconst asSource = async (resolver: SkillSourceResolver): Promise<SkillSource> => {\n  const value = typeof resolver === 'function' ? await resolver() : resolver\n  const source =\n    isObject(value) && 'default' in value ? (value as { default: SkillSource }).default : value\n  if (!source || typeof source.id !== 'string' || typeof source.discover !== 'function') {\n    throw new Error('does not implement the SkillSource contract')\n  }\n  return source\n}\n\nconst bodyText = async (stream: ReadableStream<Uint8Array>): Promise<string> => {\n  const response = new Response(stream)\n  return response.text()\n}\n\n/**\n * Create a skills manager. Construct one manager per conversation/session, alongside its runner;\n * share source objects when discovery caching is desired, but never share loaded manager state.\n */\nexport const createSkillManager = async (config: SkillManagerConfig): Promise<SkillManager> => {\n  if (!config || !Array.isArray(config.sources) || typeof config.gate !== 'function') {\n    throw new E_INVALID_SKILLS_CONFIG(['sources and gate are required'])\n  }\n  validateIsolationConfig(config)\n  if (\n    config.scripts &&\n    !config.scripts.hostEnvIsolated &&\n    !config.unsafe?.scriptsPermissivePolicy\n  ) {\n    throw new E_INVALID_SKILLS_CONFIG([\n      'scripts.hostEnvIsolated is required unless unsafe.scriptsPermissivePolicy is enabled',\n    ])\n  }\n  const unsafe = [\n    config.isolation && !config.isolation.resolveGuest && config.unsafe?.isolatedToolsInProcess\n      ? 'isolatedToolsInProcess'\n      : undefined,\n    config.unsafe?.scriptsPermissivePolicy ? 'scriptsPermissivePolicy' : undefined,\n    config.unsafe?.ungatedSkillTools ? 'ungatedSkillTools' : undefined,\n  ].filter((value): value is string => value !== undefined)\n  for (const control of unsafe) console.warn(`Skill unsafe control enabled: ${control}`)\n  const sources: SkillSource[] = []\n  try {\n    for (const resolver of config.sources) sources.push(await asSource(resolver))\n  } catch (error) {\n    throw new E_INVALID_SKILLS_CONFIG([`sources resolver failed: ${String(error)}`])\n  }\n  const sourceIds = new Set<string>()\n  for (const source of sources) {\n    if (sourceIds.has(source.id))\n      throw new E_INVALID_SKILLS_CONFIG([`duplicate source id: ${source.id}`])\n    sourceIds.add(source.id)\n  }\n\n  const artifactRegistry = await createSkillArtifactRegistry(config)\n  const withLock = (() => {\n    let tail = Promise.resolve()\n    return async <T>(fn: () => Promise<T>): Promise<T> => {\n      const previous = tail\n      let release!: () => void\n      tail = new Promise<void>((resolve) => {\n        release = resolve\n      })\n      await previous\n      try {\n        return await fn()\n      } finally {\n        release()\n      }\n    }\n  })()\n\n  let candidates: Candidate[] = []\n  const updateAvailable = new Set<string>()\n  const records = new Map<string, LiveRecord>()\n  const reservations = new Map<string, string>()\n  let disposed = false\n\n  const discover = async (onlyId?: string): Promise<RefreshResult> => {\n    const next: Candidate[] = []\n    const seen = new Map<string, SkillRef>()\n    for (const source of sources) {\n      try {\n        for await (const discovered of source.discover()) {\n          if (onlyId !== undefined && discovered.id !== onlyId) continue\n          const ref = { ...discovered, sourceId: source.id } as SkillRef\n          const prior = seen.get(ref.id)\n          if (!prior) {\n            seen.set(ref.id, ref)\n            next.push({ ref })\n          } else next.push({ ref, shadowedBy: prior })\n        }\n      } catch (error) {\n        throw new E_INVALID_SKILLS_CONFIG([\n          `source discovery failed: ${source.id}: ${String(error)}`,\n        ])\n      }\n    }\n    if (onlyId === undefined) candidates = next\n    else candidates = [...candidates.filter((c) => c.ref.id !== onlyId), ...next]\n    const updates = [...records]\n      .filter(\n        ([id]) => candidates.find((c) => c.ref.id === id)?.ref.version !== records.get(id)?.version\n      )\n      .map(([id]) => id)\n    for (const id of updates) updateAvailable.add(id)\n    return {\n      ids: [...new Set(next.map((c) => c.ref.id))],\n      updateAvailable: updates,\n    }\n  }\n  await discover()\n\n  const winner = (id: string): Candidate | undefined =>\n    candidates.find((c) => c.ref.id === id && !c.shadowedBy)\n  const sourceFor = (ref: SkillRef): SkillSource =>\n    sources.find((source) => source.id === ref.sourceId) as SkillSource\n  const descriptorFor = async (ref: SkillRef): Promise<SkillDescriptor> => {\n    const descriptor = await sourceFor(ref).descriptor(ref)\n    if (!descriptor || typeof descriptor !== 'object') throw new E_SKILL_MANIFEST_INVALID([ref.id])\n    const value = descriptor as SkillDescriptor\n    if (value.id !== ref.id || value.version !== ref.version)\n      throw new E_SKILL_MANIFEST_INVALID([`${ref.id}: id/version mismatch`])\n    if (typeof value.name !== 'string' || typeof value.description !== 'string')\n      throw new E_SKILL_MANIFEST_INVALID([ref.id])\n    return value\n  }\n\n  const makeRecord = (\n    ref: SkillRef,\n    descriptor: SkillDescriptor,\n    tools: readonly Tool[],\n    retrievable: Retrievable | undefined,\n    root: string | undefined,\n    workspace: SkillWorkspace | undefined\n  ): LiveRecord => {\n    let retired = false\n    let active = 0\n    // Workspace disposal is refcount-gated, not racy. `disposeRoot` is only ever called when\n    // `active === 0` (from `exit()` as the last call settles, or from `retire()`/`forceDispose()`\n    // when none is in flight), so no live call can be mid-`handle.run` against a directory being\n    // disposed — `tryEnter()` returns false the instant `retired` is set, so a new call cannot\n    // start either. The dispose promise is captured (not fired-and-forgotten) so `dispose()` can\n    // await every record's `waitForDisposal()` before returning, and `disposeRoot` is idempotent:\n    // the `!disposal` guard means a second trigger (e.g. retire after exit) never starts a second\n    // teardown. That is why disposal is not awaited inline at each call site — awaiting it there\n    // would serialise unrelated unloads for no benefit, since the guarantee is structural.\n    let disposal: Promise<void> | undefined\n    const disposeRoot = (): void => {\n      if (!disposal && root && workspace) disposal = workspace.dispose(root)\n    }\n    const record: LiveRecord = {\n      id: ref.id,\n      version: ref.version,\n      ref,\n      descriptor,\n      tools: [...tools],\n      retrievable,\n      loadedAt: DateTime.now(),\n      root,\n      workspace,\n      get retired() {\n        return retired\n      },\n      tryEnter() {\n        if (retired) return false\n        active++\n        return true\n      },\n      exit() {\n        active--\n        if (active === 0 && retired) disposeRoot()\n      },\n      retire() {\n        retired = true\n        if (active === 0) disposeRoot()\n      },\n      activeCalls() {\n        return active\n      },\n      forceDispose() {\n        disposeRoot()\n      },\n      waitForDisposal() {\n        return disposal ?? Promise.resolve()\n      },\n    }\n    return record\n  }\n\n  const project = (ctx: DispatchContext | TurnContext, record: LiveRecord): void => {\n    for (const tool of record.tools) ctx.tools.register(tool, true)\n    if (record.retrievable) ctx.turnRetrievables.add(record.retrievable)\n  }\n  const registryNames = (ctx: DispatchContext): readonly string[] =>\n    ctx.tools.all().map((tool) => tool.name)\n  const registryOwners = (ctx: DispatchContext): ReadonlyMap<string, string | undefined> =>\n    new Map(\n      ctx.tools.all().map((tool) => [tool.name, tool.meta.get('skill') as string | undefined])\n    )\n\n  /**\n   * The PREPARE half of prepare-then-swap. It resolves the descriptor, validates and reserves\n   * names, materialises the workspace, spools the body and rewraps tools — everything that can\n   * fail or await — and returns a ready-to-install {@link LiveRecord} WITHOUT touching the live\n   * `records` map or the context registry. Its only externally visible mutation is the name\n   * reservation, which it rolls back itself on any failure (restoring `priorReservations`) before\n   * rethrowing.\n   *\n   * This purity is the failure-safety contract for both {@link load} and refresh: because nothing\n   * live is swapped until `prepareLocked` has already succeeded, a throw here leaves the previously\n   * loaded version — its record, its registered tools, its projected body — entirely intact. The\n   * caller performs the swap synchronously (no awaits between prepare succeeding and the records/\n   * registry/reservations exchange), so there is no window in which a half-prepared skill is\n   * observable. Do NOT move any live mutation into this function, and do NOT add an `await` into\n   * the caller's swap block — either change would reintroduce the incoherent-on-failure state this\n   * design exists to prevent. Covered by the \"preserves old state on failure\" case in\n   * `tests/unit/batteries/skills/concurrency.cross.spec.ts`.\n   */\n  const prepareLocked = async (\n    id: string,\n    ctx: DispatchContext,\n    replacing?: LiveRecord\n  ): Promise<{ record: LiveRecord; result: LoadResult }> => {\n    if (disposed) throw new E_SKILL_NOT_LOADED([id])\n    const entry = winner(id)\n    if (!entry) throw new E_SKILL_NOT_FOUND([id])\n    if (records.has(id) && !replacing) throw new E_SKILL_ALREADY_LOADED([id])\n    const descriptor = await descriptorFor(entry.ref)\n    const originals = descriptor.tools ?? []\n    const isolatedDeclarations =\n      config.isolation && descriptor.isolatedTools ? descriptor.isolatedTools : []\n    const scriptDeclarations = config.scripts && descriptor.scripts ? descriptor.scripts : []\n    const scriptNames = scriptDeclarations.map((script) => validateSkillScript(id, script))\n    const names = [\n      ...originals.map((tool) => tool.name),\n      ...isolatedDeclarations.map((tool) => tool.name),\n      ...scriptNames,\n    ]\n    assertSkillToolNames({\n      candidates: names,\n      reserved: new Set(\n        [...reservations].filter(([, owner]) => owner !== id).map(([name]) => name)\n      ),\n      registryNames: registryNames(ctx),\n      registryOwners: registryOwners(ctx),\n      skillId: id,\n      artifactKinds: [SpooledMarkdownArtifact, ...artifactRegistry.kinds.values()],\n    })\n    const priorReservations = new Map([...reservations].filter(([, owner]) => owner === id))\n    for (const name of names) reservations.set(name, id)\n    let workspace: SkillWorkspace | undefined\n    let root: string | undefined\n    try {\n      const source = sourceFor(entry.ref)\n      const body = await bodyText(await source.read(entry.ref))\n      if (scriptDeclarations.length) {\n        const scriptPaths = scriptDeclarations.map((script) => validateSkillSourcePath(script.path))\n        if (!source.list)\n          throw new E_SKILL_MANIFEST_INVALID([`${id}: source does not list script files`])\n        const listed = await source.list(entry.ref)\n        for (const path of scriptPaths) {\n          if (!listed.map(validateSkillSourcePath).includes(path))\n            throw new E_SKILL_MANIFEST_INVALID([`${id}: script file is not listed: ${path}`])\n        }\n        workspace = config.scripts!.workspace\n        root = await workspace.materialize(\n          entry.ref,\n          (async function* () {\n            for (const path of listed) {\n              const normalized = validateSkillSourcePath(path)\n              yield {\n                path: normalized,\n                bytes: await source.read(entry.ref, normalized),\n              }\n            }\n          })()\n        )\n      }\n      const channel = resolveSkillChannel(descriptor, config.defaultChannel)\n      const retrievable = await spoolSkillBody(ctx, entry.ref, descriptor, body, channel)\n      const recordPlaceholder = makeRecord(entry.ref, descriptor, [], retrievable, root, workspace)\n      const tools = [\n        ...originals.map((original) =>\n          rewrapSkillTool({\n            original,\n            skill: { id, version: entry.ref.version, trustTier: descriptor.trustTier },\n            record: recordPlaceholder,\n            gate: config.unsafe?.ungatedSkillTools ? undefined : config.gate,\n            resolveArtifact: () => artifactRegistry.resolve(id, original.name, descriptor),\n            // Own-property only: bracket access would walk the prototype chain, so a tool named\n            // after an inherited Object key ('toString', 'constructor', …) would pick up a\n            // function as its \"declared\" output kind and reject every valid return as a mismatch.\n            declaredOutput:\n              descriptor.toolOutputs && Object.hasOwn(descriptor.toolOutputs, original.name)\n                ? descriptor.toolOutputs[original.name]\n                : undefined,\n          })\n        ),\n        ...(scriptDeclarations.length\n          ? scriptDeclarations.map((spec) =>\n              forgeSkillScriptTool({\n                skill: {\n                  id,\n                  version: entry.ref.version,\n                  trustTier: descriptor.trustTier,\n                },\n                record: recordPlaceholder,\n                spec,\n                config: config.scripts!,\n                sessionPolicy: config.unsafe?.scriptsPermissivePolicy ?? config.scripts!.policy,\n                gate: config.unsafe?.ungatedSkillTools ? undefined : config.gate,\n                materializedRoot: root!,\n              })\n            )\n          : []),\n        ...(config.isolation && isolatedDeclarations.length\n          ? forgeIsolatedTools({\n              declarations: isolatedDeclarations,\n              isolation: config.isolation,\n              gate: config.unsafe?.ungatedSkillTools ? undefined : config.gate,\n              record: recordPlaceholder,\n              skill: { id, version: entry.ref.version },\n            })\n          : []),\n      ]\n      recordPlaceholder.workspace = workspace\n      recordPlaceholder.root = root\n      recordPlaceholder.tools = tools\n      return {\n        record: recordPlaceholder,\n        result: {\n          id,\n          channel,\n          tools,\n          retrievable,\n        },\n      }\n    } catch (error) {\n      for (const name of names) if (reservations.get(name) === id) reservations.delete(name)\n      for (const [name, owner] of priorReservations) reservations.set(name, owner)\n      if (root && workspace) await workspace.dispose(root)\n      throw error\n    }\n  }\n\n  const loadLocked = async (id: string, ctx: DispatchContext): Promise<LoadResult> => {\n    const prepared = await prepareLocked(id, ctx)\n    records.set(id, prepared.record)\n    project(ctx, prepared.record)\n    return prepared.result\n  }\n\n  const refresh = async (id?: string): Promise<RefreshResult> => withLock(async () => discover(id))\n  const load = async (id: string, ctx: DispatchContext): Promise<LoadResult> =>\n    withLock(() => loadLocked(id, ctx))\n  const unload = async (id: string, ctx: DispatchContext): Promise<void> =>\n    withLock(async () => {\n      const record = records.get(id)\n      if (!record) throw new E_SKILL_NOT_LOADED([id])\n      record.retire()\n      // Only unregister the entry if it is still OUR tool object; a later projection may have\n      // replaced the name with a different owner's tool, which we must not clobber.\n      for (const tool of record.tools)\n        if (ctx.tools.get(tool.name) === tool) ctx.tools.unregister(tool.name)\n      if (record.retrievable) {\n        ctx.turnRetrievables.delete(record.retrievable)\n        // ArtifactTool calls carry the selected artifact id in args.callId and are marked\n        // fromArtifactTool. Requiring both fields avoids deleting ordinary tool results and\n        // reads of a script's separately-spooled output artifact.\n        for (const call of ctx.turnToolCalls) {\n          if (\n            call.fromArtifactTool &&\n            call.createdAt.toMillis() >= record.loadedAt.toMillis() &&\n            call.args.callId === record.retrievable.id\n          ) {\n            await ctx.deleteToolCall(call.id)\n          }\n        }\n      }\n      records.delete(id)\n      for (const [name, owner] of reservations) if (owner === id) reservations.delete(name)\n    })\n  const projected = (_ctx: DispatchContext | TurnContext): readonly ProjectedSkill[] =>\n    [...records.values()].map((record) => ({\n      id: record.id,\n      retrievable: record.retrievable,\n      tools: record.tools,\n    }))\n  const managerCore: Omit<SkillManager, 'middleware'> = {\n    unsafe,\n    catalog: () =>\n      candidates.map((c) => ({\n        ref: c.ref,\n        loaded: records.has(c.ref.id),\n        ...(updateAvailable.has(c.ref.id) ? { updateAvailable: true } : {}),\n        ...(c.shadowedBy ? { shadowedBy: c.shadowedBy } : {}),\n      })),\n    loaded: () => [...records.keys()],\n    projected,\n    refresh,\n    refreshAndProject: async (ctx, id) =>\n      withLock(async () => {\n        const result = await discover(id)\n        // An omitted `id` refreshes EVERY loaded skill — the tool contract for a bare\n        // `refresh_skills` is \"re-read and swap the loaded version\", so guarding the swap behind\n        // `if (id)` would re-discover the catalog yet leave every loaded body and tool stale while\n        // still reporting a refresh. Snapshot the target ids before the loop so a swap that\n        // re-keys `records` cannot perturb the iteration.\n        const targetIds = id ? [id] : [...records.keys()]\n        for (const targetId of targetIds) {\n          const old = records.get(targetId)\n          if (!old) continue\n          // Prepare-then-swap, PER SKILL. `prepareLocked` does all the fallible/awaiting work and\n          // mutates no live state; if it throws, `old` stays loaded, projected and reserved, and\n          // the swap below never runs for it — a failed refresh of one skill is a no-op for that\n          // skill, not a torn state. Everything below is the swap: synchronous, no awaits, so no\n          // half-swapped skill is ever observable. Order matters — unregister the outgoing tools\n          // by identity (guarding against a tool another owner replaced ours with), drop the old\n          // retrievable and reservations, then install the prepared record — and `old.retire()`\n          // runs LAST so its deferred workspace disposal targets the now-replaced materialisation.\n          const prepared = await prepareLocked(targetId, ctx as DispatchContext, old)\n          for (const tool of old.tools)\n            if (ctx.tools.get(tool.name) === tool) ctx.tools.unregister(tool.name)\n          if (old.retrievable) ctx.turnRetrievables.delete(old.retrievable)\n          for (const [name, owner] of reservations)\n            if (owner === targetId) reservations.delete(name)\n          for (const tool of prepared.record.tools) reservations.set(tool.name, targetId)\n          records.set(targetId, prepared.record)\n          updateAvailable.delete(targetId)\n          project(ctx, prepared.record)\n          old.retire()\n        }\n        return result\n      }),\n    load,\n    unload,\n    dispose: async () =>\n      withLock(async () => {\n        disposed = true\n        const current = [...records.values()]\n        for (const record of current) record.retire()\n        const ceilings = [\n          config.scripts?.maxTimeoutSeconds,\n          config.isolation?.maxTimeoutSeconds,\n        ].filter((value): value is number => value !== undefined)\n        const timeout = Math.max(0, ...(ceilings.length ? ceilings : [0])) * 1000\n        const deadline = Date.now() + timeout\n        while (current.some((record) => record.activeCalls() > 0) && Date.now() < deadline) {\n          await new Promise<void>((resolve) => setTimeout(resolve, 10))\n        }\n        for (const record of current) record.forceDispose()\n        await Promise.all(current.map((record) => record.waitForDisposal()))\n        records.clear()\n        reservations.clear()\n      }),\n  }\n  const manager = managerCore as SkillManager\n  Object.defineProperties(manager, {\n    middleware: {\n      value: createSkillMiddlewareSet(manager, {\n        autoRefresh: config.autoRefresh,\n      }),\n      enumerable: true,\n      writable: false,\n      configurable: false,\n    },\n  })\n  return manager\n}\n","import { validator } from '@nhtio/validation'\nimport { Tool, SpooledJsonArtifact } from '@nhtio/adk/common'\nimport { runToolGate } from '@nhtio/adk/batteries/tools/_shared'\nimport type { SkillManager } from './types'\nimport type { DispatchContext } from '@nhtio/adk/types'\nimport type { ToolGateFn } from '@nhtio/adk/batteries/tools/_shared'\n\n/** Deployment-time controls for the lifecycle tools forged by {@link forgeSkillTools}. */\nexport interface ForgeSkillToolsOptions {\n  /** The gate used for lifecycle mutations. */\n  readonly gate?: ToolGateFn\n}\n\nconst context = (value: unknown): DispatchContext => value as DispatchContext\n\n/** Forge the five stateful lifecycle tools for one skill manager. */\nexport const forgeSkillTools = (\n  manager: SkillManager,\n  options: ForgeSkillToolsOptions = {}\n): Record<string, Tool> => {\n  const tools: Record<string, Tool> = {}\n  const make = (\n    name: string,\n    description: string,\n    inputSchema: ReturnType<typeof validator.object>,\n    handler: (args: Record<string, unknown>, ctx: DispatchContext) => Promise<unknown>\n  ): void => {\n    const tool = new Tool({\n      name,\n      description,\n      inputSchema,\n      artifactConstructor: () => SpooledJsonArtifact,\n      handler: async (args, ctx) =>\n        JSON.stringify(await handler(args as Record<string, unknown>, context(ctx))),\n    })\n    tools[name] = tool\n  }\n\n  make(\n    'list_skills',\n    'List discoverable skills and their routing metadata. Use query to filter by id, name, or description.',\n    validator\n      .object({\n        refresh: validator.boolean(),\n        query: validator.string(),\n      })\n      .unknown(false),\n    async (args) => {\n      if (args.refresh === true) await manager.refresh()\n      const query = typeof args.query === 'string' ? args.query.toLocaleLowerCase() : undefined\n      const entries = manager\n        .catalog()\n        .filter((entry) => {\n          if (!query) return true\n          return [entry.ref.id, entry.ref.name, entry.ref.description].some((value) =>\n            value.toLocaleLowerCase().includes(query)\n          )\n        })\n        .map((entry) => ({\n          id: entry.ref.id,\n          name: entry.ref.name,\n          description: entry.ref.description,\n          version: entry.ref.version,\n          sourceId: entry.ref.sourceId,\n          loaded: entry.loaded,\n          ...(entry.updateAvailable === undefined\n            ? {}\n            : { updateAvailable: entry.updateAvailable }),\n          ...(entry.shadowedBy ? { shadowedBy: entry.shadowedBy.sourceId } : {}),\n          ...(entry.ref.license === undefined ? {} : { license: entry.ref.license }),\n          ...(entry.ref.metadata === undefined ? {} : { metadata: entry.ref.metadata }),\n          ...(entry.ref.compatibility === undefined\n            ? {}\n            : { compatibility: entry.ref.compatibility }),\n        }))\n      return { skills: entries, unsafe: manager.unsafe }\n    }\n  )\n  make(\n    'list_loaded_skills',\n    'List skills projected into this dispatch and therefore callable right now.',\n    validator.object({}).unknown(false),\n    async (_args, ctx) => ({\n      skills: manager.projected(ctx).map((skill) => skill.id),\n      initialized: manager.loaded(),\n    })\n  )\n  make(\n    'refresh_skills',\n    'Refresh one named skill and replace its loaded version in this dispatch, or omit skill to refresh all skills.',\n    validator.object({ skill: validator.string() }).unknown(false),\n    async (args, ctx) => {\n      await runToolGate(options.gate, ctx, 'refresh_skills', {\n        ...(typeof args.skill === 'string' ? { skill: args.skill } : {}),\n      })\n      const result = await manager.refreshAndProject(\n        ctx,\n        typeof args.skill === 'string' ? args.skill : undefined\n      )\n      return result\n    }\n  )\n  make(\n    'load_skill',\n    'Load a skill body and register its tools for this dispatch.',\n    validator.object({ skill: validator.string().required() }).unknown(false),\n    async (args, ctx) => {\n      const skill = args.skill as string\n      await runToolGate(options.gate, ctx, 'load_skill', { skill })\n      return manager.load(skill, ctx)\n    }\n  )\n  make(\n    'unload_skill',\n    'Deactivate a loaded skill and unregister its tools.',\n    validator.object({ skill: validator.string().required() }).unknown(false),\n    async (args, ctx) => {\n      const skill = args.skill as string\n      await runToolGate(options.gate, ctx, 'unload_skill', { skill })\n      await manager.unload(skill, ctx)\n      return { id: skill, unloaded: true }\n    }\n  )\n  return tools\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AA4FA,IAAa,yBAAyB,UAAyC;CAC7E,IAAI,UAAU,QAAQ,OAAO,UAAU,UAAU,OAAO;CACxD,MAAM,YAAY;CAClB,OACE,OAAO,UAAU,OAAO,YACxB,OAAO,UAAU,aAAa,cAC9B,OAAO,UAAU,eAAe,cAChC,OAAO,UAAU,SAAS,cAC1B,OAAO,UAAU,SAAS;AAE9B;;;;;;;;;AC9DA,IAAM,yCAAyB,IAAI,QAAwC;AAC3E,IAAM,uBAAuB,YAA4C;CACvE,IAAI,SAAS,uBAAuB,IAAI,OAAO;CAC/C,IAAI,CAAC,QAAQ;EACX,yBAAS,IAAI,QAAiC;EAC9C,uBAAuB,IAAI,SAAS,MAAM;CAC5C;CACA,OAAO;AACT;AAEA,IAAM,YAAY,KAAmB,qBAAwD;C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