@agimon-ai/po-core 0.0.0-alpha.97 → 0.0.0-alpha.98
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/src/systems/main/adapters/headlessHost.cjs +23 -10
- package/dist/src/systems/main/adapters/headlessHost.cjs.map +1 -1
- package/dist/src/systems/main/adapters/headlessHost.d.mts +2 -0
- package/dist/src/systems/main/adapters/headlessHost.d.mts.map +1 -1
- package/dist/src/systems/main/adapters/headlessHost.mjs +23 -10
- package/dist/src/systems/main/adapters/headlessHost.mjs.map +1 -1
- package/dist/src/systems/main/adapters/headlessSessionHost.cjs +0 -1
- package/dist/src/systems/main/adapters/headlessSessionHost.cjs.map +1 -1
- package/dist/src/systems/main/adapters/headlessSessionHost.mjs +0 -1
- package/dist/src/systems/main/adapters/headlessSessionHost.mjs.map +1 -1
- package/package.json +4 -4
|
@@ -38,6 +38,7 @@ function escapeXml(value) {
|
|
|
38
38
|
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
39
39
|
}
|
|
40
40
|
const FLAT_SKILL_LIMIT = 20;
|
|
41
|
+
const RESOURCE_READ_ATTEMPTS = 5;
|
|
41
42
|
function uniqueSkills(resources) {
|
|
42
43
|
return resources.filter((skill, index, all) => skill.kind === "skill" && all.findLastIndex((entry) => entry.kind === "skill" && entry.name === skill.name) === index);
|
|
43
44
|
}
|
|
@@ -533,10 +534,7 @@ var HeadlessHost = class extends _deepseek_ai_cordis.Service {
|
|
|
533
534
|
});
|
|
534
535
|
await result;
|
|
535
536
|
await this.settled();
|
|
536
|
-
|
|
537
|
-
if (failure instanceof Error) throw failure;
|
|
538
|
-
if (failure !== void 0) throw new Error(typeof failure === "string" ? failure : "Headless selection failed", { cause: failure });
|
|
539
|
-
this.assertReady();
|
|
537
|
+
this.assertApplied();
|
|
540
538
|
}
|
|
541
539
|
/** Drain selections, including ones queued by selection listeners. */
|
|
542
540
|
async settled() {
|
|
@@ -546,6 +544,13 @@ var HeadlessHost = class extends _deepseek_ai_cordis.Service {
|
|
|
546
544
|
await pending;
|
|
547
545
|
} while (pending !== this.tail);
|
|
548
546
|
}
|
|
547
|
+
/** Preserve a failed apply's cause instead of replacing it with the readiness error. */
|
|
548
|
+
assertApplied() {
|
|
549
|
+
const failure = this.failure;
|
|
550
|
+
if (failure instanceof Error) throw failure;
|
|
551
|
+
if (failure !== void 0) throw new Error(typeof failure === "string" ? failure : "Headless selection failed", { cause: failure });
|
|
552
|
+
this.assertReady();
|
|
553
|
+
}
|
|
549
554
|
assertReady() {
|
|
550
555
|
if (this.disposed || !this.ready) throw new Error("Headless dispatch is blocked until selection is coherently applied");
|
|
551
556
|
}
|
|
@@ -698,12 +703,20 @@ var HeadlessHost = class extends _deepseek_ai_cordis.Service {
|
|
|
698
703
|
return result;
|
|
699
704
|
}
|
|
700
705
|
async readResources() {
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
706
|
+
let result;
|
|
707
|
+
let revision = 0;
|
|
708
|
+
for (let attempt = 0;; attempt++) {
|
|
709
|
+
let pending;
|
|
710
|
+
do {
|
|
711
|
+
pending = this.tail;
|
|
712
|
+
await pending;
|
|
713
|
+
} while (pending !== this.tail);
|
|
714
|
+
this.assertApplied();
|
|
715
|
+
if (result !== void 0 && revision === this.appliedRevision) return result;
|
|
716
|
+
if (attempt === RESOURCE_READ_ATTEMPTS) throw new Error("Selection changed while reading resources");
|
|
717
|
+
revision = this.appliedRevision;
|
|
718
|
+
result = await this.resolveResources(this.applied);
|
|
719
|
+
}
|
|
707
720
|
}
|
|
708
721
|
async close() {
|
|
709
722
|
if (this.disposed) return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headlessHost.cjs","names":["PO_SEARCH_SKILLS_TOOL","Service","createPoKernel","PO_HEADLESS_HOST_SERVICE","PO_APPROVAL_SERVICE","readPoApproval","gateApproval","isPoHeadlessToolModelVisible","readPoMcpStatus","formatSkillsForSystemPrompt","readPoHeadlessOwner","isPoHeadlessPromptAdmissionError"],"sources":["../../../../../src/systems/main/adapters/headlessHost.ts"],"sourcesContent":["import { Context, Service } from '@deepseek-ai/cordis';\nimport type { TSchema } from 'typebox';\n\nimport { PO_APPROVAL_SERVICE, type PoApprovedCall, readPoApproval } from '../../../exports/approval';\nimport {\n PO_HEADLESS_HOST_SERVICE,\n PO_LOAD_SKILL_TOOL,\n PO_SEARCH_SKILLS_TOOL,\n readPoHeadlessOwner,\n isPoHeadlessPromptAdmissionError,\n type PoHeadlessActivity,\n type PoHeadlessCommand,\n type PoHeadlessEventName,\n type PoHeadlessExecutionContext,\n type PoHeadlessHook,\n type PoHeadlessHostService,\n isPoHeadlessToolModelVisible,\n type PoHeadlessRegistration,\n type PoHeadlessResource,\n type PoHeadlessRefreshAxis,\n type PoHeadlessSelection,\n type PoHeadlessSelectionApplied,\n type PoHeadlessSelectionChange,\n type PoHeadlessTool,\n type PoHeadlessToolResult,\n type PoHeadlessCondition,\n type PoHeadlessToolRestriction,\n} from '../../../exports/headless';\nimport { createPoKernel } from '../../../exports/kernel';\nimport { readPoMcpStatus } from '../../../exports/mcpStatus';\nimport type { PoServerBundleEntry } from '../../../exports/serverPlugin';\nimport { gateApproval } from '../../../services/approvalGate';\nimport type { PackageAttribution } from '../../../services/contextProjection';\nimport type {\n ContextConditionalAttribution,\n ContextToolInventory,\n ContextToolSource,\n} from '../../../services/contextProjection';\nimport { formatSkillsForSystemPrompt } from '../../../services/skillPrompt';\nimport type { CountTokens } from '../../../services/toolInventory';\nimport type {\n HeadlessContextInventory,\n HeadlessHostOptions,\n HeadlessSelectionStatus,\n ResolvedHeadlessResource,\n} from '../types/headlessHost';\n\ntype Owned<T> = { source: string; value: T };\ntype StopActivity = () => void | Promise<void>;\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction sameValues(left: readonly unknown[], right: readonly unknown[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction sameSelection(left: PoHeadlessSelection, right: PoHeadlessSelection): boolean {\n return (\n left.majorMode === right.majorMode &&\n left.profile === right.profile &&\n sameStrings(left.activeLayers, right.activeLayers) &&\n sameStrings(left.domains, right.domains) &&\n JSON.stringify(left.state ?? {}) === JSON.stringify(right.state ?? {})\n );\n}\n\n/**\n * Maps one typed headless resource to the exact skill shape installed in AgentHarness.\n *\n * Prefers the resource's own `description` and `path`. The fallbacks below are what\n * every skill used to get, and they are only good enough for explicit invocation,\n * which matches on name: `po-headless://` is not a path any tool can open, and\n * \"Headless skill from <source>\" gives the model nothing to select on. A skill is\n * only advertised in the prompt once it carries a real path.\n */\nexport function headlessHarnessSkill(resource: ResolvedHeadlessResource) {\n return {\n name: resource.name,\n description: resource.description ?? `Headless skill from ${resource.source}`,\n content: resource.text,\n filePath: resource.path ?? `po-headless://${resource.source}/${resource.name}`,\n };\n}\n\nfunction escapeXml(value: string): string {\n return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n}\n\nconst FLAT_SKILL_LIMIT = 20;\n\nfunction uniqueSkills(resources: readonly ResolvedHeadlessResource[]): readonly ResolvedHeadlessResource[] {\n return resources.filter(\n (skill, index, all) =>\n skill.kind === 'skill' &&\n all.findLastIndex((entry) => entry.kind === 'skill' && entry.name === skill.name) === index,\n );\n}\n\n/** The searchable catalog. Pinned skills are listed in the system prompt instead. */\nfunction activeSkills(resources: readonly ResolvedHeadlessResource[]): readonly ResolvedHeadlessResource[] {\n return uniqueSkills(resources).filter((skill) => skill.pinned !== true);\n}\n\n/** Exactly the summaries emitted in the system prompt, also used for context billing. */\nexport function systemPromptSkills(resources: readonly ResolvedHeadlessResource[], hasLoader: boolean) {\n return uniqueSkills(resources).filter((skill) => skill.path !== undefined && (!hasLoader || skill.pinned === true));\n}\n\n/** Skill discovery prose follows the applied catalog, including selection changes. */\nexport function describeSkillTool(\n tool: Pick<PoHeadlessTool, 'name' | 'description'>,\n resources: readonly ResolvedHeadlessResource[],\n): string {\n if (tool.name !== PO_LOAD_SKILL_TOOL && tool.name !== PO_SEARCH_SKILLS_TOOL) return tool.description;\n const listed = activeSkills(resources);\n if (tool.name === PO_LOAD_SKILL_TOOL && listed.length > FLAT_SKILL_LIMIT)\n return `${tool.description}\\nUse ${PO_SEARCH_SKILLS_TOOL} to find available skill names.`;\n if (listed.length === 0) return tool.description;\n return [\n tool.description,\n '',\n '<available_skills>',\n ...listed.flatMap((skill) =>\n tool.name === PO_SEARCH_SKILLS_TOOL\n ? [` <name>${escapeXml(skill.name)}</name>`]\n : [\n ' <skill>',\n ` <name>${escapeXml(skill.name)}</name>`,\n ` <description>${escapeXml(headlessHarnessSkill(skill).description)}</description>`,\n ' </skill>',\n ],\n ),\n '</available_skills>',\n ].join('\\n');\n}\n\n/** Retains packages and their state; only kernel-computed active contributions change. */\nexport class HeadlessHost extends Service<PoHeadlessHostService> implements PoHeadlessHostService {\n private readonly kernel = createPoKernel();\n /** Each selection listener and the package that subscribed it; undefined for the host's own. */\n private readonly selectionListeners = new Map<\n (selection: PoHeadlessSelection, applied: PoHeadlessSelectionApplied) => void | Promise<void>,\n string | undefined\n >();\n private readonly initialSelectionResolvers = new Set<\n (selection: PoHeadlessSelection) => PoHeadlessSelection | Promise<PoHeadlessSelection>\n >();\n private restrictions: readonly PoHeadlessToolRestriction[] = [];\n private restrictionsChanged = false;\n private contributionsChanged = false;\n private options: HeadlessHostOptions;\n private readonly selectionOverrides: Set<string>;\n private applied: PoHeadlessSelection;\n private requested: PoHeadlessSelection;\n private applying: PoHeadlessSelection;\n private refreshing = false;\n private requestedRevision = 0;\n private appliedRevision = 0;\n private recoveryRevision = 0;\n private ready = false;\n private disposed = false;\n private failure: unknown;\n private tail: Promise<void> = Promise.resolve();\n private activeSources = new Set<string>();\n private availableSources = new Set<string>();\n private tools = new Map<string, Owned<PoHeadlessTool>>();\n private resources: readonly Owned<PoHeadlessResource>[] = [];\n private resolvedResources: readonly ResolvedHeadlessResource[] = [];\n private readonly resourceDeclarations = new WeakMap<ResolvedHeadlessResource, PoHeadlessResource>();\n private commands = new Map<string, Owned<PoHeadlessCommand>>();\n private hooks: readonly Owned<PoHeadlessHook>[] = [];\n private readonly activities = new Map<Owned<PoHeadlessActivity>, StopActivity>();\n\n constructor(context: Context, options: HeadlessHostOptions) {\n super(context, PO_HEADLESS_HOST_SERVICE);\n this.options = options;\n this.selectionOverrides = new Set(options.selectionOverrides);\n this.applied = structuredClone(options.selection);\n this.requested = this.applied;\n this.applying = this.applied;\n context.effect(() => () => this.close(), 'headless host lifetime');\n context.inject([PO_APPROVAL_SERVICE], (child) =>\n readPoApproval(child)?.registerExecutor('tool', (call, signal) => this.runApproved(call, signal)),\n );\n this.kernel.defineSlot<Owned<PoHeadlessToolRestriction>>('restrictions', (entries) => {\n this.restrictionsChanged = true;\n this.restrictions = entries.map((entry) => entry.value).filter((restriction) => this.matches(restriction.when));\n });\n const applyTools = async (entries: readonly Owned<PoHeadlessTool>[]): Promise<void> => {\n const next = new Map<string, Owned<PoHeadlessTool>>();\n for (const entry of this.selected(entries)) {\n if (!this.allowsTool(entry.value.name)) continue;\n if (!next.has(entry.value.name)) next.set(entry.value.name, entry);\n }\n const tools = [...next.values()].map((entry): PoHeadlessTool => ({\n ...entry.value,\n execute: async (id, parameters, signal, onUpdate, execution) => {\n this.assertReady();\n const active = () => this.tools.get(entry.value.name) === entry && this.activeSources.has(entry.source);\n if (!active()) throw new Error(`Tool '${entry.value.name}' is no longer active`);\n const context = this.context;\n const caller =\n context.caller === 'child' || execution?.caller === 'child'\n ? 'child'\n : (execution?.caller ?? context.caller);\n const interaction = context.interaction === 'unattended' ? 'unattended' : context.sessionContext?.interaction;\n const gate = await gateApproval({\n policy: entry.value.approval,\n operation: { kind: 'tool', name: entry.value.name },\n input: parameters,\n arguments: parameters,\n sessionId: context.sessionId,\n toolCallId: id,\n ...(caller === undefined ? {} : { caller }),\n ...(interaction === undefined ? {} : { interaction }),\n service: readPoApproval(this.ctx),\n ...(signal === undefined ? {} : { signal }),\n });\n if (gate.ok === false && gate.pending === true)\n return { content: [{ type: 'text', text: gate.reason }], details: { approvalId: gate.approvalId } };\n if (!gate.ok) throw new Error(gate.reason);\n return entry.value.execute(id, parameters, signal, onUpdate, {\n ...this.context,\n ...(execution?.toolContinuation ? { toolContinuation: execution.toolContinuation } : {}),\n ...(caller === undefined ? {} : { caller }),\n });\n },\n }));\n await this.options.applyTools(tools);\n this.tools = next;\n };\n this.kernel.defineSlot<Owned<PoHeadlessTool>>('tools', applyTools);\n this.kernel.defineSlot<Owned<PoHeadlessResource>>('resources', async (entries) => {\n const searchable = this.listSkills().length > FLAT_SKILL_LIMIT;\n this.resources = this.selected(entries);\n this.resolvedResources = await this.resolveResources(this.applying);\n await this.options.applyResources(this.resolvedResources);\n // Resources can cross the cutoff even when the tool declarations are unchanged.\n if (searchable !== this.listSkills().length > FLAT_SKILL_LIMIT)\n await applyTools(this.kernel.activeValues<Owned<PoHeadlessTool>>('tools'));\n });\n this.kernel.defineSlot<Owned<PoHeadlessCommand>>('commands', (entries) => {\n const next = new Map<string, Owned<PoHeadlessCommand>>();\n for (const entry of this.selected(entries)) if (!next.has(entry.value.name)) next.set(entry.value.name, entry);\n this.commands = next;\n });\n this.kernel.defineSlot<Owned<PoHeadlessHook>>('hooks', (entries) => {\n this.hooks = this.selected(entries);\n });\n this.kernel.defineSlot<Owned<PoHeadlessActivity>>('activities', async (entries) => {\n const desired = new Set(this.selected(entries));\n for (const [entry, stop] of [...this.activities].reverse()) {\n if (desired.has(entry)) continue;\n this.activities.delete(entry);\n try {\n await stop();\n } catch (error) {\n // A package's activity that fails to stop is reported; the others still stop and start.\n this.options.onError?.(error, 'activity');\n }\n }\n for (const entry of desired) {\n if (this.activities.has(entry)) continue;\n try {\n const stop = await entry.value.start(this.options.context(this.applying));\n this.activities.set(entry, stop);\n } catch (error) {\n if (!this.optionalSource(entry.source)) throw error;\n this.options.onError?.(error, 'activity');\n }\n }\n });\n }\n\n get context(): PoHeadlessExecutionContext {\n return this.options.context(this.applied);\n }\n\n get status(): HeadlessSelectionStatus {\n return {\n requestedRevision: this.requestedRevision,\n appliedRevision: this.appliedRevision,\n ready: this.ready,\n ...(this.failure === undefined\n ? {}\n : {\n error:\n this.failure instanceof Error\n ? this.failure.message\n : typeof this.failure === 'string'\n ? this.failure\n : 'Headless selection failed',\n }),\n };\n }\n\n /**\n * The resources the last applied selection resolved to.\n *\n * `readResources` re-reads them for a live request and refuses while a\n * selection is mid-apply. A reader describing the applied composition wants\n * the same snapshot `getContextInventory` reports against, and wants it at\n * the same moments, so it reads this instead of dispatching.\n */\n get appliedResources(): readonly ResolvedHeadlessResource[] {\n return this.resolvedResources;\n }\n\n get toolSurface(): PoHeadlessHostService['toolSurface'] {\n return this.options.toolSurface?.();\n }\n\n readSkill(name: string): string | undefined {\n // The last declaration of a name is the one the session uses.\n return this.resolvedResources.findLast((entry) => entry.kind === 'skill' && entry.name === name)?.text;\n }\n\n listSkills(): ReturnType<PoHeadlessHostService['listSkills']> {\n return activeSkills(this.resolvedResources).map((resource) => {\n const { name, description } = headlessHarnessSkill(resource);\n return { name, description };\n });\n }\n\n inspectCapabilities(): ReturnType<PoHeadlessHostService['inspectCapabilities']> {\n const ready = this.ready && !this.disposed;\n const capabilities: ReturnType<PoHeadlessHostService['inspectCapabilities']>['capabilities'][number][] = [];\n if (ready) {\n for (const entry of this.kernel.activeValues<Owned<PoHeadlessTool>>('tools')) {\n const active = this.tools.get(entry.value.name) === entry;\n const discoverable = active && isPoHeadlessToolModelVisible(entry.value);\n const reason = active\n ? discoverable\n ? undefined\n : 'not-discoverable'\n : !this.matches(entry.value.when)\n ? 'inactive'\n : !this.allowsTool(entry.value.name)\n ? 'restricted'\n : 'shadowed';\n capabilities.push({\n source: entry.source,\n name: entry.value.name,\n kind: 'tool',\n when: structuredClone(entry.value.when),\n active,\n discoverable,\n ...(reason ? { reason } : {}),\n });\n }\n // The session skill surface uses the last resolved declaration for a name.\n const resolved = new Map(\n this.resolvedResources.filter((entry) => entry.kind === 'skill').map((entry) => [entry.name, entry]),\n );\n for (const entry of this.kernel.activeValues<Owned<PoHeadlessResource>>('resources')) {\n if (entry.value.kind !== 'skill') continue;\n const current = resolved.get(entry.value.name);\n const selected = this.matches(entry.value.when);\n const active =\n selected &&\n current?.source === entry.source &&\n current.path === entry.value.path &&\n current.text.trim().length > 0;\n const discoverable = active && !!current?.path && !!current.description?.trim();\n const reason = !selected\n ? 'inactive'\n : current && current.source !== entry.source\n ? 'shadowed'\n : !active\n ? 'unavailable'\n : !discoverable\n ? 'not-discoverable'\n : undefined;\n capabilities.push({\n source: entry.source,\n name: entry.value.name,\n kind: 'skill',\n when: structuredClone(entry.value.when),\n active,\n discoverable,\n ...(reason ? { reason } : {}),\n });\n }\n }\n return { revision: this.appliedRevision, ready, capabilities };\n }\n /**\n * Every tool name this composition's eligible owners declare, including the\n * ones a condition or a restriction currently gates out.\n *\n * `appliedTools` answers what runs now. A merge that places another surface's\n * tools beside these needs what is spoken for, so a name a package deliberately\n * withheld is not handed to an unreconciled surface instead. Owner\n * eligibility stays the outer gate: a package the selection excluded declares\n * nothing here.\n */\n get declaredToolNames(): ReadonlySet<string> {\n return new Set(this.kernel.activeValues<Owned<PoHeadlessTool>>('tools').map((entry) => entry.value.name));\n }\n getContextInventory(\n selection: PoHeadlessSelection = this.applied,\n countTokens?: CountTokens,\n ): HeadlessContextInventory {\n const currentSources = new Set(\n this.options.candidates\n .filter(\n (candidate) =>\n candidate.scopes.includes('session') &&\n candidate.owners.some((owner) => owner.majorMode === selection.majorMode),\n )\n .map((candidate) => candidate.packageName),\n );\n const conditionAttribution = (when?: PoHeadlessCondition): ContextConditionalAttribution | undefined => {\n if (when?.attribution) return when.attribution;\n if (when?.domains?.length === 1) return { kind: 'domain', mode: when.domains[0]! };\n if (when?.domains && when.domains.length > 1) return { kind: 'shared', mode: 'po:shared', label: 'shared' };\n return when?.domain === undefined ? undefined : { kind: 'domain', mode: when.domain };\n };\n const mcpOwners = new Map<string, string>();\n for (const server of readPoMcpStatus(this.ctx)?.getSnapshot().servers ?? []) {\n for (const name of server.tools) mcpOwners.set(name, server.name);\n }\n const mcpPackages = new Map<string, string>();\n const toolsBySource = new Map<string, ContextToolInventory[]>();\n for (const contribution of this.kernel.contributions<Owned<PoHeadlessTool>>('tools')) {\n if (!currentSources.has(contribution.source)) continue;\n const tool = contribution.value.value;\n if (!isPoHeadlessToolModelVisible(tool)) continue;\n const contextAttribution = conditionAttribution(tool.when);\n const entry: ContextToolInventory = {\n name: tool.name,\n description: describeSkillTool(tool, this.resolvedResources),\n parameters: tool.parameters,\n ...(tool.promptSnippet === undefined ? {} : { promptSnippet: tool.promptSnippet }),\n ...(tool.promptGuidelines === undefined ? {} : { promptGuidelines: tool.promptGuidelines }),\n active: this.tools.get(tool.name) === contribution.value,\n ...(contextAttribution === undefined ? {} : { contextAttribution }),\n };\n const server = mcpOwners.get(tool.name);\n const source = server === undefined ? contribution.source : `mcp:${server}`;\n if (server !== undefined) mcpPackages.set(server, contribution.source);\n const tools = toolsBySource.get(source);\n if (tools) tools.push(entry);\n else toolsBySource.set(source, [entry]);\n }\n\n const sources: ContextToolSource[] = [...toolsBySource].map(([source, tools]) => ({\n key: source,\n label: mcpPackages.has(source.slice(4)) ? `${source.slice(4)} · mcp` : `${source} · extension`,\n kind: mcpPackages.has(source.slice(4)) ? 'mcp' : 'extension',\n packageName: mcpPackages.get(source.slice(4)) ?? source,\n tools,\n }));\n // The loader's tool description already carries the catalog. Charge standalone\n // listings only when the prompt emits them (every skill without the loader, pinned\n // ones with it), and only for paths the agent can open.\n const listedSkills = systemPromptSkills(\n this.resolvedResources,\n [...this.tools.values()].some(\n ({ value }) => value.name === PO_LOAD_SKILL_TOOL && isPoHeadlessToolModelVisible(value),\n ),\n );\n const framingTokens = countTokens === undefined ? 0 : countTokens(formatSkillsForSystemPrompt([]));\n const skills = this.resolvedResources.flatMap((resource) => {\n if (resource.kind !== 'skill') return [];\n const skill = headlessHarnessSkill(resource);\n const contextAttribution = conditionAttribution(this.resourceDeclarations.get(resource)?.when);\n return [\n {\n name: skill.name,\n description: skill.description,\n group: 'extensions' as const,\n owner: resource.source,\n modelInvocable: true,\n body: skill.content,\n ...(countTokens === undefined\n ? {}\n : {\n promptTokens: listedSkills.includes(resource)\n ? Math.max(0, countTokens(formatSkillsForSystemPrompt([skill])) - framingTokens)\n : 0,\n }),\n ...(contextAttribution === undefined ? {} : { contextAttribution }),\n },\n ];\n });\n const attribution: Record<string, PackageAttribution> = {};\n for (const candidate of this.options.candidates) {\n const owner =\n candidate.owners.find(\n (entry) =>\n entry.majorMode === selection.majorMode &&\n (entry.layer === 'default' || selection.activeLayers.includes(entry.layer)),\n ) ?? candidate.owners.find((entry) => entry.majorMode === selection.majorMode);\n if (owner && attribution[candidate.packageName] === undefined) {\n attribution[candidate.packageName] = { kind: 'major', mode: selection.majorMode, layer: owner.layer };\n }\n }\n for (const [server, source] of mcpPackages) {\n if (attribution[source]) attribution[server] = attribution[source];\n }\n return { sources, skills, attribution };\n }\n\n setAvailableSources(sources: readonly string[]): void {\n this.availableSources = new Set(sources);\n }\n\n /** Takes a reloaded package list; the next selection gates on it. */\n replaceCandidates(candidates: HeadlessHostOptions['candidates']): void {\n this.options = { ...this.options, candidates };\n }\n private matches(when?: PoHeadlessCondition): boolean {\n return (\n Object.entries(when?.state ?? {}).every(([key, value]) => this.applying.state?.[key]?.includes(value)) &&\n (when?.domain === undefined || this.applying.domains.includes(when.domain)) &&\n (when?.domains === undefined || when.domains.some((domain) => this.applying.domains.includes(domain)))\n );\n }\n private selected<T extends { when?: PoHeadlessCondition }>(entries: readonly Owned<T>[]): readonly Owned<T>[] {\n return entries.filter(({ value }) => this.matches(value.when));\n }\n\n assertActive(source?: string): void {\n this.assertReady();\n if (source !== undefined && !this.activeSources.has(source))\n throw new Error(`Contribution owner '${source}' is inactive`);\n }\n\n isSourceActive(source: string): boolean {\n return this.activeSources.has(source);\n }\n\n registerInitialSelectionResolver(\n resolve: (selection: PoHeadlessSelection) => PoHeadlessSelection | Promise<PoHeadlessSelection>,\n ): () => void {\n this.initialSelectionResolvers.add(resolve);\n const dispose = () => {\n this.initialSelectionResolvers.delete(resolve);\n };\n this.ctx.effect(() => dispose, 'headless initial selection resolver');\n return dispose;\n }\n\n subscribeSelection(\n listener: (selection: PoHeadlessSelection, applied: PoHeadlessSelectionApplied) => void | Promise<void>,\n ): () => void {\n this.selectionListeners.set(listener, readPoHeadlessOwner(this.ctx)?.packageName);\n return () => {\n this.selectionListeners.delete(listener);\n };\n }\n\n /** A contribution owned by a package that is not required, which may fail on its own. */\n private optionalSource(source: string | undefined): boolean {\n return (\n source !== undefined &&\n !this.options.candidates.some((candidate) => candidate.packageName === source && candidate.required)\n );\n }\n\n /** Shared by package reconciliation and the final Pi/package merge. */\n allowsTool(name: string): boolean {\n const allowed = this.options.allowedTools?.(this.applying);\n return (\n (name !== PO_SEARCH_SKILLS_TOOL || this.listSkills().length > FLAT_SKILL_LIMIT) &&\n (allowed === undefined || allowed.includes(name)) &&\n this.restrictions.every(\n (restriction) =>\n (restriction.allowedTools === undefined || restriction.allowedTools.includes(name)) &&\n !restriction.excludedTools?.includes(name),\n )\n );\n }\n\n registerToolRestriction(restriction: PoHeadlessToolRestriction): PoHeadlessRegistration {\n return this.add('restrictions', restriction);\n }\n\n private eligible(entry: PoServerBundleEntry, selection: PoHeadlessSelection): boolean {\n return (\n entry.scopes.includes('session') &&\n entry.owners.some(\n (owner) =>\n owner.majorMode === selection.majorMode &&\n (owner.layer === 'default' || selection.activeLayers.includes(owner.layer)),\n )\n );\n }\n\n changeSelection(change: PoHeadlessSelectionChange, options?: { atToolBoundary?: boolean }): Promise<void> {\n const apply = (change: PoHeadlessSelectionChange): Promise<void> => {\n this.selectionOverrides.add(change.axis);\n if (change.axis === 'majorMode') return this.select({ majorMode: change.majorMode });\n if (change.axis === 'domains') return this.select({ domains: change.domains });\n if (change.axis === 'profile') return this.select({ profile: change.profile });\n return this.select({ state: { ...this.requested.state, [change.key]: [...change.values] } });\n };\n return this.options.scheduleSelection?.(change, apply, options) ?? apply(change);\n }\n\n private async refreshChangedSelection(\n previous: PoHeadlessSelection,\n selection: PoHeadlessSelection,\n previousValues: ReadonlyMap<string, readonly unknown[]>,\n refreshed: readonly PoHeadlessRefreshAxis[],\n ): Promise<void> {\n const majorChanged =\n refreshed.includes('majorMode') ||\n previous.majorMode !== selection.majorMode ||\n !sameStrings(previous.activeLayers, selection.activeLayers);\n const domainsChanged = refreshed.includes('domains') || !sameStrings(previous.domains, selection.domains);\n const profileChanged = refreshed.includes('profile') || previous.profile !== selection.profile;\n const stateChanged = JSON.stringify(previous.state ?? {}) !== JSON.stringify(selection.state ?? {});\n if (this.appliedRevision === 0) return;\n\n const refresh = async (slot: string): Promise<void> => {\n const before = previousValues.get(slot) ?? [];\n if (sameValues(before, this.kernel.activeValues(slot))) await this.kernel.refresh(slot);\n };\n if (stateChanged) await refresh('restrictions');\n if (majorChanged || domainsChanged || stateChanged || this.restrictionsChanged) await refresh('tools');\n if (majorChanged || domainsChanged || profileChanged || stateChanged) await refresh('resources');\n if (domainsChanged || stateChanged) {\n await refresh('commands');\n await refresh('hooks');\n await refresh('activities');\n }\n }\n\n /** Refresh inherited defaults only at turn admission, keeping explicit session axes. */\n async inheritSelection(selection: Partial<PoHeadlessSelection>): Promise<void> {\n const patch: Partial<PoHeadlessSelection> = {\n ...(!this.selectionOverrides.has('majorMode') && selection.majorMode !== undefined\n ? { majorMode: selection.majorMode }\n : {}),\n ...(!this.selectionOverrides.has('domains') && selection.domains !== undefined\n ? { domains: selection.domains }\n : {}),\n ...(!this.selectionOverrides.has('profile') && Object.hasOwn(selection, 'profile')\n ? { profile: selection.profile }\n : {}),\n };\n if (\n (patch.majorMode === undefined || patch.majorMode === this.requested.majorMode) &&\n (patch.domains === undefined || sameStrings(patch.domains, this.requested.domains)) &&\n (!Object.hasOwn(patch, 'profile') || patch.profile === this.requested.profile)\n )\n return;\n await this.select(patch);\n }\n\n /**\n * Applies `patch` over the requested selection. `refresh` re-applies those axes as if they had\n * changed, for config edited on disk under an unchanged name, and tells selection listeners so.\n */\n async select(\n patch: Partial<PoHeadlessSelection>,\n options?: { readonly refresh?: readonly PoHeadlessRefreshAxis[] },\n ): Promise<void> {\n const refreshed = options?.refresh ?? [];\n if (this.disposed) throw new Error('The headless host is disposed');\n const requested = structuredClone({ ...this.requested, ...patch });\n this.requested = requested;\n const revision = ++this.requestedRevision;\n this.ready = false;\n const apply = async (): Promise<void> => {\n if (this.disposed) throw new Error('The headless host is disposed');\n let resolved = structuredClone(requested);\n if (this.appliedRevision === 0) {\n for (const resolve of this.initialSelectionResolvers) resolved = await resolve(resolved);\n if (this.disposed) throw new Error('The headless host is disposed');\n // A completed launch decision, including unchanged None, cannot be replaced by turn defaults.\n // If resolution rejects above no decision is latched, so a retry can resolve again.\n if (this.initialSelectionResolvers.size > 0) this.selectionOverrides.add('profile');\n }\n const selection = structuredClone((await this.options.resolveSelection?.(resolved)) ?? resolved);\n await this.options.validateSelection?.(selection);\n if (revision === this.requestedRevision) this.requested = selection;\n const eligible = this.options.candidates.filter((entry) => this.eligible(entry, selection));\n const missing = eligible.find((entry) => entry.required && !this.availableSources.has(entry.packageName));\n if (missing) throw new Error(`Required headless package '${missing.packageName}' is unavailable`);\n // The kernel's layer key here is the precomputed package eligibility key.\n // Minor tool restrictions run in the tools sink only after this owner gate.\n this.applying = selection;\n this.refreshing = true;\n let compositionChanged = false;\n try {\n const previousValues = new Map(\n this.kernel.slots.map((slot) => [slot, this.kernel.activeValues(slot)] as const),\n );\n await this.kernel.setActiveLayers(eligible.map((entry) => entry.packageName));\n await this.refreshChangedSelection(this.applied, selection, previousValues, refreshed);\n compositionChanged =\n refreshed.length > 0 ||\n this.failure !== undefined ||\n this.appliedRevision === 0 ||\n !sameSelection(this.applied, selection) ||\n this.restrictionsChanged ||\n this.contributionsChanged ||\n !sameValues(previousValues.get('tools') ?? [], this.kernel.activeValues('tools')) ||\n !sameValues(previousValues.get('resources') ?? [], this.kernel.activeValues('resources'));\n this.restrictionsChanged = false;\n this.contributionsChanged = false;\n } finally {\n this.refreshing = false;\n }\n if (this.disposed) throw new Error('The headless host is disposed');\n this.activeSources = new Set(eligible.map((entry) => entry.packageName));\n this.applied = selection;\n this.appliedRevision = revision;\n this.failure = undefined;\n this.ready = revision === this.requestedRevision;\n for (const [listener, owner] of this.selectionListeners) {\n try {\n await listener(selection, refreshed.length === 0 ? {} : { refresh: refreshed });\n } catch (error) {\n if (isPoHeadlessPromptAdmissionError(error)) this.recoveryRevision = revision;\n // A host listener or a required package fails the selection; any other package's is reported.\n if (isPoHeadlessPromptAdmissionError(error) || !this.optionalSource(owner)) throw error;\n const reason = error instanceof Error ? error.message : String(error);\n this.options.onError?.(new Error(`package '${owner}': ${reason}`, { cause: error }), 'selection');\n }\n }\n if (compositionChanged) await this.options.onApplied?.(selection, revision);\n };\n const result = this.tail.catch(() => undefined).then(apply);\n this.tail = result.catch((error: unknown) => {\n this.failure = error;\n this.ready = false;\n // close() marks the host disposed before draining this tail, so every selection still\n // queued at that point rejects by design. Those rejections are teardown artifacts, not\n // actionable failures, and reporting them surfaces one notice per queued contribution.\n if (!this.disposed) this.options.onError?.(error, 'apply');\n });\n await result;\n await this.settled();\n const failure: unknown = this.failure;\n if (failure instanceof Error) throw failure;\n if (failure !== undefined)\n throw new Error(typeof failure === 'string' ? failure : 'Headless selection failed', { cause: failure });\n this.assertReady();\n }\n\n /** Drain selections, including ones queued by selection listeners. */\n async settled(): Promise<void> {\n let pending: Promise<void>;\n do {\n pending = this.tail;\n await pending;\n } while (pending !== this.tail);\n }\n\n private assertReady(): void {\n if (this.disposed || !this.ready)\n throw new Error('Headless dispatch is blocked until selection is coherently applied');\n }\n\n /** Runs an approved direct tool call against the tool as it is now: removed or inactive tools do not run. */\n private async runApproved(call: PoApprovedCall, signal: AbortSignal): Promise<PoHeadlessToolResult> {\n await this.settled();\n this.assertReady();\n const entry = this.tools.get(call.operation.name);\n if (entry === undefined || !this.activeSources.has(entry.source))\n throw new Error(`Tool '${call.operation.name}' is no longer active. Nothing ran.`);\n signal.throwIfAborted();\n return entry.value.execute(`approval:${call.approvalId}`, call.input, signal, undefined, {\n ...this.context,\n caller: 'main',\n });\n }\n\n private add<T>(slot: string, value: T): PoHeadlessRegistration {\n const owner = readPoHeadlessOwner(this.ctx);\n if (!owner) throw new Error('A headless contribution must have descriptor-owned package identity');\n this.ready = false;\n this.contributionsChanged = true;\n const registration = this.kernel.contribute(slot, {\n source: owner.packageName,\n layer: owner.packageName,\n value: { source: owner.packageName, value } satisfies Owned<T>,\n });\n let disposed = false;\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n this.ready = false;\n this.contributionsChanged = true;\n registration.dispose();\n // Reconciled on the same terms as the registration below: before the first applied\n // selection the caller's own select() computes the whole composition, and the sources\n // that selection gates on are not known yet.\n if (this.appliedRevision > 0 && !this.disposed && !this.refreshing) void this.select({}).catch(() => undefined);\n };\n this.ctx.effect(() => dispose, `headless ${slot} contribution`);\n // Initial registration is reconciled once the caller has installed all packages.\n if (this.appliedRevision > 0 && !this.refreshing) void this.select({}).catch(() => undefined);\n return { dispose };\n }\n\n registerTool<TParameters extends TSchema>(tool: PoHeadlessTool<TParameters>): PoHeadlessRegistration {\n return this.add('tools', tool);\n }\n registerResource(resource: PoHeadlessResource): PoHeadlessRegistration {\n return this.add('resources', resource);\n }\n registerCommand(command: PoHeadlessCommand): PoHeadlessRegistration {\n return this.add('commands', command);\n }\n registerHook(hook: PoHeadlessHook): PoHeadlessRegistration {\n return this.add('hooks', hook);\n }\n registerActivity(activity: PoHeadlessActivity): PoHeadlessRegistration {\n return this.add('activities', activity);\n }\n\n private canRecoverSelection(): boolean {\n return (\n !this.disposed &&\n !this.ready &&\n !this.refreshing &&\n !this.contributionsChanged &&\n !this.restrictionsChanged &&\n this.recoveryRevision === this.requestedRevision &&\n this.appliedRevision === this.requestedRevision &&\n isPoHeadlessPromptAdmissionError(this.failure)\n );\n }\n\n listCommands(): Array<Pick<PoHeadlessCommand, 'name' | 'description'>> {\n const recovering = this.canRecoverSelection();\n if (!recovering) this.assertReady();\n return [...this.commands.values()]\n .filter(\n ({ source, value }) =>\n !recovering ||\n (value.selectionRecovery === true && this.activeSources.has(source) && this.availableSources.has(source)),\n )\n .map(({ value }) => ({ name: value.name, description: value.description }));\n }\n\n async dispatchCommand(name: string, args: string): Promise<void> {\n const command = this.commands.get(name);\n if (!this.canRecoverSelection() || command?.value.selectionRecovery !== true) this.assertReady();\n if (!command || !this.activeSources.has(command.source) || !this.availableSources.has(command.source))\n throw new Error(`Command '${name}' is inactive or unknown`);\n await command.value.execute(args, this.context);\n }\n\n async dispatchHook(\n event: PoHeadlessEventName,\n payload: Readonly<Record<string, unknown>>,\n signal?: AbortSignal,\n ): Promise<unknown[]> {\n this.assertReady();\n signal?.throwIfAborted();\n const results: unknown[] = [];\n const revision = this.appliedRevision;\n let current = payload;\n for (const hook of this.hooks.filter((entry) => entry.value.event === event)) {\n this.assertReady();\n signal?.throwIfAborted();\n if (!this.hooks.includes(hook)) continue;\n let result: unknown;\n try {\n result = await hook.value.handle(current as never, signal ? { ...this.context, signal } : this.context);\n signal?.throwIfAborted();\n } catch (error) {\n if (isPoHeadlessPromptAdmissionError(error)) throw error;\n signal?.throwIfAborted();\n this.options.onError?.(error, 'hook');\n continue;\n }\n if (event === 'session_start') {\n // Startup hooks may register retained contributions. Finish their queued reconciliation\n // before the next hook, without relaxing dispatch guards during the transition.\n await this.tail;\n this.assertReady();\n }\n results.push(result);\n if (result && typeof result === 'object' && !Array.isArray(result)) {\n const patch = result as Record<string, unknown>;\n // Execution hooks compose in registration order, just like the public harness hooks.\n const fields =\n event === 'context'\n ? ['messages', 'systemPrompt']\n : event === 'tool_call'\n ? ['args']\n : event === 'tool_result'\n ? ['content', 'details', 'isError', 'usage']\n : event === 'before_agent_start'\n ? ['systemPrompt']\n : event === 'before_provider_request'\n ? ['payload']\n : [];\n for (const field of fields) {\n if (event === 'before_agent_start' && typeof patch[field] !== 'string') continue;\n if (patch[field] !== undefined) current = { ...current, [field]: patch[field] };\n }\n // Denials and structural decisions use upstream first-result semantics.\n if (event === 'tool_call' && patch.block !== undefined) break;\n if (\n event === 'session_before_compact' &&\n (patch.cancel !== undefined || patch.decline !== undefined || patch.compaction !== undefined)\n )\n break;\n }\n }\n if (event === 'before_agent_start' || event === 'context' || event === 'tool_call') {\n this.assertReady();\n if (revision !== this.appliedRevision) {\n throw new Error(\n event === 'before_agent_start'\n ? 'Selection changed while preparing the system prompt'\n : `Selection changed while dispatching ${event}`,\n );\n }\n }\n return results;\n }\n\n private async resolveResources(selection: PoHeadlessSelection): Promise<readonly ResolvedHeadlessResource[]> {\n const context = this.options.context(selection);\n const result: ResolvedHeadlessResource[] = [];\n for (const resource of this.resources) {\n let value: string;\n try {\n value = await resource.value.read(context);\n } catch (error) {\n // Report and skip, never rethrow. This runs on every prompt build, and a\n // throw here reaches the systemPrompt callback, sets promptPreparationFailed\n // and denies every model request for the rest of the session. One package\n // missing one shipped file must not take the session down with it.\n this.options.onError?.(\n new Error(`Could not read headless resource '${resource.source}/${resource.value.name}'`, { cause: error }),\n 'resource',\n );\n continue;\n }\n const resolved: ResolvedHeadlessResource = {\n source: resource.source,\n name: resource.value.name,\n kind: resource.value.kind,\n ...(resource.value.description === undefined ? {} : { description: resource.value.description }),\n ...(resource.value.path === undefined ? {} : { path: resource.value.path }),\n ...(resource.value.pinned === true ? { pinned: true } : {}),\n text: value,\n };\n this.resourceDeclarations.set(resolved, resource.value);\n result.push(resolved);\n }\n return result;\n }\n\n async readResources(): Promise<readonly ResolvedHeadlessResource[]> {\n this.assertReady();\n const revision = this.appliedRevision;\n const result = await this.resolveResources(this.applied);\n this.assertReady();\n if (revision !== this.appliedRevision) throw new Error('Selection changed while reading resources');\n return result;\n }\n\n async close(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n this.ready = false;\n this.selectionListeners.clear();\n await this.tail.catch(() => undefined);\n const failures: unknown[] = [];\n for (const stop of [...this.activities.values()].reverse()) {\n try {\n await stop();\n } catch (error) {\n failures.push(error);\n }\n }\n this.activities.clear();\n this.kernel.dispose();\n if (failures.length) throw new AggregateError(failures, 'Headless activities failed to stop');\n }\n}\n"],"mappings":";;;;;;;;;;AAkDA,SAAS,YAAY,MAAyB,OAAmC;CAC/E,OAAO,KAAK,WAAW,MAAM,UAAU,KAAK,OAAO,OAAO,UAAU,UAAU,MAAM,MAAM;AAC5F;AAEA,SAAS,WAAW,MAA0B,OAAoC;CAChF,OAAO,KAAK,WAAW,MAAM,UAAU,KAAK,OAAO,OAAO,UAAU,UAAU,MAAM,MAAM;AAC5F;AAEA,SAAS,cAAc,MAA2B,OAAqC;CACrF,OACE,KAAK,cAAc,MAAM,aACzB,KAAK,YAAY,MAAM,WACvB,YAAY,KAAK,cAAc,MAAM,YAAY,KACjD,YAAY,KAAK,SAAS,MAAM,OAAO,KACvC,KAAK,UAAU,KAAK,SAAS,CAAC,CAAC,MAAM,KAAK,UAAU,MAAM,SAAS,CAAC,CAAC;AAEzE;;;;;;;;;;AAWA,SAAgB,qBAAqB,UAAoC;CACvE,OAAO;EACL,MAAM,SAAS;EACf,aAAa,SAAS,eAAe,uBAAuB,SAAS;EACrE,SAAS,SAAS;EAClB,UAAU,SAAS,QAAQ,iBAAiB,SAAS,OAAO,GAAG,SAAS;CAC1E;AACF;AAEA,SAAS,UAAU,OAAuB;CACxC,OAAO,MAAM,QAAQ,MAAM,OAAO,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,MAAM,CAAC,CAAC,QAAQ,MAAM,QAAQ;AACxG;AAEA,MAAM,mBAAmB;AAEzB,SAAS,aAAa,WAAqF;CACzG,OAAO,UAAU,QACd,OAAO,OAAO,QACb,MAAM,SAAS,WACf,IAAI,eAAe,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ACtB,MAAM,SAAS,MAAM,KAAK,iBAAiB,KAAK,OAAO;EACvD,KAAK,YAAY;EACjB,IAAI,aAAa,KAAK,iBAAiB,MAAM,IAAI,MAAM,2CAA2C;EAClG,OAAO;CACT;CAEA,MAAM,QAAuB;EAC3B,IAAI,KAAK,UAAU;EACnB,KAAK,WAAW;EAChB,KAAK,QAAQ;EACb,KAAK,mBAAmB,MAAM;EAC9B,MAAM,KAAK,KAAK,YAAY,KAAA,CAAS;EACrC,MAAM,WAAsB,CAAC;EAC7B,KAAK,MAAM,QAAQ,CAAC,GAAG,KAAK,WAAW,OAAO,CAAC,CAAC,CAAC,QAAQ,GACvD,IAAI;GACF,MAAM,KAAK;EACb,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAEF,KAAK,WAAW,MAAM;EACtB,KAAK,OAAO,QAAQ;EACpB,IAAI,SAAS,QAAQ,MAAM,IAAI,eAAe,UAAU,oCAAoC;CAC9F;AACF"}
|
|
1
|
+
{"version":3,"file":"headlessHost.cjs","names":["PO_SEARCH_SKILLS_TOOL","Service","createPoKernel","PO_HEADLESS_HOST_SERVICE","PO_APPROVAL_SERVICE","readPoApproval","gateApproval","isPoHeadlessToolModelVisible","readPoMcpStatus","formatSkillsForSystemPrompt","readPoHeadlessOwner","isPoHeadlessPromptAdmissionError"],"sources":["../../../../../src/systems/main/adapters/headlessHost.ts"],"sourcesContent":["import { Context, Service } from '@deepseek-ai/cordis';\nimport type { TSchema } from 'typebox';\n\nimport { PO_APPROVAL_SERVICE, type PoApprovedCall, readPoApproval } from '../../../exports/approval';\nimport {\n PO_HEADLESS_HOST_SERVICE,\n PO_LOAD_SKILL_TOOL,\n PO_SEARCH_SKILLS_TOOL,\n readPoHeadlessOwner,\n isPoHeadlessPromptAdmissionError,\n type PoHeadlessActivity,\n type PoHeadlessCommand,\n type PoHeadlessEventName,\n type PoHeadlessExecutionContext,\n type PoHeadlessHook,\n type PoHeadlessHostService,\n isPoHeadlessToolModelVisible,\n type PoHeadlessRegistration,\n type PoHeadlessResource,\n type PoHeadlessRefreshAxis,\n type PoHeadlessSelection,\n type PoHeadlessSelectionApplied,\n type PoHeadlessSelectionChange,\n type PoHeadlessTool,\n type PoHeadlessToolResult,\n type PoHeadlessCondition,\n type PoHeadlessToolRestriction,\n} from '../../../exports/headless';\nimport { createPoKernel } from '../../../exports/kernel';\nimport { readPoMcpStatus } from '../../../exports/mcpStatus';\nimport type { PoServerBundleEntry } from '../../../exports/serverPlugin';\nimport { gateApproval } from '../../../services/approvalGate';\nimport type { PackageAttribution } from '../../../services/contextProjection';\nimport type {\n ContextConditionalAttribution,\n ContextToolInventory,\n ContextToolSource,\n} from '../../../services/contextProjection';\nimport { formatSkillsForSystemPrompt } from '../../../services/skillPrompt';\nimport type { CountTokens } from '../../../services/toolInventory';\nimport type {\n HeadlessContextInventory,\n HeadlessHostOptions,\n HeadlessSelectionStatus,\n ResolvedHeadlessResource,\n} from '../types/headlessHost';\n\ntype Owned<T> = { source: string; value: T };\ntype StopActivity = () => void | Promise<void>;\n\nfunction sameStrings(left: readonly string[], right: readonly string[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction sameValues(left: readonly unknown[], right: readonly unknown[]): boolean {\n return left.length === right.length && left.every((value, index) => value === right[index]);\n}\n\nfunction sameSelection(left: PoHeadlessSelection, right: PoHeadlessSelection): boolean {\n return (\n left.majorMode === right.majorMode &&\n left.profile === right.profile &&\n sameStrings(left.activeLayers, right.activeLayers) &&\n sameStrings(left.domains, right.domains) &&\n JSON.stringify(left.state ?? {}) === JSON.stringify(right.state ?? {})\n );\n}\n\n/**\n * Maps one typed headless resource to the exact skill shape installed in AgentHarness.\n *\n * Prefers the resource's own `description` and `path`. The fallbacks below are what\n * every skill used to get, and they are only good enough for explicit invocation,\n * which matches on name: `po-headless://` is not a path any tool can open, and\n * \"Headless skill from <source>\" gives the model nothing to select on. A skill is\n * only advertised in the prompt once it carries a real path.\n */\nexport function headlessHarnessSkill(resource: ResolvedHeadlessResource) {\n return {\n name: resource.name,\n description: resource.description ?? `Headless skill from ${resource.source}`,\n content: resource.text,\n filePath: resource.path ?? `po-headless://${resource.source}/${resource.name}`,\n };\n}\n\nfunction escapeXml(value: string): string {\n return value.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/\"/g, '"');\n}\n\nconst FLAT_SKILL_LIMIT = 20;\nconst RESOURCE_READ_ATTEMPTS = 5;\n\nfunction uniqueSkills(resources: readonly ResolvedHeadlessResource[]): readonly ResolvedHeadlessResource[] {\n return resources.filter(\n (skill, index, all) =>\n skill.kind === 'skill' &&\n all.findLastIndex((entry) => entry.kind === 'skill' && entry.name === skill.name) === index,\n );\n}\n\n/** The searchable catalog. Pinned skills are listed in the system prompt instead. */\nfunction activeSkills(resources: readonly ResolvedHeadlessResource[]): readonly ResolvedHeadlessResource[] {\n return uniqueSkills(resources).filter((skill) => skill.pinned !== true);\n}\n\n/** Exactly the summaries emitted in the system prompt, also used for context billing. */\nexport function systemPromptSkills(resources: readonly ResolvedHeadlessResource[], hasLoader: boolean) {\n return uniqueSkills(resources).filter((skill) => skill.path !== undefined && (!hasLoader || skill.pinned === true));\n}\n\n/** Skill discovery prose follows the applied catalog, including selection changes. */\nexport function describeSkillTool(\n tool: Pick<PoHeadlessTool, 'name' | 'description'>,\n resources: readonly ResolvedHeadlessResource[],\n): string {\n if (tool.name !== PO_LOAD_SKILL_TOOL && tool.name !== PO_SEARCH_SKILLS_TOOL) return tool.description;\n const listed = activeSkills(resources);\n if (tool.name === PO_LOAD_SKILL_TOOL && listed.length > FLAT_SKILL_LIMIT)\n return `${tool.description}\\nUse ${PO_SEARCH_SKILLS_TOOL} to find available skill names.`;\n if (listed.length === 0) return tool.description;\n return [\n tool.description,\n '',\n '<available_skills>',\n ...listed.flatMap((skill) =>\n tool.name === PO_SEARCH_SKILLS_TOOL\n ? [` <name>${escapeXml(skill.name)}</name>`]\n : [\n ' <skill>',\n ` <name>${escapeXml(skill.name)}</name>`,\n ` <description>${escapeXml(headlessHarnessSkill(skill).description)}</description>`,\n ' </skill>',\n ],\n ),\n '</available_skills>',\n ].join('\\n');\n}\n\n/** Retains packages and their state; only kernel-computed active contributions change. */\nexport class HeadlessHost extends Service<PoHeadlessHostService> implements PoHeadlessHostService {\n private readonly kernel = createPoKernel();\n /** Each selection listener and the package that subscribed it; undefined for the host's own. */\n private readonly selectionListeners = new Map<\n (selection: PoHeadlessSelection, applied: PoHeadlessSelectionApplied) => void | Promise<void>,\n string | undefined\n >();\n private readonly initialSelectionResolvers = new Set<\n (selection: PoHeadlessSelection) => PoHeadlessSelection | Promise<PoHeadlessSelection>\n >();\n private restrictions: readonly PoHeadlessToolRestriction[] = [];\n private restrictionsChanged = false;\n private contributionsChanged = false;\n private options: HeadlessHostOptions;\n private readonly selectionOverrides: Set<string>;\n private applied: PoHeadlessSelection;\n private requested: PoHeadlessSelection;\n private applying: PoHeadlessSelection;\n private refreshing = false;\n private requestedRevision = 0;\n private appliedRevision = 0;\n private recoveryRevision = 0;\n private ready = false;\n private disposed = false;\n private failure: unknown;\n private tail: Promise<void> = Promise.resolve();\n private activeSources = new Set<string>();\n private availableSources = new Set<string>();\n private tools = new Map<string, Owned<PoHeadlessTool>>();\n private resources: readonly Owned<PoHeadlessResource>[] = [];\n private resolvedResources: readonly ResolvedHeadlessResource[] = [];\n private readonly resourceDeclarations = new WeakMap<ResolvedHeadlessResource, PoHeadlessResource>();\n private commands = new Map<string, Owned<PoHeadlessCommand>>();\n private hooks: readonly Owned<PoHeadlessHook>[] = [];\n private readonly activities = new Map<Owned<PoHeadlessActivity>, StopActivity>();\n\n constructor(context: Context, options: HeadlessHostOptions) {\n super(context, PO_HEADLESS_HOST_SERVICE);\n this.options = options;\n this.selectionOverrides = new Set(options.selectionOverrides);\n this.applied = structuredClone(options.selection);\n this.requested = this.applied;\n this.applying = this.applied;\n context.effect(() => () => this.close(), 'headless host lifetime');\n context.inject([PO_APPROVAL_SERVICE], (child) =>\n readPoApproval(child)?.registerExecutor('tool', (call, signal) => this.runApproved(call, signal)),\n );\n this.kernel.defineSlot<Owned<PoHeadlessToolRestriction>>('restrictions', (entries) => {\n this.restrictionsChanged = true;\n this.restrictions = entries.map((entry) => entry.value).filter((restriction) => this.matches(restriction.when));\n });\n const applyTools = async (entries: readonly Owned<PoHeadlessTool>[]): Promise<void> => {\n const next = new Map<string, Owned<PoHeadlessTool>>();\n for (const entry of this.selected(entries)) {\n if (!this.allowsTool(entry.value.name)) continue;\n if (!next.has(entry.value.name)) next.set(entry.value.name, entry);\n }\n const tools = [...next.values()].map((entry): PoHeadlessTool => ({\n ...entry.value,\n execute: async (id, parameters, signal, onUpdate, execution) => {\n this.assertReady();\n const active = () => this.tools.get(entry.value.name) === entry && this.activeSources.has(entry.source);\n if (!active()) throw new Error(`Tool '${entry.value.name}' is no longer active`);\n const context = this.context;\n const caller =\n context.caller === 'child' || execution?.caller === 'child'\n ? 'child'\n : (execution?.caller ?? context.caller);\n const interaction = context.interaction === 'unattended' ? 'unattended' : context.sessionContext?.interaction;\n const gate = await gateApproval({\n policy: entry.value.approval,\n operation: { kind: 'tool', name: entry.value.name },\n input: parameters,\n arguments: parameters,\n sessionId: context.sessionId,\n toolCallId: id,\n ...(caller === undefined ? {} : { caller }),\n ...(interaction === undefined ? {} : { interaction }),\n service: readPoApproval(this.ctx),\n ...(signal === undefined ? {} : { signal }),\n });\n if (gate.ok === false && gate.pending === true)\n return { content: [{ type: 'text', text: gate.reason }], details: { approvalId: gate.approvalId } };\n if (!gate.ok) throw new Error(gate.reason);\n return entry.value.execute(id, parameters, signal, onUpdate, {\n ...this.context,\n ...(execution?.toolContinuation ? { toolContinuation: execution.toolContinuation } : {}),\n ...(caller === undefined ? {} : { caller }),\n });\n },\n }));\n await this.options.applyTools(tools);\n this.tools = next;\n };\n this.kernel.defineSlot<Owned<PoHeadlessTool>>('tools', applyTools);\n this.kernel.defineSlot<Owned<PoHeadlessResource>>('resources', async (entries) => {\n const searchable = this.listSkills().length > FLAT_SKILL_LIMIT;\n this.resources = this.selected(entries);\n this.resolvedResources = await this.resolveResources(this.applying);\n await this.options.applyResources(this.resolvedResources);\n // Resources can cross the cutoff even when the tool declarations are unchanged.\n if (searchable !== this.listSkills().length > FLAT_SKILL_LIMIT)\n await applyTools(this.kernel.activeValues<Owned<PoHeadlessTool>>('tools'));\n });\n this.kernel.defineSlot<Owned<PoHeadlessCommand>>('commands', (entries) => {\n const next = new Map<string, Owned<PoHeadlessCommand>>();\n for (const entry of this.selected(entries)) if (!next.has(entry.value.name)) next.set(entry.value.name, entry);\n this.commands = next;\n });\n this.kernel.defineSlot<Owned<PoHeadlessHook>>('hooks', (entries) => {\n this.hooks = this.selected(entries);\n });\n this.kernel.defineSlot<Owned<PoHeadlessActivity>>('activities', async (entries) => {\n const desired = new Set(this.selected(entries));\n for (const [entry, stop] of [...this.activities].reverse()) {\n if (desired.has(entry)) continue;\n this.activities.delete(entry);\n try {\n await stop();\n } catch (error) {\n // A package's activity that fails to stop is reported; the others still stop and start.\n this.options.onError?.(error, 'activity');\n }\n }\n for (const entry of desired) {\n if (this.activities.has(entry)) continue;\n try {\n const stop = await entry.value.start(this.options.context(this.applying));\n this.activities.set(entry, stop);\n } catch (error) {\n if (!this.optionalSource(entry.source)) throw error;\n this.options.onError?.(error, 'activity');\n }\n }\n });\n }\n\n get context(): PoHeadlessExecutionContext {\n return this.options.context(this.applied);\n }\n\n get status(): HeadlessSelectionStatus {\n return {\n requestedRevision: this.requestedRevision,\n appliedRevision: this.appliedRevision,\n ready: this.ready,\n ...(this.failure === undefined\n ? {}\n : {\n error:\n this.failure instanceof Error\n ? this.failure.message\n : typeof this.failure === 'string'\n ? this.failure\n : 'Headless selection failed',\n }),\n };\n }\n\n /**\n * The resources the last applied selection resolved to.\n *\n * `readResources` re-reads them for a live request and refuses while a\n * selection is mid-apply. A reader describing the applied composition wants\n * the same snapshot `getContextInventory` reports against, and wants it at\n * the same moments, so it reads this instead of dispatching.\n */\n get appliedResources(): readonly ResolvedHeadlessResource[] {\n return this.resolvedResources;\n }\n\n get toolSurface(): PoHeadlessHostService['toolSurface'] {\n return this.options.toolSurface?.();\n }\n\n readSkill(name: string): string | undefined {\n // The last declaration of a name is the one the session uses.\n return this.resolvedResources.findLast((entry) => entry.kind === 'skill' && entry.name === name)?.text;\n }\n\n listSkills(): ReturnType<PoHeadlessHostService['listSkills']> {\n return activeSkills(this.resolvedResources).map((resource) => {\n const { name, description } = headlessHarnessSkill(resource);\n return { name, description };\n });\n }\n\n inspectCapabilities(): ReturnType<PoHeadlessHostService['inspectCapabilities']> {\n const ready = this.ready && !this.disposed;\n const capabilities: ReturnType<PoHeadlessHostService['inspectCapabilities']>['capabilities'][number][] = [];\n if (ready) {\n for (const entry of this.kernel.activeValues<Owned<PoHeadlessTool>>('tools')) {\n const active = this.tools.get(entry.value.name) === entry;\n const discoverable = active && isPoHeadlessToolModelVisible(entry.value);\n const reason = active\n ? discoverable\n ? undefined\n : 'not-discoverable'\n : !this.matches(entry.value.when)\n ? 'inactive'\n : !this.allowsTool(entry.value.name)\n ? 'restricted'\n : 'shadowed';\n capabilities.push({\n source: entry.source,\n name: entry.value.name,\n kind: 'tool',\n when: structuredClone(entry.value.when),\n active,\n discoverable,\n ...(reason ? { reason } : {}),\n });\n }\n // The session skill surface uses the last resolved declaration for a name.\n const resolved = new Map(\n this.resolvedResources.filter((entry) => entry.kind === 'skill').map((entry) => [entry.name, entry]),\n );\n for (const entry of this.kernel.activeValues<Owned<PoHeadlessResource>>('resources')) {\n if (entry.value.kind !== 'skill') continue;\n const current = resolved.get(entry.value.name);\n const selected = this.matches(entry.value.when);\n const active =\n selected &&\n current?.source === entry.source &&\n current.path === entry.value.path &&\n current.text.trim().length > 0;\n const discoverable = active && !!current?.path && !!current.description?.trim();\n const reason = !selected\n ? 'inactive'\n : current && current.source !== entry.source\n ? 'shadowed'\n : !active\n ? 'unavailable'\n : !discoverable\n ? 'not-discoverable'\n : undefined;\n capabilities.push({\n source: entry.source,\n name: entry.value.name,\n kind: 'skill',\n when: structuredClone(entry.value.when),\n active,\n discoverable,\n ...(reason ? { reason } : {}),\n });\n }\n }\n return { revision: this.appliedRevision, ready, capabilities };\n }\n /**\n * Every tool name this composition's eligible owners declare, including the\n * ones a condition or a restriction currently gates out.\n *\n * `appliedTools` answers what runs now. A merge that places another surface's\n * tools beside these needs what is spoken for, so a name a package deliberately\n * withheld is not handed to an unreconciled surface instead. Owner\n * eligibility stays the outer gate: a package the selection excluded declares\n * nothing here.\n */\n get declaredToolNames(): ReadonlySet<string> {\n return new Set(this.kernel.activeValues<Owned<PoHeadlessTool>>('tools').map((entry) => entry.value.name));\n }\n getContextInventory(\n selection: PoHeadlessSelection = this.applied,\n countTokens?: CountTokens,\n ): HeadlessContextInventory {\n const currentSources = new Set(\n this.options.candidates\n .filter(\n (candidate) =>\n candidate.scopes.includes('session') &&\n candidate.owners.some((owner) => owner.majorMode === selection.majorMode),\n )\n .map((candidate) => candidate.packageName),\n );\n const conditionAttribution = (when?: PoHeadlessCondition): ContextConditionalAttribution | undefined => {\n if (when?.attribution) return when.attribution;\n if (when?.domains?.length === 1) return { kind: 'domain', mode: when.domains[0]! };\n if (when?.domains && when.domains.length > 1) return { kind: 'shared', mode: 'po:shared', label: 'shared' };\n return when?.domain === undefined ? undefined : { kind: 'domain', mode: when.domain };\n };\n const mcpOwners = new Map<string, string>();\n for (const server of readPoMcpStatus(this.ctx)?.getSnapshot().servers ?? []) {\n for (const name of server.tools) mcpOwners.set(name, server.name);\n }\n const mcpPackages = new Map<string, string>();\n const toolsBySource = new Map<string, ContextToolInventory[]>();\n for (const contribution of this.kernel.contributions<Owned<PoHeadlessTool>>('tools')) {\n if (!currentSources.has(contribution.source)) continue;\n const tool = contribution.value.value;\n if (!isPoHeadlessToolModelVisible(tool)) continue;\n const contextAttribution = conditionAttribution(tool.when);\n const entry: ContextToolInventory = {\n name: tool.name,\n description: describeSkillTool(tool, this.resolvedResources),\n parameters: tool.parameters,\n ...(tool.promptSnippet === undefined ? {} : { promptSnippet: tool.promptSnippet }),\n ...(tool.promptGuidelines === undefined ? {} : { promptGuidelines: tool.promptGuidelines }),\n active: this.tools.get(tool.name) === contribution.value,\n ...(contextAttribution === undefined ? {} : { contextAttribution }),\n };\n const server = mcpOwners.get(tool.name);\n const source = server === undefined ? contribution.source : `mcp:${server}`;\n if (server !== undefined) mcpPackages.set(server, contribution.source);\n const tools = toolsBySource.get(source);\n if (tools) tools.push(entry);\n else toolsBySource.set(source, [entry]);\n }\n\n const sources: ContextToolSource[] = [...toolsBySource].map(([source, tools]) => ({\n key: source,\n label: mcpPackages.has(source.slice(4)) ? `${source.slice(4)} · mcp` : `${source} · extension`,\n kind: mcpPackages.has(source.slice(4)) ? 'mcp' : 'extension',\n packageName: mcpPackages.get(source.slice(4)) ?? source,\n tools,\n }));\n // The loader's tool description already carries the catalog. Charge standalone\n // listings only when the prompt emits them (every skill without the loader, pinned\n // ones with it), and only for paths the agent can open.\n const listedSkills = systemPromptSkills(\n this.resolvedResources,\n [...this.tools.values()].some(\n ({ value }) => value.name === PO_LOAD_SKILL_TOOL && isPoHeadlessToolModelVisible(value),\n ),\n );\n const framingTokens = countTokens === undefined ? 0 : countTokens(formatSkillsForSystemPrompt([]));\n const skills = this.resolvedResources.flatMap((resource) => {\n if (resource.kind !== 'skill') return [];\n const skill = headlessHarnessSkill(resource);\n const contextAttribution = conditionAttribution(this.resourceDeclarations.get(resource)?.when);\n return [\n {\n name: skill.name,\n description: skill.description,\n group: 'extensions' as const,\n owner: resource.source,\n modelInvocable: true,\n body: skill.content,\n ...(countTokens === undefined\n ? {}\n : {\n promptTokens: listedSkills.includes(resource)\n ? Math.max(0, countTokens(formatSkillsForSystemPrompt([skill])) - framingTokens)\n : 0,\n }),\n ...(contextAttribution === undefined ? {} : { contextAttribution }),\n },\n ];\n });\n const attribution: Record<string, PackageAttribution> = {};\n for (const candidate of this.options.candidates) {\n const owner =\n candidate.owners.find(\n (entry) =>\n entry.majorMode === selection.majorMode &&\n (entry.layer === 'default' || selection.activeLayers.includes(entry.layer)),\n ) ?? candidate.owners.find((entry) => entry.majorMode === selection.majorMode);\n if (owner && attribution[candidate.packageName] === undefined) {\n attribution[candidate.packageName] = { kind: 'major', mode: selection.majorMode, layer: owner.layer };\n }\n }\n for (const [server, source] of mcpPackages) {\n if (attribution[source]) attribution[server] = attribution[source];\n }\n return { sources, skills, attribution };\n }\n\n setAvailableSources(sources: readonly string[]): void {\n this.availableSources = new Set(sources);\n }\n\n /** Takes a reloaded package list; the next selection gates on it. */\n replaceCandidates(candidates: HeadlessHostOptions['candidates']): void {\n this.options = { ...this.options, candidates };\n }\n private matches(when?: PoHeadlessCondition): boolean {\n return (\n Object.entries(when?.state ?? {}).every(([key, value]) => this.applying.state?.[key]?.includes(value)) &&\n (when?.domain === undefined || this.applying.domains.includes(when.domain)) &&\n (when?.domains === undefined || when.domains.some((domain) => this.applying.domains.includes(domain)))\n );\n }\n private selected<T extends { when?: PoHeadlessCondition }>(entries: readonly Owned<T>[]): readonly Owned<T>[] {\n return entries.filter(({ value }) => this.matches(value.when));\n }\n\n assertActive(source?: string): void {\n this.assertReady();\n if (source !== undefined && !this.activeSources.has(source))\n throw new Error(`Contribution owner '${source}' is inactive`);\n }\n\n isSourceActive(source: string): boolean {\n return this.activeSources.has(source);\n }\n\n registerInitialSelectionResolver(\n resolve: (selection: PoHeadlessSelection) => PoHeadlessSelection | Promise<PoHeadlessSelection>,\n ): () => void {\n this.initialSelectionResolvers.add(resolve);\n const dispose = () => {\n this.initialSelectionResolvers.delete(resolve);\n };\n this.ctx.effect(() => dispose, 'headless initial selection resolver');\n return dispose;\n }\n\n subscribeSelection(\n listener: (selection: PoHeadlessSelection, applied: PoHeadlessSelectionApplied) => void | Promise<void>,\n ): () => void {\n this.selectionListeners.set(listener, readPoHeadlessOwner(this.ctx)?.packageName);\n return () => {\n this.selectionListeners.delete(listener);\n };\n }\n\n /** A contribution owned by a package that is not required, which may fail on its own. */\n private optionalSource(source: string | undefined): boolean {\n return (\n source !== undefined &&\n !this.options.candidates.some((candidate) => candidate.packageName === source && candidate.required)\n );\n }\n\n /** Shared by package reconciliation and the final Pi/package merge. */\n allowsTool(name: string): boolean {\n const allowed = this.options.allowedTools?.(this.applying);\n return (\n (name !== PO_SEARCH_SKILLS_TOOL || this.listSkills().length > FLAT_SKILL_LIMIT) &&\n (allowed === undefined || allowed.includes(name)) &&\n this.restrictions.every(\n (restriction) =>\n (restriction.allowedTools === undefined || restriction.allowedTools.includes(name)) &&\n !restriction.excludedTools?.includes(name),\n )\n );\n }\n\n registerToolRestriction(restriction: PoHeadlessToolRestriction): PoHeadlessRegistration {\n return this.add('restrictions', restriction);\n }\n\n private eligible(entry: PoServerBundleEntry, selection: PoHeadlessSelection): boolean {\n return (\n entry.scopes.includes('session') &&\n entry.owners.some(\n (owner) =>\n owner.majorMode === selection.majorMode &&\n (owner.layer === 'default' || selection.activeLayers.includes(owner.layer)),\n )\n );\n }\n\n changeSelection(change: PoHeadlessSelectionChange, options?: { atToolBoundary?: boolean }): Promise<void> {\n const apply = (change: PoHeadlessSelectionChange): Promise<void> => {\n this.selectionOverrides.add(change.axis);\n if (change.axis === 'majorMode') return this.select({ majorMode: change.majorMode });\n if (change.axis === 'domains') return this.select({ domains: change.domains });\n if (change.axis === 'profile') return this.select({ profile: change.profile });\n return this.select({ state: { ...this.requested.state, [change.key]: [...change.values] } });\n };\n return this.options.scheduleSelection?.(change, apply, options) ?? apply(change);\n }\n\n private async refreshChangedSelection(\n previous: PoHeadlessSelection,\n selection: PoHeadlessSelection,\n previousValues: ReadonlyMap<string, readonly unknown[]>,\n refreshed: readonly PoHeadlessRefreshAxis[],\n ): Promise<void> {\n const majorChanged =\n refreshed.includes('majorMode') ||\n previous.majorMode !== selection.majorMode ||\n !sameStrings(previous.activeLayers, selection.activeLayers);\n const domainsChanged = refreshed.includes('domains') || !sameStrings(previous.domains, selection.domains);\n const profileChanged = refreshed.includes('profile') || previous.profile !== selection.profile;\n const stateChanged = JSON.stringify(previous.state ?? {}) !== JSON.stringify(selection.state ?? {});\n if (this.appliedRevision === 0) return;\n\n const refresh = async (slot: string): Promise<void> => {\n const before = previousValues.get(slot) ?? [];\n if (sameValues(before, this.kernel.activeValues(slot))) await this.kernel.refresh(slot);\n };\n if (stateChanged) await refresh('restrictions');\n if (majorChanged || domainsChanged || stateChanged || this.restrictionsChanged) await refresh('tools');\n if (majorChanged || domainsChanged || profileChanged || stateChanged) await refresh('resources');\n if (domainsChanged || stateChanged) {\n await refresh('commands');\n await refresh('hooks');\n await refresh('activities');\n }\n }\n\n /** Refresh inherited defaults only at turn admission, keeping explicit session axes. */\n async inheritSelection(selection: Partial<PoHeadlessSelection>): Promise<void> {\n const patch: Partial<PoHeadlessSelection> = {\n ...(!this.selectionOverrides.has('majorMode') && selection.majorMode !== undefined\n ? { majorMode: selection.majorMode }\n : {}),\n ...(!this.selectionOverrides.has('domains') && selection.domains !== undefined\n ? { domains: selection.domains }\n : {}),\n ...(!this.selectionOverrides.has('profile') && Object.hasOwn(selection, 'profile')\n ? { profile: selection.profile }\n : {}),\n };\n if (\n (patch.majorMode === undefined || patch.majorMode === this.requested.majorMode) &&\n (patch.domains === undefined || sameStrings(patch.domains, this.requested.domains)) &&\n (!Object.hasOwn(patch, 'profile') || patch.profile === this.requested.profile)\n )\n return;\n await this.select(patch);\n }\n\n /**\n * Applies `patch` over the requested selection. `refresh` re-applies those axes as if they had\n * changed, for config edited on disk under an unchanged name, and tells selection listeners so.\n */\n async select(\n patch: Partial<PoHeadlessSelection>,\n options?: { readonly refresh?: readonly PoHeadlessRefreshAxis[] },\n ): Promise<void> {\n const refreshed = options?.refresh ?? [];\n if (this.disposed) throw new Error('The headless host is disposed');\n const requested = structuredClone({ ...this.requested, ...patch });\n this.requested = requested;\n const revision = ++this.requestedRevision;\n this.ready = false;\n const apply = async (): Promise<void> => {\n if (this.disposed) throw new Error('The headless host is disposed');\n let resolved = structuredClone(requested);\n if (this.appliedRevision === 0) {\n for (const resolve of this.initialSelectionResolvers) resolved = await resolve(resolved);\n if (this.disposed) throw new Error('The headless host is disposed');\n // A completed launch decision, including unchanged None, cannot be replaced by turn defaults.\n // If resolution rejects above no decision is latched, so a retry can resolve again.\n if (this.initialSelectionResolvers.size > 0) this.selectionOverrides.add('profile');\n }\n const selection = structuredClone((await this.options.resolveSelection?.(resolved)) ?? resolved);\n await this.options.validateSelection?.(selection);\n if (revision === this.requestedRevision) this.requested = selection;\n const eligible = this.options.candidates.filter((entry) => this.eligible(entry, selection));\n const missing = eligible.find((entry) => entry.required && !this.availableSources.has(entry.packageName));\n if (missing) throw new Error(`Required headless package '${missing.packageName}' is unavailable`);\n // The kernel's layer key here is the precomputed package eligibility key.\n // Minor tool restrictions run in the tools sink only after this owner gate.\n this.applying = selection;\n this.refreshing = true;\n let compositionChanged = false;\n try {\n const previousValues = new Map(\n this.kernel.slots.map((slot) => [slot, this.kernel.activeValues(slot)] as const),\n );\n await this.kernel.setActiveLayers(eligible.map((entry) => entry.packageName));\n await this.refreshChangedSelection(this.applied, selection, previousValues, refreshed);\n compositionChanged =\n refreshed.length > 0 ||\n this.failure !== undefined ||\n this.appliedRevision === 0 ||\n !sameSelection(this.applied, selection) ||\n this.restrictionsChanged ||\n this.contributionsChanged ||\n !sameValues(previousValues.get('tools') ?? [], this.kernel.activeValues('tools')) ||\n !sameValues(previousValues.get('resources') ?? [], this.kernel.activeValues('resources'));\n this.restrictionsChanged = false;\n this.contributionsChanged = false;\n } finally {\n this.refreshing = false;\n }\n if (this.disposed) throw new Error('The headless host is disposed');\n this.activeSources = new Set(eligible.map((entry) => entry.packageName));\n this.applied = selection;\n this.appliedRevision = revision;\n this.failure = undefined;\n this.ready = revision === this.requestedRevision;\n for (const [listener, owner] of this.selectionListeners) {\n try {\n await listener(selection, refreshed.length === 0 ? {} : { refresh: refreshed });\n } catch (error) {\n if (isPoHeadlessPromptAdmissionError(error)) this.recoveryRevision = revision;\n // A host listener or a required package fails the selection; any other package's is reported.\n if (isPoHeadlessPromptAdmissionError(error) || !this.optionalSource(owner)) throw error;\n const reason = error instanceof Error ? error.message : String(error);\n this.options.onError?.(new Error(`package '${owner}': ${reason}`, { cause: error }), 'selection');\n }\n }\n if (compositionChanged) await this.options.onApplied?.(selection, revision);\n };\n const result = this.tail.catch(() => undefined).then(apply);\n this.tail = result.catch((error: unknown) => {\n this.failure = error;\n this.ready = false;\n // close() marks the host disposed before draining this tail, so every selection still\n // queued at that point rejects by design. Those rejections are teardown artifacts, not\n // actionable failures, and reporting them surfaces one notice per queued contribution.\n if (!this.disposed) this.options.onError?.(error, 'apply');\n });\n await result;\n await this.settled();\n this.assertApplied();\n }\n\n /** Drain selections, including ones queued by selection listeners. */\n async settled(): Promise<void> {\n let pending: Promise<void>;\n do {\n pending = this.tail;\n await pending;\n } while (pending !== this.tail);\n }\n\n /** Preserve a failed apply's cause instead of replacing it with the readiness error. */\n private assertApplied(): void {\n const failure: unknown = this.failure;\n if (failure instanceof Error) throw failure;\n if (failure !== undefined)\n throw new Error(typeof failure === 'string' ? failure : 'Headless selection failed', { cause: failure });\n this.assertReady();\n }\n\n private assertReady(): void {\n if (this.disposed || !this.ready)\n throw new Error('Headless dispatch is blocked until selection is coherently applied');\n }\n\n /** Runs an approved direct tool call against the tool as it is now: removed or inactive tools do not run. */\n private async runApproved(call: PoApprovedCall, signal: AbortSignal): Promise<PoHeadlessToolResult> {\n await this.settled();\n this.assertReady();\n const entry = this.tools.get(call.operation.name);\n if (entry === undefined || !this.activeSources.has(entry.source))\n throw new Error(`Tool '${call.operation.name}' is no longer active. Nothing ran.`);\n signal.throwIfAborted();\n return entry.value.execute(`approval:${call.approvalId}`, call.input, signal, undefined, {\n ...this.context,\n caller: 'main',\n });\n }\n\n private add<T>(slot: string, value: T): PoHeadlessRegistration {\n const owner = readPoHeadlessOwner(this.ctx);\n if (!owner) throw new Error('A headless contribution must have descriptor-owned package identity');\n this.ready = false;\n this.contributionsChanged = true;\n const registration = this.kernel.contribute(slot, {\n source: owner.packageName,\n layer: owner.packageName,\n value: { source: owner.packageName, value } satisfies Owned<T>,\n });\n let disposed = false;\n const dispose = (): void => {\n if (disposed) return;\n disposed = true;\n this.ready = false;\n this.contributionsChanged = true;\n registration.dispose();\n // Reconciled on the same terms as the registration below: before the first applied\n // selection the caller's own select() computes the whole composition, and the sources\n // that selection gates on are not known yet.\n if (this.appliedRevision > 0 && !this.disposed && !this.refreshing) void this.select({}).catch(() => undefined);\n };\n this.ctx.effect(() => dispose, `headless ${slot} contribution`);\n // Initial registration is reconciled once the caller has installed all packages.\n if (this.appliedRevision > 0 && !this.refreshing) void this.select({}).catch(() => undefined);\n return { dispose };\n }\n\n registerTool<TParameters extends TSchema>(tool: PoHeadlessTool<TParameters>): PoHeadlessRegistration {\n return this.add('tools', tool);\n }\n registerResource(resource: PoHeadlessResource): PoHeadlessRegistration {\n return this.add('resources', resource);\n }\n registerCommand(command: PoHeadlessCommand): PoHeadlessRegistration {\n return this.add('commands', command);\n }\n registerHook(hook: PoHeadlessHook): PoHeadlessRegistration {\n return this.add('hooks', hook);\n }\n registerActivity(activity: PoHeadlessActivity): PoHeadlessRegistration {\n return this.add('activities', activity);\n }\n\n private canRecoverSelection(): boolean {\n return (\n !this.disposed &&\n !this.ready &&\n !this.refreshing &&\n !this.contributionsChanged &&\n !this.restrictionsChanged &&\n this.recoveryRevision === this.requestedRevision &&\n this.appliedRevision === this.requestedRevision &&\n isPoHeadlessPromptAdmissionError(this.failure)\n );\n }\n\n listCommands(): Array<Pick<PoHeadlessCommand, 'name' | 'description'>> {\n const recovering = this.canRecoverSelection();\n if (!recovering) this.assertReady();\n return [...this.commands.values()]\n .filter(\n ({ source, value }) =>\n !recovering ||\n (value.selectionRecovery === true && this.activeSources.has(source) && this.availableSources.has(source)),\n )\n .map(({ value }) => ({ name: value.name, description: value.description }));\n }\n\n async dispatchCommand(name: string, args: string): Promise<void> {\n const command = this.commands.get(name);\n if (!this.canRecoverSelection() || command?.value.selectionRecovery !== true) this.assertReady();\n if (!command || !this.activeSources.has(command.source) || !this.availableSources.has(command.source))\n throw new Error(`Command '${name}' is inactive or unknown`);\n await command.value.execute(args, this.context);\n }\n\n async dispatchHook(\n event: PoHeadlessEventName,\n payload: Readonly<Record<string, unknown>>,\n signal?: AbortSignal,\n ): Promise<unknown[]> {\n this.assertReady();\n signal?.throwIfAborted();\n const results: unknown[] = [];\n const revision = this.appliedRevision;\n let current = payload;\n for (const hook of this.hooks.filter((entry) => entry.value.event === event)) {\n this.assertReady();\n signal?.throwIfAborted();\n if (!this.hooks.includes(hook)) continue;\n let result: unknown;\n try {\n result = await hook.value.handle(current as never, signal ? { ...this.context, signal } : this.context);\n signal?.throwIfAborted();\n } catch (error) {\n if (isPoHeadlessPromptAdmissionError(error)) throw error;\n signal?.throwIfAborted();\n this.options.onError?.(error, 'hook');\n continue;\n }\n if (event === 'session_start') {\n // Startup hooks may register retained contributions. Finish their queued reconciliation\n // before the next hook, without relaxing dispatch guards during the transition.\n await this.tail;\n this.assertReady();\n }\n results.push(result);\n if (result && typeof result === 'object' && !Array.isArray(result)) {\n const patch = result as Record<string, unknown>;\n // Execution hooks compose in registration order, just like the public harness hooks.\n const fields =\n event === 'context'\n ? ['messages', 'systemPrompt']\n : event === 'tool_call'\n ? ['args']\n : event === 'tool_result'\n ? ['content', 'details', 'isError', 'usage']\n : event === 'before_agent_start'\n ? ['systemPrompt']\n : event === 'before_provider_request'\n ? ['payload']\n : [];\n for (const field of fields) {\n if (event === 'before_agent_start' && typeof patch[field] !== 'string') continue;\n if (patch[field] !== undefined) current = { ...current, [field]: patch[field] };\n }\n // Denials and structural decisions use upstream first-result semantics.\n if (event === 'tool_call' && patch.block !== undefined) break;\n if (\n event === 'session_before_compact' &&\n (patch.cancel !== undefined || patch.decline !== undefined || patch.compaction !== undefined)\n )\n break;\n }\n }\n if (event === 'before_agent_start' || event === 'context' || event === 'tool_call') {\n this.assertReady();\n if (revision !== this.appliedRevision) {\n throw new Error(\n event === 'before_agent_start'\n ? 'Selection changed while preparing the system prompt'\n : `Selection changed while dispatching ${event}`,\n );\n }\n }\n return results;\n }\n\n private async resolveResources(selection: PoHeadlessSelection): Promise<readonly ResolvedHeadlessResource[]> {\n const context = this.options.context(selection);\n const result: ResolvedHeadlessResource[] = [];\n for (const resource of this.resources) {\n let value: string;\n try {\n value = await resource.value.read(context);\n } catch (error) {\n // Report and skip, never rethrow. This runs on every prompt build, and a\n // throw here reaches the systemPrompt callback, sets promptPreparationFailed\n // and denies every model request for the rest of the session. One package\n // missing one shipped file must not take the session down with it.\n this.options.onError?.(\n new Error(`Could not read headless resource '${resource.source}/${resource.value.name}'`, { cause: error }),\n 'resource',\n );\n continue;\n }\n const resolved: ResolvedHeadlessResource = {\n source: resource.source,\n name: resource.value.name,\n kind: resource.value.kind,\n ...(resource.value.description === undefined ? {} : { description: resource.value.description }),\n ...(resource.value.path === undefined ? {} : { path: resource.value.path }),\n ...(resource.value.pinned === true ? { pinned: true } : {}),\n text: value,\n };\n this.resourceDeclarations.set(resolved, resource.value);\n result.push(resolved);\n }\n return result;\n }\n\n async readResources(): Promise<readonly ResolvedHeadlessResource[]> {\n let result: readonly ResolvedHeadlessResource[] | undefined;\n let revision = 0;\n for (let attempt = 0; ; attempt++) {\n // Drain inline: awaiting settled() would leave a continuation gap before the readiness check.\n let pending: Promise<void>;\n do {\n pending = this.tail;\n await pending;\n } while (pending !== this.tail);\n this.assertApplied();\n if (result !== undefined && revision === this.appliedRevision) return result;\n if (attempt === RESOURCE_READ_ATTEMPTS) throw new Error('Selection changed while reading resources');\n revision = this.appliedRevision;\n result = await this.resolveResources(this.applied);\n }\n }\n\n async close(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n this.ready = false;\n this.selectionListeners.clear();\n await this.tail.catch(() => undefined);\n const failures: unknown[] = [];\n for (const stop of [...this.activities.values()].reverse()) {\n try {\n await stop();\n } catch (error) {\n failures.push(error);\n }\n }\n this.activities.clear();\n this.kernel.dispose();\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KAAa,aAAa,KAAK,iBAAiB,OAAO;GACtE,IAAI,YAAY,wBAAwB,MAAM,IAAI,MAAM,2CAA2C;GACnG,WAAW,KAAK;GAChB,SAAS,MAAM,KAAK,iBAAiB,KAAK,OAAO;EACnD;CACF;CAEA,MAAM,QAAuB;EAC3B,IAAI,KAAK,UAAU;EACnB,KAAK,WAAW;EAChB,KAAK,QAAQ;EACb,KAAK,mBAAmB,MAAM;EAC9B,MAAM,KAAK,KAAK,YAAY,KAAA,CAAS;EACrC,MAAM,WAAsB,CAAC;EAC7B,KAAK,MAAM,QAAQ,CAAC,GAAG,KAAK,WAAW,OAAO,CAAC,CAAC,CAAC,QAAQ,GACvD,IAAI;GACF,MAAM,KAAK;EACb,SAAS,OAAO;GACd,SAAS,KAAK,KAAK;EACrB;EAEF,KAAK,WAAW,MAAM;EACtB,KAAK,OAAO,QAAQ;EACpB,IAAI,SAAS,QAAQ,MAAM,IAAI,eAAe,UAAU,oCAAoC;CAC9F;AACF"}
|
|
@@ -114,6 +114,8 @@ export declare class HeadlessHost extends Service<PoHeadlessHostService> impleme
|
|
|
114
114
|
}): Promise<void>;
|
|
115
115
|
/** Drain selections, including ones queued by selection listeners. */
|
|
116
116
|
settled(): Promise<void>;
|
|
117
|
+
/** Preserve a failed apply's cause instead of replacing it with the readiness error. */
|
|
118
|
+
private assertApplied;
|
|
117
119
|
private assertReady;
|
|
118
120
|
/** Runs an approved direct tool call against the tool as it is now: removed or inactive tools do not run. */
|
|
119
121
|
private runApproved;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"headlessHost.d.mts","names":[],"sources":["../../../../../src/systems/main/adapters/headlessHost.ts"],"mappings":";;;;;;;;;;;;;;;;;wBA6EgB,qBAAqB,UAAU;EAE3C;EACA;EACA;EACA;;;
|
|
1
|
+
{"version":3,"file":"headlessHost.d.mts","names":[],"sources":["../../../../../src/systems/main/adapters/headlessHost.ts"],"mappings":";;;;;;;;;;;;;;;;;wBA6EgB,qBAAqB,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BAAiB;EAkBlC,SAAS"}
|
|
@@ -38,6 +38,7 @@ function escapeXml(value) {
|
|
|
38
38
|
return value.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
|
39
39
|
}
|
|
40
40
|
const FLAT_SKILL_LIMIT = 20;
|
|
41
|
+
const RESOURCE_READ_ATTEMPTS = 5;
|
|
41
42
|
function uniqueSkills(resources) {
|
|
42
43
|
return resources.filter((skill, index, all) => skill.kind === "skill" && all.findLastIndex((entry) => entry.kind === "skill" && entry.name === skill.name) === index);
|
|
43
44
|
}
|
|
@@ -533,10 +534,7 @@ var HeadlessHost = class extends Service {
|
|
|
533
534
|
});
|
|
534
535
|
await result;
|
|
535
536
|
await this.settled();
|
|
536
|
-
|
|
537
|
-
if (failure instanceof Error) throw failure;
|
|
538
|
-
if (failure !== void 0) throw new Error(typeof failure === "string" ? failure : "Headless selection failed", { cause: failure });
|
|
539
|
-
this.assertReady();
|
|
537
|
+
this.assertApplied();
|
|
540
538
|
}
|
|
541
539
|
/** Drain selections, including ones queued by selection listeners. */
|
|
542
540
|
async settled() {
|
|
@@ -546,6 +544,13 @@ var HeadlessHost = class extends Service {
|
|
|
546
544
|
await pending;
|
|
547
545
|
} while (pending !== this.tail);
|
|
548
546
|
}
|
|
547
|
+
/** Preserve a failed apply's cause instead of replacing it with the readiness error. */
|
|
548
|
+
assertApplied() {
|
|
549
|
+
const failure = this.failure;
|
|
550
|
+
if (failure instanceof Error) throw failure;
|
|
551
|
+
if (failure !== void 0) throw new Error(typeof failure === "string" ? failure : "Headless selection failed", { cause: failure });
|
|
552
|
+
this.assertReady();
|
|
553
|
+
}
|
|
549
554
|
assertReady() {
|
|
550
555
|
if (this.disposed || !this.ready) throw new Error("Headless dispatch is blocked until selection is coherently applied");
|
|
551
556
|
}
|
|
@@ -698,12 +703,20 @@ var HeadlessHost = class extends Service {
|
|
|
698
703
|
return result;
|
|
699
704
|
}
|
|
700
705
|
async readResources() {
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
706
|
+
let result;
|
|
707
|
+
let revision = 0;
|
|
708
|
+
for (let attempt = 0;; attempt++) {
|
|
709
|
+
let pending;
|
|
710
|
+
do {
|
|
711
|
+
pending = this.tail;
|
|
712
|
+
await pending;
|
|
713
|
+
} while (pending !== this.tail);
|
|
714
|
+
this.assertApplied();
|
|
715
|
+
if (result !== void 0 && revision === this.appliedRevision) return result;
|
|
716
|
+
if (attempt === RESOURCE_READ_ATTEMPTS) throw new Error("Selection changed while reading resources");
|
|
717
|
+
revision = this.appliedRevision;
|
|
718
|
+
result = await this.resolveResources(this.applied);
|
|
719
|
+
}
|
|
707
720
|
}
|
|
708
721
|
async close() {
|
|
709
722
|
if (this.disposed) return;
|