@ai-agent-forge/plugin-sdk 0.85.4 → 0.85.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/public-api.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"public-api.js","sourceRoot":"","sources":["../src/public-api.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Experimental, host-facing contracts for capability plugins.\n *\n * This module deliberately contains no product policy. It describes the\n * capabilities a host may expose; policy plugins decide how to compose them.\n *\n * Authority: `@agent-forge/plugin-sdk` is the single authoring source for this\n * surface (D-075 S2); the host (`@agent-forge/agent-forge`) re-exports it from\n * its historical module path so existing imports keep resolving.\n */\n\nimport type { MemoryStorageComponentsV1 } from \"./memory.ts\";\nimport type { ObservabilityHostAdapterV1, TraceSinkOptionsV1 } from \"./observability.ts\";\n\n/** @experimental Promoted out of draft only when a real consumer drives stabilization. */\nexport const EXPERIMENTAL_PUBLIC_API_VERSION = \"1-draft\" as const;\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from the host to detect support for a concrete model.\n *\n * Authority moved from `@agent-forge/agent-core` (D-075 S2); agent-core\n * re-exports it from here.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\nexport type HostMode = \"readonly\" | \"full-control\";\n\n/** Estimated context usage for the active model; the session read face (`getContextUsage`) projects it. */\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport type PluginConfigValue =\n\t| null\n\t| boolean\n\t| number\n\t| string\n\t| readonly PluginConfigValue[]\n\t| { readonly [key: string]: PluginConfigValue };\n\n/** JSON configuration declared by a plugin's own manifest. */\nexport type PluginConfig = Readonly<Record<string, PluginConfigValue>>;\n\n/** Draft plugin-provided capability contract. Version is an exact integer schema version. */\nexport interface PluginCapabilityDeclaration {\n\tid: string;\n\tversion: number;\n\tkind: \"service\" | \"contribution\" | \"transform\";\n}\n\n/** Draft plugin capability dependency. Requirements use exact version matching. */\nexport interface PluginCapabilityRequirement {\n\tid: string;\n\tversion: number;\n\toptional?: boolean;\n}\n\n/** Roles that a plugin may expose through the experimental Agent composition facade. */\nexport type PluginAgentRole = \"root-agent-controller\" | \"child-agent-controller\";\n\n/** Manifest declaration for an AgentDefinition that a plugin may register. */\nexport interface AgentDefinitionDeclaration {\n\tid: string;\n\tversion: number;\n\trole: PluginAgentRole;\n\tentry: string;\n}\n\nexport interface PluginManifest {\n\tid: string;\n\tversion: string;\n\t/**\n\t * Semver range of host (agent-forge application) versions this plugin\n\t * supports, e.g. `\">=0.84.0 <1.0.0\"`. When declared and the running host\n\t * version is outside the range, the plugin is rejected at discovery\n\t * (D-073). Paired with the plugin's own `version` (the \"two version\n\t * numbers\" contract).\n\t */\n\thostVersion?: string;\n\tapiVersion: typeof EXPERIMENTAL_PUBLIC_API_VERSION;\n\tentry: string;\n\trequiredCapabilities?: string[];\n\toptionalCapabilities?: string[];\n\t/** Plugin capabilities provided to the runtime directory. */\n\tprovides?: readonly PluginCapabilityDeclaration[];\n\t/** Plugin capabilities required from other loaded plugins. */\n\trequires?: readonly PluginCapabilityRequirement[];\n\t/** Experimental Agent controller roles exposed by this plugin. */\n\troles?: readonly PluginAgentRole[];\n\t/** Experimental Agent definitions that the plugin factory may register. */\n\tagents?: readonly AgentDefinitionDeclaration[];\n\tconfig?: PluginConfig;\n}\n\n/**\n * 子↔子/子→父的有界信箱消息(D-060 S4)。第一方信箱实现(`@agent-forge/protocol`\n * subagent mailbox)与宿主通信接线共用此形状。\n */\nexport interface SubagentInboxMessageV1 {\n\t/** 发送方子会话 id。 */\n\treadonly from: string;\n\treadonly text: string;\n}\n\n/**\n * 通信面的宿主接线(D-060 S4,与通信配置开关分离):身份绑定与血缘校验都在宿主侧,\n * capability 只暴露模型工具面。迁自宿主 `subagent-delegate.ts`(D-075 S4 第三批)。\n */\nexport interface SubagentCommunicationWiringV1 {\n\t/** 父侧:取走某子会话的 escalation 队列(有界、取后即清)。 */\n\tdrainEscalations?(sessionId: string): string[];\n\t/** 子侧:向父上抛一条有界消息(发送者身份由宿主绑定,调用方无法伪造)。 */\n\tpostEscalate?(text: string): void;\n\t/** 子侧:向同父兄弟投递一条有界消息(宿主校验双方血缘,越界同型拒绝)。 */\n\tsendSibling?(toSessionId: string, text: string): void;\n\t/** 子侧:取走自己收件箱里最早的至多 `limit` 条(取后即清)。 */\n\tdrainInbox?(limit: number): SubagentInboxMessageV1[];\n}\n\nexport interface HostCapabilities {\n\tapiVersion: typeof EXPERIMENTAL_PUBLIC_API_VERSION;\n\tmode: HostMode;\n\tfeatures: readonly string[];\n\ttransports: readonly (\"in-process\" | \"stdio\" | \"http\" | \"rpc\")[];\n\t/**\n\t * Host agent directory (D-075 S4 second batch). Present on hosts that own\n\t * an on-disk agent dir; lets plugins that keep disk state locate their\n\t * config files, e.g. `<agentDir>/capabilities/<id>.json` — the same\n\t * channel the host's embedded builtins used before the package split.\n\t * Absent on hosts without an agent dir; plugins must treat it as optional.\n\t */\n\tagentDir?: string;\n\t/**\n\t * Subagent communication wiring (D-075 S4 third batch, host service\n\t * contract). Present on hosts that assemble a subagent mailbox for the\n\t * session's delegation domain; the first-party subagent-delegate plugin\n\t * binds its escalate/sibling tool faces to these callbacks (identity\n\t * binding and lineage scoping stay host-side). Absent = communication\n\t * tools stay unregistered (D-060 S4 default-off).\n\t */\n\tcommunication?: SubagentCommunicationWiringV1;\n\t/**\n\t * Turn-scoped host context (D-075 S4 third batch, host service contract).\n\t * `backgroundDigestSink` receives one bounded JSON line per settled\n\t * background delegation (taskId/sessionId/status/reasonCode) for the host\n\t * to inject into the parent's next model turn; `getTurnCorrelationId`\n\t * returns the correlation id of the parent turn at submission time — an\n\t * absent getter or undefined return means the lineage key is not written\n\t * and behavior falls back. Absent = background tasks still run, just\n\t * without push notification or turn-lineage attribution.\n\t */\n\tturnContext?: {\n\t\tbackgroundDigestSink?: (line: string) => void;\n\t\tgetTurnCorrelationId?: () => string | undefined;\n\t};\n\t/**\n\t * Role ids associated with the active suite (D-075 S4 third batch, host\n\t * service contract). Roles are disk-only definitions\n\t * (`<agentDir>/roles/<id>.json`); only associated ids surface in the\n\t * delegation tool menu. Absent = the session exposes no roles (there is\n\t * no built-in fallback — the engine ships none).\n\t */\n\troleAssociations?: readonly string[];\n\t/**\n\t * Memory storage components (D-075 S4 fourth batch, host service\n\t * contract). Runtime services, not just types: a host that assembles the\n\t * memory capability passes the A1/A2 storage injection face here\n\t * (store/ledger factories plus optional vector components) and the\n\t * first-party memory plugin binds them in place of its built-in\n\t * defaults. Absent = the plugin runs its default local implementation\n\t * (in-memory store + JSONL ledger under `<agentDir>/memory/`); hosts\n\t * without memory support leave it undefined and the plugin registers\n\t * nothing when no agentDir is declared.\n\t */\n\tmemoryStorage?: MemoryStorageComponentsV1;\n}\n\nexport interface DisposableRegistration {\n\tid: string;\n\tkind: string;\n\tdispose(): void | Promise<void>;\n}\n\nexport type OperationStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\" | \"timed_out\";\n\nexport interface OperationHandle<TResult = unknown> {\n\tid: string;\n\tsignal: AbortSignal;\n\tstatus(): OperationStatus;\n\tresult: Promise<TResult>;\n\tcancel(reason?: string): Promise<void>;\n}\n\n/** A detached, serializable progress fact emitted by a running operation. */\nexport interface OperationProgress {\n\tmessage?: string;\n\tdata?: PluginConfigValue;\n}\n\n/** Execution controls available to a registered Capability operation. */\nexport interface OperationExecutionContext {\n\treadonly operationId: string;\n\treadonly signal: AbortSignal;\n\t/** Returns false after cancellation, terminal settlement, or owner revoke. */\n\treportProgress(progress: OperationProgress): boolean;\n}\n\nexport interface EventEnvelope<TData = unknown> {\n\tid: string;\n\ttype: string;\n\tversion: number;\n\tsource: string;\n\ttimestamp: number;\n\tcorrelationId: string;\n\tcausationId?: string;\n\tdata: TData;\n}\n\n/** @experimental Stage 1A draft data phase for a host lifecycle event. */\nexport type LifecyclePhase = \"raw\" | \"candidate\" | \"committed\";\n\n/** @experimental Stage 1A draft registration kinds for the lifecycle directory. */\nexport type LifecycleRegistrationKind = \"observe\" | \"transform\" | \"execute\" | \"after-commit\";\n\n/** Optional host-side buffering for an observation subscription. */\nexport interface LifecycleDeliveryOptions {\n\t/** Maximum in-flight plus queued events for this one subscription. */\n\tmaxPendingEvents: number;\n\t/** Optional UTF-8 serialized-event budget for this one subscription. */\n\tmaxPendingBytes?: number;\n}\n\nexport type LifecycleDeliveryMode = \"inline\" | \"bounded-queue\";\n\n/** Read-only subscription delivery state exposed by the runtime inspector. */\nexport interface LifecycleDeliverySnapshot {\n\tmode: LifecycleDeliveryMode;\n\tmaxPendingEvents?: number;\n\tmaxPendingBytes?: number;\n\tstatus?: \"active\" | \"overflowed\" | \"closed\";\n\tpendingEvents?: number;\n\tpendingBytes?: number;\n\taccepted?: number;\n\tdelivered?: number;\n\trejected?: number;\n}\n\n/** @experimental Stage 1A draft lifecycle event definition. */\nexport interface LifecycleEventDefinition<TData = unknown> {\n\tid: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\t/** Optional additional phases accepted by multi-phase events. */\n\tallowedPhases?: readonly LifecyclePhase[];\n\tschema: string;\n\t/**\n\t * Registration kinds permitted by this event contract. Omitted keeps the\n\t * phase-compatible default for custom draft events; standard events should\n\t * declare the narrowest set they support.\n\t */\n\tallowedRegistrationKinds?: readonly LifecycleRegistrationKind[];\n\tvalidate(value: unknown): TData;\n}\n\n/** A reference accepted by lifecycle registration methods. */\nexport interface LifecycleEventReference {\n\tid: string;\n\tversion: number;\n}\n\n/** An immutable event delivered to a lifecycle handler. */\nexport interface LifecycleEvent<TData = unknown> {\n\tid: string;\n\tdeliveryId: string;\n\ttype: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\tsource: string;\n\ttimestamp: number;\n\toperationId?: string;\n\tcorrelationId?: string;\n\tcausationId?: string;\n\tdata: TData;\n}\n\n/** Input accepted by the host lifecycle dispatcher. */\nexport interface LifecycleDispatchRequest<TData = unknown> {\n\ttype: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\tdata: TData;\n\t/** Optional host cancellation fence for an in-flight lifecycle delivery. */\n\tsignal?: AbortSignal;\n\toperationId?: string;\n\tcorrelationId?: string;\n\tcausationId?: string;\n\tsource?: string;\n}\n\nexport type LifecycleObserveHandler<TData = unknown> = (\n\tevent: LifecycleEvent<TData>,\n\tsignal?: AbortSignal,\n) => void | Promise<void>;\nexport type LifecycleTransformHandler<TData = unknown> = (\n\tevent: LifecycleEvent<TData>,\n\tsignal?: AbortSignal,\n) => TData | Promise<TData>;\n/**\n * An owner-side execution step. Execution is awaited for completion but does\n * not replace the lifecycle event data; any owner result belongs to the\n * operation facade that initiated the lifecycle dispatch.\n */\nexport type LifecycleExecuteHandler<TData = unknown> = (\n\tevent: LifecycleEvent<TData>,\n\tsignal?: AbortSignal,\n) => unknown | Promise<unknown>;\nexport type LifecycleAfterCommitHandler<TData = unknown> = LifecycleObserveHandler<TData>;\n\n/** A failed lifecycle delivery, retaining the original handler error. */\nexport interface LifecycleDeliveryFailure {\n\tpluginId: string;\n\tregistrationId: string;\n\tkind: LifecycleRegistrationKind;\n\terror: unknown;\n}\n\n/** The delivery result is separate from the underlying operation or commit result. */\nexport interface LifecycleDeliveryReport {\n\teventId: string;\n\ttype: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\tstatus: \"delivered\" | \"queued\" | \"transform-failed\" | \"execute-failed\";\n\tattempted: number;\n\tsucceeded: number;\n\t/** Number accepted by detached subscriber queues, when non-zero. */\n\tqueued?: number;\n\tfailed: number;\n\tfailures: readonly LifecycleDeliveryFailure[];\n}\n\nexport interface LifecycleDispatchResult<TData = unknown> {\n\tevent: LifecycleEvent<TData>;\n\tdata: TData;\n\texecuteResults: readonly unknown[];\n\treport: LifecycleDeliveryReport;\n}\n\n/** @experimental Rejected candidate transform, with an independent delivery report. */\nexport class LifecycleTransformError extends Error {\n\treadonly report: LifecycleDeliveryReport;\n\treadonly cause: unknown;\n\n\tconstructor(cause: unknown, report: LifecycleDeliveryReport) {\n\t\tsuper(\"Lifecycle transform failed\");\n\t\tthis.name = \"LifecycleTransformError\";\n\t\tthis.cause = cause;\n\t\tthis.report = report;\n\t}\n}\n\n/** @experimental Rejected owner execution, with an independent delivery report. */\nexport class LifecycleExecuteError extends Error {\n\treadonly report: LifecycleDeliveryReport;\n\treadonly cause: unknown;\n\n\tconstructor(cause: unknown, report: LifecycleDeliveryReport) {\n\t\tsuper(\"Lifecycle execute failed\");\n\t\tthis.name = \"LifecycleExecuteError\";\n\t\tthis.cause = cause;\n\t\tthis.report = report;\n\t}\n}\n\n/** @experimental Stage 1A draft lifecycle registration facade. */\nexport interface LifecycleAPI {\n\tdefine<TData>(definition: LifecycleEventDefinition<TData>): LifecycleEventDefinition<TData>;\n\tget<TData = unknown>(id: string, version: number): LifecycleEventDefinition<TData>;\n\tregisterObserve<TData = unknown>(\n\t\tevent: LifecycleEventDefinition<TData> | LifecycleEventReference | string,\n\t\thandler: LifecycleObserveHandler<TData>,\n\t\tversion?: number,\n\t\toptions?: LifecycleDeliveryOptions,\n\t): DisposableRegistration;\n\tregisterTransform<TData = unknown>(\n\t\tevent: LifecycleEventDefinition<TData> | LifecycleEventReference | string,\n\t\thandler: LifecycleTransformHandler<TData>,\n\t\tversion?: number,\n\t): DisposableRegistration;\n\tregisterExecute<TData = unknown>(\n\t\tevent: LifecycleEventDefinition<TData> | LifecycleEventReference | string,\n\t\thandler: LifecycleExecuteHandler<TData>,\n\t\tversion?: number,\n\t): DisposableRegistration;\n\tregisterAfterCommit<TData = unknown>(\n\t\tevent: LifecycleEventDefinition<TData> | LifecycleEventReference | string,\n\t\thandler: LifecycleAfterCommitHandler<TData>,\n\t\tversion?: number,\n\t\toptions?: LifecycleDeliveryOptions,\n\t): DisposableRegistration;\n}\n\n/** @experimental Stage 1A draft lifecycle semantics for a generic contribution point. */\nexport type ContributionLifecycle = \"observe\" | \"transform\" | \"execute\" | \"after-commit\";\n\n/** @experimental Stage 1A draft contribution point declaration. */\nexport interface ContributionPointDefinition<TValue = unknown> {\n\tid: string;\n\tversion: number;\n\tschema: string;\n\tlifecycle?: ContributionLifecycle;\n\tvalidate(value: unknown): TValue;\n}\n\n/** @experimental Stage 1A draft contribution entry snapshot. */\nexport interface ContributionEntry<TValue = unknown> {\n\tid: string;\n\tpointId: string;\n\tversion: number;\n\towner: string;\n\tlifecycle: ContributionLifecycle;\n\tvalue: TValue;\n}\n\n/** @experimental Stage 1A draft contribution change notification. */\nexport interface ContributionChangeEvent<TValue = unknown> {\n\tpointId: string;\n\tversion: number;\n\taction: \"added\" | \"removed\";\n\tcontributionId: string;\n\towner: string;\n\tentry?: ContributionEntry<TValue>;\n}\n\n/** @experimental Stage 1A draft contribution lifecycle handle. */\nexport interface ContributionHandle {\n\treadonly id: string;\n\treadonly pointId: string;\n\treadonly version: number;\n\treadonly owner: string;\n\tdispose(): void | Promise<void>;\n}\n\n/** @experimental Stage 1A draft contribution point facade. */\nexport interface ContributionPoint<TValue = unknown> {\n\treadonly id: string;\n\treadonly version: number;\n\treadonly schema: string;\n\treadonly lifecycle: ContributionLifecycle;\n\tadd(input: { id: string; value: TValue }): Promise<ContributionHandle>;\n\tremove(id: string): Promise<void>;\n\tlist(): readonly ContributionEntry<TValue>[];\n\tsubscribe(handler: (event: ContributionChangeEvent<TValue>) => void | Promise<void>): DisposableRegistration;\n}\n\n/** @experimental Stage 1A draft contribution registry facade. */\nexport interface ContributionAPI {\n\tdefine<TValue>(definition: ContributionPointDefinition<TValue>): ContributionPoint<TValue>;\n\tget<TValue = unknown>(id: string, version: number): ContributionPoint<TValue>;\n\tlist(): readonly { id: string; version: number; schema: string; lifecycle: ContributionLifecycle; owner: string }[];\n}\n\nexport type LoggerLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LoggerRecord {\n\tversion: 1;\n\tlevel: LoggerLevel;\n\tmessage: string;\n\tfields?: PluginConfigValue;\n\tcause?: unknown;\n\tpluginId: string;\n\ttimestamp: number;\n\tsessionId?: string;\n\toperationId?: string;\n\tcorrelationId?: string;\n\tphase?: string;\n}\n\nexport interface LoggerAPI {\n\tdebug(message: string, fields?: PluginConfigValue): void;\n\tinfo(message: string, fields?: PluginConfigValue): void;\n\twarn(message: string, fields?: PluginConfigValue): void;\n\terror(message: string, fields?: PluginConfigValue, cause?: unknown): void;\n}\n\nexport interface DiagnosticsSpanEnd {\n\tstatus: \"ok\" | \"error\" | \"cancelled\";\n\tresult?: PluginConfigValue;\n\tcause?: unknown;\n}\n\nexport interface DiagnosticsSpanSnapshot {\n\tversion: 1;\n\ttraceId: string;\n\tspanId: string;\n\tparentSpanId?: string;\n\tname: string;\n\tpluginId: string;\n\tsessionId?: string;\n\tstartedAt: number;\n\tendedAt?: number;\n\tstatus: \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\tattributes: PluginConfigValue;\n\tresult?: PluginConfigValue;\n\tcause?: unknown;\n\toperationId?: string;\n\tcorrelationId?: string;\n\tphase?: string;\n}\n\nexport interface DiagnosticsSpan {\n\treadonly traceId: string;\n\treadonly spanId: string;\n\tannotate(fields: PluginConfigValue): void;\n\tend(outcome?: DiagnosticsSpanEnd): void;\n}\n\nexport interface DiagnosticsAPI {\n\tstart(name: string, attributes?: PluginConfigValue, parentSpanId?: string): DiagnosticsSpan;\n}\n\n/** @experimental Read-only runtime plugin facts exposed by the inspector. */\nexport interface RuntimeInspectorPluginSnapshot {\n\tid: string;\n\tversion: string;\n\tactive: boolean;\n\tmanifest: PluginManifest;\n\tprovides: readonly PluginCapabilityDeclaration[];\n\trequires: readonly PluginCapabilityRequirement[];\n}\n\n/** @experimental Read-only contribution entry facts exposed by the inspector. */\nexport interface RuntimeInspectorContributionSnapshot {\n\tid: string;\n\tpointId: string;\n\tversion: number;\n\towner: string;\n\tlifecycle: ContributionLifecycle;\n\tvalue: unknown;\n}\n\n/** @experimental Read-only contribution point facts exposed by the inspector. */\nexport interface RuntimeInspectorContributionPointSnapshot {\n\tid: string;\n\tversion: number;\n\tschema: string;\n\tlifecycle: ContributionLifecycle;\n\towner: string;\n\tactive: boolean;\n}\n\n/** @experimental Read-only lifecycle registration facts exposed by the inspector. */\nexport interface RuntimeInspectorLifecycleRegistrationSnapshot {\n\tid: string;\n\tkind: LifecycleRegistrationKind;\n\towner: string;\n\tactive: boolean;\n\tdelivery: LifecycleDeliverySnapshot;\n}\n\n/** @experimental Read-only lifecycle event facts exposed by the inspector. */\nexport interface RuntimeInspectorLifecycleSnapshot {\n\tid: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\tallowedPhases?: readonly LifecyclePhase[];\n\tschema: string;\n\towner: string;\n\tactive: boolean;\n\tregistrations: readonly RuntimeInspectorLifecycleRegistrationSnapshot[];\n}\n\n/** Immutable error facts retained by the runtime inspector. */\nexport interface RuntimeInspectorErrorSnapshot {\n\treadonly name: string;\n\treadonly message: string;\n\treadonly cause?: RuntimeInspectorErrorSnapshot;\n\treadonly code?: string;\n}\n\n/** A normalized lifecycle delivery failure suitable for an immutable inspector snapshot. */\nexport interface RuntimeInspectorLifecycleDeliveryFailureSnapshot {\n\treadonly pluginId: string;\n\treadonly registrationId: string;\n\treadonly kind: LifecycleRegistrationKind;\n\treadonly error: RuntimeInspectorErrorSnapshot;\n}\n\n/** A bounded, immutable record of one completed lifecycle delivery. */\nexport interface RuntimeInspectorLifecycleDeliveryReportSnapshot {\n\treadonly eventId: string;\n\treadonly type: string;\n\treadonly version: number;\n\treadonly phase: LifecyclePhase;\n\treadonly status: LifecycleDeliveryReport[\"status\"];\n\treadonly attempted: number;\n\treadonly succeeded: number;\n\treadonly queued?: number;\n\treadonly failed: number;\n\treadonly completedAt: number;\n\treadonly failures: readonly RuntimeInspectorLifecycleDeliveryFailureSnapshot[];\n}\n\n/**\n * Reason a discovered capability plugin was rejected during session startup\n * without preventing the remaining plugins from loading (D-028).\n */\nexport type PluginRejectionCode =\n\t| \"invalid_manifest\"\n\t| \"host_version_incompatible\"\n\t| \"duplicate_plugin_id\"\n\t| \"missing_dependency\"\n\t| \"plugin_load_failed\";\n\n/** Structured, immutable record of one rejected capability plugin. */\nexport interface PluginRejection {\n\treadonly code: PluginRejectionCode;\n\treadonly manifestPath: string;\n\treadonly pluginId?: string;\n\treadonly message: string;\n}\n\nexport interface RuntimeInspectorSnapshot {\n\tversion: 1;\n\thost: HostCapabilities;\n\tplugins: readonly RuntimeInspectorPluginSnapshot[];\n\tpluginRejections: readonly PluginRejection[];\n\tregistrations: readonly { kind: string; name: string; owner: string }[];\n\tcontributionPoints: readonly RuntimeInspectorContributionPointSnapshot[];\n\tcontributions: readonly RuntimeInspectorContributionSnapshot[];\n\tlifecycle: readonly RuntimeInspectorLifecycleSnapshot[];\n\tlifecycleReports: readonly RuntimeInspectorLifecycleDeliveryReportSnapshot[];\n\tsubscriptions: readonly { id: string; type: string; owner: string }[];\n\toperations: readonly { id: string; status: OperationStatus }[];\n\tlogs: readonly LoggerRecord[];\n\tspans: readonly DiagnosticsSpanSnapshot[];\n}\n\nexport interface RuntimeInspectorAPI {\n\tsnapshot(): RuntimeInspectorSnapshot;\n}\n\nexport interface StateEntry {\n\tkey: string;\n\trevision: number;\n\tvalue: PluginConfigValue;\n}\n\nexport interface StateSetOptions {\n\texpectedRevision?: number;\n\toperationId?: string;\n\tcorrelationId?: string;\n}\n\nexport interface StateChange {\n\t/** Stable owner namespace that produced this state transition. */\n\tpluginId: string;\n\tkey: string;\n\trevision: number;\n\tvalue?: PluginConfigValue;\n\toperationId?: string;\n\tcorrelationId?: string;\n}\n\nexport interface StateAPI {\n\tget(key: string): StateEntry | undefined;\n\tset(key: string, value: PluginConfigValue, options?: StateSetOptions): number;\n\tdelete(key: string, options?: StateSetOptions): number;\n\tlist(prefix?: string): readonly StateEntry[];\n\twatch(prefix: string | undefined, handler: (change: StateChange) => void): DisposableRegistration;\n}\n\n/** A branch-local, append-only view for plugins that persist their own state. */\nexport interface SessionEntryView {\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n\ttype: string;\n\t/** Structured message view carried by `type: \"message\"` entries only. */\n\tmessage?: SessionEntryMessageView;\n\tcustomType?: string;\n\tdata?: unknown;\n}\n\n/**\n * Minimal structured projection of a message entry: only the fields consumers\n * actually branch on (role/content). The host projects these instead of the\n * full internal message so the view stays a stable public contract.\n */\nexport interface SessionEntryMessageView {\n\trole: string;\n\tcontent?: unknown;\n}\n\n/** Snapshot of a tool/command registration source, mirroring the core SourceInfo fields. */\nexport interface SourceInfoViewV1 {\n\tpath: string;\n\tsource: string;\n\tscope: \"user\" | \"project\" | \"temporary\";\n\torigin: \"package\" | \"top-level\";\n\tbaseDir?: string;\n}\n\n/** Tool enumeration entry: name, description, JSON-schema parameters, prompt guidelines, and source metadata. */\nexport interface ToolInfoViewV1 {\n\tname: string;\n\tdescription: string;\n\t/** Parameter schema as declared on the tool definition (TypeBox). */\n\tparameters: unknown;\n\tpromptGuidelines?: readonly string[];\n\tsourceInfo: SourceInfoViewV1;\n}\n\nexport type CommandSourceViewV1 = \"extension\" | \"prompt\" | \"skill\";\n\n/** Slash command enumeration entry across extension, prompt-template, and skill sources. */\nexport interface CommandInfoViewV1 {\n\tname: string;\n\tdescription?: string;\n\tsource: CommandSourceViewV1;\n\tsourceInfo: SourceInfoViewV1;\n}\n\n/** Provider-agnostic facts about a model, mirroring the modelRuntime.getModelFacts projection. */\nexport interface ModelFactsViewV1 {\n\tprovider: string;\n\tid: string;\n\tcontextWindow: number;\n\tmaxTokens: number;\n\treasoning: boolean;\n}\n\n/** Scoped model entry: model facts plus the pattern's explicit thinking level, if any. */\nexport interface ScopedModelFactsViewV1 {\n\tmodel: ModelFactsViewV1;\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/** A versioned, in-memory export of the current session branch. */\nexport interface SessionExportArtifact {\n\tversion: 1;\n\tformat: \"jsonl\";\n\tmediaType: \"application/x-ndjson\";\n\tfileName: string;\n\tbytes: Uint8Array;\n}\n\nexport interface SessionExportRequest {\n\tformat: SessionExportArtifact[\"format\"];\n}\n\n/** Versioned, opaque session fact for optimistic host operations. */\nexport interface SessionRevisionV1 {\n\tversion: 1;\n\tsessionId: string;\n\tsequence: number;\n\tleafId: string | null;\n}\n\n/**\n * One serializable, optimistic request to append a compaction entry.\n *\n * The host owns the commit decision. This value only carries the immutable\n * facts that make retries and stale work observable to the host.\n */\nexport interface CompactionCommitRequestV1<TDetails = unknown> {\n\tversion: 1;\n\toperationId: string;\n\texpectedRevision: SessionRevisionV1;\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: TDetails;\n\tfromHook?: boolean;\n\tusage?: unknown;\n}\n\nexport interface CompactionCommitAppliedV1 {\n\tversion: 1;\n\tstatus: \"committed\" | \"replayed\";\n\tentryId: string;\n\t/** The revision produced by the original successful commit. */\n\trevision: SessionRevisionV1;\n}\n\nexport interface CompactionCommitRevisionConflictV1 {\n\tversion: 1;\n\tstatus: \"revision_conflict\";\n\tcurrentRevision: SessionRevisionV1;\n}\n\nexport type CompactionCommitResultV1 = CompactionCommitAppliedV1 | CompactionCommitRevisionConflictV1;\n\n/** A versioned execution boundary supplied by the host to an orchestration plugin. */\nexport type ExecutionPhaseV1 = \"agent\" | \"compaction\" | \"overflow\" | \"retry\" | \"branch_summary\" | \"reload\" | \"tree\";\n\n/**\n * Immutable input facts for a single host operation. These facts identify an\n * optimistic commit boundary; they do not themselves grant commit authority.\n */\nexport interface ExecutionFactsV1 {\n\treadonly version: 1;\n\treadonly operationId: string;\n\treadonly sessionId: string;\n\treadonly inputRevision: SessionRevisionV1;\n\treadonly phase: ExecutionPhaseV1;\n}\n\n/** A validated retry outcome attached to one immutable execution boundary. */\nexport interface RetryScheduleV1 extends ExecutionFactsV1 {\n\treadonly action: \"retry\" | \"stop\";\n\t/** `retry` is one-based; `stop` records the number of attempts already made. */\n\treadonly attempt: number;\n\t/** A `stop` action must not request a delay. */\n\treadonly delayMs: number;\n}\n\nexport type CapabilityProviderHandler<TInput = unknown, TResult = unknown> = (\n\tinput: TInput,\n\tcontext: { signal: AbortSignal },\n) => TResult | Promise<TResult>;\n\nexport interface CapabilityHandle<TResult = unknown> {\n\treadonly declaration: PluginCapabilityDeclaration;\n\treadonly owner: string;\n\tcall(input: unknown, options?: { signal?: AbortSignal }): OperationHandle<TResult>;\n}\n\nexport interface CapabilityDirectoryAPI {\n\tprovide<TInput = unknown, TResult = unknown>(\n\t\tdeclaration: PluginCapabilityDeclaration,\n\t\thandler: CapabilityProviderHandler<TInput, TResult>,\n\t): DisposableRegistration;\n\trequire<TResult = unknown>(id: string, options?: { version?: number }): CapabilityHandle<TResult>;\n\tlist(options?: { kind?: PluginCapabilityDeclaration[\"kind\"] }): readonly {\n\t\tdeclaration: PluginCapabilityDeclaration;\n\t\towner: string;\n\t}[];\n}\n\nexport interface OutputArtifactRef {\n\tsessionId: string;\n\toperationId: string;\n\tartifactId: string;\n\tkind: string;\n\tmediaType: string;\n\tsizeBytes?: number;\n\ttruncated: boolean;\n\tcreatedAt: number;\n}\n\nexport interface OutputArtifactChunk {\n\tdata: Uint8Array;\n\tnextOffset?: number;\n\teof: boolean;\n}\n\nexport type OutputArtifactErrorCode = \"invalid_ref\" | \"not_found\" | \"cancelled\";\n\nexport type OutputArtifactPutInput = Omit<OutputArtifactRef, \"artifactId\" | \"sizeBytes\" | \"createdAt\"> & {\n\tdata: Uint8Array | AsyncIterable<Uint8Array>;\n};\n\nexport interface OutputArtifactAPI {\n\tput(input: OutputArtifactPutInput, options?: { signal?: AbortSignal }): Promise<OutputArtifactRef>;\n\tstat(ref: OutputArtifactRef): Promise<OutputArtifactRef>;\n\tread(ref: OutputArtifactRef, options?: { offset?: number; maxBytes?: number }): Promise<OutputArtifactChunk>;\n}\n\nexport interface CredentialResolveRequest {\n\tproviderId: string;\n\tminValidityMs?: number;\n\tsignal?: AbortSignal;\n}\n\n/** Resolved provider auth facts for a plugin's explicit request. */\nexport interface CredentialResolution {\n\tapiKey?: string;\n\theaders: Readonly<Record<string, string | null>>;\n\tbaseUrl?: string;\n\tsource?: string;\n}\n\nexport interface CredentialAPI {\n\tresolve(request: CredentialResolveRequest): Promise<CredentialResolution | undefined>;\n}\n\n/**\n * Structural skill shape accepted by {@link BuildSystemPromptOptions.skills}\n * (D-075 S2). The host's full `Skill` type carries host-owned source facts;\n * host skill objects are structurally assignable to this projection.\n */\nexport interface BuildSystemPromptSkill {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tsourceInfo: unknown;\n\tdisableModelInvocation: boolean;\n}\n\n/**\n * System prompt assembly options (authority moved from the host's\n * `core/system-prompt.ts`, D-075 S2; the host re-exports it from here).\n */\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/**\n\t * Session-nature orientation text (suite persona, 设计 §6.2) injected right\n\t * after the opening paragraph (customPrompt branch: right after the custom\n\t * prompt body), before tools, guidelines, and context files.\n\t */\n\torientationPrompt?: string;\n\t/**\n\t * Assistant preference card (统一修复轮 A 交付3, H2 接线): the durable\n\t * user-profile card, injected immediately after the orientation section\n\t * (same M2 pattern — it can also appear alone when no persona is set),\n\t * before tools, guidelines, and context files.\n\t */\n\tpreferenceCard?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: readonly BuildSystemPromptSkill[];\n}\n\n/**\n * Public session mechanism. Product state remains plugin-owned and is written\n * as append-only custom entries, so a plugin never mutates SessionManager\n * internals or another branch's history.\n */\n/**\n * Terminal outcome of a prompt run. User-initiated aborts are normal outcomes:\n * the promise resolves with `status: \"aborted\"` instead of rejecting.\n */\nexport type PromptOutcome = { status: \"done\" } | { status: \"aborted\"; reason: \"interrupted\" | \"replaced\" };\n\n/**\n * Content accepted by {@link SessionAPI.sendMessage}. Verbatim structural\n * equivalent of the host's `sendCustomMessage` content type (`TextContent` /\n * `ImageContent`), registered inline so this contract does not depend on\n * `@agent-forge/ai`.\n */\nexport type SessionMessageContent =\n\t| string\n\t| ({ type: \"text\"; text: string; textSignature?: string } | { type: \"image\"; data: string; mimeType: string })[];\n\nexport interface SessionAPI {\n\tgetSessionId(): string;\n\t/**\n\t * 会话**自身**的身份(D-060 S1)。当宿主可见的 `getSessionId()` 是一个宿主侧标识\n\t * (池化 runner 下是 wire 任务 id)时,本成员给出底层 agent 会话的真实 id;缺省表示\n\t * 两者相同(shared 模式即如此)。\n\t */\n\tgetAgentSessionId?(): string;\n\t/** Available on hosts that expose revision facts; required by future commit APIs. */\n\tgetRevision?: () => SessionRevisionV1;\n\t/** Optional immutable context projection for operation-scoped Agent hosts. */\n\tgetContextSnapshot?: <TValue = unknown>() => AgentContextSnapshotV1<TValue>;\n\t/** Optional revision-checked context commit for operation-scoped Agent hosts. */\n\tcommitContext?: <TValue = unknown>(\n\t\trequest: AgentContextCommitRequestV1<TValue>,\n\t) => Promise<AgentContextCommitResultV1<TValue>>;\n\tgetMessages(): readonly unknown[];\n\tisIdle(): boolean;\n\tprompt(text: string): Promise<PromptOutcome>;\n\t/** Queue a steering message when the host session is running. */\n\tsteer?(text: string): Promise<void>;\n\t/** Experimental: queue a follow-up message that waits for the active run instead of interrupting it. */\n\tqueueFollowUp?(text: string): Promise<void>;\n\tabort(): Promise<void>;\n\twaitForIdle(): Promise<void>;\n\t/** Current active (prompt-visible) tool names. Available on hosts that expose the tool registry. */\n\tgetActiveTools?(): string[];\n\t/** Replace the active tool set by name; names not in the registry are ignored. */\n\tsetActiveTools?(toolNames: string[]): void;\n\t/** Experimental (R3 tool-enumeration slice): all configured tools with name, description, parameter schema, prompt guidelines, and source metadata. */\n\tgetAllTools?(): readonly ToolInfoViewV1[];\n\t/**\n\t * Registers a GENERIC entry projection on the underlying session\n\t * (see {@link EntryProjection}). Optional: hosts without session-entry\n\t * projection support reject the registration with a visible error.\n\t * Returns a disposer that removes the projection.\n\t */\n\tregisterEntryProjection?(projection: EntryProjection): () => void;\n\t/** Experimental (R3 tool-enumeration slice): slash command enumeration across extension, prompt-template, and skill sources. */\n\tgetCommands?(): readonly CommandInfoViewV1[];\n\t/** Experimental (R3 model-domain slice): provider-agnostic facts about the current session model. */\n\tgetModel?(): ModelFactsViewV1 | undefined;\n\t/** Experimental (R3 model-domain slice): scoped model facts with their explicit thinking levels. */\n\tgetScopedModels?(): readonly ScopedModelFactsViewV1[];\n\t/** Experimental (R3 model-domain slice): current thinking level. */\n\tgetThinkingLevel?(): ThinkingLevel;\n\t/** Experimental (R3 model-domain slice): set the thinking level. */\n\tsetThinkingLevel?(level: ThinkingLevel): void;\n\t/** Experimental (R3 model-domain slice): set the session model by id (resolved against the scoped models). Resolves to false when the id is unknown or auth is not configured. */\n\tsetModel?(modelId: string): Promise<boolean>;\n\t/** Experimental (R3 prompt-facts slice): the current system prompt. */\n\tgetSystemPrompt?(): string;\n\t/** Experimental (R3 prompt-facts slice): the system prompt assembly options. */\n\tgetSystemPromptOptions?(): BuildSystemPromptOptions;\n\t/** Experimental (context-facts slice): estimated usage of the current context; undefined when the host cannot measure it. */\n\tgetContextUsage?(): ContextUsage | undefined;\n\t/**\n\t * Experimental: inject a custom message into the session. Verbatim passthrough of\n\t * AgentSession.sendCustomMessage (without deliverAs): streamed hosts steer with it,\n\t * idle hosts append it, and `options.triggerTurn` starts a new turn.\n\t */\n\tsendMessage?(\n\t\tmessage: { customType: string; content: SessionMessageContent; display: boolean },\n\t\toptions?: { triggerTurn?: boolean },\n\t): Promise<void>;\n\tcompact?(customInstructions?: string): Promise<unknown>;\n\tnavigateTree?(\n\t\ttargetId: string,\n\t\toptions?: {\n\t\t\tsummarize?: boolean;\n\t\t\tcustomInstructions?: string;\n\t\t\treplaceInstructions?: boolean;\n\t\t\tlabel?: string;\n\t\t},\n\t): Promise<unknown>;\n\tappendEntry(customType: string, data?: unknown): string;\n\t/** Experimental (R3 session-metadata slice): renames the session. Delegates to AgentSession.setSessionName. */\n\tsetSessionName?(name: string): void;\n\t/** Experimental (R3 session-metadata slice): current session display name. */\n\tgetSessionName?(): string | undefined;\n\t/** Experimental (R3 session-metadata slice): appends a label-change entry; returns the new entry id. Mirrors facade appendLabelChange. */\n\tsetLabel?(entryId: string, label: string | undefined): string;\n\t/** Experimental (R3 session-metadata slice): current label of the branch entry. */\n\tgetLabel?(entryId: string): string | undefined;\n\tgetBranchEntries(): readonly SessionEntryView[];\n\t/** Available when the host declares the `session-export` feature. */\n\texportArtifact?(request: SessionExportRequest): SessionExportArtifact;\n}\n\n/** A session view scoped to one AgentInstance execution. */\nexport interface AgentSessionFacadeV1 {\n\treadonly version: 1;\n\tgetSessionId(): string;\n\tgetRevision?(): SessionRevisionV1;\n\tgetMessages(): readonly unknown[];\n\tgetBranchEntries(): readonly SessionEntryView[];\n\tisIdle(): boolean;\n\tprompt?(text: string): Promise<PromptOutcome>;\n\t/** Queue a steering message when the host session is running. */\n\tsteer?(text: string): Promise<void>;\n\tabort?(): Promise<void>;\n\twaitForIdle(): Promise<void>;\n\tappendEntry(customType: string, data?: unknown): string;\n}\n\n/** Immutable context value returned by an Agent host. */\nexport interface AgentContextSnapshotV1<TValue = unknown> {\n\treadonly version: 1;\n\treadonly revision: number;\n\treadonly value: TValue;\n}\n\nexport interface AgentContextCommitRequestV1<TValue = unknown> {\n\treadonly version: 1;\n\treadonly operationId: string;\n\treadonly expectedRevision: number;\n\treadonly value: TValue;\n\tsignal?: AbortSignal;\n}\n\nexport interface AgentContextCommitResultV1<TValue = unknown> {\n\treadonly version: 1;\n\treadonly status: \"committed\" | \"replayed\";\n\treadonly revision: number;\n\treadonly value: TValue;\n}\n\n/** Per-instance context snapshot/commit boundary. */\nexport interface AgentContextFacadeV1 {\n\treadonly version: 1;\n\tget<TValue = unknown>(): AgentContextSnapshotV1<TValue>;\n\tcommit<TValue = unknown>(request: AgentContextCommitRequestV1<TValue>): Promise<AgentContextCommitResultV1<TValue>>;\n}\n\n/** Operation facts and cancellation boundary visible to an AgentDefinition. */\nexport interface AgentOperationFacadeV1 {\n\treadonly version: 1;\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\tstatus(): OperationStatus;\n\tisActive(): boolean;\n\treportProgress(progress: OperationProgress): boolean;\n\tonCancel(handler: (reason: unknown) => void | Promise<void>): DisposableRegistration;\n\tcancel(reason?: string): Promise<void>;\n}\n\n/**\n * Optional, host-injected primitives for one AgentDefinition execution.\n * Implementations are scoped to the active operation and become revoked once\n * that operation is cancelled, completes, or its controller lease is released.\n */\nexport interface AgentHostPrimitivesV1 {\n\treadonly version: 1;\n\treadonly session?: AgentSessionFacadeV1;\n\treadonly context?: AgentContextFacadeV1;\n\treadonly state?: StateAPI;\n\t/**\n\t * Instance-private StateAPI view for this Agent instance execution only.\n\t * Same shape and semantics as `state` (CAS, detached snapshots, watchers),\n\t * but scoped to `owner + instanceId`: invisible to sibling instances and to\n\t * the owner namespace. Runtime-memory scoped; cleared on instance dispose;\n\t * not restored on rebuild.\n\t */\n\treadonly instanceState?: StateAPI;\n\treadonly artifact?: OutputArtifactAPI;\n\treadonly operation?: AgentOperationFacadeV1;\n\t/** Agent-only host model binding. */\n\treadonly model?: AgentModelFacadeV1;\n\t/** Agent-only host tool binding. */\n\treadonly tool?: AgentToolFacadeV1;\n}\n\n/**\n * Model facts and invoke surface bound to one Agent instance execution.\n *\n * `facts` carries provider-agnostic model metadata; `invocation` is a\n * single-shot completion boundary — the host resolves auth, transport and\n * cache routing, and provider internals never cross to the plugin. Each\n * invoke is exactly one completion without tools or session state.\n */\nexport interface AgentModelFacadeV1 {\n\treadonly version: 1;\n\t/** Provider-agnostic facts about the current session model. */\n\treadonly facts: AgentModelFactsV1;\n\t/** Single-shot completion boundary. */\n\treadonly invocation: AgentModelInvocationV1;\n}\n\n/** Provider-agnostic facts about the model the host will use for model calls. */\nexport interface AgentModelFactsV1 {\n\treadonly provider: string;\n\treadonly id: string;\n\treadonly contextWindow: number;\n\treadonly maxTokens: number;\n\treadonly reasoning: boolean;\n}\n\nexport interface AgentModelInvocationRequestV1 {\n\treadonly version: 1;\n\treadonly systemPrompt?: string;\n\treadonly prompt: string;\n\treadonly maxTokens?: number;\n\treadonly thinkingLevel?: ThinkingLevel;\n}\n\nexport type AgentModelInvocationResultV1 =\n\t| { readonly version: 1; readonly status: \"completed\"; readonly text: string; readonly usage?: unknown }\n\t| { readonly version: 1; readonly status: \"aborted\" }\n\t| {\n\t\t\treadonly version: 1;\n\t\t\treadonly status: \"failed\";\n\t\t\treadonly error: { readonly code: string; readonly message: string };\n\t };\n\nexport interface AgentModelInvocationV1 {\n\treadonly invoke: (\n\t\tinput: AgentModelInvocationRequestV1,\n\t\tsignal: AbortSignal,\n\t) => Promise<AgentModelInvocationResultV1>;\n}\n\n/**\n * Tool invocation surface bound to one Agent instance execution. The plugin\n * can list and invoke tools registered in the CapabilityRuntime without\n * importing internal execution paths.\n */\nexport interface AgentToolFacadeV1 {\n\treadonly version: 1;\n\t/** Tool definitions keyed by name (definition + source per tool). */\n\treadonly listTools: () => readonly {\n\t\treadonly name: string;\n\t\treadonly definition: unknown;\n\t\treadonly source: string;\n\t\t/** Owning-plugin readonly-mode declaration (宪法 §6), read off the definition. */\n\t\treadonly readonlySafe: boolean;\n\t}[];\n\t/** Invoke a registered tool by name. */\n\tinvokeTool: (name: string, input: unknown, options?: { readonly signal?: AbortSignal }) => Promise<unknown>;\n}\n\nexport interface AgentHostPrimitivesFactoryContext {\n\treadonly instance: AgentInstanceSnapshot;\n\treadonly operationId: string;\n\treadonly signal: AbortSignal;\n\treadonly leaseOwner: string;\n}\n\nexport type AgentHostPrimitivesFactory = (\n\tcontext: AgentHostPrimitivesFactoryContext,\n) => AgentHostPrimitivesV1 | undefined | Promise<AgentHostPrimitivesV1 | undefined>;\n\n/**\n * A slash command declared by a capability plugin. Names omit the leading\n * slash so every host can render and route the same command metadata.\n */\nexport interface CapabilityCommandDefinition {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n\texecute(\n\t\targs: string,\n\t\tcontext: CapabilityCommandContext,\n\t): CapabilityCommandResult | undefined | Promise<CapabilityCommandResult | undefined>;\n}\n\nexport interface CapabilityCommandContext {\n\tsignal: AbortSignal;\n\t/** Experimental: the session working directory, for commands that need cwd facts. */\n\tcwd?: string;\n}\n\n/**\n * Experimental: second argument the runtime invoke face passes to a capability\n * tool's execute (additive; existing single-parameter tools are unaffected).\n * The host injects the session working directory through\n * CapabilityRuntimeOptions.toolExecutionContext; without that injection the\n * argument stays undefined. Mirrors CapabilityCommandContext.cwd.\n */\nexport interface CapabilityToolContext {\n\t/** Experimental: the session working directory, mirroring CapabilityCommandContext.cwd. */\n\tcwd?: string;\n}\n\nexport interface CapabilityCommandLink {\n\tlabel: string;\n\turl: string;\n}\n\n/** Host-independent, serializable result returned by a capability command. */\nexport interface CapabilityCommandResult {\n\tstatus: \"success\" | \"error\";\n\tmessage: string;\n\tlinks?: readonly CapabilityCommandLink[];\n\tdata?: PluginConfigValue;\n}\n\nexport type AgentTaskStatus = \"created\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\";\n\nexport interface AgentTaskCreateRequest {\n\tprompt: string;\n\tmetadata?: Record<string, unknown>;\n}\n\n/**\n * 子任务档案(child task profile)——版本化的公共契约,经\n * `AgentTaskCreateRequest.metadata[AGENT_TASK_CHILD_PROFILE_KEY]` 传递。\n *\n * 用途:调用方(如子代理角色)要求宿主在**创建子会话时**收窄它的模型 / 思考级别 /\n * 工具面 / 会话模式,或给子会话追加一段系统提示词。所有字段都是\"收窄\"语义:工具面只会\n * 被裁到更小(与宿主自身继承面求交),模式只能更严(`readonly` 不会被放宽)。\n *\n * 契约义务(宿主 adapter 侧):\n * - 支持的宿主必须落地这些字段,并在 `AgentTaskHandle.session` 上暴露可核验事实\n * (`getActiveTools` / `getModel`)——调用方据此确认\"要求已生效\",而不是相信约定;\n * - 不支持的宿主**不得静默忽略**:应让 `create` 失败(结构化错误指名字段),因为静默\n * 忽略会让上层的\"只读评审者\"变成一句空话。\n */\nexport const AGENT_TASK_CHILD_PROFILE_KEY = \"agent-forge.agentTaskChildProfile\" as const;\n\n/**\n * metadata 键:发起 create 的**父 agent 会话 id**(D-060 S1 血缘)。宿主把它写进子会话文件头\n * 的 `parentAgentSession`,池化下随协议 `create` 过线;读取方据此做父作用域校验与按父反查。\n */\nexport const AGENT_TASK_PARENT_SESSION_KEY = \"agent-forge.agentTaskParentSession\" as const;\n\n/**\n * metadata 键:创建子会话的父回合 correlationId(第 3 期第二批,委派提交时刻捕获)。\n * 契约义务(宿主 adapter 侧):**仅 create 新建子会话消费**——宿主 adapter 读取该键并传入\n * `NewSessionOptions.parentTraceId`;resume 打开既有会话不适用(`SessionHeader.parentTraceId`\n * 随头定格,不重写)。shared 模式 embedder adapter 不读取时行为安全降级(子轨迹缺\n * parentTraceId,无回归)。\n */\nexport const AGENT_TASK_PARENT_TRACE_KEY = \"agent-forge.agentTaskParentTrace\" as const;\n\n/**\n * metadata 键:resume 目标的子会话 id(D-060 S4)。宿主据此**打开既有会话文件**继续跑\n * (同一份 JSONL 续写,形成多轮子任务),而不是新建会话。宿主必须核验文件头\n * `parentAgentSession` 等于发起方父会话 id,否则结构化拒绝——越界与不存在同型。\n */\nexport const AGENT_TASK_RESUME_SESSION_KEY = \"agent-forge.agentTaskResumeSession\" as const;\n\nexport interface AgentTaskChildProfileV1 {\n\treadonly version: 1;\n\t/** 目标模型 id:必须能在父会话的 scoped models 里解析,否则 create 失败并列出可用 id。 */\n\treadonly model?: string;\n\t/** 思考级别(minimal/low/medium/high/xhigh/max);越界值 create 失败。 */\n\treadonly thinkingLevel?: string;\n\t/** 工具面白名单:与宿主继承面求交;空数组表示\"一个工具都不给\"。 */\n\treadonly tools?: readonly string[];\n\t/** 会话模式:`readonly` 只收窄不放宽(父会话已是 readonly 时保持 readonly)。 */\n\treadonly mode?: \"readonly\" | \"full-control\";\n\t/** 追加到子会话 system prompt 末尾的文本(不替换继承来的系统提示词)。 */\n\treadonly systemPromptAppend?: string;\n\t/**\n\t * 创建该子会话的角色 id(血缘/审计用途,写进子会话文件头;**不是权限判据**,也不参与收窄)。\n\t * 由子代理能力从角色定义注入;手工构造档案的调用方可以省略。\n\t */\n\treadonly roleId?: string;\n}\n\n/** 档案解析结果:合法则给出规范化副本,否则给出可直接回给调用方的原因。 */\nexport type AgentTaskChildProfileParseResultV1 =\n\t| { readonly ok: true; readonly profile: AgentTaskChildProfileV1 }\n\t| { readonly ok: false; readonly message: string };\n\nconst CHILD_PROFILE_KEYS = [\n\t\"version\",\n\t\"model\",\n\t\"thinkingLevel\",\n\t\"tools\",\n\t\"mode\",\n\t\"systemPromptAppend\",\n\t\"roleId\",\n] as const;\nconst CHILD_PROFILE_TOOL_LIMIT = 64;\nconst CHILD_PROFILE_APPEND_CHARS = 8000;\nconst CHILD_PROFILE_THINKING_LEVELS: readonly string[] = [\"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\n/**\n * 解析并校验一份子任务档案:类型/取值范围/未知键都在这里拦下,错误文本指名键,\n * 由调用方决定是本地失败还是回给上层(子代理能力把它变成条目级 rejected)。\n */\nexport function parseAgentTaskChildProfileV1(value: unknown): AgentTaskChildProfileParseResultV1 {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn { ok: false, message: \"child task profile must be an object\" };\n\t}\n\tconst record = value as Record<string, unknown>;\n\tfor (const key of Object.keys(record)) {\n\t\tif (!(CHILD_PROFILE_KEYS as readonly string[]).includes(key)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: `child task profile has unknown key ${JSON.stringify(key)} (known: ${CHILD_PROFILE_KEYS.join(\", \")})`,\n\t\t\t};\n\t\t}\n\t}\n\tif (record.version !== 1) {\n\t\treturn { ok: false, message: `child task profile version must be 1, found ${JSON.stringify(record.version)}` };\n\t}\n\tlet model: string | undefined;\n\tif (record.model !== undefined) {\n\t\tif (typeof record.model !== \"string\" || record.model.trim() === \"\") {\n\t\t\treturn { ok: false, message: \"child task profile model must be a non-empty string\" };\n\t\t}\n\t\tmodel = record.model;\n\t}\n\tlet thinkingLevel: string | undefined;\n\tif (record.thinkingLevel !== undefined) {\n\t\tif (typeof record.thinkingLevel !== \"string\" || !CHILD_PROFILE_THINKING_LEVELS.includes(record.thinkingLevel)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage:\n\t\t\t\t\t`child task profile thinkingLevel must be one of ${CHILD_PROFILE_THINKING_LEVELS.join(\", \")}, found ` +\n\t\t\t\t\tJSON.stringify(record.thinkingLevel),\n\t\t\t};\n\t\t}\n\t\tthinkingLevel = record.thinkingLevel;\n\t}\n\tlet tools: readonly string[] | undefined;\n\tif (record.tools !== undefined) {\n\t\tif (!Array.isArray(record.tools) || record.tools.length > CHILD_PROFILE_TOOL_LIMIT) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: `child task profile tools must be an array of at most ${CHILD_PROFILE_TOOL_LIMIT} names`,\n\t\t\t};\n\t\t}\n\t\tconst names = new Set<string>();\n\t\tfor (const entry of record.tools) {\n\t\t\tif (typeof entry !== \"string\" || entry.trim() === \"\") {\n\t\t\t\treturn { ok: false, message: \"child task profile tools entries must be non-empty strings\" };\n\t\t\t}\n\t\t\tnames.add(entry);\n\t\t}\n\t\ttools = Object.freeze([...names]);\n\t}\n\tlet mode: \"readonly\" | \"full-control\" | undefined;\n\tif (record.mode !== undefined) {\n\t\tif (record.mode !== \"readonly\" && record.mode !== \"full-control\") {\n\t\t\treturn { ok: false, message: 'child task profile mode must be \"readonly\" or \"full-control\"' };\n\t\t}\n\t\tmode = record.mode;\n\t}\n\tlet roleId: string | undefined;\n\tif (record.roleId !== undefined) {\n\t\tif (typeof record.roleId !== \"string\" || record.roleId.trim() === \"\") {\n\t\t\treturn { ok: false, message: \"child task profile roleId must be a non-empty string\" };\n\t\t}\n\t\troleId = record.roleId;\n\t}\n\tlet systemPromptAppend: string | undefined;\n\tif (record.systemPromptAppend !== undefined) {\n\t\tif (\n\t\t\ttypeof record.systemPromptAppend !== \"string\" ||\n\t\t\trecord.systemPromptAppend.trim() === \"\" ||\n\t\t\trecord.systemPromptAppend.length > CHILD_PROFILE_APPEND_CHARS\n\t\t) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage:\n\t\t\t\t\t`child task profile systemPromptAppend must be a non-empty string of at most ` +\n\t\t\t\t\t`${CHILD_PROFILE_APPEND_CHARS} chars`,\n\t\t\t};\n\t\t}\n\t\tsystemPromptAppend = record.systemPromptAppend;\n\t}\n\treturn {\n\t\tok: true,\n\t\tprofile: Object.freeze({\n\t\t\tversion: 1,\n\t\t\t...(model === undefined ? {} : { model }),\n\t\t\t...(thinkingLevel === undefined ? {} : { thinkingLevel }),\n\t\t\t...(tools === undefined ? {} : { tools }),\n\t\t\t...(mode === undefined ? {} : { mode }),\n\t\t\t...(systemPromptAppend === undefined ? {} : { systemPromptAppend }),\n\t\t\t...(roleId === undefined ? {} : { roleId }),\n\t\t}),\n\t};\n}\n\n/** 便捷读取:从 metadata 里取出并校验档案;undefined 表示没带档案。 */\nexport function readAgentTaskChildProfileV1(\n\tmetadata: Record<string, unknown> | undefined,\n): AgentTaskChildProfileParseResultV1 | undefined {\n\tconst raw = metadata?.[AGENT_TASK_CHILD_PROFILE_KEY];\n\tif (raw === undefined) return undefined;\n\treturn parseAgentTaskChildProfileV1(raw);\n}\n\nexport interface AgentTaskWaitResult {\n\tsessionId: string;\n\tmessages: readonly unknown[];\n}\n\n/** Frozen terminal outcome of an agent task; the replay read survives dispose. */\nexport interface AgentTaskResultV1 {\n\treadonly taskId: string;\n\treadonly parentSessionId: string;\n\t/** Terminal only: succeeded | failed | cancelled. */\n\treadonly status: AgentTaskStatus;\n\treadonly sessionId: string;\n\treadonly messages: readonly unknown[];\n}\n\nexport interface AgentTaskHandle {\n\treadonly id: string;\n\treadonly parentSessionId: string;\n\treadonly session: SessionAPI;\n\tstatus(): AgentTaskStatus;\n\trun(): Promise<void>;\n\twait(options?: { signal?: AbortSignal }): Promise<AgentTaskWaitResult>;\n\t/**\n\t * Terminal replay read: undefined until the task settles; afterwards the\n\t * frozen terminal outcome, even after dispose (no liveness assertion).\n\t */\n\tresult(): AgentTaskResultV1 | undefined;\n\tcancel(reason?: string): Promise<void>;\n\tdispose(): Promise<void>;\n}\n\n/** Host adapter for isolated child sessions. It contains lifecycle mechanics, not scheduling policy. */\nexport interface AgentTaskHost {\n\treadonly session: SessionAPI;\n\trun(prompt: string, signal: AbortSignal): Promise<void>;\n\tcancel(reason?: string): Promise<void>;\n\tdispose(): Promise<void>;\n}\n\nexport interface AgentTaskAdapter {\n\tcreate(request: AgentTaskCreateRequest): Promise<AgentTaskHost>;\n\tdispose?(): Promise<void>;\n}\n\n/** 会话回读视图(D-060):按 sessionId 读到的有界 transcript 片段。 */\nexport interface AgentTaskSessionViewV1 {\n\treadonly sessionId: string;\n\t/** 血缘:父 agent 会话 id(子会话必有)。 */\n\treadonly parentAgentSession?: string;\n\t/** 血缘:创建该会话的角色 id(审计用途)。 */\n\treadonly agentRole?: string;\n\treadonly createdAt?: string;\n\t/** 整份 transcript 的字节数(不是返回片段的)。 */\n\treadonly bytes: number;\n\t/** 返回的消息/entry 条数;`truncated` 为真时是已返回的条数。 */\n\treadonly entryCount: number;\n\t/** 达到返回上限、只给了前段时为 true。 */\n\treadonly truncated: boolean;\n\treadonly entries: readonly unknown[];\n}\n\nexport interface AgentTaskAPI {\n\t/**\n\t * 创建子任务(宿主 adapter 驱动)。宿主只注入会话回读面(无任务 adapter)时该\n\t * 成员不存在——此时 agents 只承载 `session`/`list` 回读面,不承载委派。\n\t */\n\tcreate?(request: AgentTaskCreateRequest): Promise<AgentTaskHandle>;\n\t/**\n\t * Durable replay read by task id: loads the terminal record persisted at\n\t * settle from the host-injected durable store. Undefined when the store is\n\t * absent, the task has not settled, or no record exists under the id.\n\t *\n\t * The store is host-owned and shared per runtime: any plugin holding the\n\t * agents capability can read any task's record by id, including tasks of\n\t * other owners. Unlike the handle's in-memory `result()` (deep-frozen\n\t * projection), records reloaded from the durable backend are reparsed plain\n\t * objects and carry no freeze guarantee.\n\t */\n\t/**\n\t * Durable replay read(宿主 adapter 驱动)。宿主只注入会话回读面(无任务 adapter)\n\t * 时该成员不存在。\n\t */\n\tresult?(taskId: string): Promise<AgentTaskResultV1 | undefined>;\n\t/**\n\t * 父→子引导(D-060 S4,程序面):对**运行中**的任务投递一条有界引导消息\n\t * (≤2048 utf-8 字节,复用子会话自身 steer 语义,不新增队列)。只在发起方\n\t * runtime 的活跃任务里定位:未启动/已终态的按 `subagent_not_running`、宿主\n\t * 会话无 steer 面按 `subagent_steer_unsupported`、未知 id 按\n\t * `subagent_unknown_task` 以带 code 的错误拒绝。父回合不被打断。\n\t * runtime 桥接总是提供;宿主适配器自身无需实现。\n\t */\n\tsteer?(request: { readonly taskId: string; readonly text: string }): Promise<void>;\n\t/**\n\t * 按 `sessionId` 回读子会话 transcript(有界)。宿主未注入会话读取器时该成员不存在;\n\t * 作用域由宿主强制(默认宿主只放行本会话自己的子会话),越界与不存在同型返回 undefined。\n\t */\n\tsession?(sessionId: string): Promise<AgentTaskSessionViewV1 | undefined>;\n\t/**\n\t * 列出本会话**自己的**子代理会话摘要(按最近活动倒序,D-060 模型面盘点通道)。\n\t * 宿主未注入列举器时该成员不存在;作用域由宿主强制(只回本会话的子会话),\n\t * 摘要不含消息正文。跨进程重启仍可列出(读的是落盘目录,不是内存)。\n\t */\n\tlist?(): Promise<AgentTaskSessionSummaryV1[]>;\n}\n\n/**\n * 子代理会话摘要(`agents.list()` 的条目):只读头行信息,不含消息正文。\n * `modifiedAt` 为最后活动时间(epoch 毫秒),按它倒序返回。\n */\nexport interface AgentTaskSessionSummaryV1 {\n\treadonly sessionId: string;\n\t/** 血缘:创建该会话的角色 id(审计用途)。 */\n\treadonly agentRole?: string;\n\treadonly createdAt?: string;\n\treadonly modifiedAt: number;\n\t/** 整份 transcript 的字节数。 */\n\treadonly bytes: number;\n}\n\nexport type InteractionNotifyLevel = \"info\" | \"warning\" | \"error\";\n\nexport type InteractionRequestV1 =\n\t| { kind: \"notify\"; message: string; level?: InteractionNotifyLevel }\n\t| { kind: \"confirm\"; title: string; message: string }\n\t| { kind: \"select\"; title: string; options: readonly string[] }\n\t/** `placeholder` and `defaultValue` are part of the frozen wire shape, but current TUI/RPC hosts have no prefill support and silently ignore both (plain free-text input only). */\n\t| { kind: \"input\"; title: string; placeholder?: string; defaultValue?: string };\n\n/**\n * Outcome production conditions (frozen 1A.8 semantics):\n * - `delivered` — notify prompts only; the host accepted the fire-and-forget\n * notification.\n * - `answered` — the user completed a confirm/select/input prompt.\n * - `cancelled` — the user dismissed the prompt, `options.signal` aborted, or\n * the plugin's registration was disposed. Never produced by `timeoutMs`.\n * - `timeout` — `options.timeoutMs` elapsed before settlement; only that\n * source produces it.\n * - `unavailable` — the host's prompt implementation failed (including hosts\n * without an installed interaction UI settling \"unavailable\").\n *\n * The wrapper validates host-resolved outcomes against these conditions: an\n * unknown status, a missing/invalid `answered` value, extra fields, a\n * host-produced `timeout`, or a `delivered` outside a notify request makes\n * request() reject instead of handing a malformed outcome to the plugin.\n */\nexport type InteractionOutcomeV1 =\n\t| { status: \"delivered\" }\n\t| { status: \"answered\"; value: boolean | string }\n\t| { status: \"cancelled\" }\n\t| { status: \"timeout\" }\n\t| { status: \"unavailable\" };\n\nexport interface InteractionPromptContextV1 {\n\treadonly signal: AbortSignal;\n}\n\n/** Host-side implementation. Hosts MUST honor prompt ctx.signal and settle promptly when aborted. */\n/** Options for extension UI dialogs. */\nexport interface InteractionDialogOptions {\n\t/** AbortSignal to programmatically dismiss the dialog. */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */\n\ttimeout?: number;\n}\n\nexport interface InteractionHostV1 {\n\tnotify(request: { message: string; level?: InteractionNotifyLevel }): void;\n\tprompt(request: InteractionRequestV1, context: InteractionPromptContextV1): Promise<InteractionOutcomeV1>;\n\t/**\n\t * Implementations must be idempotent; the session dispose path and the\n\t * per-plugin registration may each invoke it.\n\t */\n\tdispose?(): void | Promise<void>;\n}\n\nexport interface InteractionAPI {\n\t/**\n\t * Fire-and-forget notification; mirrors the legacy sync void semantics.\n\t * Info-level notifications surface as transient host state (a later status\n\t * update may overwrite them) and persistent display is not guaranteed;\n\t * plugins that need a persistent notice should render their own durable UI.\n\t */\n\tnotify(request: { message: string; level?: InteractionNotifyLevel }): void;\n\t/**\n\t * Cancellable interaction task. Resolves with a structured outcome (see\n\t * {@link InteractionOutcomeV1} for the per-outcome production conditions);\n\t * user dismissal yields \"cancelled\", never a rejection. Rejections only for\n\t * invalid input (thrown synchronously), a revoked API, or a malformed host\n\t * outcome. Cancellation is per request: `options.signal` and `timeoutMs`\n\t * affect only this request, never concurrent requests of the same plugin.\n\t */\n\trequest(\n\t\trequest: InteractionRequestV1,\n\t\toptions?: { signal?: AbortSignal; timeoutMs?: number },\n\t): Promise<InteractionOutcomeV1>;\n}\n\n/** Experimental, host-independent Agent composition contract. */\nexport type AgentInstanceStatus = \"created\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\" | \"disposed\";\n\nexport type AgentControllerRole = PluginAgentRole;\n\nexport interface AgentInstanceSnapshot {\n\treadonly id: string;\n\treadonly definitionId: string;\n\treadonly definitionVersion: number;\n\treadonly role: AgentControllerRole;\n\treadonly parentInstanceId?: string;\n\treadonly status: AgentInstanceStatus;\n\treadonly revision: number;\n\treadonly leaseOwner?: string;\n}\n\nexport interface AgentExecutionContext {\n\treadonly instance: AgentInstanceSnapshot;\n\treadonly signal: AbortSignal;\n\treadonly inputRevision: number;\n\t/** Optional host primitives; absent when the host did not negotiate them. */\n\treadonly host?: AgentHostPrimitivesV1;\n}\n\nexport interface AgentDefinition<TInput = unknown, TResult = unknown> {\n\treadonly id: string;\n\treadonly version: number;\n\treadonly role: AgentControllerRole;\n\treadonly owner?: string;\n\trun(input: TInput, context: AgentExecutionContext): TResult | Promise<TResult>;\n}\n\nexport interface AgentControllerLease {\n\treadonly id: string;\n\treadonly instanceId: string;\n\treadonly owner: string;\n\treadonly revision: number;\n\tisActive(): boolean;\n\trelease(): Promise<void>;\n}\n\nexport interface AgentInstanceResult<TResult = unknown> {\n\treadonly status: \"succeeded\" | \"failed\" | \"cancelled\" | \"disposed\";\n\treadonly output?: TResult;\n\treadonly error?: unknown;\n\treadonly revision: number;\n}\n\nexport interface AgentInstance<TInput = unknown, TResult = unknown> {\n\treadonly id: string;\n\treadonly definition: AgentDefinition<TInput, TResult>;\n\tsnapshot(): AgentInstanceSnapshot;\n\tacquireControllerLease(owner?: string): Promise<AgentControllerLease>;\n\trun(input: TInput, options?: { lease?: AgentControllerLease; signal?: AbortSignal }): OperationHandle<TResult>;\n\twait(): Promise<AgentInstanceResult<TResult>>;\n\tcancel(reason?: string): Promise<void>;\n\tdispose(): Promise<void>;\n}\n\nexport interface AgentCompositionAPI {\n\tdefine<TInput = unknown, TResult = unknown>(\n\t\tdefinition: AgentDefinition<TInput, TResult>,\n\t): AgentDefinition<TInput, TResult>;\n\tget<TInput = unknown, TResult = unknown>(id: string, version: number): AgentDefinition<TInput, TResult>;\n\tcreate<TInput = unknown, TResult = unknown>(\n\t\tdefinition: AgentDefinition<TInput, TResult> | { id: string; version: number },\n\t\toptions?: { id?: string; parentInstanceId?: string },\n\t): AgentInstance<TInput, TResult>;\n\tlistInstances(): readonly AgentInstanceSnapshot[];\n}\n\n/** Optional host binding implemented by the built-in composition runtime. */\nexport interface AgentCompositionHostBinding {\n\tsetHostPrimitivesFactory(factory?: AgentHostPrimitivesFactory): void;\n}\n\n/** Optional owner-scoped cleanup implemented by the built-in composition runtime. */\nexport interface AgentCompositionDefinitionBinding {\n\tdisposeDefinitions(definitions: readonly AgentDefinition[]): void;\n}\n\n/**\n * Optional host-only binding for the built-in composition runtime. It lets a\n * CapabilityRuntime add owner-scoped primitives without exposing that control\n * to capability plugins.\n */\nexport interface AgentCompositionScopedHostBinding {\n\tcreateWithHostPrimitives<TInput = unknown, TResult = unknown>(\n\t\tdefinition: AgentDefinition<TInput, TResult> | { id: string; version: number },\n\t\toptions: { id?: string; parentInstanceId?: string } | undefined,\n\t\thostPrimitivesFactory: AgentHostPrimitivesFactory,\n\t): AgentInstance<TInput, TResult>;\n}\n\nexport interface ContextStrategy<TContext = unknown, TSnapshot = unknown> {\n\ttransform(context: TContext, options?: ContextOperationOptions): TContext | Promise<TContext>;\n\tsnapshot?(context: TContext, options?: ContextOperationOptions): TSnapshot | Promise<TSnapshot>;\n\trestore?(snapshot: TSnapshot, options?: ContextOperationOptions): TContext | Promise<TContext>;\n\treplace?(context: TContext, options?: ContextOperationOptions): TContext | Promise<TContext>;\n}\n\nexport interface ContextOperationOptions {\n\tsignal?: AbortSignal;\n\treason?: \"request\" | \"reload\" | \"session_replace\" | \"compaction\" | \"overflow_recovery\" | \"retry\" | \"tree\";\n\tsessionId?: string;\n}\n\n/**\n * Generic transform over the projected session entry list, registered per\n * session. The kernel applies registered projections verbatim; semantics\n * belong to the registering plugin.\n */\nexport interface EntryProjection {\n\t/** The plugin-owned custom entry type this projection is associated with. */\n\treadonly customType: string;\n\treadonly project: (entries: readonly unknown[]) => readonly unknown[];\n}\n\nexport interface SkillDefinition {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tdisableModelInvocation?: boolean;\n}\n\n/** Versioned, provider-agnostic facts shared by replaceable policy calls. */\nexport interface PolicyInvocationContextV1 {\n\tversion: 1;\n\tsessionId: string;\n\tphase: \"agent\" | \"compaction\" | \"overflow\" | \"retry\" | \"branch_summary\";\n\toperationId?: string;\n}\n\nexport interface RetryPolicyRequest {\n\tsignal?: AbortSignal;\n\tretryable: boolean;\n\tenabled: boolean;\n\tattempt: number;\n\tmaxAttempts: number;\n\tbaseDelayMs: number;\n\terrorMessage?: string;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface RetryClassificationRequest {\n\tsignal?: AbortSignal;\n\tmessage: unknown;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface RetryPolicyDecision {\n\tretry: boolean;\n\tdelayMs?: number;\n}\n\nexport interface RetryPolicy {\n\tclassify?(request: RetryClassificationRequest): boolean | Promise<boolean>;\n\tdecide(request: RetryPolicyRequest): RetryPolicyDecision | Promise<RetryPolicyDecision>;\n}\n\nexport interface CompactionPolicyRequest {\n\tsignal?: AbortSignal;\n\tenabled: boolean;\n\treason: \"overflow\" | \"threshold\";\n\tcontextOverflow: boolean;\n\trecoverableLength: boolean;\n\t/** Facts measured by the host; the policy owns the threshold decision. */\n\tcontextUsage?: CompactionContextUsage;\n\trecoveryAttempted: boolean;\n\tcanContinue: boolean;\n\t/**\n\t * Branch path entry snapshot (threshold requests only). Provided so a\n\t * policy can plan CHEAP RELIEF (see {@link CompactionPolicyDecision.relief})\n\t * from real history facts instead of ordering a summarization run.\n\t */\n\tbranchEntries?: readonly unknown[];\n\t/** Recent-tail protection budget (settings fact) for relief planning. */\n\tkeepRecentTokens?: number;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface CompactionContextUsage {\n\tcontextTokens: number;\n\tcontextWindow: number;\n\treserveTokens: number;\n}\n\nexport interface CompactionPreparationRequest {\n\tsignal?: AbortSignal;\n\tentries: unknown;\n\tsettings: unknown;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface CompactionPolicyDecision {\n\tcompact: boolean;\n\tretry?: boolean;\n\tfailureMessage?: string;\n\t/**\n\t * Cheap RELIEF plan: the host appends this custom entry (generic\n\t * `appendCustomEntry`) and reprojects the context instead of running a\n\t * summarization. The semantics of the entry belong entirely to the policy;\n\t * the projection that interprets it is registered separately via\n\t * {@link CapabilityAPI.registerEntryProjection}. When relief is present the\n\t * host skips compaction, so `compact` must be false.\n\t */\n\trelief?: { readonly customType: string; readonly data?: unknown };\n}\n\n/** Provider-agnostic facts about the model the host will use for a summary call. */\nexport interface SummaryModelFactsV1 {\n\treadonly id: string;\n\treadonly contextWindow: number;\n\treadonly maxTokens: number;\n\treadonly reasoning: boolean;\n}\n\n/**\n * Host-owned, provider-agnostic single-shot completion boundary for summary\n * policies. The host resolves the model, auth, transport, retry budget and\n * cache routing; provider internals never cross to the plugin. Each invoke is\n * exactly one completion without tools or session state, and never writes the\n * prompt cache. A plugin that can read these types can implement a summary\n * strategy without importing provider internals.\n */\nexport interface SummaryModelInvocationV1 {\n\treadonly invoke: (\n\t\tinput: SummaryModelInvocationRequestV1,\n\t\tsignal: AbortSignal,\n\t) => Promise<SummaryModelInvocationResultV1>;\n}\n\n/** One host-mediated summary completion request. */\nexport interface SummaryModelInvocationRequestV1 {\n\treadonly version: 1;\n\treadonly systemPrompt?: string;\n\treadonly prompt: string;\n\t/** Requested output budget; the host clamps it to the summary model cap. */\n\treadonly maxTokens?: number;\n\treadonly thinkingLevel?: ThinkingLevel;\n}\n\n/** Stable failure codes reported through {@link SummaryModelInvocationResultV1} errors. */\nexport const SUMMARY_MODEL_INVOCATION_ERROR_CODES = {\n\t/** Provider returned an error stop; `message` mirrors the provider error text. */\n\tproviderError: \"summary_provider_error\",\n\t/** Generation hit the requested output cap and the summary is incomplete. */\n\tlengthCap: \"summary_length_cap\",\n\t/** The model attempted a tool call in a tool-less completion. */\n\ttoolCall: \"summary_tool_call\",\n\t/** The transport threw; `message` mirrors the original error text. */\n\ttransportError: \"summary_transport_error\",\n} as const;\n\n/**\n * One host-mediated summary completion outcome, as a discriminated union:\n * `completed` always carries text, `failed` always carries structured error\n * facts whose `code` is one of {@link SUMMARY_MODEL_INVOCATION_ERROR_CODES}.\n */\nexport type SummaryModelInvocationResultV1 =\n\t| { readonly version: 1; readonly status: \"completed\"; readonly text: string; readonly usage?: unknown }\n\t| { readonly version: 1; readonly status: \"aborted\" }\n\t| {\n\t\t\treadonly version: 1;\n\t\t\treadonly status: \"failed\";\n\t\t\treadonly error: { readonly code: string; readonly message: string };\n\t };\n\nexport interface CompactionSummaryRequest {\n\tpreparation: unknown;\n\tmodel: SummaryModelFactsV1;\n\tinvocation: SummaryModelInvocationV1;\n\tcustomInstructions?: string;\n\tsignal: AbortSignal;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\tthinkingLevel?: ThinkingLevel;\n\tsessionId?: string;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface CompactionSummaryResult {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tusage?: unknown;\n\tdetails?: unknown;\n}\n\nexport interface CompactionPolicy {\n\tprepare?(request: CompactionPreparationRequest): unknown | Promise<unknown>;\n\tdecide(request: CompactionPolicyRequest): CompactionPolicyDecision | Promise<CompactionPolicyDecision>;\n\tsummarize?(request: CompactionSummaryRequest): CompactionSummaryResult | Promise<CompactionSummaryResult>;\n}\n\n/** Provider-agnostic overflow classification supplied by a capability plugin. */\nexport interface OverflowPolicyRequest {\n\tsignal?: AbortSignal;\n\tmessage: unknown;\n\tcontextWindow?: number;\n\tdesiredMaxOutput: number;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface OverflowPolicyDecision {\n\tcontextOverflow: boolean;\n\trecoverableLength: boolean;\n}\n\nexport interface OverflowPolicy {\n\tdecide(request: OverflowPolicyRequest): OverflowPolicyDecision | Promise<OverflowPolicyDecision>;\n}\n\nexport interface BranchSummaryRequest {\n\tentries: unknown;\n\tmodel: SummaryModelFactsV1;\n\tinvocation: SummaryModelInvocationV1;\n\tsignal: AbortSignal;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\treserveTokens?: number;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\tusage?: unknown;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\nexport interface BranchSummaryPolicy {\n\tsummarize(request: BranchSummaryRequest): BranchSummaryResult | Promise<BranchSummaryResult>;\n}\n\n/**\n * Experimental provider request header boundary. `null` retains the provider\n * header deletion semantics used by the host model runtime.\n */\nexport interface ProviderHeaderTransformRequest {\n\tmodel: unknown;\n\tsessionId?: string;\n\theaders: Record<string, string | null>;\n}\n\n/**\n * Experimental request-time hook for plugins that own provider header policy.\n * Transforms run in registration order and receive the previous transform's\n * result.\n */\nexport type ProviderHeaderTransform = (\n\trequest: ProviderHeaderTransformRequest,\n) => Record<string, string | null> | Promise<Record<string, string | null>>;\n\n/**\n * Hook positions on the default agent loop. Links run in registration order\n * after the host's legacy chain head.\n */\nexport type AgentLoopHookPositionV1 =\n\t| \"beforeInput\"\n\t| \"beforeToolCall\"\n\t| \"afterToolCall\"\n\t| \"transformContext\"\n\t| \"prepareNextTurn\"\n\t| \"shouldStopAfterTurn\";\n\n/**\n * One ordered link of the input gate chain (输入 gate,扩展位盘点 A3). Runs at\n * prompt submission — before the input is accepted (`input.received@1` is the\n * observe fact of an ACCEPTED input and never fires for blocked inputs) and\n * before skill/template expansion. A `{ block: true, reason? }` result rejects\n * the input: the session dispatches `input.gate.blocked@1` and the prompt call\n * fails with the reason. A `{ text }` result rewrites the input for everything\n * downstream (later gates, expansion, the turn). `undefined` keeps the input.\n */\nexport type AgentLoopBeforeInputHookV1 = (input: {\n\treadonly text: string;\n\treadonly source: string;\n\treadonly signal?: AbortSignal;\n}) => Promise<AgentLoopBeforeInputOutputV1 | undefined>;\n\nexport interface AgentLoopBeforeInputOutputV1 {\n\tblock?: boolean;\n\treason?: string;\n\ttext?: string;\n}\n\nexport interface AgentLoopBeforeToolCallInputV1 {\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tsignal?: AbortSignal;\n}\n\n/**\n * One ordered link of the default tool-call gating chain. Return\n * `{ block: true, reason? }` to block, `{ args }` to replace the candidate\n * arguments, or `undefined` to keep the input.\n */\nexport interface AgentLoopBeforeToolCallOutputV1 {\n\tblock?: boolean;\n\treason?: string;\n\targs?: unknown;\n}\n\nexport type AgentLoopBeforeToolCallHookV1 = (\n\tinput: AgentLoopBeforeToolCallInputV1,\n) => Promise<AgentLoopBeforeToolCallOutputV1 | undefined>;\n\nexport interface AgentLoopAfterToolCallInputV1 {\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\t/** The result produced by the previous link, or the executed tool result for the first link. */\n\tresult: unknown;\n\tisError: boolean;\n\tsignal?: AbortSignal;\n}\n\n/**\n * One ordered link of the post-execution chain. Return a partial tool-result\n * override to rewrite the result, or `undefined` to keep the input.\n */\nexport type AgentLoopAfterToolCallHookV1 = (input: AgentLoopAfterToolCallInputV1) => Promise<unknown | undefined>;\n\n/**\n * One ordered link of the request-time context transform chain. Receives and\n * returns the message array; `undefined` keeps the input.\n */\nexport type AgentLoopTransformContextHookV1 = (\n\tmessages: readonly unknown[],\n\tsignal?: AbortSignal,\n) => Promise<readonly unknown[] | undefined>;\n\n/**\n * One ordered link of the next-turn preparation chain. Receives the turn\n * snapshot, returns a revised snapshot or `undefined`.\n */\nexport type AgentLoopPrepareNextTurnHookV1 = (turn: unknown, signal?: AbortSignal) => Promise<unknown | undefined>;\n\n/**\n * One ordered link of the post-turn stop chain. Receives the completed turn's\n * stop context; return `true` to request stopping after the current turn. The\n * host OR-composes the chain: the first link returning `true` stops the run\n * without consulting later links.\n *\n * The stop context stays kernel-typed (`@agent-forge/agent-core`\n * `ShouldStopAfterTurnContext`: its fields reference the provider message\n * model, which must not cross into the SDK — D-075 S2). Hosts hand the same\n * runtime object they hand the kernel callback; `context` is therefore typed\n * `any` here so kernel-typed handlers remain assignable.\n */\n// biome-ignore lint/suspicious/noExplicitAny: kernel loop-stop context is provider-model typed and cannot cross into the SDK (D-075 S2).\nexport type AgentLoopShouldStopAfterTurnHookV1 = (context: any, signal?: AbortSignal) => boolean | Promise<boolean>;\n\nexport type AgentLoopHookForV1<P extends AgentLoopHookPositionV1> = P extends \"beforeInput\"\n\t? AgentLoopBeforeInputHookV1\n\t: P extends \"beforeToolCall\"\n\t\t? AgentLoopBeforeToolCallHookV1\n\t\t: P extends \"afterToolCall\"\n\t\t\t? AgentLoopAfterToolCallHookV1\n\t\t\t: P extends \"transformContext\"\n\t\t\t\t? AgentLoopTransformContextHookV1\n\t\t\t\t: P extends \"prepareNextTurn\"\n\t\t\t\t\t? AgentLoopPrepareNextTurnHookV1\n\t\t\t\t\t: P extends \"shouldStopAfterTurn\"\n\t\t\t\t\t\t? AgentLoopShouldStopAfterTurnHookV1\n\t\t\t\t\t\t: never;\n\nexport type AgentLoopHookHandlerV1 =\n\t| AgentLoopBeforeInputHookV1\n\t| AgentLoopBeforeToolCallHookV1\n\t| AgentLoopAfterToolCallHookV1\n\t| AgentLoopTransformContextHookV1\n\t| AgentLoopPrepareNextTurnHookV1\n\t| AgentLoopShouldStopAfterTurnHookV1;\n\n/**\n * Post-run continuation facts for the default agent loop. The host evaluates\n * its own candidate decision first; the strategy makes the final\n * continue/stop call for the post-run loop.\n */\nexport interface AgentRunLoopStrategyRequestV1 {\n\t/** The policy decision signal for the current prompt run. */\n\treadonly signal?: AbortSignal;\n\t/** The retry path fired: a retry was prepared and the host would continue into it. */\n\treadonly willRetry: boolean;\n\t/** The compaction path fired: compaction was prepared and the host would continue into it. */\n\treadonly willCompact: boolean;\n\t/** The agent still holds queued steering/follow-up messages. */\n\treadonly queuedFollowUp: boolean;\n\t/** The host's own continuation decision (the replaceable default behavior). */\n\treadonly hostWillContinue: boolean;\n}\n\nexport interface AgentRunLoopStrategyDecisionV1 {\n\treadonly continueLoop: boolean;\n\treadonly reason?: string;\n}\n\n/**\n * Post-run continuation strategy for the default agent loop. The host proposes\n * the continuation (retry, compaction, or queued input); the strategy may veto\n * it per cycle. `continueLoop: true` without a host-proposed continuation is\n * clamped to stop: the agent loop can only continue from pending retry,\n * compaction, or queued input.\n */\nexport interface AgentRunLoopStrategyV1 {\n\tdecideNextCycle(\n\t\trequest: AgentRunLoopStrategyRequestV1,\n\t): AgentRunLoopStrategyDecisionV1 | Promise<AgentRunLoopStrategyDecisionV1>;\n}\n\nexport interface CapabilityAPI {\n\treadonly manifest: PluginManifest;\n\treadonly host: HostCapabilities;\n\treadonly config: PluginConfig;\n\treadonly session?: SessionAPI;\n\t/** Available when the host declares the `output-artifacts` feature. */\n\treadonly output?: OutputArtifactAPI;\n\treadonly credentials?: CredentialAPI;\n\treadonly agents?: AgentTaskAPI;\n\t/**\n\t * 宿主会话取消栅栏(D-044 §4.2):getter 形态,按调用时刻返回当前 epoch 的\n\t * AbortSignal(用户中止/销毁会话时触发;epoch 刷新后旧信号不再影响新任务)。\n\t * 宿主未注入 parentSignal 时为 undefined。插件编排(如 subagent delegate)用它级联取消。\n\t */\n\tsessionAbortSignal?: () => AbortSignal | undefined;\n\t/** Available when the host declares `interaction` feature. */\n\treadonly interaction?: InteractionAPI;\n\t/** Available when the host declares `agent-composition-v1`. */\n\treadonly composition?: AgentCompositionAPI;\n\t/** Available when the host declares `logger-v1`. */\n\treadonly logger?: LoggerAPI;\n\t/** Available when the host declares `diagnostics-v1`. */\n\treadonly diagnostics?: DiagnosticsAPI;\n\t/** Available when the host declares `plugin-state-v1`. */\n\treadonly state?: StateAPI;\n\t/** Available when the host declares `runtime-inspector-v1`. */\n\treadonly inspector?: RuntimeInspectorAPI;\n\t/**\n\t * Host trace adapter service (D-075 S4 second batch, observability host\n\t * contract). Present when the host runs session trace collection; the\n\t * first-party observability plugin binds it as its trace sink adapter.\n\t * Optional probe: hosts without tracing (or third-party hosts) leave it\n\t * undefined and the plugin stays trace-free.\n\t */\n\treadonly trace?: ObservabilityHostAdapterV1;\n\t/**\n\t * Trace-sink budget overrides accompanying {@link CapabilityAPI.trace}\n\t * (host `traceOptions` face, design §6 control plane). Present only\n\t * together with `trace`; omitted fields fall back to the plugin defaults.\n\t */\n\treadonly traceSinkOptions?: TraceSinkOptionsV1;\n\treadonly contributions: ContributionAPI;\n\t/** Draft host lifecycle event directory. */\n\treadonly lifecycle: LifecycleAPI;\n\t/** Draft plugin-to-plugin capability directory. */\n\treadonly capabilities: CapabilityDirectoryAPI;\n\t/**\n\t * Register a tool. `definition` stays loosely typed (any `{ name, execute }`\n\t * shape the host can normalize); when the host configures\n\t * CapabilityRuntimeOptions.toolExecutionContext, `execute` receives a\n\t * {@link CapabilityToolContext} as its second argument on the runtime invoke\n\t * face. Re-registering an existing name replaces the current registration\n\t * (last load wins) and it is restored when the replacing registration\n\t * disposes. Experimental.\n\t */\n\tregisterTool(definition: unknown): DisposableRegistration;\n\tregisterCommand(definition: CapabilityCommandDefinition): DisposableRegistration;\n\tregisterOperation(\n\t\tname: string,\n\t\thandler: (input: unknown, context: OperationExecutionContext) => unknown | Promise<unknown>,\n\t): DisposableRegistration;\n\tregisterRpcMethod(name: string, handler: (input: unknown) => unknown | Promise<unknown>): DisposableRegistration;\n\tregisterContextStrategy(name: string, strategy: ContextStrategy): DisposableRegistration;\n\t/**\n\t * Registers a GENERIC entry projection for this session's context\n\t * projection: `project` receives the projected session entry list and may\n\t * replace entries. The kernel applies registered projections verbatim and\n\t * knows nothing about their semantics — first-party and third-party plugins\n\t * use the same channel for custom-entry-based context policies (e.g. a\n\t * compaction policy eliding bulky old tool results). The returned disposer\n\t * removes the projection.\n\t */\n\tregisterEntryProjection(projection: EntryProjection): DisposableRegistration;\n\tregisterProviderHeaderTransform(name: string, transform: ProviderHeaderTransform): DisposableRegistration;\n\tregisterSkill(definition: SkillDefinition): DisposableRegistration;\n\tregisterRetryPolicy(name: string, policy: RetryPolicy): DisposableRegistration;\n\tregisterCompactionPolicy(name: string, policy: CompactionPolicy): DisposableRegistration;\n\tregisterOverflowPolicy(name: string, policy: OverflowPolicy): DisposableRegistration;\n\tregisterBranchSummaryPolicy(name: string, policy: BranchSummaryPolicy): DisposableRegistration;\n\tregisterLoopHook(position: \"beforeInput\", handler: AgentLoopBeforeInputHookV1): DisposableRegistration;\n\tregisterLoopHook(position: \"beforeToolCall\", handler: AgentLoopBeforeToolCallHookV1): DisposableRegistration;\n\tregisterLoopHook(position: \"afterToolCall\", handler: AgentLoopAfterToolCallHookV1): DisposableRegistration;\n\tregisterLoopHook(position: \"transformContext\", handler: AgentLoopTransformContextHookV1): DisposableRegistration;\n\tregisterLoopHook(position: \"prepareNextTurn\", handler: AgentLoopPrepareNextTurnHookV1): DisposableRegistration;\n\tregisterLoopHook(\n\t\tposition: \"shouldStopAfterTurn\",\n\t\thandler: AgentLoopShouldStopAfterTurnHookV1,\n\t): DisposableRegistration;\n\tregisterRunLoopStrategy(name: string, strategy: AgentRunLoopStrategyV1): DisposableRegistration;\n\tsubscribe<TEvent>(\n\t\ttype: string,\n\t\thandler: (event: EventEnvelope<TEvent>) => void | Promise<void>,\n\t): DisposableRegistration;\n\tpublish<TData>(event: Omit<EventEnvelope<TData>, \"id\" | \"timestamp\" | \"source\">): Promise<EventEnvelope<TData>>;\n\tcall<TResult = unknown>(\n\t\toperation: string,\n\t\tinput: unknown,\n\t\toptions?: { signal?: AbortSignal },\n\t): OperationHandle<TResult>;\n}\n\n/** Resources owned by a capability plugin beyond runtime registrations. */\nexport interface CapabilityPluginInstance {\n\tdispose(): void | Promise<void>;\n}\n\n/** Resources returned by a synchronous embedded plugin factory. */\nexport interface CapabilityPluginSyncInstance {\n\tdispose(): void;\n}\n\n// biome-ignore lint/suspicious/noConfusingVoidType: factories conventionally return void or a disposable instance.\nexport type CapabilityPluginFactoryResult = void | CapabilityPluginInstance;\nexport type CapabilityPluginFactory = (\n\tapi: CapabilityAPI,\n) => CapabilityPluginFactoryResult | Promise<CapabilityPluginFactoryResult>;\n// biome-ignore lint/suspicious/noConfusingVoidType: synchronous factories conventionally return void or a disposable instance.\nexport type CapabilityPluginSyncFactory = (api: CapabilityAPI) => void | CapabilityPluginSyncInstance;\n\nexport function createDisposableRegistration(\n\tkind: string,\n\tdispose: () => void | Promise<void>,\n\tid: string,\n): DisposableRegistration {\n\tlet disposed = false;\n\treturn {\n\t\tid,\n\t\tkind,\n\t\tdispose: () => {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\treturn dispose();\n\t\t},\n\t};\n}\n\nexport function createEventEnvelope<TData>(\n\tevent: Omit<EventEnvelope<TData>, \"id\" | \"timestamp\">,\n\toptions: { id: string; timestamp?: number },\n): EventEnvelope<TData> {\n\treturn {\n\t\t...event,\n\t\tid: options.id,\n\t\ttimestamp: options.timestamp ?? 0,\n\t};\n}\n\n/**\n * Detach a session value into a read-only projection: the value is deep-cloned\n * via `structuredClone` and the clone is frozen recursively (ArrayBuffer views\n * are cloned but not frozen). Lifecycle payload builders use this so handlers\n * receive data that cannot be mutated in place and share no identity with live\n * session state. Available to hosts and plugins alike through the public face;\n * the default loop bootstrap uses it for tool-call inputs and tool-result\n * content.\n */\nexport function detachedSessionSnapshot<T>(value: T): T {\n\tconst clone = structuredClone(value);\n\tconst freeze = (candidate: unknown): void => {\n\t\tif (!candidate || typeof candidate !== \"object\") return;\n\t\tif (ArrayBuffer.isView(candidate)) return;\n\t\tfor (const child of Object.values(candidate as Record<string, unknown>)) freeze(child);\n\t\tObject.freeze(candidate);\n\t};\n\tfreeze(clone);\n\treturn clone;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"public-api.js","sourceRoot":"","sources":["../src/public-api.ts"],"names":[],"mappings":"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","sourcesContent":["/**\n * Experimental, host-facing contracts for capability plugins.\n *\n * This module deliberately contains no product policy. It describes the\n * capabilities a host may expose; policy plugins decide how to compose them.\n *\n * Authority: `@agent-forge/plugin-sdk` is the single authoring source for this\n * surface (D-075 S2); the host (`@agent-forge/agent-forge`) re-exports it from\n * its historical module path so existing imports keep resolving.\n */\n\nimport type { MemoryStorageComponentsV1 } from \"./memory.ts\";\nimport type { ObservabilityHostAdapterV1, TraceSinkOptionsV1 } from \"./observability.ts\";\n\n/** @experimental Promoted out of draft only when a real consumer drives stabilization. */\nexport const EXPERIMENTAL_PUBLIC_API_VERSION = \"1-draft\" as const;\n\n/**\n * Thinking/reasoning level for models that support it.\n * Note: \"xhigh\" and \"max\" are only supported by selected model families. Use model\n * thinking-level metadata from the host to detect support for a concrete model.\n *\n * Authority moved from `@agent-forge/agent-core` (D-075 S2); agent-core\n * re-exports it from here.\n */\nexport type ThinkingLevel = \"off\" | \"minimal\" | \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\nexport type HostMode = \"readonly\" | \"full-control\";\n\n/** Estimated context usage for the active model; the session read face (`getContextUsage`) projects it. */\nexport interface ContextUsage {\n\t/** Estimated context tokens, or null if unknown (e.g. right after compaction, before next LLM response). */\n\ttokens: number | null;\n\tcontextWindow: number;\n\t/** Context usage as percentage of context window, or null if tokens is unknown. */\n\tpercent: number | null;\n}\n\nexport type PluginConfigValue =\n\t| null\n\t| boolean\n\t| number\n\t| string\n\t| readonly PluginConfigValue[]\n\t| { readonly [key: string]: PluginConfigValue };\n\n/** JSON configuration declared by a plugin's own manifest. */\nexport type PluginConfig = Readonly<Record<string, PluginConfigValue>>;\n\n/** Draft plugin-provided capability contract. Version is an exact integer schema version. */\nexport interface PluginCapabilityDeclaration {\n\tid: string;\n\tversion: number;\n\tkind: \"service\" | \"contribution\" | \"transform\";\n}\n\n/** Draft plugin capability dependency. Requirements use exact version matching. */\nexport interface PluginCapabilityRequirement {\n\tid: string;\n\tversion: number;\n\toptional?: boolean;\n}\n\n/** Roles that a plugin may expose through the experimental Agent composition facade. */\nexport type PluginAgentRole = \"root-agent-controller\" | \"child-agent-controller\";\n\n/** Manifest declaration for an AgentDefinition that a plugin may register. */\nexport interface AgentDefinitionDeclaration {\n\tid: string;\n\tversion: number;\n\trole: PluginAgentRole;\n\tentry: string;\n}\n\nexport interface PluginManifest {\n\tid: string;\n\tversion: string;\n\t/**\n\t * Semver range of host (agent-forge application) versions this plugin\n\t * supports, e.g. `\">=0.84.0 <1.0.0\"`. When declared and the running host\n\t * version is outside the range, the plugin is rejected at discovery\n\t * (D-073). Paired with the plugin's own `version` (the \"two version\n\t * numbers\" contract).\n\t */\n\thostVersion?: string;\n\tapiVersion: typeof EXPERIMENTAL_PUBLIC_API_VERSION;\n\tentry: string;\n\trequiredCapabilities?: string[];\n\toptionalCapabilities?: string[];\n\t/** Plugin capabilities provided to the runtime directory. */\n\tprovides?: readonly PluginCapabilityDeclaration[];\n\t/** Plugin capabilities required from other loaded plugins. */\n\trequires?: readonly PluginCapabilityRequirement[];\n\t/** Experimental Agent controller roles exposed by this plugin. */\n\troles?: readonly PluginAgentRole[];\n\t/** Experimental Agent definitions that the plugin factory may register. */\n\tagents?: readonly AgentDefinitionDeclaration[];\n\tconfig?: PluginConfig;\n}\n\n/**\n * 子↔子/子→父的有界信箱消息(D-060 S4)。第一方信箱实现(`@agent-forge/protocol`\n * subagent mailbox)与宿主通信接线共用此形状。\n */\nexport interface SubagentInboxMessageV1 {\n\t/** 发送方子会话 id。 */\n\treadonly from: string;\n\treadonly text: string;\n}\n\n/**\n * 通信面的宿主接线(D-060 S4,与通信配置开关分离):身份绑定与血缘校验都在宿主侧,\n * capability 只暴露模型工具面。迁自宿主 `subagent-delegate.ts`(D-075 S4 第三批)。\n */\nexport interface SubagentCommunicationWiringV1 {\n\t/** 父侧:取走某子会话的 escalation 队列(有界、取后即清)。 */\n\tdrainEscalations?(sessionId: string): string[];\n\t/** 子侧:向父上抛一条有界消息(发送者身份由宿主绑定,调用方无法伪造)。 */\n\tpostEscalate?(text: string): void;\n\t/** 子侧:向同父兄弟投递一条有界消息(宿主校验双方血缘,越界同型拒绝)。 */\n\tsendSibling?(toSessionId: string, text: string): void;\n\t/** 子侧:取走自己收件箱里最早的至多 `limit` 条(取后即清)。 */\n\tdrainInbox?(limit: number): SubagentInboxMessageV1[];\n}\n\nexport interface HostCapabilities {\n\tapiVersion: typeof EXPERIMENTAL_PUBLIC_API_VERSION;\n\tmode: HostMode;\n\tfeatures: readonly string[];\n\ttransports: readonly (\"in-process\" | \"stdio\" | \"http\" | \"rpc\")[];\n\t/**\n\t * Host agent directory (D-075 S4 second batch). Present on hosts that own\n\t * an on-disk agent dir; lets plugins that keep disk state locate their\n\t * config files, e.g. `<agentDir>/capabilities/<id>.json` — the same\n\t * channel the host's embedded builtins used before the package split.\n\t * Absent on hosts without an agent dir; plugins must treat it as optional.\n\t */\n\tagentDir?: string;\n\t/**\n\t * Host service contract: absolute session working directory (the user's\n\t * project workspace). Plugins that resolve workspace-local tooling\n\t * (language servers, formatters) bind host adapters from it; absent hosts\n\t * keep such plugins fail-closed.\n\t */\n\tworkspaceDirectory?: string;\n\t/**\n\t * Subagent communication wiring (D-075 S4 third batch, host service\n\t * contract). Present on hosts that assemble a subagent mailbox for the\n\t * session's delegation domain; the first-party subagent-delegate plugin\n\t * binds its escalate/sibling tool faces to these callbacks (identity\n\t * binding and lineage scoping stay host-side). Absent = communication\n\t * tools stay unregistered (D-060 S4 default-off).\n\t */\n\tcommunication?: SubagentCommunicationWiringV1;\n\t/**\n\t * Turn-scoped host context (D-075 S4 third batch, host service contract).\n\t * `backgroundDigestSink` receives one bounded JSON line per settled\n\t * background delegation (taskId/sessionId/status/reasonCode) for the host\n\t * to inject into the parent's next model turn; `getTurnCorrelationId`\n\t * returns the correlation id of the parent turn at submission time — an\n\t * absent getter or undefined return means the lineage key is not written\n\t * and behavior falls back. Absent = background tasks still run, just\n\t * without push notification or turn-lineage attribution.\n\t */\n\tturnContext?: {\n\t\tbackgroundDigestSink?: (line: string) => void;\n\t\tgetTurnCorrelationId?: () => string | undefined;\n\t};\n\t/**\n\t * Role ids associated with the active suite (D-075 S4 third batch, host\n\t * service contract). Roles are disk-only definitions\n\t * (`<agentDir>/roles/<id>.json`); only associated ids surface in the\n\t * delegation tool menu. Absent = the session exposes no roles (there is\n\t * no built-in fallback — the engine ships none).\n\t */\n\troleAssociations?: readonly string[];\n\t/**\n\t * Memory storage components (D-075 S4 fourth batch, host service\n\t * contract). Runtime services, not just types: a host that assembles the\n\t * memory capability passes the A1/A2 storage injection face here\n\t * (store/ledger factories plus optional vector components) and the\n\t * first-party memory plugin binds them in place of its built-in\n\t * defaults. Absent = the plugin runs its default local implementation\n\t * (in-memory store + JSONL ledger under `<agentDir>/memory/`); hosts\n\t * without memory support leave it undefined and the plugin registers\n\t * nothing when no agentDir is declared.\n\t */\n\tmemoryStorage?: MemoryStorageComponentsV1;\n}\n\nexport interface DisposableRegistration {\n\tid: string;\n\tkind: string;\n\tdispose(): void | Promise<void>;\n}\n\nexport type OperationStatus = \"queued\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\" | \"timed_out\";\n\nexport interface OperationHandle<TResult = unknown> {\n\tid: string;\n\tsignal: AbortSignal;\n\tstatus(): OperationStatus;\n\tresult: Promise<TResult>;\n\tcancel(reason?: string): Promise<void>;\n}\n\n/** A detached, serializable progress fact emitted by a running operation. */\nexport interface OperationProgress {\n\tmessage?: string;\n\tdata?: PluginConfigValue;\n}\n\n/** Execution controls available to a registered Capability operation. */\nexport interface OperationExecutionContext {\n\treadonly operationId: string;\n\treadonly signal: AbortSignal;\n\t/** Returns false after cancellation, terminal settlement, or owner revoke. */\n\treportProgress(progress: OperationProgress): boolean;\n}\n\nexport interface EventEnvelope<TData = unknown> {\n\tid: string;\n\ttype: string;\n\tversion: number;\n\tsource: string;\n\ttimestamp: number;\n\tcorrelationId: string;\n\tcausationId?: string;\n\tdata: TData;\n}\n\n/** @experimental Stage 1A draft data phase for a host lifecycle event. */\nexport type LifecyclePhase = \"raw\" | \"candidate\" | \"committed\";\n\n/** @experimental Stage 1A draft registration kinds for the lifecycle directory. */\nexport type LifecycleRegistrationKind = \"observe\" | \"transform\" | \"execute\" | \"after-commit\";\n\n/** Optional host-side buffering for an observation subscription. */\nexport interface LifecycleDeliveryOptions {\n\t/** Maximum in-flight plus queued events for this one subscription. */\n\tmaxPendingEvents: number;\n\t/** Optional UTF-8 serialized-event budget for this one subscription. */\n\tmaxPendingBytes?: number;\n}\n\nexport type LifecycleDeliveryMode = \"inline\" | \"bounded-queue\";\n\n/** Read-only subscription delivery state exposed by the runtime inspector. */\nexport interface LifecycleDeliverySnapshot {\n\tmode: LifecycleDeliveryMode;\n\tmaxPendingEvents?: number;\n\tmaxPendingBytes?: number;\n\tstatus?: \"active\" | \"overflowed\" | \"closed\";\n\tpendingEvents?: number;\n\tpendingBytes?: number;\n\taccepted?: number;\n\tdelivered?: number;\n\trejected?: number;\n}\n\n/** @experimental Stage 1A draft lifecycle event definition. */\nexport interface LifecycleEventDefinition<TData = unknown> {\n\tid: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\t/** Optional additional phases accepted by multi-phase events. */\n\tallowedPhases?: readonly LifecyclePhase[];\n\tschema: string;\n\t/**\n\t * Registration kinds permitted by this event contract. Omitted keeps the\n\t * phase-compatible default for custom draft events; standard events should\n\t * declare the narrowest set they support.\n\t */\n\tallowedRegistrationKinds?: readonly LifecycleRegistrationKind[];\n\tvalidate(value: unknown): TData;\n}\n\n/** A reference accepted by lifecycle registration methods. */\nexport interface LifecycleEventReference {\n\tid: string;\n\tversion: number;\n}\n\n/** An immutable event delivered to a lifecycle handler. */\nexport interface LifecycleEvent<TData = unknown> {\n\tid: string;\n\tdeliveryId: string;\n\ttype: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\tsource: string;\n\ttimestamp: number;\n\toperationId?: string;\n\tcorrelationId?: string;\n\tcausationId?: string;\n\tdata: TData;\n}\n\n/** Input accepted by the host lifecycle dispatcher. */\nexport interface LifecycleDispatchRequest<TData = unknown> {\n\ttype: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\tdata: TData;\n\t/** Optional host cancellation fence for an in-flight lifecycle delivery. */\n\tsignal?: AbortSignal;\n\toperationId?: string;\n\tcorrelationId?: string;\n\tcausationId?: string;\n\tsource?: string;\n}\n\nexport type LifecycleObserveHandler<TData = unknown> = (\n\tevent: LifecycleEvent<TData>,\n\tsignal?: AbortSignal,\n) => void | Promise<void>;\nexport type LifecycleTransformHandler<TData = unknown> = (\n\tevent: LifecycleEvent<TData>,\n\tsignal?: AbortSignal,\n) => TData | Promise<TData>;\n/**\n * An owner-side execution step. Execution is awaited for completion but does\n * not replace the lifecycle event data; any owner result belongs to the\n * operation facade that initiated the lifecycle dispatch.\n */\nexport type LifecycleExecuteHandler<TData = unknown> = (\n\tevent: LifecycleEvent<TData>,\n\tsignal?: AbortSignal,\n) => unknown | Promise<unknown>;\nexport type LifecycleAfterCommitHandler<TData = unknown> = LifecycleObserveHandler<TData>;\n\n/** A failed lifecycle delivery, retaining the original handler error. */\nexport interface LifecycleDeliveryFailure {\n\tpluginId: string;\n\tregistrationId: string;\n\tkind: LifecycleRegistrationKind;\n\terror: unknown;\n}\n\n/** The delivery result is separate from the underlying operation or commit result. */\nexport interface LifecycleDeliveryReport {\n\teventId: string;\n\ttype: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\tstatus: \"delivered\" | \"queued\" | \"transform-failed\" | \"execute-failed\";\n\tattempted: number;\n\tsucceeded: number;\n\t/** Number accepted by detached subscriber queues, when non-zero. */\n\tqueued?: number;\n\tfailed: number;\n\tfailures: readonly LifecycleDeliveryFailure[];\n}\n\nexport interface LifecycleDispatchResult<TData = unknown> {\n\tevent: LifecycleEvent<TData>;\n\tdata: TData;\n\texecuteResults: readonly unknown[];\n\treport: LifecycleDeliveryReport;\n}\n\n/** @experimental Rejected candidate transform, with an independent delivery report. */\nexport class LifecycleTransformError extends Error {\n\treadonly report: LifecycleDeliveryReport;\n\treadonly cause: unknown;\n\n\tconstructor(cause: unknown, report: LifecycleDeliveryReport) {\n\t\tsuper(\"Lifecycle transform failed\");\n\t\tthis.name = \"LifecycleTransformError\";\n\t\tthis.cause = cause;\n\t\tthis.report = report;\n\t}\n}\n\n/** @experimental Rejected owner execution, with an independent delivery report. */\nexport class LifecycleExecuteError extends Error {\n\treadonly report: LifecycleDeliveryReport;\n\treadonly cause: unknown;\n\n\tconstructor(cause: unknown, report: LifecycleDeliveryReport) {\n\t\tsuper(\"Lifecycle execute failed\");\n\t\tthis.name = \"LifecycleExecuteError\";\n\t\tthis.cause = cause;\n\t\tthis.report = report;\n\t}\n}\n\n/** @experimental Stage 1A draft lifecycle registration facade. */\nexport interface LifecycleAPI {\n\tdefine<TData>(definition: LifecycleEventDefinition<TData>): LifecycleEventDefinition<TData>;\n\tget<TData = unknown>(id: string, version: number): LifecycleEventDefinition<TData>;\n\tregisterObserve<TData = unknown>(\n\t\tevent: LifecycleEventDefinition<TData> | LifecycleEventReference | string,\n\t\thandler: LifecycleObserveHandler<TData>,\n\t\tversion?: number,\n\t\toptions?: LifecycleDeliveryOptions,\n\t): DisposableRegistration;\n\tregisterTransform<TData = unknown>(\n\t\tevent: LifecycleEventDefinition<TData> | LifecycleEventReference | string,\n\t\thandler: LifecycleTransformHandler<TData>,\n\t\tversion?: number,\n\t): DisposableRegistration;\n\tregisterExecute<TData = unknown>(\n\t\tevent: LifecycleEventDefinition<TData> | LifecycleEventReference | string,\n\t\thandler: LifecycleExecuteHandler<TData>,\n\t\tversion?: number,\n\t): DisposableRegistration;\n\tregisterAfterCommit<TData = unknown>(\n\t\tevent: LifecycleEventDefinition<TData> | LifecycleEventReference | string,\n\t\thandler: LifecycleAfterCommitHandler<TData>,\n\t\tversion?: number,\n\t\toptions?: LifecycleDeliveryOptions,\n\t): DisposableRegistration;\n}\n\n/** @experimental Stage 1A draft lifecycle semantics for a generic contribution point. */\nexport type ContributionLifecycle = \"observe\" | \"transform\" | \"execute\" | \"after-commit\";\n\n/** @experimental Stage 1A draft contribution point declaration. */\nexport interface ContributionPointDefinition<TValue = unknown> {\n\tid: string;\n\tversion: number;\n\tschema: string;\n\tlifecycle?: ContributionLifecycle;\n\tvalidate(value: unknown): TValue;\n}\n\n/** @experimental Stage 1A draft contribution entry snapshot. */\nexport interface ContributionEntry<TValue = unknown> {\n\tid: string;\n\tpointId: string;\n\tversion: number;\n\towner: string;\n\tlifecycle: ContributionLifecycle;\n\tvalue: TValue;\n}\n\n/** @experimental Stage 1A draft contribution change notification. */\nexport interface ContributionChangeEvent<TValue = unknown> {\n\tpointId: string;\n\tversion: number;\n\taction: \"added\" | \"removed\";\n\tcontributionId: string;\n\towner: string;\n\tentry?: ContributionEntry<TValue>;\n}\n\n/** @experimental Stage 1A draft contribution lifecycle handle. */\nexport interface ContributionHandle {\n\treadonly id: string;\n\treadonly pointId: string;\n\treadonly version: number;\n\treadonly owner: string;\n\tdispose(): void | Promise<void>;\n}\n\n/** @experimental Stage 1A draft contribution point facade. */\nexport interface ContributionPoint<TValue = unknown> {\n\treadonly id: string;\n\treadonly version: number;\n\treadonly schema: string;\n\treadonly lifecycle: ContributionLifecycle;\n\tadd(input: { id: string; value: TValue }): Promise<ContributionHandle>;\n\tremove(id: string): Promise<void>;\n\tlist(): readonly ContributionEntry<TValue>[];\n\tsubscribe(handler: (event: ContributionChangeEvent<TValue>) => void | Promise<void>): DisposableRegistration;\n}\n\n/** @experimental Stage 1A draft contribution registry facade. */\nexport interface ContributionAPI {\n\tdefine<TValue>(definition: ContributionPointDefinition<TValue>): ContributionPoint<TValue>;\n\tget<TValue = unknown>(id: string, version: number): ContributionPoint<TValue>;\n\tlist(): readonly { id: string; version: number; schema: string; lifecycle: ContributionLifecycle; owner: string }[];\n}\n\nexport type LoggerLevel = \"debug\" | \"info\" | \"warn\" | \"error\";\n\nexport interface LoggerRecord {\n\tversion: 1;\n\tlevel: LoggerLevel;\n\tmessage: string;\n\tfields?: PluginConfigValue;\n\tcause?: unknown;\n\tpluginId: string;\n\ttimestamp: number;\n\tsessionId?: string;\n\toperationId?: string;\n\tcorrelationId?: string;\n\tphase?: string;\n}\n\nexport interface LoggerAPI {\n\tdebug(message: string, fields?: PluginConfigValue): void;\n\tinfo(message: string, fields?: PluginConfigValue): void;\n\twarn(message: string, fields?: PluginConfigValue): void;\n\terror(message: string, fields?: PluginConfigValue, cause?: unknown): void;\n}\n\nexport interface DiagnosticsSpanEnd {\n\tstatus: \"ok\" | \"error\" | \"cancelled\";\n\tresult?: PluginConfigValue;\n\tcause?: unknown;\n}\n\nexport interface DiagnosticsSpanSnapshot {\n\tversion: 1;\n\ttraceId: string;\n\tspanId: string;\n\tparentSpanId?: string;\n\tname: string;\n\tpluginId: string;\n\tsessionId?: string;\n\tstartedAt: number;\n\tendedAt?: number;\n\tstatus: \"running\" | \"ok\" | \"error\" | \"cancelled\";\n\tattributes: PluginConfigValue;\n\tresult?: PluginConfigValue;\n\tcause?: unknown;\n\toperationId?: string;\n\tcorrelationId?: string;\n\tphase?: string;\n}\n\nexport interface DiagnosticsSpan {\n\treadonly traceId: string;\n\treadonly spanId: string;\n\tannotate(fields: PluginConfigValue): void;\n\tend(outcome?: DiagnosticsSpanEnd): void;\n}\n\nexport interface DiagnosticsAPI {\n\tstart(name: string, attributes?: PluginConfigValue, parentSpanId?: string): DiagnosticsSpan;\n}\n\n/** @experimental Read-only runtime plugin facts exposed by the inspector. */\nexport interface RuntimeInspectorPluginSnapshot {\n\tid: string;\n\tversion: string;\n\tactive: boolean;\n\tmanifest: PluginManifest;\n\tprovides: readonly PluginCapabilityDeclaration[];\n\trequires: readonly PluginCapabilityRequirement[];\n}\n\n/** @experimental Read-only contribution entry facts exposed by the inspector. */\nexport interface RuntimeInspectorContributionSnapshot {\n\tid: string;\n\tpointId: string;\n\tversion: number;\n\towner: string;\n\tlifecycle: ContributionLifecycle;\n\tvalue: unknown;\n}\n\n/** @experimental Read-only contribution point facts exposed by the inspector. */\nexport interface RuntimeInspectorContributionPointSnapshot {\n\tid: string;\n\tversion: number;\n\tschema: string;\n\tlifecycle: ContributionLifecycle;\n\towner: string;\n\tactive: boolean;\n}\n\n/** @experimental Read-only lifecycle registration facts exposed by the inspector. */\nexport interface RuntimeInspectorLifecycleRegistrationSnapshot {\n\tid: string;\n\tkind: LifecycleRegistrationKind;\n\towner: string;\n\tactive: boolean;\n\tdelivery: LifecycleDeliverySnapshot;\n}\n\n/** @experimental Read-only lifecycle event facts exposed by the inspector. */\nexport interface RuntimeInspectorLifecycleSnapshot {\n\tid: string;\n\tversion: number;\n\tphase: LifecyclePhase;\n\tallowedPhases?: readonly LifecyclePhase[];\n\tschema: string;\n\towner: string;\n\tactive: boolean;\n\tregistrations: readonly RuntimeInspectorLifecycleRegistrationSnapshot[];\n}\n\n/** Immutable error facts retained by the runtime inspector. */\nexport interface RuntimeInspectorErrorSnapshot {\n\treadonly name: string;\n\treadonly message: string;\n\treadonly cause?: RuntimeInspectorErrorSnapshot;\n\treadonly code?: string;\n}\n\n/** A normalized lifecycle delivery failure suitable for an immutable inspector snapshot. */\nexport interface RuntimeInspectorLifecycleDeliveryFailureSnapshot {\n\treadonly pluginId: string;\n\treadonly registrationId: string;\n\treadonly kind: LifecycleRegistrationKind;\n\treadonly error: RuntimeInspectorErrorSnapshot;\n}\n\n/** A bounded, immutable record of one completed lifecycle delivery. */\nexport interface RuntimeInspectorLifecycleDeliveryReportSnapshot {\n\treadonly eventId: string;\n\treadonly type: string;\n\treadonly version: number;\n\treadonly phase: LifecyclePhase;\n\treadonly status: LifecycleDeliveryReport[\"status\"];\n\treadonly attempted: number;\n\treadonly succeeded: number;\n\treadonly queued?: number;\n\treadonly failed: number;\n\treadonly completedAt: number;\n\treadonly failures: readonly RuntimeInspectorLifecycleDeliveryFailureSnapshot[];\n}\n\n/**\n * Reason a discovered capability plugin was rejected during session startup\n * without preventing the remaining plugins from loading (D-028).\n */\nexport type PluginRejectionCode =\n\t| \"invalid_manifest\"\n\t| \"host_version_incompatible\"\n\t| \"duplicate_plugin_id\"\n\t| \"missing_dependency\"\n\t| \"plugin_load_failed\";\n\n/** Structured, immutable record of one rejected capability plugin. */\nexport interface PluginRejection {\n\treadonly code: PluginRejectionCode;\n\treadonly manifestPath: string;\n\treadonly pluginId?: string;\n\treadonly message: string;\n}\n\nexport interface RuntimeInspectorSnapshot {\n\tversion: 1;\n\thost: HostCapabilities;\n\tplugins: readonly RuntimeInspectorPluginSnapshot[];\n\tpluginRejections: readonly PluginRejection[];\n\tregistrations: readonly { kind: string; name: string; owner: string }[];\n\tcontributionPoints: readonly RuntimeInspectorContributionPointSnapshot[];\n\tcontributions: readonly RuntimeInspectorContributionSnapshot[];\n\tlifecycle: readonly RuntimeInspectorLifecycleSnapshot[];\n\tlifecycleReports: readonly RuntimeInspectorLifecycleDeliveryReportSnapshot[];\n\tsubscriptions: readonly { id: string; type: string; owner: string }[];\n\toperations: readonly { id: string; status: OperationStatus }[];\n\tlogs: readonly LoggerRecord[];\n\tspans: readonly DiagnosticsSpanSnapshot[];\n}\n\nexport interface RuntimeInspectorAPI {\n\tsnapshot(): RuntimeInspectorSnapshot;\n}\n\nexport interface StateEntry {\n\tkey: string;\n\trevision: number;\n\tvalue: PluginConfigValue;\n}\n\nexport interface StateSetOptions {\n\texpectedRevision?: number;\n\toperationId?: string;\n\tcorrelationId?: string;\n}\n\nexport interface StateChange {\n\t/** Stable owner namespace that produced this state transition. */\n\tpluginId: string;\n\tkey: string;\n\trevision: number;\n\tvalue?: PluginConfigValue;\n\toperationId?: string;\n\tcorrelationId?: string;\n}\n\nexport interface StateAPI {\n\tget(key: string): StateEntry | undefined;\n\tset(key: string, value: PluginConfigValue, options?: StateSetOptions): number;\n\tdelete(key: string, options?: StateSetOptions): number;\n\tlist(prefix?: string): readonly StateEntry[];\n\twatch(prefix: string | undefined, handler: (change: StateChange) => void): DisposableRegistration;\n}\n\n/** A branch-local, append-only view for plugins that persist their own state. */\nexport interface SessionEntryView {\n\tid: string;\n\tparentId: string | null;\n\ttimestamp: string;\n\ttype: string;\n\t/** Structured message view carried by `type: \"message\"` entries only. */\n\tmessage?: SessionEntryMessageView;\n\tcustomType?: string;\n\tdata?: unknown;\n}\n\n/**\n * Minimal structured projection of a message entry: only the fields consumers\n * actually branch on (role/content). The host projects these instead of the\n * full internal message so the view stays a stable public contract.\n */\nexport interface SessionEntryMessageView {\n\trole: string;\n\tcontent?: unknown;\n}\n\n/** Snapshot of a tool/command registration source, mirroring the core SourceInfo fields. */\nexport interface SourceInfoViewV1 {\n\tpath: string;\n\tsource: string;\n\tscope: \"user\" | \"project\" | \"temporary\";\n\torigin: \"package\" | \"top-level\";\n\tbaseDir?: string;\n}\n\n/** Tool enumeration entry: name, description, JSON-schema parameters, prompt guidelines, and source metadata. */\nexport interface ToolInfoViewV1 {\n\tname: string;\n\tdescription: string;\n\t/** Parameter schema as declared on the tool definition (TypeBox). */\n\tparameters: unknown;\n\tpromptGuidelines?: readonly string[];\n\tsourceInfo: SourceInfoViewV1;\n}\n\nexport type CommandSourceViewV1 = \"extension\" | \"prompt\" | \"skill\";\n\n/** Slash command enumeration entry across extension, prompt-template, and skill sources. */\nexport interface CommandInfoViewV1 {\n\tname: string;\n\tdescription?: string;\n\tsource: CommandSourceViewV1;\n\tsourceInfo: SourceInfoViewV1;\n}\n\n/** Provider-agnostic facts about a model, mirroring the modelRuntime.getModelFacts projection. */\nexport interface ModelFactsViewV1 {\n\tprovider: string;\n\tid: string;\n\tcontextWindow: number;\n\tmaxTokens: number;\n\treasoning: boolean;\n}\n\n/** Scoped model entry: model facts plus the pattern's explicit thinking level, if any. */\nexport interface ScopedModelFactsViewV1 {\n\tmodel: ModelFactsViewV1;\n\tthinkingLevel?: ThinkingLevel;\n}\n\n/** A versioned, in-memory export of the current session branch. */\nexport interface SessionExportArtifact {\n\tversion: 1;\n\tformat: \"jsonl\";\n\tmediaType: \"application/x-ndjson\";\n\tfileName: string;\n\tbytes: Uint8Array;\n}\n\nexport interface SessionExportRequest {\n\tformat: SessionExportArtifact[\"format\"];\n}\n\n/** Versioned, opaque session fact for optimistic host operations. */\nexport interface SessionRevisionV1 {\n\tversion: 1;\n\tsessionId: string;\n\tsequence: number;\n\tleafId: string | null;\n}\n\n/**\n * One serializable, optimistic request to append a compaction entry.\n *\n * The host owns the commit decision. This value only carries the immutable\n * facts that make retries and stale work observable to the host.\n */\nexport interface CompactionCommitRequestV1<TDetails = unknown> {\n\tversion: 1;\n\toperationId: string;\n\texpectedRevision: SessionRevisionV1;\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tdetails?: TDetails;\n\tfromHook?: boolean;\n\tusage?: unknown;\n}\n\nexport interface CompactionCommitAppliedV1 {\n\tversion: 1;\n\tstatus: \"committed\" | \"replayed\";\n\tentryId: string;\n\t/** The revision produced by the original successful commit. */\n\trevision: SessionRevisionV1;\n}\n\nexport interface CompactionCommitRevisionConflictV1 {\n\tversion: 1;\n\tstatus: \"revision_conflict\";\n\tcurrentRevision: SessionRevisionV1;\n}\n\nexport type CompactionCommitResultV1 = CompactionCommitAppliedV1 | CompactionCommitRevisionConflictV1;\n\n/** A versioned execution boundary supplied by the host to an orchestration plugin. */\nexport type ExecutionPhaseV1 = \"agent\" | \"compaction\" | \"overflow\" | \"retry\" | \"branch_summary\" | \"reload\" | \"tree\";\n\n/**\n * Immutable input facts for a single host operation. These facts identify an\n * optimistic commit boundary; they do not themselves grant commit authority.\n */\nexport interface ExecutionFactsV1 {\n\treadonly version: 1;\n\treadonly operationId: string;\n\treadonly sessionId: string;\n\treadonly inputRevision: SessionRevisionV1;\n\treadonly phase: ExecutionPhaseV1;\n}\n\n/** A validated retry outcome attached to one immutable execution boundary. */\nexport interface RetryScheduleV1 extends ExecutionFactsV1 {\n\treadonly action: \"retry\" | \"stop\";\n\t/** `retry` is one-based; `stop` records the number of attempts already made. */\n\treadonly attempt: number;\n\t/** A `stop` action must not request a delay. */\n\treadonly delayMs: number;\n}\n\nexport type CapabilityProviderHandler<TInput = unknown, TResult = unknown> = (\n\tinput: TInput,\n\tcontext: { signal: AbortSignal },\n) => TResult | Promise<TResult>;\n\nexport interface CapabilityHandle<TResult = unknown> {\n\treadonly declaration: PluginCapabilityDeclaration;\n\treadonly owner: string;\n\tcall(input: unknown, options?: { signal?: AbortSignal }): OperationHandle<TResult>;\n}\n\nexport interface CapabilityDirectoryAPI {\n\tprovide<TInput = unknown, TResult = unknown>(\n\t\tdeclaration: PluginCapabilityDeclaration,\n\t\thandler: CapabilityProviderHandler<TInput, TResult>,\n\t): DisposableRegistration;\n\trequire<TResult = unknown>(id: string, options?: { version?: number }): CapabilityHandle<TResult>;\n\tlist(options?: { kind?: PluginCapabilityDeclaration[\"kind\"] }): readonly {\n\t\tdeclaration: PluginCapabilityDeclaration;\n\t\towner: string;\n\t}[];\n}\n\nexport interface OutputArtifactRef {\n\tsessionId: string;\n\toperationId: string;\n\tartifactId: string;\n\tkind: string;\n\tmediaType: string;\n\tsizeBytes?: number;\n\ttruncated: boolean;\n\tcreatedAt: number;\n}\n\nexport interface OutputArtifactChunk {\n\tdata: Uint8Array;\n\tnextOffset?: number;\n\teof: boolean;\n}\n\nexport type OutputArtifactErrorCode = \"invalid_ref\" | \"not_found\" | \"cancelled\";\n\nexport type OutputArtifactPutInput = Omit<OutputArtifactRef, \"artifactId\" | \"sizeBytes\" | \"createdAt\"> & {\n\tdata: Uint8Array | AsyncIterable<Uint8Array>;\n};\n\nexport interface OutputArtifactAPI {\n\tput(input: OutputArtifactPutInput, options?: { signal?: AbortSignal }): Promise<OutputArtifactRef>;\n\tstat(ref: OutputArtifactRef): Promise<OutputArtifactRef>;\n\tread(ref: OutputArtifactRef, options?: { offset?: number; maxBytes?: number }): Promise<OutputArtifactChunk>;\n}\n\nexport interface CredentialResolveRequest {\n\tproviderId: string;\n\tminValidityMs?: number;\n\tsignal?: AbortSignal;\n}\n\n/** Resolved provider auth facts for a plugin's explicit request. */\nexport interface CredentialResolution {\n\tapiKey?: string;\n\theaders: Readonly<Record<string, string | null>>;\n\tbaseUrl?: string;\n\tsource?: string;\n}\n\nexport interface CredentialAPI {\n\tresolve(request: CredentialResolveRequest): Promise<CredentialResolution | undefined>;\n}\n\n/**\n * Structural skill shape accepted by {@link BuildSystemPromptOptions.skills}\n * (D-075 S2). The host's full `Skill` type carries host-owned source facts;\n * host skill objects are structurally assignable to this projection.\n */\nexport interface BuildSystemPromptSkill {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tsourceInfo: unknown;\n\tdisableModelInvocation: boolean;\n}\n\n/**\n * System prompt assembly options (authority moved from the host's\n * `core/system-prompt.ts`, D-075 S2; the host re-exports it from here).\n */\nexport interface BuildSystemPromptOptions {\n\t/** Custom system prompt (replaces default). */\n\tcustomPrompt?: string;\n\t/**\n\t * Session-nature orientation text (suite persona, 设计 §6.2) injected right\n\t * after the opening paragraph (customPrompt branch: right after the custom\n\t * prompt body), before tools, guidelines, and context files.\n\t */\n\torientationPrompt?: string;\n\t/**\n\t * Assistant preference card (统一修复轮 A 交付3, H2 接线): the durable\n\t * user-profile card, injected immediately after the orientation section\n\t * (same M2 pattern — it can also appear alone when no persona is set),\n\t * before tools, guidelines, and context files.\n\t */\n\tpreferenceCard?: string;\n\t/** Tools to include in prompt. Default: [read, bash, edit, write] */\n\tselectedTools?: string[];\n\t/** Optional one-line tool snippets keyed by tool name. */\n\ttoolSnippets?: Record<string, string>;\n\t/** Additional guideline bullets appended to the default system prompt guidelines. */\n\tpromptGuidelines?: string[];\n\t/** Text to append to system prompt. */\n\tappendSystemPrompt?: string;\n\t/** Working directory. */\n\tcwd: string;\n\t/** Pre-loaded context files. */\n\tcontextFiles?: Array<{ path: string; content: string }>;\n\t/** Pre-loaded skills. */\n\tskills?: readonly BuildSystemPromptSkill[];\n}\n\n/**\n * Public session mechanism. Product state remains plugin-owned and is written\n * as append-only custom entries, so a plugin never mutates SessionManager\n * internals or another branch's history.\n */\n/**\n * Terminal outcome of a prompt run. User-initiated aborts are normal outcomes:\n * the promise resolves with `status: \"aborted\"` instead of rejecting.\n */\nexport type PromptOutcome = { status: \"done\" } | { status: \"aborted\"; reason: \"interrupted\" | \"replaced\" };\n\n/**\n * Content accepted by {@link SessionAPI.sendMessage}. Verbatim structural\n * equivalent of the host's `sendCustomMessage` content type (`TextContent` /\n * `ImageContent`), registered inline so this contract does not depend on\n * `@agent-forge/ai`.\n */\nexport type SessionMessageContent =\n\t| string\n\t| ({ type: \"text\"; text: string; textSignature?: string } | { type: \"image\"; data: string; mimeType: string })[];\n\nexport interface SessionAPI {\n\tgetSessionId(): string;\n\t/**\n\t * 会话**自身**的身份(D-060 S1)。当宿主可见的 `getSessionId()` 是一个宿主侧标识\n\t * (池化 runner 下是 wire 任务 id)时,本成员给出底层 agent 会话的真实 id;缺省表示\n\t * 两者相同(shared 模式即如此)。\n\t */\n\tgetAgentSessionId?(): string;\n\t/** Available on hosts that expose revision facts; required by future commit APIs. */\n\tgetRevision?: () => SessionRevisionV1;\n\t/** Optional immutable context projection for operation-scoped Agent hosts. */\n\tgetContextSnapshot?: <TValue = unknown>() => AgentContextSnapshotV1<TValue>;\n\t/** Optional revision-checked context commit for operation-scoped Agent hosts. */\n\tcommitContext?: <TValue = unknown>(\n\t\trequest: AgentContextCommitRequestV1<TValue>,\n\t) => Promise<AgentContextCommitResultV1<TValue>>;\n\tgetMessages(): readonly unknown[];\n\tisIdle(): boolean;\n\tprompt(text: string): Promise<PromptOutcome>;\n\t/** Queue a steering message when the host session is running. */\n\tsteer?(text: string): Promise<void>;\n\t/** Experimental: queue a follow-up message that waits for the active run instead of interrupting it. */\n\tqueueFollowUp?(text: string): Promise<void>;\n\tabort(): Promise<void>;\n\twaitForIdle(): Promise<void>;\n\t/** Current active (prompt-visible) tool names. Available on hosts that expose the tool registry. */\n\tgetActiveTools?(): string[];\n\t/** Replace the active tool set by name; names not in the registry are ignored. */\n\tsetActiveTools?(toolNames: string[]): void;\n\t/** Experimental (R3 tool-enumeration slice): all configured tools with name, description, parameter schema, prompt guidelines, and source metadata. */\n\tgetAllTools?(): readonly ToolInfoViewV1[];\n\t/**\n\t * Registers a GENERIC entry projection on the underlying session\n\t * (see {@link EntryProjection}). Optional: hosts without session-entry\n\t * projection support reject the registration with a visible error.\n\t * Returns a disposer that removes the projection.\n\t */\n\tregisterEntryProjection?(projection: EntryProjection): () => void;\n\t/** Experimental (R3 tool-enumeration slice): slash command enumeration across extension, prompt-template, and skill sources. */\n\tgetCommands?(): readonly CommandInfoViewV1[];\n\t/** Experimental (R3 model-domain slice): provider-agnostic facts about the current session model. */\n\tgetModel?(): ModelFactsViewV1 | undefined;\n\t/** Experimental (R3 model-domain slice): scoped model facts with their explicit thinking levels. */\n\tgetScopedModels?(): readonly ScopedModelFactsViewV1[];\n\t/** Experimental (R3 model-domain slice): current thinking level. */\n\tgetThinkingLevel?(): ThinkingLevel;\n\t/** Experimental (R3 model-domain slice): set the thinking level. */\n\tsetThinkingLevel?(level: ThinkingLevel): void;\n\t/** Experimental (R3 model-domain slice): set the session model by id (resolved against the scoped models). Resolves to false when the id is unknown or auth is not configured. */\n\tsetModel?(modelId: string): Promise<boolean>;\n\t/** Experimental (R3 prompt-facts slice): the current system prompt. */\n\tgetSystemPrompt?(): string;\n\t/** Experimental (R3 prompt-facts slice): the system prompt assembly options. */\n\tgetSystemPromptOptions?(): BuildSystemPromptOptions;\n\t/** Experimental (context-facts slice): estimated usage of the current context; undefined when the host cannot measure it. */\n\tgetContextUsage?(): ContextUsage | undefined;\n\t/**\n\t * Experimental: inject a custom message into the session. Verbatim passthrough of\n\t * AgentSession.sendCustomMessage (without deliverAs): streamed hosts steer with it,\n\t * idle hosts append it, and `options.triggerTurn` starts a new turn.\n\t */\n\tsendMessage?(\n\t\tmessage: { customType: string; content: SessionMessageContent; display: boolean },\n\t\toptions?: { triggerTurn?: boolean },\n\t): Promise<void>;\n\tcompact?(customInstructions?: string): Promise<unknown>;\n\tnavigateTree?(\n\t\ttargetId: string,\n\t\toptions?: {\n\t\t\tsummarize?: boolean;\n\t\t\tcustomInstructions?: string;\n\t\t\treplaceInstructions?: boolean;\n\t\t\tlabel?: string;\n\t\t},\n\t): Promise<unknown>;\n\tappendEntry(customType: string, data?: unknown): string;\n\t/** Experimental (R3 session-metadata slice): renames the session. Delegates to AgentSession.setSessionName. */\n\tsetSessionName?(name: string): void;\n\t/** Experimental (R3 session-metadata slice): current session display name. */\n\tgetSessionName?(): string | undefined;\n\t/** Experimental (R3 session-metadata slice): appends a label-change entry; returns the new entry id. Mirrors facade appendLabelChange. */\n\tsetLabel?(entryId: string, label: string | undefined): string;\n\t/** Experimental (R3 session-metadata slice): current label of the branch entry. */\n\tgetLabel?(entryId: string): string | undefined;\n\tgetBranchEntries(): readonly SessionEntryView[];\n\t/** Available when the host declares the `session-export` feature. */\n\texportArtifact?(request: SessionExportRequest): SessionExportArtifact;\n}\n\n/** A session view scoped to one AgentInstance execution. */\nexport interface AgentSessionFacadeV1 {\n\treadonly version: 1;\n\tgetSessionId(): string;\n\tgetRevision?(): SessionRevisionV1;\n\tgetMessages(): readonly unknown[];\n\tgetBranchEntries(): readonly SessionEntryView[];\n\tisIdle(): boolean;\n\tprompt?(text: string): Promise<PromptOutcome>;\n\t/** Queue a steering message when the host session is running. */\n\tsteer?(text: string): Promise<void>;\n\tabort?(): Promise<void>;\n\twaitForIdle(): Promise<void>;\n\tappendEntry(customType: string, data?: unknown): string;\n}\n\n/** Immutable context value returned by an Agent host. */\nexport interface AgentContextSnapshotV1<TValue = unknown> {\n\treadonly version: 1;\n\treadonly revision: number;\n\treadonly value: TValue;\n}\n\nexport interface AgentContextCommitRequestV1<TValue = unknown> {\n\treadonly version: 1;\n\treadonly operationId: string;\n\treadonly expectedRevision: number;\n\treadonly value: TValue;\n\tsignal?: AbortSignal;\n}\n\nexport interface AgentContextCommitResultV1<TValue = unknown> {\n\treadonly version: 1;\n\treadonly status: \"committed\" | \"replayed\";\n\treadonly revision: number;\n\treadonly value: TValue;\n}\n\n/** Per-instance context snapshot/commit boundary. */\nexport interface AgentContextFacadeV1 {\n\treadonly version: 1;\n\tget<TValue = unknown>(): AgentContextSnapshotV1<TValue>;\n\tcommit<TValue = unknown>(request: AgentContextCommitRequestV1<TValue>): Promise<AgentContextCommitResultV1<TValue>>;\n}\n\n/** Operation facts and cancellation boundary visible to an AgentDefinition. */\nexport interface AgentOperationFacadeV1 {\n\treadonly version: 1;\n\treadonly id: string;\n\treadonly signal: AbortSignal;\n\tstatus(): OperationStatus;\n\tisActive(): boolean;\n\treportProgress(progress: OperationProgress): boolean;\n\tonCancel(handler: (reason: unknown) => void | Promise<void>): DisposableRegistration;\n\tcancel(reason?: string): Promise<void>;\n}\n\n/**\n * Optional, host-injected primitives for one AgentDefinition execution.\n * Implementations are scoped to the active operation and become revoked once\n * that operation is cancelled, completes, or its controller lease is released.\n */\nexport interface AgentHostPrimitivesV1 {\n\treadonly version: 1;\n\treadonly session?: AgentSessionFacadeV1;\n\treadonly context?: AgentContextFacadeV1;\n\treadonly state?: StateAPI;\n\t/**\n\t * Instance-private StateAPI view for this Agent instance execution only.\n\t * Same shape and semantics as `state` (CAS, detached snapshots, watchers),\n\t * but scoped to `owner + instanceId`: invisible to sibling instances and to\n\t * the owner namespace. Runtime-memory scoped; cleared on instance dispose;\n\t * not restored on rebuild.\n\t */\n\treadonly instanceState?: StateAPI;\n\treadonly artifact?: OutputArtifactAPI;\n\treadonly operation?: AgentOperationFacadeV1;\n\t/** Agent-only host model binding. */\n\treadonly model?: AgentModelFacadeV1;\n\t/** Agent-only host tool binding. */\n\treadonly tool?: AgentToolFacadeV1;\n}\n\n/**\n * Model facts and invoke surface bound to one Agent instance execution.\n *\n * `facts` carries provider-agnostic model metadata; `invocation` is a\n * single-shot completion boundary — the host resolves auth, transport and\n * cache routing, and provider internals never cross to the plugin. Each\n * invoke is exactly one completion without tools or session state.\n */\nexport interface AgentModelFacadeV1 {\n\treadonly version: 1;\n\t/** Provider-agnostic facts about the current session model. */\n\treadonly facts: AgentModelFactsV1;\n\t/** Single-shot completion boundary. */\n\treadonly invocation: AgentModelInvocationV1;\n}\n\n/** Provider-agnostic facts about the model the host will use for model calls. */\nexport interface AgentModelFactsV1 {\n\treadonly provider: string;\n\treadonly id: string;\n\treadonly contextWindow: number;\n\treadonly maxTokens: number;\n\treadonly reasoning: boolean;\n}\n\nexport interface AgentModelInvocationRequestV1 {\n\treadonly version: 1;\n\treadonly systemPrompt?: string;\n\treadonly prompt: string;\n\treadonly maxTokens?: number;\n\treadonly thinkingLevel?: ThinkingLevel;\n}\n\nexport type AgentModelInvocationResultV1 =\n\t| { readonly version: 1; readonly status: \"completed\"; readonly text: string; readonly usage?: unknown }\n\t| { readonly version: 1; readonly status: \"aborted\" }\n\t| {\n\t\t\treadonly version: 1;\n\t\t\treadonly status: \"failed\";\n\t\t\treadonly error: { readonly code: string; readonly message: string };\n\t };\n\nexport interface AgentModelInvocationV1 {\n\treadonly invoke: (\n\t\tinput: AgentModelInvocationRequestV1,\n\t\tsignal: AbortSignal,\n\t) => Promise<AgentModelInvocationResultV1>;\n}\n\n/**\n * Tool invocation surface bound to one Agent instance execution. The plugin\n * can list and invoke tools registered in the CapabilityRuntime without\n * importing internal execution paths.\n */\nexport interface AgentToolFacadeV1 {\n\treadonly version: 1;\n\t/** Tool definitions keyed by name (definition + source per tool). */\n\treadonly listTools: () => readonly {\n\t\treadonly name: string;\n\t\treadonly definition: unknown;\n\t\treadonly source: string;\n\t\t/** Owning-plugin readonly-mode declaration (宪法 §6), read off the definition. */\n\t\treadonly readonlySafe: boolean;\n\t}[];\n\t/** Invoke a registered tool by name. */\n\tinvokeTool: (name: string, input: unknown, options?: { readonly signal?: AbortSignal }) => Promise<unknown>;\n}\n\nexport interface AgentHostPrimitivesFactoryContext {\n\treadonly instance: AgentInstanceSnapshot;\n\treadonly operationId: string;\n\treadonly signal: AbortSignal;\n\treadonly leaseOwner: string;\n}\n\nexport type AgentHostPrimitivesFactory = (\n\tcontext: AgentHostPrimitivesFactoryContext,\n) => AgentHostPrimitivesV1 | undefined | Promise<AgentHostPrimitivesV1 | undefined>;\n\n/**\n * A slash command declared by a capability plugin. Names omit the leading\n * slash so every host can render and route the same command metadata.\n */\nexport interface CapabilityCommandDefinition {\n\tname: string;\n\tdescription: string;\n\targumentHint?: string;\n\texecute(\n\t\targs: string,\n\t\tcontext: CapabilityCommandContext,\n\t): CapabilityCommandResult | undefined | Promise<CapabilityCommandResult | undefined>;\n}\n\nexport interface CapabilityCommandContext {\n\tsignal: AbortSignal;\n\t/** Experimental: the session working directory, for commands that need cwd facts. */\n\tcwd?: string;\n}\n\n/**\n * Experimental: second argument the runtime invoke face passes to a capability\n * tool's execute (additive; existing single-parameter tools are unaffected).\n * The host injects the session working directory through\n * CapabilityRuntimeOptions.toolExecutionContext; without that injection the\n * argument stays undefined. Mirrors CapabilityCommandContext.cwd.\n */\nexport interface CapabilityToolContext {\n\t/** Experimental: the session working directory, mirroring CapabilityCommandContext.cwd. */\n\tcwd?: string;\n}\n\nexport interface CapabilityCommandLink {\n\tlabel: string;\n\turl: string;\n}\n\n/** Host-independent, serializable result returned by a capability command. */\nexport interface CapabilityCommandResult {\n\tstatus: \"success\" | \"error\";\n\tmessage: string;\n\tlinks?: readonly CapabilityCommandLink[];\n\tdata?: PluginConfigValue;\n}\n\nexport type AgentTaskStatus = \"created\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\";\n\nexport interface AgentTaskCreateRequest {\n\tprompt: string;\n\tmetadata?: Record<string, unknown>;\n}\n\n/**\n * 子任务档案(child task profile)——版本化的公共契约,经\n * `AgentTaskCreateRequest.metadata[AGENT_TASK_CHILD_PROFILE_KEY]` 传递。\n *\n * 用途:调用方(如子代理角色)要求宿主在**创建子会话时**收窄它的模型 / 思考级别 /\n * 工具面 / 会话模式,或给子会话追加一段系统提示词。所有字段都是\"收窄\"语义:工具面只会\n * 被裁到更小(与宿主自身继承面求交),模式只能更严(`readonly` 不会被放宽)。\n *\n * 契约义务(宿主 adapter 侧):\n * - 支持的宿主必须落地这些字段,并在 `AgentTaskHandle.session` 上暴露可核验事实\n * (`getActiveTools` / `getModel`)——调用方据此确认\"要求已生效\",而不是相信约定;\n * - 不支持的宿主**不得静默忽略**:应让 `create` 失败(结构化错误指名字段),因为静默\n * 忽略会让上层的\"只读评审者\"变成一句空话。\n */\nexport const AGENT_TASK_CHILD_PROFILE_KEY = \"agent-forge.agentTaskChildProfile\" as const;\n\n/**\n * metadata 键:发起 create 的**父 agent 会话 id**(D-060 S1 血缘)。宿主把它写进子会话文件头\n * 的 `parentAgentSession`,池化下随协议 `create` 过线;读取方据此做父作用域校验与按父反查。\n */\nexport const AGENT_TASK_PARENT_SESSION_KEY = \"agent-forge.agentTaskParentSession\" as const;\n\n/**\n * metadata 键:创建子会话的父回合 correlationId(第 3 期第二批,委派提交时刻捕获)。\n * 契约义务(宿主 adapter 侧):**仅 create 新建子会话消费**——宿主 adapter 读取该键并传入\n * `NewSessionOptions.parentTraceId`;resume 打开既有会话不适用(`SessionHeader.parentTraceId`\n * 随头定格,不重写)。shared 模式 embedder adapter 不读取时行为安全降级(子轨迹缺\n * parentTraceId,无回归)。\n */\nexport const AGENT_TASK_PARENT_TRACE_KEY = \"agent-forge.agentTaskParentTrace\" as const;\n\n/**\n * metadata 键:resume 目标的子会话 id(D-060 S4)。宿主据此**打开既有会话文件**继续跑\n * (同一份 JSONL 续写,形成多轮子任务),而不是新建会话。宿主必须核验文件头\n * `parentAgentSession` 等于发起方父会话 id,否则结构化拒绝——越界与不存在同型。\n */\nexport const AGENT_TASK_RESUME_SESSION_KEY = \"agent-forge.agentTaskResumeSession\" as const;\n\nexport interface AgentTaskChildProfileV1 {\n\treadonly version: 1;\n\t/** 目标模型 id:必须能在父会话的 scoped models 里解析,否则 create 失败并列出可用 id。 */\n\treadonly model?: string;\n\t/** 思考级别(minimal/low/medium/high/xhigh/max);越界值 create 失败。 */\n\treadonly thinkingLevel?: string;\n\t/** 工具面白名单:与宿主继承面求交;空数组表示\"一个工具都不给\"。 */\n\treadonly tools?: readonly string[];\n\t/** 会话模式:`readonly` 只收窄不放宽(父会话已是 readonly 时保持 readonly)。 */\n\treadonly mode?: \"readonly\" | \"full-control\";\n\t/** 追加到子会话 system prompt 末尾的文本(不替换继承来的系统提示词)。 */\n\treadonly systemPromptAppend?: string;\n\t/**\n\t * 创建该子会话的角色 id(血缘/审计用途,写进子会话文件头;**不是权限判据**,也不参与收窄)。\n\t * 由子代理能力从角色定义注入;手工构造档案的调用方可以省略。\n\t */\n\treadonly roleId?: string;\n}\n\n/** 档案解析结果:合法则给出规范化副本,否则给出可直接回给调用方的原因。 */\nexport type AgentTaskChildProfileParseResultV1 =\n\t| { readonly ok: true; readonly profile: AgentTaskChildProfileV1 }\n\t| { readonly ok: false; readonly message: string };\n\nconst CHILD_PROFILE_KEYS = [\n\t\"version\",\n\t\"model\",\n\t\"thinkingLevel\",\n\t\"tools\",\n\t\"mode\",\n\t\"systemPromptAppend\",\n\t\"roleId\",\n] as const;\nconst CHILD_PROFILE_TOOL_LIMIT = 64;\nconst CHILD_PROFILE_APPEND_CHARS = 8000;\nconst CHILD_PROFILE_THINKING_LEVELS: readonly string[] = [\"minimal\", \"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\n/**\n * 解析并校验一份子任务档案:类型/取值范围/未知键都在这里拦下,错误文本指名键,\n * 由调用方决定是本地失败还是回给上层(子代理能力把它变成条目级 rejected)。\n */\nexport function parseAgentTaskChildProfileV1(value: unknown): AgentTaskChildProfileParseResultV1 {\n\tif (value === null || typeof value !== \"object\" || Array.isArray(value)) {\n\t\treturn { ok: false, message: \"child task profile must be an object\" };\n\t}\n\tconst record = value as Record<string, unknown>;\n\tfor (const key of Object.keys(record)) {\n\t\tif (!(CHILD_PROFILE_KEYS as readonly string[]).includes(key)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: `child task profile has unknown key ${JSON.stringify(key)} (known: ${CHILD_PROFILE_KEYS.join(\", \")})`,\n\t\t\t};\n\t\t}\n\t}\n\tif (record.version !== 1) {\n\t\treturn { ok: false, message: `child task profile version must be 1, found ${JSON.stringify(record.version)}` };\n\t}\n\tlet model: string | undefined;\n\tif (record.model !== undefined) {\n\t\tif (typeof record.model !== \"string\" || record.model.trim() === \"\") {\n\t\t\treturn { ok: false, message: \"child task profile model must be a non-empty string\" };\n\t\t}\n\t\tmodel = record.model;\n\t}\n\tlet thinkingLevel: string | undefined;\n\tif (record.thinkingLevel !== undefined) {\n\t\tif (typeof record.thinkingLevel !== \"string\" || !CHILD_PROFILE_THINKING_LEVELS.includes(record.thinkingLevel)) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage:\n\t\t\t\t\t`child task profile thinkingLevel must be one of ${CHILD_PROFILE_THINKING_LEVELS.join(\", \")}, found ` +\n\t\t\t\t\tJSON.stringify(record.thinkingLevel),\n\t\t\t};\n\t\t}\n\t\tthinkingLevel = record.thinkingLevel;\n\t}\n\tlet tools: readonly string[] | undefined;\n\tif (record.tools !== undefined) {\n\t\tif (!Array.isArray(record.tools) || record.tools.length > CHILD_PROFILE_TOOL_LIMIT) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage: `child task profile tools must be an array of at most ${CHILD_PROFILE_TOOL_LIMIT} names`,\n\t\t\t};\n\t\t}\n\t\tconst names = new Set<string>();\n\t\tfor (const entry of record.tools) {\n\t\t\tif (typeof entry !== \"string\" || entry.trim() === \"\") {\n\t\t\t\treturn { ok: false, message: \"child task profile tools entries must be non-empty strings\" };\n\t\t\t}\n\t\t\tnames.add(entry);\n\t\t}\n\t\ttools = Object.freeze([...names]);\n\t}\n\tlet mode: \"readonly\" | \"full-control\" | undefined;\n\tif (record.mode !== undefined) {\n\t\tif (record.mode !== \"readonly\" && record.mode !== \"full-control\") {\n\t\t\treturn { ok: false, message: 'child task profile mode must be \"readonly\" or \"full-control\"' };\n\t\t}\n\t\tmode = record.mode;\n\t}\n\tlet roleId: string | undefined;\n\tif (record.roleId !== undefined) {\n\t\tif (typeof record.roleId !== \"string\" || record.roleId.trim() === \"\") {\n\t\t\treturn { ok: false, message: \"child task profile roleId must be a non-empty string\" };\n\t\t}\n\t\troleId = record.roleId;\n\t}\n\tlet systemPromptAppend: string | undefined;\n\tif (record.systemPromptAppend !== undefined) {\n\t\tif (\n\t\t\ttypeof record.systemPromptAppend !== \"string\" ||\n\t\t\trecord.systemPromptAppend.trim() === \"\" ||\n\t\t\trecord.systemPromptAppend.length > CHILD_PROFILE_APPEND_CHARS\n\t\t) {\n\t\t\treturn {\n\t\t\t\tok: false,\n\t\t\t\tmessage:\n\t\t\t\t\t`child task profile systemPromptAppend must be a non-empty string of at most ` +\n\t\t\t\t\t`${CHILD_PROFILE_APPEND_CHARS} chars`,\n\t\t\t};\n\t\t}\n\t\tsystemPromptAppend = record.systemPromptAppend;\n\t}\n\treturn {\n\t\tok: true,\n\t\tprofile: Object.freeze({\n\t\t\tversion: 1,\n\t\t\t...(model === undefined ? {} : { model }),\n\t\t\t...(thinkingLevel === undefined ? {} : { thinkingLevel }),\n\t\t\t...(tools === undefined ? {} : { tools }),\n\t\t\t...(mode === undefined ? {} : { mode }),\n\t\t\t...(systemPromptAppend === undefined ? {} : { systemPromptAppend }),\n\t\t\t...(roleId === undefined ? {} : { roleId }),\n\t\t}),\n\t};\n}\n\n/** 便捷读取:从 metadata 里取出并校验档案;undefined 表示没带档案。 */\nexport function readAgentTaskChildProfileV1(\n\tmetadata: Record<string, unknown> | undefined,\n): AgentTaskChildProfileParseResultV1 | undefined {\n\tconst raw = metadata?.[AGENT_TASK_CHILD_PROFILE_KEY];\n\tif (raw === undefined) return undefined;\n\treturn parseAgentTaskChildProfileV1(raw);\n}\n\nexport interface AgentTaskWaitResult {\n\tsessionId: string;\n\tmessages: readonly unknown[];\n}\n\n/** Frozen terminal outcome of an agent task; the replay read survives dispose. */\nexport interface AgentTaskResultV1 {\n\treadonly taskId: string;\n\treadonly parentSessionId: string;\n\t/** Terminal only: succeeded | failed | cancelled. */\n\treadonly status: AgentTaskStatus;\n\treadonly sessionId: string;\n\treadonly messages: readonly unknown[];\n}\n\nexport interface AgentTaskHandle {\n\treadonly id: string;\n\treadonly parentSessionId: string;\n\treadonly session: SessionAPI;\n\tstatus(): AgentTaskStatus;\n\trun(): Promise<void>;\n\twait(options?: { signal?: AbortSignal }): Promise<AgentTaskWaitResult>;\n\t/**\n\t * Terminal replay read: undefined until the task settles; afterwards the\n\t * frozen terminal outcome, even after dispose (no liveness assertion).\n\t */\n\tresult(): AgentTaskResultV1 | undefined;\n\tcancel(reason?: string): Promise<void>;\n\tdispose(): Promise<void>;\n}\n\n/** Host adapter for isolated child sessions. It contains lifecycle mechanics, not scheduling policy. */\nexport interface AgentTaskHost {\n\treadonly session: SessionAPI;\n\trun(prompt: string, signal: AbortSignal): Promise<void>;\n\tcancel(reason?: string): Promise<void>;\n\tdispose(): Promise<void>;\n}\n\nexport interface AgentTaskAdapter {\n\tcreate(request: AgentTaskCreateRequest): Promise<AgentTaskHost>;\n\tdispose?(): Promise<void>;\n}\n\n/** 会话回读视图(D-060):按 sessionId 读到的有界 transcript 片段。 */\nexport interface AgentTaskSessionViewV1 {\n\treadonly sessionId: string;\n\t/** 血缘:父 agent 会话 id(子会话必有)。 */\n\treadonly parentAgentSession?: string;\n\t/** 血缘:创建该会话的角色 id(审计用途)。 */\n\treadonly agentRole?: string;\n\treadonly createdAt?: string;\n\t/** 整份 transcript 的字节数(不是返回片段的)。 */\n\treadonly bytes: number;\n\t/** 返回的消息/entry 条数;`truncated` 为真时是已返回的条数。 */\n\treadonly entryCount: number;\n\t/** 达到返回上限、只给了前段时为 true。 */\n\treadonly truncated: boolean;\n\treadonly entries: readonly unknown[];\n}\n\nexport interface AgentTaskAPI {\n\t/**\n\t * 创建子任务(宿主 adapter 驱动)。宿主只注入会话回读面(无任务 adapter)时该\n\t * 成员不存在——此时 agents 只承载 `session`/`list` 回读面,不承载委派。\n\t */\n\tcreate?(request: AgentTaskCreateRequest): Promise<AgentTaskHandle>;\n\t/**\n\t * Durable replay read by task id: loads the terminal record persisted at\n\t * settle from the host-injected durable store. Undefined when the store is\n\t * absent, the task has not settled, or no record exists under the id.\n\t *\n\t * The store is host-owned and shared per runtime: any plugin holding the\n\t * agents capability can read any task's record by id, including tasks of\n\t * other owners. Unlike the handle's in-memory `result()` (deep-frozen\n\t * projection), records reloaded from the durable backend are reparsed plain\n\t * objects and carry no freeze guarantee.\n\t */\n\t/**\n\t * Durable replay read(宿主 adapter 驱动)。宿主只注入会话回读面(无任务 adapter)\n\t * 时该成员不存在。\n\t */\n\tresult?(taskId: string): Promise<AgentTaskResultV1 | undefined>;\n\t/**\n\t * 父→子引导(D-060 S4,程序面):对**运行中**的任务投递一条有界引导消息\n\t * (≤2048 utf-8 字节,复用子会话自身 steer 语义,不新增队列)。只在发起方\n\t * runtime 的活跃任务里定位:未启动/已终态的按 `subagent_not_running`、宿主\n\t * 会话无 steer 面按 `subagent_steer_unsupported`、未知 id 按\n\t * `subagent_unknown_task` 以带 code 的错误拒绝。父回合不被打断。\n\t * runtime 桥接总是提供;宿主适配器自身无需实现。\n\t */\n\tsteer?(request: { readonly taskId: string; readonly text: string }): Promise<void>;\n\t/**\n\t * 按 `sessionId` 回读子会话 transcript(有界)。宿主未注入会话读取器时该成员不存在;\n\t * 作用域由宿主强制(默认宿主只放行本会话自己的子会话),越界与不存在同型返回 undefined。\n\t */\n\tsession?(sessionId: string): Promise<AgentTaskSessionViewV1 | undefined>;\n\t/**\n\t * 列出本会话**自己的**子代理会话摘要(按最近活动倒序,D-060 模型面盘点通道)。\n\t * 宿主未注入列举器时该成员不存在;作用域由宿主强制(只回本会话的子会话),\n\t * 摘要不含消息正文。跨进程重启仍可列出(读的是落盘目录,不是内存)。\n\t */\n\tlist?(): Promise<AgentTaskSessionSummaryV1[]>;\n}\n\n/**\n * 子代理会话摘要(`agents.list()` 的条目):只读头行信息,不含消息正文。\n * `modifiedAt` 为最后活动时间(epoch 毫秒),按它倒序返回。\n */\nexport interface AgentTaskSessionSummaryV1 {\n\treadonly sessionId: string;\n\t/** 血缘:创建该会话的角色 id(审计用途)。 */\n\treadonly agentRole?: string;\n\treadonly createdAt?: string;\n\treadonly modifiedAt: number;\n\t/** 整份 transcript 的字节数。 */\n\treadonly bytes: number;\n}\n\nexport type InteractionNotifyLevel = \"info\" | \"warning\" | \"error\";\n\nexport type InteractionRequestV1 =\n\t| { kind: \"notify\"; message: string; level?: InteractionNotifyLevel }\n\t| { kind: \"confirm\"; title: string; message: string }\n\t| { kind: \"select\"; title: string; options: readonly string[] }\n\t/** `placeholder` and `defaultValue` are part of the frozen wire shape, but current TUI/RPC hosts have no prefill support and silently ignore both (plain free-text input only). */\n\t| { kind: \"input\"; title: string; placeholder?: string; defaultValue?: string };\n\n/**\n * Outcome production conditions (frozen 1A.8 semantics):\n * - `delivered` — notify prompts only; the host accepted the fire-and-forget\n * notification.\n * - `answered` — the user completed a confirm/select/input prompt.\n * - `cancelled` — the user dismissed the prompt, `options.signal` aborted, or\n * the plugin's registration was disposed. Never produced by `timeoutMs`.\n * - `timeout` — `options.timeoutMs` elapsed before settlement; only that\n * source produces it.\n * - `unavailable` — the host's prompt implementation failed (including hosts\n * without an installed interaction UI settling \"unavailable\").\n *\n * The wrapper validates host-resolved outcomes against these conditions: an\n * unknown status, a missing/invalid `answered` value, extra fields, a\n * host-produced `timeout`, or a `delivered` outside a notify request makes\n * request() reject instead of handing a malformed outcome to the plugin.\n */\nexport type InteractionOutcomeV1 =\n\t| { status: \"delivered\" }\n\t| { status: \"answered\"; value: boolean | string }\n\t| { status: \"cancelled\" }\n\t| { status: \"timeout\" }\n\t| { status: \"unavailable\" };\n\nexport interface InteractionPromptContextV1 {\n\treadonly signal: AbortSignal;\n}\n\n/** Host-side implementation. Hosts MUST honor prompt ctx.signal and settle promptly when aborted. */\n/** Options for extension UI dialogs. */\nexport interface InteractionDialogOptions {\n\t/** AbortSignal to programmatically dismiss the dialog. */\n\tsignal?: AbortSignal;\n\t/** Timeout in milliseconds. Dialog auto-dismisses with live countdown display. */\n\ttimeout?: number;\n}\n\nexport interface InteractionHostV1 {\n\tnotify(request: { message: string; level?: InteractionNotifyLevel }): void;\n\tprompt(request: InteractionRequestV1, context: InteractionPromptContextV1): Promise<InteractionOutcomeV1>;\n\t/**\n\t * Implementations must be idempotent; the session dispose path and the\n\t * per-plugin registration may each invoke it.\n\t */\n\tdispose?(): void | Promise<void>;\n}\n\nexport interface InteractionAPI {\n\t/**\n\t * Fire-and-forget notification; mirrors the legacy sync void semantics.\n\t * Info-level notifications surface as transient host state (a later status\n\t * update may overwrite them) and persistent display is not guaranteed;\n\t * plugins that need a persistent notice should render their own durable UI.\n\t */\n\tnotify(request: { message: string; level?: InteractionNotifyLevel }): void;\n\t/**\n\t * Cancellable interaction task. Resolves with a structured outcome (see\n\t * {@link InteractionOutcomeV1} for the per-outcome production conditions);\n\t * user dismissal yields \"cancelled\", never a rejection. Rejections only for\n\t * invalid input (thrown synchronously), a revoked API, or a malformed host\n\t * outcome. Cancellation is per request: `options.signal` and `timeoutMs`\n\t * affect only this request, never concurrent requests of the same plugin.\n\t */\n\trequest(\n\t\trequest: InteractionRequestV1,\n\t\toptions?: { signal?: AbortSignal; timeoutMs?: number },\n\t): Promise<InteractionOutcomeV1>;\n}\n\n/** Experimental, host-independent Agent composition contract. */\nexport type AgentInstanceStatus = \"created\" | \"running\" | \"succeeded\" | \"failed\" | \"cancelled\" | \"disposed\";\n\nexport type AgentControllerRole = PluginAgentRole;\n\nexport interface AgentInstanceSnapshot {\n\treadonly id: string;\n\treadonly definitionId: string;\n\treadonly definitionVersion: number;\n\treadonly role: AgentControllerRole;\n\treadonly parentInstanceId?: string;\n\treadonly status: AgentInstanceStatus;\n\treadonly revision: number;\n\treadonly leaseOwner?: string;\n}\n\nexport interface AgentExecutionContext {\n\treadonly instance: AgentInstanceSnapshot;\n\treadonly signal: AbortSignal;\n\treadonly inputRevision: number;\n\t/** Optional host primitives; absent when the host did not negotiate them. */\n\treadonly host?: AgentHostPrimitivesV1;\n}\n\nexport interface AgentDefinition<TInput = unknown, TResult = unknown> {\n\treadonly id: string;\n\treadonly version: number;\n\treadonly role: AgentControllerRole;\n\treadonly owner?: string;\n\trun(input: TInput, context: AgentExecutionContext): TResult | Promise<TResult>;\n}\n\nexport interface AgentControllerLease {\n\treadonly id: string;\n\treadonly instanceId: string;\n\treadonly owner: string;\n\treadonly revision: number;\n\tisActive(): boolean;\n\trelease(): Promise<void>;\n}\n\nexport interface AgentInstanceResult<TResult = unknown> {\n\treadonly status: \"succeeded\" | \"failed\" | \"cancelled\" | \"disposed\";\n\treadonly output?: TResult;\n\treadonly error?: unknown;\n\treadonly revision: number;\n}\n\nexport interface AgentInstance<TInput = unknown, TResult = unknown> {\n\treadonly id: string;\n\treadonly definition: AgentDefinition<TInput, TResult>;\n\tsnapshot(): AgentInstanceSnapshot;\n\tacquireControllerLease(owner?: string): Promise<AgentControllerLease>;\n\trun(input: TInput, options?: { lease?: AgentControllerLease; signal?: AbortSignal }): OperationHandle<TResult>;\n\twait(): Promise<AgentInstanceResult<TResult>>;\n\tcancel(reason?: string): Promise<void>;\n\tdispose(): Promise<void>;\n}\n\nexport interface AgentCompositionAPI {\n\tdefine<TInput = unknown, TResult = unknown>(\n\t\tdefinition: AgentDefinition<TInput, TResult>,\n\t): AgentDefinition<TInput, TResult>;\n\tget<TInput = unknown, TResult = unknown>(id: string, version: number): AgentDefinition<TInput, TResult>;\n\tcreate<TInput = unknown, TResult = unknown>(\n\t\tdefinition: AgentDefinition<TInput, TResult> | { id: string; version: number },\n\t\toptions?: { id?: string; parentInstanceId?: string },\n\t): AgentInstance<TInput, TResult>;\n\tlistInstances(): readonly AgentInstanceSnapshot[];\n}\n\n/** Optional host binding implemented by the built-in composition runtime. */\nexport interface AgentCompositionHostBinding {\n\tsetHostPrimitivesFactory(factory?: AgentHostPrimitivesFactory): void;\n}\n\n/** Optional owner-scoped cleanup implemented by the built-in composition runtime. */\nexport interface AgentCompositionDefinitionBinding {\n\tdisposeDefinitions(definitions: readonly AgentDefinition[]): void;\n}\n\n/**\n * Optional host-only binding for the built-in composition runtime. It lets a\n * CapabilityRuntime add owner-scoped primitives without exposing that control\n * to capability plugins.\n */\nexport interface AgentCompositionScopedHostBinding {\n\tcreateWithHostPrimitives<TInput = unknown, TResult = unknown>(\n\t\tdefinition: AgentDefinition<TInput, TResult> | { id: string; version: number },\n\t\toptions: { id?: string; parentInstanceId?: string } | undefined,\n\t\thostPrimitivesFactory: AgentHostPrimitivesFactory,\n\t): AgentInstance<TInput, TResult>;\n}\n\nexport interface ContextStrategy<TContext = unknown, TSnapshot = unknown> {\n\ttransform(context: TContext, options?: ContextOperationOptions): TContext | Promise<TContext>;\n\tsnapshot?(context: TContext, options?: ContextOperationOptions): TSnapshot | Promise<TSnapshot>;\n\trestore?(snapshot: TSnapshot, options?: ContextOperationOptions): TContext | Promise<TContext>;\n\treplace?(context: TContext, options?: ContextOperationOptions): TContext | Promise<TContext>;\n}\n\nexport interface ContextOperationOptions {\n\tsignal?: AbortSignal;\n\treason?: \"request\" | \"reload\" | \"session_replace\" | \"compaction\" | \"overflow_recovery\" | \"retry\" | \"tree\";\n\tsessionId?: string;\n}\n\n/**\n * Generic transform over the projected session entry list, registered per\n * session. The kernel applies registered projections verbatim; semantics\n * belong to the registering plugin.\n */\nexport interface EntryProjection {\n\t/** The plugin-owned custom entry type this projection is associated with. */\n\treadonly customType: string;\n\treadonly project: (entries: readonly unknown[]) => readonly unknown[];\n}\n\nexport interface SkillDefinition {\n\tname: string;\n\tdescription: string;\n\tfilePath: string;\n\tbaseDir: string;\n\tdisableModelInvocation?: boolean;\n}\n\n/** Versioned, provider-agnostic facts shared by replaceable policy calls. */\nexport interface PolicyInvocationContextV1 {\n\tversion: 1;\n\tsessionId: string;\n\tphase: \"agent\" | \"compaction\" | \"overflow\" | \"retry\" | \"branch_summary\";\n\toperationId?: string;\n}\n\nexport interface RetryPolicyRequest {\n\tsignal?: AbortSignal;\n\tretryable: boolean;\n\tenabled: boolean;\n\tattempt: number;\n\tmaxAttempts: number;\n\tbaseDelayMs: number;\n\terrorMessage?: string;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface RetryClassificationRequest {\n\tsignal?: AbortSignal;\n\tmessage: unknown;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface RetryPolicyDecision {\n\tretry: boolean;\n\tdelayMs?: number;\n}\n\nexport interface RetryPolicy {\n\tclassify?(request: RetryClassificationRequest): boolean | Promise<boolean>;\n\tdecide(request: RetryPolicyRequest): RetryPolicyDecision | Promise<RetryPolicyDecision>;\n}\n\nexport interface CompactionPolicyRequest {\n\tsignal?: AbortSignal;\n\tenabled: boolean;\n\treason: \"overflow\" | \"threshold\";\n\tcontextOverflow: boolean;\n\trecoverableLength: boolean;\n\t/** Facts measured by the host; the policy owns the threshold decision. */\n\tcontextUsage?: CompactionContextUsage;\n\trecoveryAttempted: boolean;\n\tcanContinue: boolean;\n\t/**\n\t * Branch path entry snapshot (threshold requests only). Provided so a\n\t * policy can plan CHEAP RELIEF (see {@link CompactionPolicyDecision.relief})\n\t * from real history facts instead of ordering a summarization run.\n\t */\n\tbranchEntries?: readonly unknown[];\n\t/** Recent-tail protection budget (settings fact) for relief planning. */\n\tkeepRecentTokens?: number;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface CompactionContextUsage {\n\tcontextTokens: number;\n\tcontextWindow: number;\n\treserveTokens: number;\n}\n\nexport interface CompactionPreparationRequest {\n\tsignal?: AbortSignal;\n\tentries: unknown;\n\tsettings: unknown;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface CompactionPolicyDecision {\n\tcompact: boolean;\n\tretry?: boolean;\n\tfailureMessage?: string;\n\t/**\n\t * Cheap RELIEF plan: the host appends this custom entry (generic\n\t * `appendCustomEntry`) and reprojects the context instead of running a\n\t * summarization. The semantics of the entry belong entirely to the policy;\n\t * the projection that interprets it is registered separately via\n\t * {@link CapabilityAPI.registerEntryProjection}. When relief is present the\n\t * host skips compaction, so `compact` must be false.\n\t */\n\trelief?: { readonly customType: string; readonly data?: unknown };\n}\n\n/** Provider-agnostic facts about the model the host will use for a summary call. */\nexport interface SummaryModelFactsV1 {\n\treadonly id: string;\n\treadonly contextWindow: number;\n\treadonly maxTokens: number;\n\treadonly reasoning: boolean;\n}\n\n/**\n * Host-owned, provider-agnostic single-shot completion boundary for summary\n * policies. The host resolves the model, auth, transport, retry budget and\n * cache routing; provider internals never cross to the plugin. Each invoke is\n * exactly one completion without tools or session state, and never writes the\n * prompt cache. A plugin that can read these types can implement a summary\n * strategy without importing provider internals.\n */\nexport interface SummaryModelInvocationV1 {\n\treadonly invoke: (\n\t\tinput: SummaryModelInvocationRequestV1,\n\t\tsignal: AbortSignal,\n\t) => Promise<SummaryModelInvocationResultV1>;\n}\n\n/** One host-mediated summary completion request. */\nexport interface SummaryModelInvocationRequestV1 {\n\treadonly version: 1;\n\treadonly systemPrompt?: string;\n\treadonly prompt: string;\n\t/** Requested output budget; the host clamps it to the summary model cap. */\n\treadonly maxTokens?: number;\n\treadonly thinkingLevel?: ThinkingLevel;\n}\n\n/** Stable failure codes reported through {@link SummaryModelInvocationResultV1} errors. */\nexport const SUMMARY_MODEL_INVOCATION_ERROR_CODES = {\n\t/** Provider returned an error stop; `message` mirrors the provider error text. */\n\tproviderError: \"summary_provider_error\",\n\t/** Generation hit the requested output cap and the summary is incomplete. */\n\tlengthCap: \"summary_length_cap\",\n\t/** The model attempted a tool call in a tool-less completion. */\n\ttoolCall: \"summary_tool_call\",\n\t/** The transport threw; `message` mirrors the original error text. */\n\ttransportError: \"summary_transport_error\",\n} as const;\n\n/**\n * One host-mediated summary completion outcome, as a discriminated union:\n * `completed` always carries text, `failed` always carries structured error\n * facts whose `code` is one of {@link SUMMARY_MODEL_INVOCATION_ERROR_CODES}.\n */\nexport type SummaryModelInvocationResultV1 =\n\t| { readonly version: 1; readonly status: \"completed\"; readonly text: string; readonly usage?: unknown }\n\t| { readonly version: 1; readonly status: \"aborted\" }\n\t| {\n\t\t\treadonly version: 1;\n\t\t\treadonly status: \"failed\";\n\t\t\treadonly error: { readonly code: string; readonly message: string };\n\t };\n\nexport interface CompactionSummaryRequest {\n\tpreparation: unknown;\n\tmodel: SummaryModelFactsV1;\n\tinvocation: SummaryModelInvocationV1;\n\tcustomInstructions?: string;\n\tsignal: AbortSignal;\n\treason: \"manual\" | \"threshold\" | \"overflow\";\n\tthinkingLevel?: ThinkingLevel;\n\tsessionId?: string;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface CompactionSummaryResult {\n\tsummary: string;\n\tfirstKeptEntryId: string;\n\ttokensBefore: number;\n\tusage?: unknown;\n\tdetails?: unknown;\n}\n\nexport interface CompactionPolicy {\n\tprepare?(request: CompactionPreparationRequest): unknown | Promise<unknown>;\n\tdecide(request: CompactionPolicyRequest): CompactionPolicyDecision | Promise<CompactionPolicyDecision>;\n\tsummarize?(request: CompactionSummaryRequest): CompactionSummaryResult | Promise<CompactionSummaryResult>;\n}\n\n/** Provider-agnostic overflow classification supplied by a capability plugin. */\nexport interface OverflowPolicyRequest {\n\tsignal?: AbortSignal;\n\tmessage: unknown;\n\tcontextWindow?: number;\n\tdesiredMaxOutput: number;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface OverflowPolicyDecision {\n\tcontextOverflow: boolean;\n\trecoverableLength: boolean;\n}\n\nexport interface OverflowPolicy {\n\tdecide(request: OverflowPolicyRequest): OverflowPolicyDecision | Promise<OverflowPolicyDecision>;\n}\n\nexport interface BranchSummaryRequest {\n\tentries: unknown;\n\tmodel: SummaryModelFactsV1;\n\tinvocation: SummaryModelInvocationV1;\n\tsignal: AbortSignal;\n\tcustomInstructions?: string;\n\treplaceInstructions?: boolean;\n\treserveTokens?: number;\n\tcontext?: PolicyInvocationContextV1;\n\texecution?: ExecutionFactsV1;\n}\n\nexport interface BranchSummaryResult {\n\tsummary?: string;\n\tusage?: unknown;\n\treadFiles?: string[];\n\tmodifiedFiles?: string[];\n\taborted?: boolean;\n\terror?: string;\n}\n\nexport interface BranchSummaryPolicy {\n\tsummarize(request: BranchSummaryRequest): BranchSummaryResult | Promise<BranchSummaryResult>;\n}\n\n/**\n * Experimental provider request header boundary. `null` retains the provider\n * header deletion semantics used by the host model runtime.\n */\nexport interface ProviderHeaderTransformRequest {\n\tmodel: unknown;\n\tsessionId?: string;\n\theaders: Record<string, string | null>;\n}\n\n/**\n * Experimental request-time hook for plugins that own provider header policy.\n * Transforms run in registration order and receive the previous transform's\n * result.\n */\nexport type ProviderHeaderTransform = (\n\trequest: ProviderHeaderTransformRequest,\n) => Record<string, string | null> | Promise<Record<string, string | null>>;\n\n/**\n * Hook positions on the default agent loop. Links run in registration order\n * after the host's legacy chain head.\n */\nexport type AgentLoopHookPositionV1 =\n\t| \"beforeInput\"\n\t| \"beforeToolCall\"\n\t| \"afterToolCall\"\n\t| \"transformContext\"\n\t| \"prepareNextTurn\"\n\t| \"shouldStopAfterTurn\";\n\n/**\n * One ordered link of the input gate chain (输入 gate,扩展位盘点 A3). Runs at\n * prompt submission — before the input is accepted (`input.received@1` is the\n * observe fact of an ACCEPTED input and never fires for blocked inputs) and\n * before skill/template expansion. A `{ block: true, reason? }` result rejects\n * the input: the session dispatches `input.gate.blocked@1` and the prompt call\n * fails with the reason. A `{ text }` result rewrites the input for everything\n * downstream (later gates, expansion, the turn). `undefined` keeps the input.\n */\nexport type AgentLoopBeforeInputHookV1 = (input: {\n\treadonly text: string;\n\treadonly source: string;\n\treadonly signal?: AbortSignal;\n}) => Promise<AgentLoopBeforeInputOutputV1 | undefined>;\n\nexport interface AgentLoopBeforeInputOutputV1 {\n\tblock?: boolean;\n\treason?: string;\n\ttext?: string;\n}\n\nexport interface AgentLoopBeforeToolCallInputV1 {\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\tsignal?: AbortSignal;\n}\n\n/**\n * One ordered link of the default tool-call gating chain. Return\n * `{ block: true, reason? }` to block, `{ args }` to replace the candidate\n * arguments, or `undefined` to keep the input.\n */\nexport interface AgentLoopBeforeToolCallOutputV1 {\n\tblock?: boolean;\n\treason?: string;\n\targs?: unknown;\n}\n\nexport type AgentLoopBeforeToolCallHookV1 = (\n\tinput: AgentLoopBeforeToolCallInputV1,\n) => Promise<AgentLoopBeforeToolCallOutputV1 | undefined>;\n\nexport interface AgentLoopAfterToolCallInputV1 {\n\ttoolCallId: string;\n\ttoolName: string;\n\targs: unknown;\n\t/** The result produced by the previous link, or the executed tool result for the first link. */\n\tresult: unknown;\n\tisError: boolean;\n\tsignal?: AbortSignal;\n}\n\n/**\n * One ordered link of the post-execution chain. Return a partial tool-result\n * override to rewrite the result, or `undefined` to keep the input.\n */\nexport type AgentLoopAfterToolCallHookV1 = (input: AgentLoopAfterToolCallInputV1) => Promise<unknown | undefined>;\n\n/**\n * One ordered link of the request-time context transform chain. Receives and\n * returns the message array; `undefined` keeps the input.\n */\nexport type AgentLoopTransformContextHookV1 = (\n\tmessages: readonly unknown[],\n\tsignal?: AbortSignal,\n) => Promise<readonly unknown[] | undefined>;\n\n/**\n * One ordered link of the next-turn preparation chain. Receives the turn\n * snapshot, returns a revised snapshot or `undefined`.\n */\nexport type AgentLoopPrepareNextTurnHookV1 = (turn: unknown, signal?: AbortSignal) => Promise<unknown | undefined>;\n\n/**\n * One ordered link of the post-turn stop chain. Receives the completed turn's\n * stop context; return `true` to request stopping after the current turn. The\n * host OR-composes the chain: the first link returning `true` stops the run\n * without consulting later links.\n *\n * The stop context stays kernel-typed (`@agent-forge/agent-core`\n * `ShouldStopAfterTurnContext`: its fields reference the provider message\n * model, which must not cross into the SDK — D-075 S2). Hosts hand the same\n * runtime object they hand the kernel callback; `context` is therefore typed\n * `any` here so kernel-typed handlers remain assignable.\n */\n// biome-ignore lint/suspicious/noExplicitAny: kernel loop-stop context is provider-model typed and cannot cross into the SDK (D-075 S2).\nexport type AgentLoopShouldStopAfterTurnHookV1 = (context: any, signal?: AbortSignal) => boolean | Promise<boolean>;\n\nexport type AgentLoopHookForV1<P extends AgentLoopHookPositionV1> = P extends \"beforeInput\"\n\t? AgentLoopBeforeInputHookV1\n\t: P extends \"beforeToolCall\"\n\t\t? AgentLoopBeforeToolCallHookV1\n\t\t: P extends \"afterToolCall\"\n\t\t\t? AgentLoopAfterToolCallHookV1\n\t\t\t: P extends \"transformContext\"\n\t\t\t\t? AgentLoopTransformContextHookV1\n\t\t\t\t: P extends \"prepareNextTurn\"\n\t\t\t\t\t? AgentLoopPrepareNextTurnHookV1\n\t\t\t\t\t: P extends \"shouldStopAfterTurn\"\n\t\t\t\t\t\t? AgentLoopShouldStopAfterTurnHookV1\n\t\t\t\t\t\t: never;\n\nexport type AgentLoopHookHandlerV1 =\n\t| AgentLoopBeforeInputHookV1\n\t| AgentLoopBeforeToolCallHookV1\n\t| AgentLoopAfterToolCallHookV1\n\t| AgentLoopTransformContextHookV1\n\t| AgentLoopPrepareNextTurnHookV1\n\t| AgentLoopShouldStopAfterTurnHookV1;\n\n/**\n * Post-run continuation facts for the default agent loop. The host evaluates\n * its own candidate decision first; the strategy makes the final\n * continue/stop call for the post-run loop.\n */\nexport interface AgentRunLoopStrategyRequestV1 {\n\t/** The policy decision signal for the current prompt run. */\n\treadonly signal?: AbortSignal;\n\t/** The retry path fired: a retry was prepared and the host would continue into it. */\n\treadonly willRetry: boolean;\n\t/** The compaction path fired: compaction was prepared and the host would continue into it. */\n\treadonly willCompact: boolean;\n\t/** The agent still holds queued steering/follow-up messages. */\n\treadonly queuedFollowUp: boolean;\n\t/** The host's own continuation decision (the replaceable default behavior). */\n\treadonly hostWillContinue: boolean;\n}\n\nexport interface AgentRunLoopStrategyDecisionV1 {\n\treadonly continueLoop: boolean;\n\treadonly reason?: string;\n}\n\n/**\n * Post-run continuation strategy for the default agent loop. The host proposes\n * the continuation (retry, compaction, or queued input); the strategy may veto\n * it per cycle. `continueLoop: true` without a host-proposed continuation is\n * clamped to stop: the agent loop can only continue from pending retry,\n * compaction, or queued input.\n */\nexport interface AgentRunLoopStrategyV1 {\n\tdecideNextCycle(\n\t\trequest: AgentRunLoopStrategyRequestV1,\n\t): AgentRunLoopStrategyDecisionV1 | Promise<AgentRunLoopStrategyDecisionV1>;\n}\n\nexport interface CapabilityAPI {\n\treadonly manifest: PluginManifest;\n\treadonly host: HostCapabilities;\n\treadonly config: PluginConfig;\n\treadonly session?: SessionAPI;\n\t/** Available when the host declares the `output-artifacts` feature. */\n\treadonly output?: OutputArtifactAPI;\n\treadonly credentials?: CredentialAPI;\n\treadonly agents?: AgentTaskAPI;\n\t/**\n\t * 宿主会话取消栅栏(D-044 §4.2):getter 形态,按调用时刻返回当前 epoch 的\n\t * AbortSignal(用户中止/销毁会话时触发;epoch 刷新后旧信号不再影响新任务)。\n\t * 宿主未注入 parentSignal 时为 undefined。插件编排(如 subagent delegate)用它级联取消。\n\t */\n\tsessionAbortSignal?: () => AbortSignal | undefined;\n\t/** Available when the host declares `interaction` feature. */\n\treadonly interaction?: InteractionAPI;\n\t/** Available when the host declares `agent-composition-v1`. */\n\treadonly composition?: AgentCompositionAPI;\n\t/** Available when the host declares `logger-v1`. */\n\treadonly logger?: LoggerAPI;\n\t/** Available when the host declares `diagnostics-v1`. */\n\treadonly diagnostics?: DiagnosticsAPI;\n\t/** Available when the host declares `plugin-state-v1`. */\n\treadonly state?: StateAPI;\n\t/** Available when the host declares `runtime-inspector-v1`. */\n\treadonly inspector?: RuntimeInspectorAPI;\n\t/**\n\t * Host trace adapter service (D-075 S4 second batch, observability host\n\t * contract). Present when the host runs session trace collection; the\n\t * first-party observability plugin binds it as its trace sink adapter.\n\t * Optional probe: hosts without tracing (or third-party hosts) leave it\n\t * undefined and the plugin stays trace-free.\n\t */\n\treadonly trace?: ObservabilityHostAdapterV1;\n\t/**\n\t * Trace-sink budget overrides accompanying {@link CapabilityAPI.trace}\n\t * (host `traceOptions` face, design §6 control plane). Present only\n\t * together with `trace`; omitted fields fall back to the plugin defaults.\n\t */\n\treadonly traceSinkOptions?: TraceSinkOptionsV1;\n\treadonly contributions: ContributionAPI;\n\t/** Draft host lifecycle event directory. */\n\treadonly lifecycle: LifecycleAPI;\n\t/** Draft plugin-to-plugin capability directory. */\n\treadonly capabilities: CapabilityDirectoryAPI;\n\t/**\n\t * Register a tool. `definition` stays loosely typed (any `{ name, execute }`\n\t * shape the host can normalize); when the host configures\n\t * CapabilityRuntimeOptions.toolExecutionContext, `execute` receives a\n\t * {@link CapabilityToolContext} as its second argument on the runtime invoke\n\t * face. Re-registering an existing name replaces the current registration\n\t * (last load wins) and it is restored when the replacing registration\n\t * disposes. Experimental.\n\t */\n\tregisterTool(definition: unknown): DisposableRegistration;\n\tregisterCommand(definition: CapabilityCommandDefinition): DisposableRegistration;\n\tregisterOperation(\n\t\tname: string,\n\t\thandler: (input: unknown, context: OperationExecutionContext) => unknown | Promise<unknown>,\n\t): DisposableRegistration;\n\tregisterRpcMethod(name: string, handler: (input: unknown) => unknown | Promise<unknown>): DisposableRegistration;\n\tregisterContextStrategy(name: string, strategy: ContextStrategy): DisposableRegistration;\n\t/**\n\t * Registers a GENERIC entry projection for this session's context\n\t * projection: `project` receives the projected session entry list and may\n\t * replace entries. The kernel applies registered projections verbatim and\n\t * knows nothing about their semantics — first-party and third-party plugins\n\t * use the same channel for custom-entry-based context policies (e.g. a\n\t * compaction policy eliding bulky old tool results). The returned disposer\n\t * removes the projection.\n\t */\n\tregisterEntryProjection(projection: EntryProjection): DisposableRegistration;\n\tregisterProviderHeaderTransform(name: string, transform: ProviderHeaderTransform): DisposableRegistration;\n\tregisterSkill(definition: SkillDefinition): DisposableRegistration;\n\tregisterRetryPolicy(name: string, policy: RetryPolicy): DisposableRegistration;\n\tregisterCompactionPolicy(name: string, policy: CompactionPolicy): DisposableRegistration;\n\tregisterOverflowPolicy(name: string, policy: OverflowPolicy): DisposableRegistration;\n\tregisterBranchSummaryPolicy(name: string, policy: BranchSummaryPolicy): DisposableRegistration;\n\tregisterLoopHook(position: \"beforeInput\", handler: AgentLoopBeforeInputHookV1): DisposableRegistration;\n\tregisterLoopHook(position: \"beforeToolCall\", handler: AgentLoopBeforeToolCallHookV1): DisposableRegistration;\n\tregisterLoopHook(position: \"afterToolCall\", handler: AgentLoopAfterToolCallHookV1): DisposableRegistration;\n\tregisterLoopHook(position: \"transformContext\", handler: AgentLoopTransformContextHookV1): DisposableRegistration;\n\tregisterLoopHook(position: \"prepareNextTurn\", handler: AgentLoopPrepareNextTurnHookV1): DisposableRegistration;\n\tregisterLoopHook(\n\t\tposition: \"shouldStopAfterTurn\",\n\t\thandler: AgentLoopShouldStopAfterTurnHookV1,\n\t): DisposableRegistration;\n\tregisterRunLoopStrategy(name: string, strategy: AgentRunLoopStrategyV1): DisposableRegistration;\n\tsubscribe<TEvent>(\n\t\ttype: string,\n\t\thandler: (event: EventEnvelope<TEvent>) => void | Promise<void>,\n\t): DisposableRegistration;\n\tpublish<TData>(event: Omit<EventEnvelope<TData>, \"id\" | \"timestamp\" | \"source\">): Promise<EventEnvelope<TData>>;\n\tcall<TResult = unknown>(\n\t\toperation: string,\n\t\tinput: unknown,\n\t\toptions?: { signal?: AbortSignal },\n\t): OperationHandle<TResult>;\n}\n\n/** Resources owned by a capability plugin beyond runtime registrations. */\nexport interface CapabilityPluginInstance {\n\tdispose(): void | Promise<void>;\n}\n\n/** Resources returned by a synchronous embedded plugin factory. */\nexport interface CapabilityPluginSyncInstance {\n\tdispose(): void;\n}\n\n// biome-ignore lint/suspicious/noConfusingVoidType: factories conventionally return void or a disposable instance.\nexport type CapabilityPluginFactoryResult = void | CapabilityPluginInstance;\nexport type CapabilityPluginFactory = (\n\tapi: CapabilityAPI,\n) => CapabilityPluginFactoryResult | Promise<CapabilityPluginFactoryResult>;\n// biome-ignore lint/suspicious/noConfusingVoidType: synchronous factories conventionally return void or a disposable instance.\nexport type CapabilityPluginSyncFactory = (api: CapabilityAPI) => void | CapabilityPluginSyncInstance;\n\nexport function createDisposableRegistration(\n\tkind: string,\n\tdispose: () => void | Promise<void>,\n\tid: string,\n): DisposableRegistration {\n\tlet disposed = false;\n\treturn {\n\t\tid,\n\t\tkind,\n\t\tdispose: () => {\n\t\t\tif (disposed) return;\n\t\t\tdisposed = true;\n\t\t\treturn dispose();\n\t\t},\n\t};\n}\n\nexport function createEventEnvelope<TData>(\n\tevent: Omit<EventEnvelope<TData>, \"id\" | \"timestamp\">,\n\toptions: { id: string; timestamp?: number },\n): EventEnvelope<TData> {\n\treturn {\n\t\t...event,\n\t\tid: options.id,\n\t\ttimestamp: options.timestamp ?? 0,\n\t};\n}\n\n/**\n * Detach a session value into a read-only projection: the value is deep-cloned\n * via `structuredClone` and the clone is frozen recursively (ArrayBuffer views\n * are cloned but not frozen). Lifecycle payload builders use this so handlers\n * receive data that cannot be mutated in place and share no identity with live\n * session state. Available to hosts and plugins alike through the public face;\n * the default loop bootstrap uses it for tool-call inputs and tool-result\n * content.\n */\nexport function detachedSessionSnapshot<T>(value: T): T {\n\tconst clone = structuredClone(value);\n\tconst freeze = (candidate: unknown): void => {\n\t\tif (!candidate || typeof candidate !== \"object\") return;\n\t\tif (ArrayBuffer.isView(candidate)) return;\n\t\tfor (const child of Object.values(candidate as Record<string, unknown>)) freeze(child);\n\t\tObject.freeze(candidate);\n\t};\n\tfreeze(clone);\n\treturn clone;\n}\n"]}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ai-agent-forge/plugin-sdk",
|
|
3
|
-
"version": "0.85.
|
|
3
|
+
"version": "0.85.5",
|
|
4
4
|
"description": "Shared plugin development contracts (artifact, operation, diff, render, context budget DTOs) for Agent Forge plugins",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|